repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
duanlunming/imageHandle | refs/heads/master | GPUImage-ObjC/examples/iOS/FilterShowcaseSwift/FilterShowcaseSwift/FilterListViewController.swift | bsd-3-clause | 1 | import UIKit
class FilterListViewController: UITableViewController {
var filterDisplayViewController: FilterDisplayViewController? = nil
var objects = NSMutableArray()
// #pragma mark - Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let filterInList = filterOperations[indexPath.row]
(segue.destination as! FilterDisplayViewController).filterOperation = filterInList
}
}
}
// #pragma mark - Table View
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filterOperations.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
let filterInList:FilterOperationInterface = filterOperations[indexPath.row]
cell.textLabel?.text = filterInList.listName
return cell
}
}
| 797d857a169fe37ffd3101eea3dc0b7c | 32.378378 | 109 | 0.689879 | false | false | false | false |
alltheflow/iCopyPasta | refs/heads/master | Carthage/Checkouts/Moya/Carthage/Checkouts/RxSwift/Rx.playground/Pages/Filtering_Observables.xcplaygroundpage/Contents.swift | mit | 6 | //: [<< Previous](@previous) - [Index](Index)
import RxSwift
/*:
## Filtering Observables
Operators that selectively emit items from a source Observable.
*/
/*:
### `filter`
Emit only those items from an Observable that pass a predicate test

[More info in reactive.io website]( http://reactivex.io/documentation/operators/filter.html )
*/
example("filter") {
let subscription = Observable.of(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
.filter {
$0 % 2 == 0
}
.subscribe {
print($0)
}
}
/*:
### `distinctUntilChanged`
Suppress duplicate items emitted by an Observable

[More info in reactive.io website]( http://reactivex.io/documentation/operators/distinct.html )
*/
example("distinctUntilChanged") {
let subscription = Observable.of(1, 2, 3, 1, 1, 4)
.distinctUntilChanged()
.subscribe {
print($0)
}
}
/*:
### `take`
Emit only the first n items emitted by an Observable

[More info in reactive.io website]( http://reactivex.io/documentation/operators/take.html )
*/
example("take") {
let subscription = Observable.of(1, 2, 3, 4, 5, 6)
.take(3)
.subscribe {
print($0)
}
}
//: [Index](Index) - [Next >>](@next)
| f9d2e824cd78ff9480eef8377fc53893 | 21.463768 | 99 | 0.643871 | false | false | false | false |
apple-programmer/general_mac_anonymizer | refs/heads/master | MKO project/Network setup.swift | artistic-2.0 | 1 | //
// Network setup.swift
// MKO project
//
// Created by Roman Nikitin on 08.02.16.
// Copyright © 2016 NikRom. All rights reserved.
//
import Foundation
import Cocoa
func configureProxy() {
let services = runCommand(command: "networksetup -listallnetworkservices | grep -vw \"An asterisk\"").componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet())
for serv in services {
if !serv.isEmpty {
runCommand(command: "\(askpass) sudo -Ak networksetup -setsecurewebproxy \"\(serv)\" 127.0.0.1 8118")
runCommand(command: "\(askpass) sudo -Ak networksetup -setwebproxy \"\(serv)\" 127.0.0.1 8118")
runCommand(command: "\(askpass) sudo -Ak networksetup -setsocksfirewallproxy \"\(serv)\" 127.0.0.1 9050")
printToGUI("Configured proxy on service \(serv)")
}
}
}
func getCurrentLocation() {
let output = runCommand(command: "\(askpass) sudo -Ak networksetup -getcurrentlocation").componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()).first
if output == "Automatic" || output == "Авто" {
createLocation(locationName: "Main Location")
switchToLocation(locationName: "Main Location")
runCommand(command: "\(askpass) sudo -Ak -deletelocation \"\(output)\"")
NSUserDefaults.standardUserDefaults().setObject("Main Location", forKey: "OldLocation")
}
else {
NSUserDefaults.standardUserDefaults().setObject(output, forKey: "OldLocation")
}
}
func createLocation(locationName name : String = "Secret Location") {
runCommand(command: "\(askpass) sudo -Ak networksetup -createlocation \"\(name)\" populate")
print("Location created")
printToGUI("Created location \(name)")
}
func switchToLocation(locationName name : String = "Secret Location") {
var name = name
let result = runCommand(command: "\(askpass) sudo -Ak networksetup -switchtolocation \"\(name)\"")
if result.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()).contains("** Error: The parameters were not valid.") {
printToGUI("Could not find old location")
createLocation(locationName: "Main Location")
switchToLocation(locationName: "Main Location")
name = "Main Location"
}
print("Switched to location \(name)")
printToGUI("Switched to location \(name)")
}
func initNetwork() {
getPassword()
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), {
getCurrentLocation()
createLocation()
switchToLocation()
configureProxy()
})
dispatch_sync(dispatch_get_global_queue(QOS_CLASS_USER_INTERACTIVE, 0), {
if !isTorInstalled() || !isPrivoxyInstalled() {
initBrew()
}
})
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
initPrivoxy()
initTor()
})
}
func deinitNetwork() {
var location = NSUserDefaults.standardUserDefaults().objectForKey("OldLocation") as! String
if location == "Secret Location" {
location = "Main Location"
}
switchToLocation(locationName: location)
runCommand(command: "\(askpass) sudo -Ak networksetup -deletelocation \"Secret Location\"")
print("Deleted location")
printToGUI("Deleted location \"Secret Location\"")
isTorLaunched = false
runCommand(command: "killall tor")
runCommand(command: "killall privoxy")
printToGUI("Killed Privoxy")
} | 9d379fe7e73d8dd7ba12f18b96264c16 | 37.811111 | 180 | 0.678408 | false | false | false | false |
bingoogolapple/SwiftNote-PartOne | refs/heads/master | 数据优化/数据优化/MainViewController.swift | apache-2.0 | 1 | //
// MainViewController.swift
// 数据优化
//
// Created by bingoogol on 14/9/23.
// Copyright (c) 2014年 bingoogol. All rights reserved.
//
import UIKit
let CELL_ID = "MYCELL"
let HEADER_ID = "MYHEADER"
class MainViewController: UITableViewController {
override func loadView() {
self.tableView = UITableView(frame: UIScreen.mainScreen().applicationFrame)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 3
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 10
} else if section == 1 {
return 20
} else {
return 15
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier(CELL_ID) as? UITableViewCell
if cell == nil {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: CELL_ID)
println("实例化单元格\(indexPath.section)组\(indexPath.row)行")
}
cell?.textLabel?.text = "\(indexPath.section)组\(indexPath.row)行"
return cell!
}
// 如果是字符串形式,本身不需要进行优化,因为通常会有一个数据字典维护,需要显示字符串,直接通过section从数组中提取即可
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return "第\(section)组"
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(HEADER_ID) as? UITableViewHeaderFooterView
var button:UIButton
if header == nil {
header = UITableViewHeaderFooterView(reuseIdentifier: HEADER_ID)
header?.frame = CGRectMake(0, 0, self.tableView.bounds.width, 44)
// Setting the background color on UITableViewHeaderFooterView has been deprecated. Please use contentView.backgroundColor instead.
button = UIButton.buttonWithType(UIButtonType.System) as UIButton
button.frame = header!.bounds
header?.addSubview(button)
println("实例化标题行")
} else {
button = header?.subviews[2] as UIButton
}
button.setTitle("组\(section)", forState: UIControlState.Normal)
return header
}
} | 7b288aba6d16e55fe90b0025432d491e | 33.162162 | 143 | 0.648199 | false | false | false | false |
rnystrom/GitHawk | refs/heads/master | Classes/Issues/Title/IssueTitleSectionController.swift | mit | 1 | //
// IssueTitleSectionController.swift
// Freetime
//
// Created by Ryan Nystrom on 5/19/17.
// Copyright © 2017 Ryan Nystrom. All rights reserved.
//
import UIKit
import IGListKit
final class IssueTitleSectionController: ListSectionController {
var object: IssueTitleModel?
override init() {
super.init()
inset = UIEdgeInsets(top: Styles.Sizes.rowSpacing, left: 0, bottom: 0, right: 0)
}
override func didUpdate(to object: Any) {
guard let object = object as? IssueTitleModel else { return }
self.object = object
}
override func sizeForItem(at index: Int) -> CGSize {
return collectionContext.cellSize(
with: object?.string.viewSize(in: collectionContext.safeContentWidth()).height ?? 0
)
}
override func cellForItem(at index: Int) -> UICollectionViewCell {
guard let object = self.object,
let cell = collectionContext?.dequeueReusableCell(of: IssueTitleCell.self, for: self, at: index) as? IssueTitleCell
else { fatalError("Collection context must be set, missing object, or cell incorrect type") }
cell.set(renderer: object.string)
return cell
}
}
| 80238028a2e2cbbf4a9850cd9efa4509 | 29.2 | 127 | 0.667219 | false | false | false | false |
r9ronaldozhang/ZYColumnViewController | refs/heads/master | ZYColumnViewDemo/ZYColumnViewDemo/ZYColumnView/ZYColumnConfig.swift | mit | 1 | //
// ZYColumnConfig.swift
// 掌上遂宁
//
// Created by 张宇 on 2016/10/10.
// Copyright © 2016年 张宇. All rights reserved.
//
import UIKit
/******** 在此文件中定义了此控件常用的常用尺寸变量,用户可根据自己需求进行修改 ********/
let kColumnScreenW = UIScreen.main.bounds.size.width
let kColumnScreenH = UIScreen.main.bounds.size.height
let kColumnItemEqualWidth = true // 默认横向item是否等宽 还是根据文字匹配
let kColumnViewH:CGFloat = 40.0 // 默认高度
let kColumnViewW = kColumnScreenW // 默认宽度
let kSpreadMaxH:CGFloat = kColumnScreenH - 64 // 默认下拉展开的最大高度
let kSpreadDuration = 0.4 // 动画展开收拢的时长
let kColumnLayoutCount = 4 // 排序item 每行个数
let kColumnItemH:CGFloat = (ZYinch55()) ? 40: 30 // item的高度
let kColumnItemW:CGFloat = (ZYinch55()) ? 85: 70 // item的宽度
let kColumnMarginW:CGFloat = (ZYScreenWidth-CGFloat(kColumnLayoutCount)*kColumnItemW)/CGFloat(kColumnLayoutCount+1) // item的横向间距
let kColumnMarginH:CGFloat = (ZYinch55()) ? 20:((ZYinch47()) ? 20: 15) // item的纵向间距
let kColumnEditBtnW:CGFloat = 60 // 排序删除按钮的宽度
let kColumnEditBtnH:CGFloat = 36 // 排序删除按钮的高度
let kColumnEditBtnFont:CGFloat = 10 // 排序删除按钮的字体
let kColumnEditBtnNorTitle = "排序删除" // 排序删除普通状态文字
let kColumnEditBtnSelTitle = "完成" // 排序删除选中状态文字
let kColumnItemBorderColor = UIColor.red.cgColor // item的色环
let kColumnItemColor = UIColor.red // item的文字颜色
let kColumnTitleMargin:CGFloat = 8 // title按钮之间默认没有间距,这个值保证两个按钮的间距
let kColumnTitleNorColor = UIColor.darkText // title普通状态颜色
let kColumnTitleSelColor = UIColor.red // title选中状态颜色
let kColumnTitleNorFont:CGFloat = (ZYinch47() || ZYinch55()) ? 14 : 13 // title普通状态字体
let kColumnTitleSelFont:CGFloat = (ZYinch47() || ZYinch55()) ? 16 : 15 // title选中状态字体
let kColumnHasIndicator = true // 默认有指示线条
let kColumnIndictorH:CGFloat = 2.0 // 指示线条高度
let kColumnIndictorMinW : CGFloat = 60 // 指示条默认最小宽度
let kColumnIndicatorColor = UIColor.red // 默认使用系统风格颜色
/************** 常量定义 ****************/
/// 是否是3.5英寸屏
func ZYinch35() -> Bool {
return UIScreen.main.bounds.size.height == 480.0
}
/// 是否是4.0英寸屏
func ZYinch40() -> Bool {
return UIScreen.main.bounds.size.height == 568.0
}
/// 是否是4.7英寸屏
func ZYinch47() -> Bool {
return UIScreen.main.bounds.size.height == 667.0
}
/// 是否是5.5英寸屏
func ZYinch55() -> Bool {
return UIScreen.main.bounds.size.height == 736.0
}
let ZYScreenWidth = UIScreen.main.bounds.width
let ZYScreenHeight = UIScreen.main.bounds.height
| b798c8398a81a55b08aa71f0050e0c01 | 48 | 166 | 0.542411 | false | false | false | false |
farion/eloquence | refs/heads/master | Eloquence/EloquenceIOS/RosterViewController.swift | apache-2.0 | 1 | import Foundation
import UIKit
import XMPPFramework
class RosterViewController:UIViewController, UITableViewDelegate, UITableViewDataSource, EloRosterDelegate {
@IBOutlet weak var tableView: UITableView!
var roster = EloRoster()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
roster.delegate = self
roster.initializeData()
}
/* private */
func configureCell(cell:RosterCell, atIndexPath: NSIndexPath){
NSLog("IP %d",atIndexPath.row)
let contactListItem = roster.getContactListItem(atIndexPath.row);
cell.name.text = contactListItem.bareJidStr
cell.viaLabel.text = "via " + contactListItem.streamBareJidStr
// cell.imageView!.image = user.photo;
}
/* UITableViewDataSource */
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return roster.numberOfRowsInSection(section);
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("RosterCell") as! RosterCell
configureCell(cell,atIndexPath:indexPath)
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
roster.chatWishedByUserAction(indexPath.row)
}
/* NSFetchedResultsControllerDelegate */
func rosterWillChangeContent() {
NSLog("rosterwillchange")
tableView.beginUpdates()
}
func roster(didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch(type){
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
break
case .Delete:
tableView.deleteRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
break
case .Update:
configureCell(tableView.cellForRowAtIndexPath(indexPath!) as! RosterCell ,atIndexPath: indexPath!)
break
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: UITableViewRowAnimation.Fade)
break
}
}
func rosterDidChangeContent() {
tableView.endUpdates()
}
}
| 83617c57247d801920053ce051f1d5dc | 34.155844 | 167 | 0.668267 | false | false | false | false |
tzef/BmoImageLoader | refs/heads/master | BmoImageLoader/Classes/ProgressAnimation/BaseProgressAnimation.swift | mit | 1 | //
// BaseProgressAnimation.swift
// CrazyMikeSwift
//
// Created by LEE ZHE YU on 2016/8/7.
// Copyright © 2016年 B1-Media. All rights reserved.
//
import UIKit
class BaseProgressAnimation: BmoProgressAnimator {
// Progress Animation View
weak var imageView: UIImageView?
var newImage: UIImage?
let helpPointView = BmoProgressHelpView()
// Progress Parameters
var completionBlock: ((BmoProgressCompletionResult<UIImage, NSError>) -> Void)?
var completionState = BmoProgressCompletionState.proceed
var progress = Progress(totalUnitCount: 100)
var progressColor = UIColor.black
var displayLink: CADisplayLink? = nil
var percentFont: UIFont?
// Animation Parameters
let transitionDuration = 0.33
let enlargeDuration = 0.33
var progressDuration = 0.5
var marginPercent: CGFloat = 0.1
// MARK: - Public
@objc func displayLinkAction(_ dis: CADisplayLink) {
}
func successAnimation(_ imageView: UIImageView) {
}
func failureAnimation(_ imageView: UIImageView, error: NSError?) {
}
// MARK : - Private
fileprivate func initDisplayLink() {
displayLink?.invalidate()
displayLink = nil
displayLink = CADisplayLink(target: self, selector: #selector(BaseProgressAnimation.displayLinkAction(_:)))
displayLink?.add(to: RunLoop.main, forMode: RunLoopMode.UITrackingRunLoopMode)
displayLink?.add(to: RunLoop.main, forMode: RunLoopMode.defaultRunLoopMode)
}
// MARK: - ProgressAnimator Protocol
func setCompletionBlock(_ completion: ((BmoProgressCompletionResult<UIImage, NSError>) -> Void)?) -> BmoProgressAnimator {
self.completionBlock = completion
return self
}
func setCompletionState(_ state: BmoProgressCompletionState) -> BmoProgressAnimator {
self.completionState = state
switch self.completionState {
case .succeed:
self.setCompletedUnitCount(progress.totalUnitCount).closure()
case .failed(_):
self.setCompletedUnitCount(0).closure()
default:
break
}
return self
}
func setTotalUnitCount(_ count: Int64) -> BmoProgressAnimator {
progress.totalUnitCount = count
return self
}
func setCompletedUnitCount(_ count: Int64) -> BmoProgressAnimator {
guard let strongImageView = self.imageView else {
return self
}
progress.completedUnitCount = count
initDisplayLink()
helpPointView.bounds = helpPointView.layer.presentation()?.bounds ?? helpPointView.bounds
helpPointView.layer.removeAllAnimations()
UIView.animate(withDuration: progressDuration, animations: {
self.helpPointView.bounds = CGRect(x: CGFloat(self.progress.fractionCompleted), y: 0, width: 0, height: 0)
}, completion: { (finished) in
if finished {
if self.progress.completedUnitCount >= self.progress.totalUnitCount {
switch self.completionState {
case .succeed:
self.successAnimation(strongImageView)
default:
break
}
}
if self.progress.completedUnitCount == 0 {
switch self.completionState {
case .failed(let error):
self.failureAnimation(strongImageView, error: error)
default:
break
}
}
}
})
return self
}
func resetAnimation() -> BmoProgressAnimator {
return self
}
func setAnimationDuration(_ duration: TimeInterval) -> BmoProgressAnimator {
self.progressDuration = duration
return self
}
func setNewImage(_ image: UIImage) -> BmoProgressAnimator {
self.newImage = image
return self
}
func setMarginPercent(_ percent: CGFloat) -> BmoProgressAnimator {
self.marginPercent = percent
self.resetAnimation().closure()
return self
}
func setProgressColor(_ color: UIColor) -> BmoProgressAnimator {
self.progressColor = color
self.resetAnimation().closure()
return self
}
func setPercentFont(_ font: UIFont) -> BmoProgressAnimator {
self.percentFont = font
self.resetAnimation().closure()
return self
}
/**
Do nothing, in order to avoid the warning about result of call is unused
*/
func closure() {
return
}
}
| b261e75930b6d12fee890f21d162ba07 | 33.492537 | 126 | 0.622458 | false | false | false | false |
ThumbWorks/i-meditated | refs/heads/master | Pods/RxCocoa/RxCocoa/Common/Observables/Implementations/ControlTarget.swift | mit | 1 | //
// ControlTarget.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS) || os(OSX)
import Foundation
#if !RX_NO_MODULE
import RxSwift
#endif
#if os(iOS) || os(tvOS)
import UIKit
typealias Control = UIKit.UIControl
typealias ControlEvents = UIKit.UIControlEvents
#elseif os(OSX)
import Cocoa
typealias Control = Cocoa.NSControl
#endif
// This should be only used from `MainScheduler`
class ControlTarget: RxTarget {
typealias Callback = (Control) -> Void
let selector: Selector = #selector(ControlTarget.eventHandler(_:))
weak var control: Control?
#if os(iOS) || os(tvOS)
let controlEvents: UIControlEvents
#endif
var callback: Callback?
#if os(iOS) || os(tvOS)
init(control: Control, controlEvents: UIControlEvents, callback: @escaping Callback) {
MainScheduler.ensureExecutingOnScheduler()
self.control = control
self.controlEvents = controlEvents
self.callback = callback
super.init()
control.addTarget(self, action: selector, for: controlEvents)
let method = self.method(for: selector)
if method == nil {
rxFatalError("Can't find method")
}
}
#elseif os(OSX)
init(control: Control, callback: Callback) {
MainScheduler.ensureExecutingOnScheduler()
self.control = control
self.callback = callback
super.init()
control.target = self
control.action = selector
let method = self.method(for: selector)
if method == nil {
rxFatalError("Can't find method")
}
}
#endif
func eventHandler(_ sender: Control!) {
if let callback = self.callback, let control = self.control {
callback(control)
}
}
override func dispose() {
super.dispose()
#if os(iOS) || os(tvOS)
self.control?.removeTarget(self, action: self.selector, for: self.controlEvents)
#elseif os(OSX)
self.control?.target = nil
self.control?.action = nil
#endif
self.callback = nil
}
}
#endif
| 59a8b8aaf187e989eece0487a59c68d9 | 22.619565 | 90 | 0.635067 | false | false | false | false |
SergeMaslyakov/audio-player | refs/heads/master | app/src/data/realm/CacheDescriptor.swift | apache-2.0 | 1 | //
// CacheDescriptor.swift
// AudioPlayer
//
// Created by Serge Maslyakov on 09/07/2017.
// Copyright © 2017 Maslyakov. All rights reserved.
//
import Foundation
import RealmSwift
class CacheDescriptor: Object {
dynamic var shouldUsingCache = false
dynamic var cacheInitialized = false
dynamic var rootPath: String = "/Library/Caches"
dynamic var playlistsPath: String = "/playlists"
dynamic var tracksPath: String = "/tracks"
}
| 3bed23f5d3b8ea29903f1af0eec0cbe3 | 23.105263 | 52 | 0.720524 | false | false | false | false |
rbaumbach/SpikeyMcSpikerson | refs/heads/master | SpikeyMcSpikerson/SecondViewController.swift | mit | 1 | import UIKit
class SecondViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
// MARK: Constants
let NumberCollectionViewIdentifier = "NumberCollectionViewCell"
// MARK: IBOutlets
@IBOutlet private weak var collectionView: UICollectionView!
// MARK: Private Properties
private let junk: [String] = {
print("Junk has been setup")
var someJunk: [String] = []
for index in 0...25 {
someJunk.append(String(index))
}
return someJunk
}()
// MARK: Init Methods
// if you implement the init() method for the view controller, you must implement the required init method
// for coder junk
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
title = "2nd"
}
init() {
super.init(nibName: nil, bundle: nil)
title = "2nd"
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
}
// MARK: <UICollectionViewDataSource>
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return junk.count
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NumberCollectionViewIdentifier, for: indexPath) as! NumberCollectionViewCell
cell.numLabel.text = junk[indexPath.row]
return cell
}
// MARK: Private Methods
private func setupCollectionView() {
let numberCollectionViewCellNib = UINib(nibName: NumberCollectionViewIdentifier, bundle: nil)
collectionView.register(numberCollectionViewCellNib, forCellWithReuseIdentifier: NumberCollectionViewIdentifier)
}
}
| ee2ef3f8e007e583952edfb664c07596 | 28.202899 | 151 | 0.645658 | false | false | false | false |
FraDeliro/ISaMaterialLogIn | refs/heads/master | Example/Pods/Material/Sources/iOS/Layer.swift | mit | 1 | /*
* 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
@objc(Layer)
open class Layer: CAShapeLayer {
/**
A CAShapeLayer used to manage elements that would be affected by
the clipToBounds property of the backing layer. For example, this
allows the dropshadow effect on the backing layer, while clipping
the image to a desired shape within the visualLayer.
*/
open internal(set) var visualLayer = CAShapeLayer()
/**
A property that manages an image for the visualLayer's contents
property. Images should not be set to the backing layer's contents
property to avoid conflicts when using clipsToBounds.
*/
@IBInspectable
open var image: UIImage? {
didSet {
visualLayer.contents = image?.cgImage
}
}
/**
Allows a relative subrectangle within the range of 0 to 1 to be
specified for the visualLayer's contents property. This allows
much greater flexibility than the contentsGravity property in
terms of how the image is cropped and stretched.
*/
open override var contentsRect: CGRect {
didSet {
visualLayer.contentsRect = contentsRect
}
}
/**
A CGRect that defines a stretchable region inside the visualLayer
with a fixed border around the edge.
*/
open override var contentsCenter: CGRect {
didSet {
visualLayer.contentsCenter = contentsCenter
}
}
/**
A floating point value that defines a ratio between the pixel
dimensions of the visualLayer's contents property and the size
of the layer. By default, this value is set to the Screen.scale.
*/
@IBInspectable
open override var contentsScale: CGFloat {
didSet {
visualLayer.contentsScale = contentsScale
}
}
/// A Preset for the contentsGravity property.
open var contentsGravityPreset: Gravity {
didSet {
contentsGravity = GravityToValue(gravity: contentsGravityPreset)
}
}
/// Determines how content should be aligned within the visualLayer's bounds.
@IBInspectable
open override var contentsGravity: String {
get {
return visualLayer.contentsGravity
}
set(value) {
visualLayer.contentsGravity = value
}
}
/**
A property that sets the cornerRadius of the backing layer. If the shape
property has a value of .circle when the cornerRadius is set, it will
become .none, as it no longer maintains its circle shape.
*/
@IBInspectable
open override var cornerRadius: CGFloat {
didSet {
layoutShadowPath()
shapePreset = .none
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
contentsGravityPreset = .resizeAspectFill
super.init(coder: aDecoder)
prepareVisualLayer()
}
/**
An initializer the same as init(). The layer parameter is ignored
to avoid crashes on certain architectures.
- Parameter layer: Any.
*/
public override init(layer: Any) {
contentsGravityPreset = .resizeAspectFill
super.init(layer: layer)
prepareVisualLayer()
}
/// A convenience initializer.
public override init() {
contentsGravityPreset = .resizeAspectFill
super.init()
prepareVisualLayer()
}
/**
An initializer that initializes the object with a CGRect object.
- Parameter frame: A CGRect instance.
*/
public convenience init(frame: CGRect) {
self.init()
self.frame = frame
}
open override func layoutSublayers() {
super.layoutSublayers()
layoutShape()
layoutVisualLayer()
layoutShadowPath()
}
/// Prepares the visualLayer property.
open func prepareVisualLayer() {
visualLayer.zPosition = 0
visualLayer.masksToBounds = true
addSublayer(visualLayer)
}
/// Manages the layout for the visualLayer property.
internal func layoutVisualLayer() {
visualLayer.frame = bounds
visualLayer.cornerRadius = cornerRadius
}
}
| 2bd8fc2d92e3db37f733540cb2656058 | 30.198864 | 88 | 0.727372 | false | false | false | false |
danielsaidi/iExtra | refs/heads/master | iExtra/UI/Extensions/UIImage/UIImage+Rotated.swift | mit | 1 | //
// UIImage+Rotated.swift
// iExtra
//
// Created by Daniel Saidi on 2016-01-12.
// Copyright © 2018 Daniel Saidi. All rights reserved.
//
// Source: http://stackoverflow.com/questions/27092354/rotating-uiimage-in-swift
//
import UIKit
public extension UIImage {
func rotated(byDegrees degrees: CGFloat) -> UIImage? {
return rotated(byDegrees: degrees, flipped: false)
}
func rotated(byDegrees degrees: CGFloat, flipped flip: Bool) -> UIImage? {
let degreesToRadians: (CGFloat) -> CGFloat = {
return $0 / 180.0 * CGFloat(Double.pi)
}
// Calculate the size of the rotated view's containing box for our drawing space
let rotatedViewBox = UIView(frame: CGRect(origin: CGPoint.zero, size: size))
let transform = CGAffineTransform(rotationAngle: degreesToRadians(degrees))
rotatedViewBox.transform = transform
let rotatedSize = rotatedViewBox.frame.size
// Create the bitmap context
UIGraphicsBeginImageContext(rotatedSize)
let bitmap = UIGraphicsGetCurrentContext()
// Move the origin 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))
// Draw the rotated/scaled image into the context
var yFlip: CGFloat
yFlip = flip ? CGFloat(-1.0) : CGFloat(1.0)
bitmap?.scaleBy(x: yFlip, y: -1.0)
bitmap?.draw(cgImage!, in: CGRect(x: -size.width / 2, y: -size.height / 2, width: size.width, height: size.height))
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage
}
}
| 2651bdf312a3a86fb85d37544b712467 | 34.634615 | 123 | 0.636805 | false | false | false | false |
ZachOrr/TBAKit | refs/heads/master | Testing/XCTestCase+Mock.swift | mit | 1 | import Foundation
import XCTest
import TBAKit
public protocol TBAKitMockable: class {
var kit: TBAKit! { get set }
var session: MockURLSession! { get set }
}
extension TBAKitMockable where Self: XCTestCase {
public func setUpTBAKitMockable() {
kit = TBAKit(apiKey: "abcd123")
session = MockURLSession()
kit.urlSession = session
}
}
extension XCTestCase {
public func sendUnauthorizedStub(for task: URLSessionDataTask, data: Data?) {
guard let mockRequest = task as? MockURLSessionDataTask else {
XCTFail()
return
}
guard let requestURL = mockRequest.testRequest?.url else {
XCTFail()
return
}
let response = HTTPURLResponse(url: requestURL, statusCode: 401, httpVersion: nil, headerFields: nil)
mockRequest.testResponse = response
if let completionHandler = mockRequest.completionHandler {
completionHandler(data, response, nil)
}
}
public func sendSuccessStub(for task: URLSessionDataTask, data: Data?, with code: Int = 200, headerFields: [String : String]? = nil) {
guard let mockRequest = task as? MockURLSessionDataTask else {
XCTFail()
return
}
guard let requestURL = mockRequest.testRequest?.url else {
XCTFail()
return
}
let response = HTTPURLResponse(url: requestURL, statusCode: code, httpVersion: nil, headerFields: headerFields)
mockRequest.testResponse = response
if let completionHandler = mockRequest.completionHandler {
completionHandler(data, response, nil)
}
}
}
| ed9df41dda9af2941d74a4e846bbcad5 | 29.298246 | 138 | 0.62652 | false | true | false | false |
rnystrom/GitHawk | refs/heads/master | FreetimeWatch Extension/RepoInboxController.swift | mit | 1 | //
// RepoInboxController.swift
// FreetimeWatch Extension
//
// Created by Ryan Nystrom on 4/27/18.
// Copyright © 2018 Ryan Nystrom. All rights reserved.
//
import WatchKit
import Foundation
import GitHubAPI
import DateAgo
import StringHelpers
final class RepoInboxController: WKInterfaceController {
struct Context {
let client: Client
let repo: V3Repository
let notifications: [V3Notification]
let dataController: InboxDataController
}
@IBOutlet var table: WKInterfaceTable!
private var context: Context?
override func awake(withContext context: Any?) {
super.awake(withContext: context)
guard let context = context as? Context else { return }
self.context = context
setTitle(context.repo.name)
reload()
}
override func table(_ table: WKInterfaceTable, didSelectRowAt rowIndex: Int) {
// only handle selections on the "mark read" button
guard rowIndex == 0, let context = self.context else { return }
let repo = context.repo
let dataController = context.dataController
dataController.read(repository: repo)
context.client.send(V3MarkRepositoryNotificationsRequest(
owner: repo.owner.login,
repo: repo.name
)) { result in
// will unwind the read even though the controller is pushed
if case .failure = result {
dataController.unread(repository: repo)
}
}
pop()
}
// MARK: Private API
func reload() {
guard let context = self.context else { return }
table.insertRows(at: IndexSet(integer: 0), withRowType: ReadAllRowController.rowControllerIdentifier)
let controller = table.rowController(at: 0) as? ReadAllRowController
controller?.setup()
table.insertRows(at: IndexSet(integersIn: 1 ..< context.notifications.count + 1), withRowType: RepoInboxRowController.rowControllerIdentifier)
for (i, n) in context.notifications.enumerated() {
guard let row = table.rowController(at: i+1) as? RepoInboxRowController else { continue }
row.setup(with: n)
}
}
}
| f980e53bfa592084655988c69cc51166 | 28.613333 | 150 | 0.652859 | false | false | false | false |
yidahis/ShopingCart | refs/heads/master | ShopingCart/ShopingCartView.swift | apache-2.0 | 1 | //100
// ShopingCartView.swift
// ShopingCart
//
// Created by zhouyi on 2017/9/15.
// Copyright © 2017年 NewBornTown, Inc. All rights reserved.
//
import UIKit
let XSpace: CGFloat = 10
typealias shopCartViewDoneAction = (SKUModel?) -> Void
class ShopingCartView: UIView {
//MARK: - property
var tableView: UITableView!
var doneButton: UIButton!
let doneButtonHeight: CGFloat = 50
var selectDoneAction: shopCartViewDoneAction?
var closeActionBlock: NoneArgmentAction?
var isShowing: Bool = false
var viewModel: ShopingCartViewModel = ShopingCartViewModel()
//MARK: - life
override init(frame: CGRect) {
super.init(frame: frame)
tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .none
tableView.register(ShopingCartViewHeaderCell.classForCoder(), forCellReuseIdentifier: "header")
tableView.register(ShopingCartViewCell.classForCoder(), forCellReuseIdentifier: "cell")
tableView.register(ShopingCartViewBottomCell.classForCoder(), forCellReuseIdentifier: "bottom")
tableView.layoutMargins = UIEdgeInsets.zero
self.addSubview(tableView)
doneButton = UIButton()
self.addSubview(doneButton)
doneButton.setTitle("确定", for: UIControlState.normal)
doneButton.backgroundColor = UIColor.red
doneButton.addTarget(self, action: #selector(doneButtonAction), for: UIControlEvents.touchUpInside)
tableView.addObserver(self, forKeyPath: "frame", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
print("keypath: " + keyPath!)
print(change)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
if isShowing {
self.tableView.frame = CGRect(x: 0, y: self.height/3, width: self.width, height: self.height*2/3 - self.doneButtonHeight)
self.doneButton.frame = CGRect(x: 0, y: self.tableView.bottom, width: self.width, height: self.doneButtonHeight)
}else{
tableView.frame = CGRect(x: 0, y: self.height, width: self.width, height: self.height*2/3 - self.doneButtonHeight)
doneButton.frame = CGRect(x: 0, y: tableView.bottom, width: self.width, height: self.doneButtonHeight)
}
}
func show() {
isShowing = true
self.superview?.bringSubview(toFront: self)
UIView.animate(withDuration: 0.25, delay: 0.25, options: .curveEaseIn, animations: {
self.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
self.tableView.frame = CGRect(x: 0, y: self.height/3, width: self.width, height: self.height*2/3 - self.doneButtonHeight)
self.doneButton.frame = CGRect(x: 0, y: self.tableView.bottom, width: self.width, height: self.doneButtonHeight)
}) { (finished) in
}
}
//MARK: - private method
@objc func doneButtonAction(){
selectDoneAction?(viewModel.selectSkuModel)
}
func close(){
isShowing = false
UIView.animate(withDuration: 0.25, delay: 0, options: .curveEaseIn, animations: {
self.backgroundColor = UIColor(white: 0, alpha: 0)
self.tableView.frame = CGRect(x: 0, y: self.height, width: self.width, height: self.height*2/3 - self.doneButtonHeight)
self.doneButton.frame = CGRect(x: 0, y: self.tableView.bottom, width: self.width, height: self.doneButtonHeight)
}) { (finished) in
self.superview?.sendSubview(toBack: self)
}
}
//计算第一行minY 到 最后一行 MaxY 之间的差值
func height(contentItem items: [SpecItem]) -> CGFloat{
let maxX: CGFloat = self.width - XSpace * 2
var minY: CGFloat = 0
var minX: CGFloat = XSpace
items.forEach { (item) in
let width = item.content.stringWidthWithSpace(fontSize: 14)
minX = minX + width + XSpace + 2
if minX >= maxX {
minY = minY + 28 + XSpace
minX = XSpace
}
}
return minY + 28
}
func updateShopingCartViewCellData(tip: String, title: String){
for i in 0..<viewModel.mySpecs.count {
let specs = viewModel.mySpecs[i]
if specs.key == tip {
for j in 0..<specs.vaules.count {
let item = specs.vaules[j]
if item.content == title{
viewModel.mySpecs[i].vaules[j].isSelected = true
}else{
viewModel.mySpecs[i].vaules[j].isSelected = false
}
}
}
}
}
/// 筛选已选样式的数据
///
/// - Returns: ShopingCartViewHeaderCellModel
func headerViewData() -> ShopingCartViewHeaderCellModel?{
var selectedKeyValue = [String: String]()
//筛选出已选的样式选项
viewModel.mySpecs.forEach { (specs) in
specs.vaules.forEach({ (item) in
if item.isSelected == true {
selectedKeyValue[specs.key] = item.content
}
})
}
guard let selectedSpec = selectedKeyValue.first else{
return nil
}
var skuModel: SKUModel?
viewModel.skuArray.forEach { (model) in
model.specs.forEach({ (spec) in
if spec.spec_key == selectedSpec.key, spec.spec_value == selectedSpec.value {
skuModel = model
}
})
}
guard let model = skuModel else {
return nil
}
if model.specs.count == selectedKeyValue.count{
viewModel.selectSkuModel = model
}
var content: String = ""
selectedKeyValue.forEach { (keyValue) in
content.append(keyValue.value + " ")
}
return ShopingCartViewHeaderCellModel(thumbUrl: model.thumb_url, price: model.group_price, content: content)
}
func lowAndHightPriceModel() -> (SKUModel?, SKUModel?){
guard let first = viewModel.skuArray.first else {
return (nil, nil)
}
var low: SKUModel = first
var high: SKUModel = first
viewModel.skuArray.forEach { (model) in
if model.group_price > high.group_price {
high = model
}
if model.group_price < low.group_price {
low = model
}
}
return (low, high)
}
}
//MARK: - UITableViewDelegate,UITableViewDataSource
extension ShopingCartView: UITableViewDelegate,UITableViewDataSource{
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.row {
case 0:
return 112
case viewModel.mySpecs.count + 1:
return 55
default:
if viewModel.mySpecs.count > indexPath.row - 1 {
return 34 + height(contentItem: Array(viewModel.mySpecs[indexPath.row - 1].vaules)) + 2*XSpace
}
return 0
}
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if viewModel.mySpecs.count > 0{
return viewModel.mySpecs.count + 2
}
return 0
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch indexPath.row {
case 0:
guard let cell: ShopingCartViewHeaderCell = tableView.dequeueReusableCell(withIdentifier: "header") as? ShopingCartViewHeaderCell else {
return ShopingCartViewHeaderCell()
}
//是否有选择颜色尺码等,有就直接加载已选数据,否则加载默认数据
if let model = headerViewData() {
cell.viewModel = model
}else {
let (low, high) = lowAndHightPriceModel()
if let lowModel = low, let hightModel = high {
cell.priceModel(low: lowModel, high: hightModel)
}
}
cell.clossButtonActionBlock = { [weak self] in
self?.close()
}
return cell
case viewModel.mySpecs.count + 1 :
guard let cell: ShopingCartViewBottomCell = tableView.dequeueReusableCell(withIdentifier: "bottom") as? ShopingCartViewBottomCell else {
return ShopingCartViewBottomCell()
}
return cell
default:
guard let cell: ShopingCartViewCell = tableView.dequeueReusableCell(withIdentifier: "cell") as? ShopingCartViewCell else {
return ShopingCartViewCell()
}
if viewModel.mySpecs.count > indexPath.row - 1 {
cell.model = viewModel.mySpecs[indexPath.row - 1]
}
cell.buttonTapAction = { [weak self] (tip,title) in
print(tip + " " + title)
self?.updateShopingCartViewCellData(tip: tip, title: title)
self?.tableView.reloadData()
}
return cell
}
}
}
| 5337f5c4b0d046396b0f7f60c38c325f | 34.412639 | 151 | 0.576842 | false | false | false | false |
noppoMan/aws-sdk-swift | refs/heads/main | Sources/Soto/Services/Schemas/Schemas_Error.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2020 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
/// Error enum for Schemas
public struct SchemasErrorType: AWSErrorType {
enum Code: String {
case badRequestException = "BadRequestException"
case conflictException = "ConflictException"
case forbiddenException = "ForbiddenException"
case goneException = "GoneException"
case internalServerErrorException = "InternalServerErrorException"
case notFoundException = "NotFoundException"
case preconditionFailedException = "PreconditionFailedException"
case serviceUnavailableException = "ServiceUnavailableException"
case tooManyRequestsException = "TooManyRequestsException"
case unauthorizedException = "UnauthorizedException"
}
private let error: Code
public let context: AWSErrorContext?
/// initialize Schemas
public init?(errorCode: String, context: AWSErrorContext) {
guard let error = Code(rawValue: errorCode) else { return nil }
self.error = error
self.context = context
}
internal init(_ error: Code) {
self.error = error
self.context = nil
}
/// return error code string
public var errorCode: String { self.error.rawValue }
public static var badRequestException: Self { .init(.badRequestException) }
public static var conflictException: Self { .init(.conflictException) }
public static var forbiddenException: Self { .init(.forbiddenException) }
public static var goneException: Self { .init(.goneException) }
public static var internalServerErrorException: Self { .init(.internalServerErrorException) }
public static var notFoundException: Self { .init(.notFoundException) }
public static var preconditionFailedException: Self { .init(.preconditionFailedException) }
public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) }
public static var tooManyRequestsException: Self { .init(.tooManyRequestsException) }
public static var unauthorizedException: Self { .init(.unauthorizedException) }
}
extension SchemasErrorType: Equatable {
public static func == (lhs: SchemasErrorType, rhs: SchemasErrorType) -> Bool {
lhs.error == rhs.error
}
}
extension SchemasErrorType: CustomStringConvertible {
public var description: String {
return "\(self.error.rawValue): \(self.message ?? "")"
}
}
| 05feb421ca432bb126f0349f35b9557c | 39.364865 | 117 | 0.684633 | false | false | false | false |
toicodedoec/ios-tour-flicks | refs/heads/master | Flicks/AppDelegate.swift | apache-2.0 | 1 | //
// AppDelegate.swift
// Flicks
//
// Created by john on 2/14/17.
// Copyright © 2017 doannx. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
window = UIWindow(frame: UIScreen.main.bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let nowPlayingNavigationController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController
let nowPlayingViewController = nowPlayingNavigationController.topViewController as! MoviesViewController
nowPlayingViewController.endpoint = "now_playing"
nowPlayingNavigationController.tabBarItem.title = "Now Playing"
nowPlayingNavigationController.tabBarItem.image = UIImage(named: "documentary_filled-50")
let topRatedNavigationController = storyboard.instantiateViewController(withIdentifier: "MoviesNavigationController") as! UINavigationController
let topRatedViewController = topRatedNavigationController.topViewController as! MoviesViewController
topRatedViewController.endpoint = "top_rated"
topRatedNavigationController.tabBarItem.title = "Top Rated"
topRatedNavigationController.tabBarItem.image = UIImage(named: "captain_america_filled-50")
let tabBarController = UITabBarController()
tabBarController.viewControllers = [nowPlayingNavigationController, topRatedNavigationController]
window?.rootViewController = tabBarController
window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| 657f4d1b1eb09c1ca9cb4866a28a79b0 | 51.985075 | 285 | 0.754366 | false | false | false | false |
josve05a/wikipedia-ios | refs/heads/develop | Wikipedia/Code/InsertLinkViewController.swift | mit | 3 | import UIKit
protocol InsertLinkViewControllerDelegate: AnyObject {
func insertLinkViewController(_ insertLinkViewController: InsertLinkViewController, didTapCloseButton button: UIBarButtonItem)
func insertLinkViewController(_ insertLinkViewController: InsertLinkViewController, didInsertLinkFor page: String, withLabel label: String?)
}
class InsertLinkViewController: UIViewController {
weak var delegate: InsertLinkViewControllerDelegate?
private var theme = Theme.standard
private let dataStore: MWKDataStore
typealias Link = SectionEditorWebViewMessagingController.Link
private let link: Link
private let siteURL: URL?
init(link: Link, siteURL: URL?, dataStore: MWKDataStore) {
self.link = link
self.siteURL = siteURL
self.dataStore = dataStore
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var closeButton: UIBarButtonItem = {
let closeButton = UIBarButtonItem.wmf_buttonType(.X, target: self, action: #selector(delegateCloseButtonTap(_:)))
closeButton.accessibilityLabel = CommonStrings.closeButtonAccessibilityLabel
return closeButton
}()
private lazy var searchViewController: SearchViewController = {
let searchViewController = SearchViewController()
searchViewController.dataStore = dataStore
searchViewController.siteURL = siteURL
searchViewController.searchTerm = link.page
searchViewController.areRecentSearchesEnabled = false
searchViewController.shouldBecomeFirstResponder = true
searchViewController.dataStore = SessionSingleton.sharedInstance()?.dataStore
searchViewController.shouldShowCancelButton = false
searchViewController.delegate = self
searchViewController.delegatesSelection = true
searchViewController.showLanguageBar = false
searchViewController.search()
return searchViewController
}()
override func viewDidLoad() {
super.viewDidLoad()
title = CommonStrings.insertLinkTitle
navigationItem.leftBarButtonItem = closeButton
let navigationController = WMFThemeableNavigationController(rootViewController: searchViewController)
navigationController.isNavigationBarHidden = true
wmf_add(childController: navigationController, andConstrainToEdgesOfContainerView: view)
apply(theme: theme)
}
@objc private func delegateCloseButtonTap(_ sender: UIBarButtonItem) {
delegate?.insertLinkViewController(self, didTapCloseButton: sender)
}
override func accessibilityPerformEscape() -> Bool {
delegate?.insertLinkViewController(self, didTapCloseButton: closeButton)
return true
}
}
extension InsertLinkViewController: ArticleCollectionViewControllerDelegate {
func articleCollectionViewController(_ articleCollectionViewController: ArticleCollectionViewController, didSelectArticleWith articleURL: URL, at indexPath: IndexPath) {
guard let title = articleURL.wmf_title else {
return
}
delegate?.insertLinkViewController(self, didInsertLinkFor: title, withLabel: nil)
}
}
extension InsertLinkViewController: Themeable {
func apply(theme: Theme) {
self.theme = theme
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.inputAccessoryBackground
view.layer.shadowColor = theme.colors.shadow.cgColor
closeButton.tintColor = theme.colors.primaryText
searchViewController.apply(theme: theme)
}
}
| 59a5504ecf4661e2e5a08da89b0b5076 | 40.58427 | 173 | 0.737909 | false | false | false | false |
saurabytes/JSQCoreDataKit | refs/heads/develop | Example/ExampleModel/ExampleModel/Employee.swift | mit | 1 | //
// Created by Jesse Squires
// http://www.jessesquires.com
//
//
// Documentation
// http://www.jessesquires.com/JSQCoreDataKit
//
//
// GitHub
// https://github.com/jessesquires/JSQCoreDataKit
//
//
// License
// Copyright © 2015 Jesse Squires
// Released under an MIT license: http://opensource.org/licenses/MIT
//
import Foundation
import CoreData
public final class Employee: NSManagedObject {
static public let entityName = "Employee"
@NSManaged public var name: String
@NSManaged public var birthDate: NSDate
@NSManaged public var salary: NSDecimalNumber
@NSManaged public var company: Company?
public init(context: NSManagedObjectContext,
name: String,
birthDate: NSDate,
salary: NSDecimalNumber,
company: Company? = nil) {
let entity = NSEntityDescription.entityForName(Employee.entityName, inManagedObjectContext: context)!
super.init(entity: entity, insertIntoManagedObjectContext: context)
self.name = name
self.birthDate = birthDate
self.salary = salary
self.company = company
}
public class func newEmployee(context: NSManagedObjectContext, company: Company? = nil) -> Employee {
let name = "Employee " + String(NSUUID().UUIDString.characters.split { $0 == "-" }.first!)
return Employee(context: context,
name: name,
birthDate: NSDate.distantPast(),
salary: NSDecimalNumber(unsignedInt: arc4random_uniform(100_000)),
company: company)
}
@objc
private override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
super.init(entity: entity, insertIntoManagedObjectContext: context)
}
}
| 77fd52eb5320947705c6bc92070da679 | 28.444444 | 121 | 0.650674 | false | false | false | false |
kkolli/MathGame | refs/heads/master | client/Speedy/AppDelegate.swift | gpl-2.0 | 1 |
//
// AppDelegate.swift
// SwiftBook
//
// Created by Krishna Kolli
// Copyright (c) Krishna Kolli. All rights reserved.
//import UIKit
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var mpcHandler:MPCHandler = MPCHandler()
var user:FBGraphUser?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
// Override point for customization after application launch.
FBLoginView.self
FBProfilePictureView.self
// google analytics
GAI.sharedInstance().trackUncaughtExceptions = true
GAI.sharedInstance().dispatchInterval = 20
GAI.sharedInstance().logger.logLevel = GAILogLevel.Verbose
GAI.sharedInstance().trackerWithTrackingId("UA-36281325-2")
// fabric - crashlytics
Fabric.with([Crashlytics()])
return true
}
func application(application: UIApplication, openURL url: NSURL, sourceApplication: NSString?, annotation: AnyObject) -> Bool {
var wasHandled:Bool = FBAppCall.handleOpenURL(url, sourceApplication: sourceApplication)
return wasHandled
}
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:.
}
}
| 4655fba9f3fc3bf46a6e81a4b60fb4ec | 43.742424 | 285 | 0.727057 | false | false | false | false |
katsumeshi/PhotoInfo | refs/heads/master | PhotoInfo/Classes/TabBarController.swift | mit | 1 | //
// tabBarController.swift
// photoinfo
//
// Created by Yuki Matsushita on 7/16/15.
// Copyright (c) 2015 Yuki Matsushita. All rights reserved.
//
import FontAwesome
import ReactiveCocoa
class TabBarController: UITabBarController, UITabBarControllerDelegate {
let reviewUrl = NSURL(string: "http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=998243965&mt=8&type=Purple+Software")!
override func viewDidLoad() {
super.viewDidLoad()
setUpAppearance()
didBecomeNotificationAction()
self.delegate = self
}
}
extension TabBarController {
// MARK: - Private Methods
private func setUpAppearance() {
self.view.backgroundColor = UIColor.whiteColor()
UITabBar.appearance().tintColor = UIColor.whiteColor()
self.childViewControllers.enumerate().forEach {
$0.element.tabBarItem = TabType(rawValue: $0.index)?.item
}
}
private func didBecomeNotificationAction() {
let didbecomeSignal = NSNotificationCenter.addObserver(UIApplicationDidBecomeActiveNotification)
didbecomeSignal.subscribeNext { _ in
if AppReview.canShow() {
self.showAppReviewRequestAlert()
}
}
}
private func showAppReviewRequestAlert() {
let alertView = UIAlertController(title: "Review the app, please".toGrobal(),
message: "Thank you for using the app:) Review tha app for updating the next feature".toGrobal(),
preferredStyle: .Alert)
let reviewAction = UIAlertAction(title: "Review due to satisfied".toGrobal(),
style: .Default) { _ in
UIApplication.sharedApplication().openURL(self.reviewUrl)
}
let noAction = UIAlertAction(title: "Don't review due to unsatisfied".toGrobal(), style: .Default, handler: nil)
let laterAction = UIAlertAction(title: "Review later".toGrobal(), style: .Default, handler: nil)
alertView.addAction(reviewAction)
alertView.addAction(noAction)
alertView.addAction(laterAction)
self.presentViewController(alertView, animated: true, completion: nil)
}
}
| 77b01802fba31e51ec06a79e1069c34e | 29.115942 | 148 | 0.71078 | false | false | false | false |
colemancda/SwiftSequence | refs/heads/master | SwiftSequence/Permutations.swift | mit | 1 | // MARK: - Common
public extension MutableCollectionType {
/// [Algorithm](https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order)
public mutating func nextLexPerm
(isOrderedBefore: (Generator.Element, Generator.Element) -> Bool) -> Self? {
for k in indices.reverse().dropFirst()
where isOrderedBefore(self[k], self[k.successor()]) {
for l in indices.reverse() where isOrderedBefore(self[k], self[l]) {
swap(&self[k], &self[l])
let r = (k.successor()..<endIndex)
for (x, y) in zip(r, r.reverse()) {
if x == y || x == y.successor() { return self }
swap(&self[x], &self[y])
}
}
}
return nil
}
}
public extension MutableCollectionType where Generator.Element : Comparable {
/// [Algorithm](https://en.wikipedia.org/wiki/Permutation#Generation_in_lexicographic_order)
public mutating func nextLexPerm() -> Self? {
return nextLexPerm(<)
}
}
/// :nodoc:
public struct LexPermGen<C : MutableCollectionType> : GeneratorType {
private var col: C?
private let order: (C.Generator.Element, C.Generator.Element) -> Bool
/// :nodoc:
mutating public func next() -> C? {
defer { col = col?.nextLexPerm(order) }
return col
}
}
/// :nodoc:
public struct LexPermSeq<C : MutableCollectionType> : LazySequenceType {
private let col: C
private let order: (C.Generator.Element, C.Generator.Element) -> Bool
/// :nodoc:
public func generate() -> LexPermGen<C> {
return LexPermGen(col: col, order: order)
}
}
// MARK: - Eager
public extension SequenceType {
/// Returns an array of the permutations of self, ordered lexicographically, according
/// to the closure `isOrderedBefore`.
/// - Note: The permutations returned follow self, so if self is not the first
/// lexicographically ordered permutation, not all permutations will be returned.
/// ```swift
/// [1, 2, 3].lexPermutations(<)
///
/// [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
/// ```
/// ```swift
/// [1, 2, 3].lexPermutations(>)
///
/// [[1, 2, 3]]
/// ```
public func lexPermutations
(isOrderedBefore: (Generator.Element, Generator.Element) -> Bool) -> [[Generator.Element]] {
return Array(LexPermSeq(col: Array(self), order: isOrderedBefore))
}
}
public extension MutableCollectionType where Generator.Element : Comparable {
/// Returns an array of the permutations of self, ordered lexicographically.
/// - Note: The permutations returned follow self, so if self is not the first
/// lexicographically ordered permutation, not all permutations will be returned.
/// ```swift
/// [1, 2, 3].lexPermutations()
///
/// [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
/// ```
/// ```swift
/// [3, 2, 1].lexPermutations()
///
/// [[3, 2, 1]]
/// ```
public func lexPermutations() -> [[Generator.Element]] {
return Array(LexPermSeq(col: Array(self), order: <))
}
}
public extension SequenceType {
/// Returns an array of the permutations of self.
/// ```swift
/// [1, 2, 3].permutations()
///
/// [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
/// ```
public func permutations() -> [[Generator.Element]] {
var col = Array(self)
return Array(LexPermSeq(col: Array(col.indices), order: <).map { inds in inds.map{col[$0]} })
}
/// Returns an array of the permutations of length `n` of self.
/// ```swift
/// [1, 2, 3].permutations()
///
/// [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]
/// ```
public func permutations(n: Int) -> [[Generator.Element]] {
return Array(lazyCombos(n).flatMap { a in a.permutations() })
}
}
// MARK: - Lazy
public extension SequenceType {
/// Returns a lazy sequence of the permutations of self, ordered lexicographically,
/// according to the closure `isOrderedBefore`.
/// - Note: The permutations returned follow self, so if self is not the first
/// lexicographically ordered permutation, not all permutations will be returned.
/// ```swift
/// lazy([1, 2, 3]).lazyLexPermutations(<)
///
/// [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]
/// ```
/// ```swift
/// lazy([1, 2, 3]).lazyLexPermutations(>)
///
/// [1, 2, 3]
/// ```
public func lazyLexPermutations(isOrderedBefore: (Generator.Element, Generator.Element) -> Bool)
-> LexPermSeq<[Generator.Element]> {
return LexPermSeq(col: Array(self), order: isOrderedBefore)
}
}
public extension SequenceType where Generator.Element : Comparable {
/// Returns a lazy sequence of the permutations of self, ordered lexicographically.
/// - Note: The permutations returned follow self, so if self is not the first
/// lexicographically ordered permutation, not all permutations will be returned.
/// ```swift
/// lazy([1, 2, 3]).lazyLexPermutations()
///
/// [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]
/// ```
/// ```swift
/// lazy([3, 2, 1]).lazyLexPermutations()
///
/// [3, 2, 1]
/// ```
public func lazyLexPermutations() -> LexPermSeq<[Generator.Element]> {
return LexPermSeq(col: Array(self), order: <)
}}
public extension SequenceType {
/// Returns a lazy sequence of the permutations of self.
/// - Note: The permutations are lexicographically ordered, based on the indices of self
/// ```swift
/// lazy([1, 2, 3]).lazyPermutations()
///
/// [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]
/// ```
/// ```swift
/// lazy([3, 2, 1]).lazyPermutations()
///
/// [3, 2, 1], [3, 1, 2], [2, 3, 1], [2, 1, 3], [1, 3, 2], [1, 2, 3]
/// ```
public func lazyPermutations() -> LazyMapSequence<LexPermSeq<[Int]>, [Self.Generator.Element]> {
let col = Array(self)
return col.indices.lazyLexPermutations().map { $0.map { col[$0] } }
}
}
| d4fc4c0a312b21311d834f0d889b9d10 | 31.150538 | 98 | 0.593813 | false | false | false | false |
mlilback/rc2SwiftClient | refs/heads/master | Networking/ImageCache.swift | isc | 1 | //
// ImageCache.swift
//
// Copyright ©2016 Mark Lilback. This file is licensed under the ISC license.
//
import Rc2Common
import Dispatch
import MJLLogger
import ReactiveSwift
import Model
public enum ImageCacheError: Error, Rc2DomainError {
case noSuchImage
case failedToLoadFromNetwork
}
/// Handles caching of SessionImage(s)
public class ImageCache {
///to allow dependency injection
var fileManager: Foundation.FileManager
///to allow dependency injection
var workspace: AppWorkspace?
/// the client used to fetch images from the network
let restClient: Rc2RestClient
///caching needs to be unique for each server. we don't care what the identifier is, just that it is unique per host
///mutable because we need to be able to read it from an archive
fileprivate(set) var hostIdentifier: String
fileprivate var cache: NSCache<AnyObject, AnyObject>
fileprivate var metaCache: [Int: SessionImage]
/// all cached images sorted in batches
public let images: Property< [SessionImage] >
private let _images: MutableProperty< [SessionImage] >
fileprivate(set) lazy var cacheUrl: URL =
{
var result: URL?
do {
result = try AppInfo.subdirectory(type: .cachesDirectory, named: "\(self.hostIdentifier)/images")
} catch let error as NSError {
Log.error("got error creating image cache direcctory: \(error)", .cache)
assertionFailure("failed to create image cache dir")
}
return result!
}()
public static var supportsSecureCoding: Bool { return true }
init(restClient: Rc2RestClient, fileManager fm: Foundation.FileManager = Foundation.FileManager(), hostIdentifier hostIdent: String)
{
self.restClient = restClient
fileManager = fm
cache = NSCache()
metaCache = [:]
hostIdentifier = hostIdent
_images = MutableProperty< [SessionImage] >([])
images = Property< [SessionImage] >(capturing: _images)
}
/// loads cached data from json serialized by previous call to toJSON()
///
/// - Parameter sate: the state data to restore from
/// - Throws: decoding errors
public func restore(state: SessionState.ImageCacheState) throws {
self.hostIdentifier = state.hostIdentifier
state.images.forEach { metaCache[$0.id] = $0 }
adjustImageArray()
}
/// serializes cache state
///
/// - Parameter state: where to save the state to
public func save(state: inout SessionState.ImageCacheState) throws
{
state.hostIdentifier = hostIdentifier
state.images = Array(metaCache.values)
}
/// Returns an image from the cache if it is in memory or on disk. returns nil if not in cache
///
/// - Parameter imageId: the id of the image to get
/// - Returns: the image, or nil if there is no cached image with that id
func image(withId imageId: Int) -> PlatformImage? {
if let pitem = cache.object(forKey: imageId as AnyObject) as? NSPurgeableData {
defer { pitem.endContentAccess() }
if pitem.beginContentAccess() {
return PlatformImage(data: NSData(data: pitem as Data) as Data)
}
}
//read from disk
let imgUrl = URL(fileURLWithPath: "\(imageId).png", relativeTo: cacheUrl)
guard let imgData = try? Data(contentsOf: imgUrl) else {
return nil
}
cache.setObject(NSPurgeableData(data: imgData), forKey: imageId as AnyObject)
return PlatformImage(data: imgData)
}
/// caches to disk and in memory
private func cacheImageFromServer(_ img: SessionImage) {
//cache to disk
Log.info("caching image \(img.id)", .cache)
let destUrl = URL(fileURLWithPath: "\(img.id).png", isDirectory: false, relativeTo: cacheUrl)
try? img.imageData.write(to: destUrl, options: [.atomic])
//cache in memory
let pdata = NSData(data: img.imageData) as Data
cache.setObject(pdata as AnyObject, forKey: img.id as AnyObject)
metaCache[img.id] = img
}
/// Stores an array of SessionImage objects
///
/// - Parameter images: the images to save to the cache
func cache(images: [SessionImage]) {
images.forEach { cacheImageFromServer($0) }
adjustImageArray()
}
/// Returns the images belonging to a particular batch
///
/// - Parameter batchId: the batch to get images for
/// - Returns: an array of images
public func sessionImages(forBatch batchId: Int) -> [SessionImage] {
Log.debug("look for batch \(batchId)", .cache)
return metaCache.values.filter({ $0.batchId == batchId }).sorted(by: { $0.id < $1.id })
}
/// Removes all images from the in-memory cache
public func clearCache() {
cache.removeAllObjects()
metaCache.removeAll()
_images.value = []
}
/// image(withId:) should have been called at some point to make sure the image is cached
public func urlForCachedImage(_ imageId: Int) -> URL {
return URL(fileURLWithPath: "\(imageId).png", isDirectory: false, relativeTo: self.cacheUrl).absoluteURL
}
/// Loads an image from memory, disk, or the network based on if it is cached
public func image(withId imageId: Int) -> SignalProducer<PlatformImage, ImageCacheError> {
assert(workspace != nil, "imageCache.workspace must be set before using")
let fileUrl = URL(fileURLWithPath: "\(imageId).png", isDirectory: false, relativeTo: self.cacheUrl)
return SignalProducer<PlatformImage, ImageCacheError> { observer, _ in
// swiftlint:disable:next force_try
if try! fileUrl.checkResourceIsReachable() {
observer.send(value: PlatformImage(contentsOf: fileUrl)!)
observer.sendCompleted()
return
}
//need to fetch from server
let sp = self.restClient.downloadImage(imageId: imageId, from: self.workspace!, destination: fileUrl)
sp.startWithResult { result in
if case .success(let imgUrl) = result, let pimg = PlatformImage(contentsOf: imgUrl) {
observer.send(value: pimg)
observer.sendCompleted()
} else {
observer.send(error: .failedToLoadFromNetwork)
}
}
}
}
/// reset the images property grouped by batch
private func adjustImageArray() {
_images.value = metaCache.values.sorted { img1, img2 in
guard img1.batchId == img2.batchId else { return img1.batchId < img2.batchId }
//using id because we know they are in proper order, might be created too close together to use dateCreated
return img1.id < img2.id
}
}
}
| edfaed8a60c2f91db8621ffcc2a5aad5 | 34.114286 | 133 | 0.720749 | false | false | false | false |
kharrison/CodeExamples | refs/heads/master | Container/Container-SB/Container/MapViewController.swift | bsd-3-clause | 1 | //
// MapViewController.swift
// Container
//
// Created by Keith Harrison http://useyourloaf.com
// Copyright (c) 2017 Keith Harrison. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder 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 MapKit
final class MapViewController: UIViewController {
@IBOutlet private var mapView: MKMapView!
/// The zoom level to use when setting the span
/// of the map region to show. Default is 10 degrees.
var zoom: CLLocationDegrees = 10.0
/// The coordinate to center the map on. Setting a new
/// coordinate centers the map on a region spanned by
/// the `zoom` level and drops a pin annotation at the
/// coordinate.
var coordinate: CLLocationCoordinate2D? {
didSet {
if let coordinate = coordinate {
centerMap(coordinate)
annotate(coordinate)
}
}
}
private func centerMap(_ coordinate: CLLocationCoordinate2D) {
let span = MKCoordinateSpan.init(latitudeDelta: zoom, longitudeDelta: zoom)
let region = MKCoordinateRegion(center: coordinate, span: span)
mapView.setRegion(region, animated: true)
}
private func annotate(_ coordinate: CLLocationCoordinate2D) {
let annotation = MKPointAnnotation()
annotation.coordinate = coordinate
mapView.addAnnotation(annotation)
}
}
extension MapViewController: MKMapViewDelegate {
private enum AnnotationView: String {
case pin = "Pin"
}
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
guard let annotation = annotation as? MKPointAnnotation else {
return nil
}
let identifier = AnnotationView.pin.rawValue
guard let annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: identifier) as? MKPinAnnotationView else {
return MKPinAnnotationView(annotation: annotation, reuseIdentifier: identifier)
}
annotationView.annotation = annotation
return annotationView
}
}
| 9d6a6063d8b4fa893bb82e19a5cd6f58 | 37.652174 | 131 | 0.715129 | false | false | false | false |
lakshay35/UGA-Calendar | refs/heads/master | EITS/AddViewController.swift | apache-2.0 | 1 | //
// AddViewController.swift
// EITS
//
// Created by Lakshay Sharma on 12/9/16.
// Copyright © 2016 Lakshay Sharma. All rights reserved.
//
import UIKit
class AddViewController: UIViewController {
@IBOutlet weak var eventNameLabel: UITextField!
@IBOutlet weak var fromDatePicker: UIDatePicker!
@IBOutlet weak var toDatePicker: UIDatePicker!
var cell: Event? // The cell that populates the objects in the view
override func viewDidLoad() {
super.viewDidLoad()
navigationController?.navigationBar.backgroundColor = UIColor.red
// Do any additional setup after loading the view.
/*
*
*
Sets up the view for editing if cell is not empty,
which means that the user selected a cell
*
*
*/
if let cell = cell {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
eventNameLabel.text = cell.eventName
fromDatePicker.date = dateFormatter.date(from: cell.eventStartDate)!
toDatePicker.date = dateFormatter.date(from: cell.eventEndDate)!
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func cancel(_ sender: Any) {
if(presentingViewController is UINavigationController) {
self.dismiss(animated: true, completion: nil)
} else {
self.navigationController!.popViewController(animated: true)
}
}
/*
*
*
Configures error handling if eventNameLabel is empty
or if there is a logic error between event timing
so that the application does not crash
*
*
*/
@IBAction func saveButton(_ sender: UIBarButtonItem) {
if (eventNameLabel.text == "") {
let alert = UIAlertController(title: "Error", message: "\"Event\" field empty", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
} else if (fromDatePicker.date > toDatePicker.date) {
let alert = UIAlertController(title: "Error", message: "Event start date is after end date. Please correct logic error", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
} else {
performSegue(withIdentifier: "saveButtonPressed", sender: Any?.self)
}
}
/*
*
*
Edits data so that appropriate data
can be pulled from the this file in
the root view controller
*
*
*/
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
cell = Event(name: eventNameLabel.text!, start: dateToString(date: fromDatePicker.date), end: dateToString(date: toDatePicker.date))
}
/*
*
*
Custom function to convert Date object to
a String for assignment to String type variables
*
*
*/
func dateToString(date: Date) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
return dateFormatter.string(from: date)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 8745f91fd1ffd19f13c2c387d34877e5 | 31.016949 | 156 | 0.625463 | false | false | false | false |
jonasman/TeslaSwift | refs/heads/master | Sources/TeslaSwift/Model/Authentication.swift | mit | 1 | //
// AuthToken.swift
// TeslaSwift
//
// Created by Joao Nunes on 04/03/16.
// Copyright © 2016 Joao Nunes. All rights reserved.
//
import Foundation
import CryptoKit
private let oAuthClientID: String = "81527cff06843c8634fdc09e8ac0abefb46ac849f38fe1e431c2ef2106796384"
private let oAuthWebClientID: String = "ownerapi"
private let oAuthClientSecret: String = "c7257eb71a564034f9419ee651c7d0e5f7aa6bfbd18bafb5c5c033b093bb2fa3"
private let oAuthScope: String = "openid email offline_access"
private let oAuthRedirectURI: String = "https://auth.tesla.com/void/callback"
open class AuthToken: Codable {
open var accessToken: String?
open var tokenType: String?
open var createdAt: Date? = Date()
open var expiresIn: TimeInterval?
open var refreshToken: String?
open var idToken: String?
open var isValid: Bool {
if let createdAt = createdAt, let expiresIn = expiresIn {
return -createdAt.timeIntervalSinceNow < expiresIn
} else {
return false
}
}
public init(accessToken: String) {
self.accessToken = accessToken
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
accessToken = try? container.decode(String.self, forKey: .accessToken)
tokenType = try? container.decode(String.self, forKey: .tokenType)
createdAt = (try? container.decode(Date.self, forKey: .createdAt)) ?? Date()
expiresIn = try? container.decode(TimeInterval.self, forKey: .expiresIn)
refreshToken = try? container.decode(String.self, forKey: .refreshToken)
idToken = try? container.decode(String.self, forKey: .idToken)
}
// MARK: Codable protocol
enum CodingKeys: String, CodingKey {
case accessToken = "access_token"
case tokenType = "token_type"
case createdAt = "created_at"
case expiresIn = "expires_in"
case refreshToken = "refresh_token"
case idToken = "id_token"
}
}
class AuthTokenRequest: Encodable {
enum GrantType: String, Encodable {
case password
case refreshToken = "refresh_token"
}
var grantType: GrantType
var clientID: String = oAuthClientID
var clientSecret: String = oAuthClientSecret
var email: String?
var password: String?
var refreshToken: String?
init(email: String? = nil, password: String? = nil, grantType: GrantType = .password, refreshToken: String? = nil) {
self.email = email
self.password = password
self.grantType = grantType
self.refreshToken = refreshToken
}
// MARK: Codable protocol
enum CodingKeys: String, CodingKey {
typealias RawValue = String
case grantType = "grant_type"
case clientID = "client_id"
case clientSecret = "client_secret"
case email = "email"
case password = "password"
case refreshToken = "refresh_token"
}
}
class AuthTokenRequestWeb: Encodable {
enum GrantType: String, Encodable {
case refreshToken = "refresh_token"
case authorizationCode = "authorization_code"
}
var grantType: GrantType
var clientID: String = oAuthWebClientID
var clientSecret: String = oAuthClientSecret
var codeVerifier: String?
var code: String?
var redirectURI: String?
var refreshToken: String?
var scope: String?
init(grantType: GrantType = .authorizationCode, code: String? = nil, refreshToken: String? = nil) {
if grantType == .authorizationCode {
codeVerifier = oAuthClientID.codeVerifier
self.code = code
redirectURI = oAuthRedirectURI
} else if grantType == .refreshToken {
self.refreshToken = refreshToken
self.scope = oAuthScope
}
self.grantType = grantType
}
// MARK: Codable protocol
enum CodingKeys: String, CodingKey {
typealias RawValue = String
case grantType = "grant_type"
case clientID = "client_id"
case clientSecret = "client_secret"
case code = "code"
case redirectURI = "redirect_uri"
case refreshToken = "refresh_token"
case codeVerifier = "code_verifier"
case scope = "scope"
}
}
class AuthCodeRequest: Encodable {
var responseType: String = "code"
var clientID = oAuthWebClientID
var clientSecret = oAuthClientSecret
var redirectURI = oAuthRedirectURI
var scope = oAuthScope
let codeChallenge: String
var codeChallengeMethod = "S256"
var state = "teslaSwift"
init() {
self.codeChallenge = clientID.codeVerifier.challenge
}
// MARK: Codable protocol
enum CodingKeys: String, CodingKey {
typealias RawValue = String
case clientID = "client_id"
case redirectURI = "redirect_uri"
case responseType = "response_type"
case scope = "scope"
case codeChallenge = "code_challenge"
case codeChallengeMethod = "code_challenge_method"
case state = "state"
}
func parameters() -> [URLQueryItem] {
return[
URLQueryItem(name: CodingKeys.clientID.rawValue, value: clientID),
URLQueryItem(name: CodingKeys.redirectURI.rawValue, value: redirectURI),
URLQueryItem(name: CodingKeys.responseType.rawValue, value: responseType),
URLQueryItem(name: CodingKeys.scope.rawValue, value: scope),
URLQueryItem(name: CodingKeys.codeChallenge.rawValue, value: codeChallenge),
URLQueryItem(name: CodingKeys.codeChallengeMethod.rawValue, value: codeChallengeMethod),
URLQueryItem(name: CodingKeys.state.rawValue, value: state)
]
}
}
extension String {
var codeVerifier: String {
let verifier = self.data(using: .utf8)!.base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
.trimmingCharacters(in: .whitespaces)
return verifier
}
var challenge: String {
let hash = self.sha256
let challenge = hash.base64EncodedString()
.replacingOccurrences(of: "+", with: "-")
.replacingOccurrences(of: "/", with: "_")
.replacingOccurrences(of: "=", with: "")
.trimmingCharacters(in: .whitespaces)
return challenge
}
var sha256: String {
let inputData = Data(self.utf8)
let hashed = SHA256.hash(data: inputData)
let hashString = hashed.compactMap { String(format: "%02x", $0) }.joined()
return hashString
}
func base64EncodedString() -> String {
let inputData = Data(self.utf8)
return inputData.base64EncodedString()
}
}
| bdd465327ae24374ff6cb6f77a19ce75 | 30.032407 | 120 | 0.663136 | false | false | false | false |
quickthyme/PUTcat | refs/heads/master | PUTcat/Presentation/_Shared/AppColor.swift | apache-2.0 | 1 |
import UIKit
struct AppColor {
struct Blue {
static let Light = UIColor(red: 15/255, green: 150/255, blue: 230/255, alpha: 1)
static let Dark = UIColor(red: 0/255, green: 50/255, blue: 95/255, alpha: 1)
}
struct Gray {
static let Dark = UIColor(red: 85/255, green: 85/255, blue: 90/255, alpha: 1)
static let Light = UIColor(red: 238/255, green: 238/255, blue: 238/255, alpha: 1)
}
struct Text {
static let Dark = UIColor.black
static let Light = UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1.0)
static let VariableName = UIColor(red: 0.5, green: 0.0, blue: 0.25, alpha: 1.0)
static let VariableValue = UIColor(red: 0.0, green: 0.5, blue: 0.50, alpha: 1.0)
static let TransactionMethod = UIColor(red: 1.0, green: 0.4, blue: 0.4, alpha: 1.0)
static let TransactionDelivery = UIColor(red: 0.0, green: 0.50, blue: 0.00, alpha: 1.0)
static let TransactionURL = UIColor(red: 0.0, green: 0.25, blue: 0.50, alpha: 1.0)
static let TransactionPath = UIColor(red: 0.0, green: 0.50, blue: 0.50, alpha: 1.0)
}
static func setupGlobalAppearance() {
UINavigationBar.appearance().barStyle = UIBarStyle.blackTranslucent
UINavigationBar.appearance().barTintColor = AppColor.Gray.Dark
UINavigationBar.appearance().tintColor = UIColor.white
UITabBar.appearance().tintColor = AppColor.Gray.Dark
}
}
| 51c563f2a85c97b2c232e64532d7f59c | 43.636364 | 95 | 0.624576 | false | false | false | false |
KosyanMedia/Aviasales-iOS-SDK | refs/heads/master | AviasalesSDKTemplate/Source/HotelsSource/HotelDetails/CellFactory/HLHotelDetailsAmenityCellFactory.swift | mit | 1 | struct AmenityConst {
static let depositKey = "deposit"
static let cleaningKey = "cleaning"
static let privateBathroomKey = "private_bathroom"
static let sharedBathroomKey = "shared_bathroom"
static let slugKey = "slug"
static let priceKey = "price"
}
class HLHotelDetailsAmenityCellFactory: HLHotelDetailsCellFactory {
static let kMaxAmenitiesCells = 5
static let kDefaultAmenityIconName = "amenitiesDefault"
fileprivate static let amenityImageNames: [String: String] = [
"free_parking": "amenitiesParking",
"parking" : "amenitiesParking",
"24_hours_front_desk_service" : "24hoursAmenitiesIcon",
"low_mobility_guests_welcome" : "disabledFriendly",
"restaurant_cafe" : "amenitiesRestaurant",
"bar" : "barAmenitiesIcon",
"business_centre" : "centerAmenitiesIcon",
"laundry_service" : "amenitiesLaundry",
"concierge_service" : "conciergeAmenitiesIcon",
"wi-fi_in_public_areas" : "amenitiesInternet",
"gym" : "amenitiesFitness",
"spa" : "spaAmenitiesIcon",
"pets_allowed" : "amenitiesPets",
"swimming_pool" : "amenitiesPool",
"lgbt_friendly" : "gayFriendlyAmenitiesIcon",
"medical_service" : "medicalServiceAmenitiesIcon",
"babysitting" : "babysittingAmenitiesIcon",
"children_care_activities" : "childrenActivitiesAmenitiesIcon",
"animation" : "animationAmenitiesIcon",
"bathtub" : "amenitiesTube",
"shower" : "showerAmenitiesIcon",
"tv" : "amenitiesTV",
"air_conditioning" : "amenitiesSnow",
"safe_box" : "safeAmenitiesIcon",
"mini_bar" : "minibarAmenitiesIcon",
"hairdryer" : "amenitiesHairdryer",
"coffee_tea" : "optionsBreakfast",
"bathrobes" : "robeAmenitiesIcon",
"daily_housekeeping" : "cleaningAmenitiesIcon",
"connecting_rooms" : "doorAmenitiesIcon",
"smoking_room" : "amenitiesSmoking",
"wi-fi_in_rooms" : "amenitiesInternet",
AmenityConst.privateBathroomKey : "amenitiesPrivateBathroom"
]
private static let amenitiesBlackList = [AmenityConst.depositKey, AmenityConst.cleaningKey, AmenityConst.sharedBathroomKey]
class func createAmenitiesInRoom(_ hotel: HDKHotel, tableView: UITableView) -> [TableItem] {
return createAmenitiesFromArray(hotel.roomAmenities(), tableView: tableView)
}
class func createAmenitiesInHotel(_ hotel: HDKHotel, tableView: UITableView) -> [TableItem] {
return createAmenitiesFromArray(hotel.hotelAmenities(), tableView: tableView)
}
fileprivate class func createAmenitiesFromArray(_ array: [HDKAmenity], tableView: UITableView) -> [TableItem] {
var flattenAmenities: [NamedHotelDetailsItem] = []
for amenity in array {
let key = amenity.slug
if !amenitiesBlackList.contains(key) && !amenity.name.isEmpty {
let keyWithPrice: String
if amenity.isFree {
keyWithPrice = "free_" + key
} else {
keyWithPrice = key
}
let itemImageKey = amenityImageNames[keyWithPrice] != nil ? keyWithPrice : key
let image = amenityIconWithKey(itemImageKey as NSString)
let item = AmenityItem(name: amenity.name, image: image)
flattenAmenities.append(item)
}
}
return HLTwoColumnCellsDataSource(flattenedItems: flattenAmenities, cellWidth: tableView.bounds.width, canFillHalfScreen: HLHotelDetailsFeaturesCell.canFillHalfScreen).splitItemsLongAtBottom()
}
class func amenityIconWithKey(_ key: NSString) -> UIImage {
if let imageName = amenityImageNames[key as String], let image = UIImage(named: imageName) {
return image
} else {
return UIImage(named: kDefaultAmenityIconName)!
}
}
}
| c584bc5cbbb181ac3952efa816bbfdc7 | 41.06383 | 200 | 0.651239 | false | false | false | false |
Henawey/TheArabianCenter | refs/heads/master | TheArabianCenter/ShareWorker.swift | mit | 1 | //
// ShareWorker.swift
// TheArabianCenter
//
// Created by Ahmed Henawey on 2/23/17.
// Copyright (c) 2017 Ahmed Henawey. All rights reserved.
//
// This file was generated by the Clean Swift Xcode Templates so you can apply
// clean architecture to your iOS and Mac projects, see http://clean-swift.com
//
import UIKit
import FacebookShare
import Social
import TwitterKit
import Result
class ShareWorker
{
// MARK: - Business Logic
func twitterShare(from viewController:UIViewController,request:Share.Request,
compilation:@escaping (Result<Share.Response,Share.Error>)->()) {
guard var urlAsString = Configuration.sharedInstance.twitterAppCardConfigurationLink() else{
compilation(.failure(Share.Error.configurationMissing))
return
}
guard let image = request.image else{
compilation(.failure(Share.Error.invalidData))
return
}
urlAsString.append("&offerId=\(request.id)")
guard let url = URL(string: urlAsString) else {
compilation(.failure(Share.Error.unknownError))
return
}
let composer = TWTRComposer()
composer.setText("\(request.title) - \(request.description)")
composer.setURL(url)
composer.setImage(image)
composer.show(from: viewController) { (result) in
switch result{
case .done:
let response = Share.Response(id: request.id, title: request.title, description: request.description,image:image)
compilation(.success(response))
case .cancelled:
compilation(.failure(Share.Error.shareCancelled))
}
}
}
func facebookShare(request:Share.Request,
compilation:@escaping (Result<Share.Response,Share.Error>)->()){
guard var urlAsString = Configuration.sharedInstance.facebookApplink() else{
compilation(.failure(Share.Error.configurationMissing))
return
}
guard let imageURL = request.imageURL else{
compilation(.failure(Share.Error.invalidData))
return
}
urlAsString.append("?offerId=\(request.id)")
guard let url = URL(string: urlAsString) else {
compilation(.failure(Share.Error.unknownError))
return
}
let shareContent = LinkShareContent(url: url, title: request.title, description: request.description, quote: nil, imageURL: imageURL)
let shareDialog:ShareDialog = ShareDialog(content: shareContent)
shareDialog.completion = { result in
switch result {
case let .success(result):
guard (result.postId != nil) else {
compilation(.failure(Share.Error.shareCancelled))
return
}
let response = Share.Response(id:request.id,title: request.title, description: request.description,imageURL:imageURL)
compilation(.success(response))
case .cancelled:
compilation(.failure(Share.Error.shareCancelled))
case let .failed(error):
compilation(.failure(Share.Error.failure(error: error)))
}
}
do{
try shareDialog.show()
}catch{
compilation(.failure(Share.Error.failure(error: error)))
}
}
}
| 86c77657b7e6f4355375a1d50e1a6003 | 32.971429 | 141 | 0.590692 | false | false | false | false |
eurofurence/ef-app_ios | refs/heads/release/4.0.0 | Packages/EurofurenceKit/Sources/EurofurenceKit/Properties/AppGroupModelProperties.swift | mit | 1 | import EurofurenceWebAPI
import Foundation
public class AppGroupModelProperties: EurofurenceModelProperties {
public static let shared = AppGroupModelProperties()
private let userDefaults: UserDefaults
convenience init() {
guard let appGroupUserDefaults = UserDefaults(suiteName: SecurityGroup.identifier) else {
fatalError("Cannot instantiate App Group user defaults")
}
self.init(userDefaults: appGroupUserDefaults)
// Make sure the container directory and subdirectories exist.
let fileManager = FileManager.default
var unused: ObjCBool = false
if fileManager.fileExists(atPath: imagesDirectory.path, isDirectory: &unused) == false {
do {
try fileManager.createDirectory(at: imagesDirectory, withIntermediateDirectories: true)
} catch {
print("Failed to prepare images directory!")
}
}
}
init(userDefaults: UserDefaults) {
self.userDefaults = userDefaults
}
private struct Keys {
static let synchronizationGenerationTokenData = "EFKSynchronizationGenerationTokenData"
}
public var containerDirectoryURL: URL {
let fileManager = FileManager.default
guard let url = fileManager.containerURL(forSecurityApplicationGroupIdentifier: SecurityGroup.identifier) else {
fatalError("Couldn't resolve URL for shared container")
}
return url
}
public var synchronizationChangeToken: SynchronizationPayload.GenerationToken? {
get {
guard let data = userDefaults.data(forKey: Keys.synchronizationGenerationTokenData) else { return nil }
let decoder = JSONDecoder()
return try? decoder.decode(SynchronizationPayload.GenerationToken.self, from: data)
}
set {
if let newValue = newValue {
let encoder = JSONEncoder()
guard let data = try? encoder.encode(newValue) else { return }
userDefaults.set(data, forKey: Keys.synchronizationGenerationTokenData)
} else {
userDefaults.set(nil, forKey: Keys.synchronizationGenerationTokenData)
}
}
}
public func removeContainerResource(at url: URL) throws {
try FileManager.default.removeItem(at: url)
}
}
| e43851a781f302d2feb50f84d62a26c6 | 35.117647 | 120 | 0.640879 | false | false | false | false |
ZevEisenberg/Padiddle | refs/heads/main | Padiddle/Padiddle/View Model/DrawingViewModel.swift | mit | 1 | //
// DrawingViewModel.swift
// Padiddle
//
// Created by Zev Eisenberg on 10/7/15.
// Copyright © 2015 Zev Eisenberg. All rights reserved.
//
import UIKit
protocol DrawingViewModelDelegate: AnyObject {
func startDrawing()
func pauseDrawing()
func drawingViewModelUpdatedLocation(_ newLocation: CGPoint)
}
protocol DrawingViewBoundsVendor: AnyObject {
var bounds: CGRect { get }
}
class DrawingViewModel: NSObject { // must inherit from NSObject for @objc callbacks to work
private(set) var isDrawing = false
var needToMoveNibToNewStartLocation = true
let contextSize: CGSize
let contextScale: CGFloat
private let brushDiameter: CGFloat = 12
weak var delegate: DrawingViewModelDelegate?
weak var view: DrawingViewBoundsVendor?
private var colorManager: ColorManager?
private let spinManager: SpinManager
private let maxRadius: CGFloat
private var offscreenContext: CGContext!
private var points = Array(repeating: CGPoint.zero, count: 4)
private let screenScale = UIScreen.main.scale
private var displayLink: CADisplayLink?
var imageUpdatedCallback: ((CGImage) -> Void)?
lazy private var contextScaleFactor: CGFloat = {
// The context image is scaled as Aspect Fill, so the larger dimension
// of the bounds is the limiting factor
let maxDimension = max(self.contextSize.width, self.contextSize.height)
assert(maxDimension > 0)
// Given context side length L and bounds max dimension l,
// We are looking for a factor, ƒ, such that L * ƒ = l
// So we divide both sides by L to get ƒ = l / L
let ƒ = maxDimension / self.contextSize.width
return ƒ
}()
private var currentColor: UIColor {
guard let colorManager = colorManager else {
return UIColor.magenta
}
return colorManager.currentColor
}
required init(maxRadius: CGFloat, contextSize: CGSize, contextScale: CGFloat, spinManager: SpinManager) {
assert(maxRadius > 0)
self.maxRadius = maxRadius
self.contextSize = contextSize
self.contextScale = contextScale
self.spinManager = spinManager
super.init()
let success = configureOffscreenContext()
assert(success, "Problem creating bitmap context")
displayLink = CADisplayLink(target: self, selector: #selector(DrawingViewModel.displayLinkUpdated))
if #available(iOS 15.0, *) {
displayLink?.preferredFrameRateRange = .init(minimum: 60, maximum: 120, preferred: 120)
}
displayLink?.add(to: .main, forMode: .default)
}
func addPoint(_ point: CGPoint) {
let scaledPoint = convertViewPointToContextCoordinates(point)
let distance = CGPoint.distanceBetween(points[3], scaledPoint)
if distance > 2.25 {
points.removeFirst()
points.append(scaledPoint)
addLineSegmentBasedOnUpdatedPoints()
}
}
// MARK: Drawing
func startDrawing() {
isDrawing = true
}
func stopDrawing() {
isDrawing = false
}
func clear() {
offscreenContext.setFillColor(UIColor.white.cgColor)
offscreenContext.fill(CGRect(origin: .zero, size: contextSize))
offscreenContext.makeImage().map { imageUpdatedCallback?($0) }
}
func restartAtPoint(_ point: CGPoint) {
let convertedPoint = convertViewPointToContextCoordinates(point)
points = Array(repeating: convertedPoint, count: points.count)
addLineSegmentBasedOnUpdatedPoints()
}
func setInitialImage(_ image: UIImage) {
let rect = CGRect(origin: .zero, size: contextSize)
offscreenContext.draw(image.cgImage!, in: rect)
offscreenContext.makeImage().map { imageUpdatedCallback?($0) }
}
private func addLineSegmentBasedOnUpdatedPoints() {
let pathSegment = CGPath.smoothedPathSegment(points: points)
offscreenContext.addPath(pathSegment)
offscreenContext.setStrokeColor(currentColor.cgColor)
offscreenContext.strokePath()
offscreenContext.makeImage().map { imageUpdatedCallback?($0) }
}
// Saving & Loading
func snapshot(_ orientation: UIInterfaceOrientation) -> UIImage {
let (imageOrientation, rotation) = orientation.imageRotation
let cacheCGImage = offscreenContext.makeImage()!
let unrotatedImage = UIImage(cgImage: cacheCGImage, scale: UIScreen.main.scale, orientation: imageOrientation)
let rotatedImage = unrotatedImage.imageRotatedByRadians(rotation)
return rotatedImage
}
func getSnapshotImage(interfaceOrientation: UIInterfaceOrientation, completion: @escaping (EitherImage) -> Void) {
DispatchQueue.global(qos: .default).async {
let image = self.snapshot(interfaceOrientation)
// Share raw PNG data if we can, because it results in sharing a PNG image,
// which is desirable for the large chunks of color in this app.
if let pngData = image.pngData() {
DispatchQueue.main.async {
completion(.png(pngData))
}
}
else {
// If there was a problem, fall back to saving the original image
DispatchQueue.main.async {
completion(.image(image))
}
}
}
}
func persistImageInBackground() {
let image = self.snapshot(.portrait)
ImageIO.persistImageInBackground(image, contextScale: contextScale, contextSize: contextSize)
}
func loadPersistedImage() {
ImageIO.loadPersistedImage(contextScale: contextScale, contextSize: contextSize) { image in
if let image = image {
self.setInitialImage(image)
}
}
}
}
extension DrawingViewModel {
@objc func displayLinkUpdated() {
updateMotion()
}
}
extension DrawingViewModel: RecordingDelegate {
@objc func recordingStatusChanged(_ recording: Bool) {
if recording {
delegate?.startDrawing()
}
else {
delegate?.pauseDrawing()
}
}
@objc func motionUpdatesStatusChanged(_ updates: Bool) {
if updates {
startMotionUpdates()
}
else {
stopMotionUpdates()
}
}
}
extension DrawingViewModel: RootColorManagerDelegate {
func colorManagerPicked(_ colorManager: ColorManager) {
var newManager = colorManager
newManager.maxRadius = maxRadius
self.colorManager = newManager
}
}
extension DrawingViewModel { // Coordinate conversions
private func convertViewPointToContextCoordinates(_ point: CGPoint) -> CGPoint {
guard let view = view else {
fatalError("Not having a view represents a programmer error")
}
var newPoint = point
// 1. Multiply the point by the reciprocal of the context scale factor
newPoint.x *= (1 / contextScaleFactor)
newPoint.y *= (1 / contextScaleFactor)
// 2. Get the size of self in context coordinates
let viewSize = view.bounds.size
let scaledViewSize = CGSize(
width: viewSize.width * (1 / contextScaleFactor),
height: viewSize.height * (1 / contextScaleFactor)
)
// 3. Get the difference in size between self and the context
let difference = CGSize(
width: contextSize.width - scaledViewSize.width,
height: contextSize.height - scaledViewSize.height
)
// 4. Shift the point by half the difference in width and height
newPoint.x += difference.width / 2
newPoint.y += difference.height / 2
return newPoint
}
func convertContextRectToViewCoordinates(_ rect: CGRect) -> CGRect {
guard !rect.equalTo(CGRect.null) else { return CGRect.null }
guard let view = view else { fatalError("Not having a view represents a programmer error") }
// 1. Get the size of the context in self coordinates
let scaledContextSize = CGSize(
width: contextSize.width * contextScaleFactor,
height: contextSize.height * contextScaleFactor
)
// 2. Get the difference in size between self and the context
let boundsSize = view.bounds.size
let difference = CGSize(
width: scaledContextSize.width - boundsSize.width,
height: scaledContextSize.height - boundsSize.height
)
// 3. Scale the rect by the context scale factor
let scaledRect = rect.applying(CGAffineTransform(scaleX: contextScaleFactor, y: contextScaleFactor))
// 4. Shift the rect by negative the half the difference in width and height
let offsetRect = scaledRect.offsetBy(dx: -difference.width / 2.0, dy: -difference.height / 2.0)
return offsetRect
}
func convertContextPointToViewCoordinates(_ point: CGPoint) -> CGPoint {
guard let view = view else {
fatalError("Not having a view represents a programmer error")
}
// 1. Get the size of the context in self coordinates
let scaledContextSize = CGSize(
width: contextSize.width * contextScaleFactor,
height: contextSize.height * contextScaleFactor
)
// 2. Get the difference in size between self and the context
let boundsSize = view.bounds.size
let difference = CGSize(
width: scaledContextSize.width - boundsSize.width,
height: scaledContextSize.height - boundsSize.height
)
// 3. Scale the rect by the context scale factor
let scaledPoint = point.applying(CGAffineTransform(scaleX: contextScaleFactor, y: contextScaleFactor))
// 4. Shift the rect by negative the half the difference in width and height
let offsetPoint = scaledPoint.offsetBy(dx: -difference.width / 2.0, dy: -difference.height / 2.0)
return offsetPoint
}
}
// MARK: Context configuration
private extension DrawingViewModel {
func configureOffscreenContext() -> Bool {
let bitmapBytesPerRow: Int
// Declare the number of bytes per row. Each pixel in the bitmap in this
// example is represented by 4 bytes: 8 bits each of red, green, blue, and
// alpha.
bitmapBytesPerRow = Int(contextSize.width) * bytesPerPixel * Int(screenScale)
let widthPx = Int(contextSize.width * screenScale)
let heightPx = Int(contextSize.height * screenScale)
let context = CGContext(
data: nil,
width: widthPx,
height: heightPx,
bitsPerComponent: bitsPerComponent,
bytesPerRow: bitmapBytesPerRow,
space: CGColorSpaceCreateDeviceRGB(),
bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue
)
guard context != nil else {
assertionFailure("Problem creating context")
return false
}
offscreenContext = context
// Scale by screen scale because the context is in pixels, not points.
// If we don't invert the y axis, the world will be turned upside down
offscreenContext?.translateBy(x: 0, y: CGFloat(heightPx))
offscreenContext?.scaleBy(x: screenScale, y: -screenScale)
offscreenContext?.setLineCap(.round)
offscreenContext?.setLineWidth(brushDiameter)
clear()
return true
}
}
// MARK: Core Motion
extension DrawingViewModel {
func startMotionUpdates() {
// startDrawing()
spinManager.startMotionUpdates()
}
func stopMotionUpdates() {
stopDrawing()
spinManager.stopMotionUpdates()
}
@objc func updateMotion() {
if let deviceMotion = spinManager.deviceMotion {
let zRotation = deviceMotion.rotationRate.z
let radius = maxRadius / UIDevice.gyroMaxValue * CGFloat(fabs(zRotation))
// Yaw is on the range [-π...π]. Remap to [0...π]
let theta = deviceMotion.attitude.yaw + .pi
let x = radius * CGFloat(cos(theta)) + contextSize.width / 2.0
let y = radius * CGFloat(sin(theta)) + contextSize.height / 2.0
colorManager?.radius = radius
colorManager?.theta = CGFloat(theta)
delegate?.drawingViewModelUpdatedLocation(CGPoint(x: x, y: y))
}
}
}
enum EitherImage {
case png(Data)
case image(UIImage)
var valueForSharing: Any {
switch self {
case .png(let data): return data
case .image(let image): return image
}
}
}
| 8941202782ebded219df83e81529dfba | 30.126829 | 118 | 0.642846 | false | false | false | false |
yeziahehe/Gank | refs/heads/master | Gank/ViewControllers/New/NewViewController.swift | gpl-3.0 | 1 | //
// NewViewController.swift
// Gank
//
// Created by 叶帆 on 2016/10/27.
// Copyright © 2016年 Suzhou Coryphaei Information&Technology Co., Ltd. All rights reserved.
//
import UIKit
import Kingfisher
import UserNotifications
final class NewViewController: BaseViewController {
fileprivate var isNoData = false
@IBOutlet var dailyGankButton: UIBarButtonItem!
@IBOutlet var calendarButton: UIBarButtonItem!
@IBOutlet weak var tipView: UIView!
@IBOutlet weak var newTableView: UITableView! {
didSet {
newTableView.isScrollEnabled = false
newTableView.tableHeaderView = coverHeaderView
newTableView.tableFooterView = UIView()
newTableView.separatorStyle = .none
newTableView.rowHeight = 158
newTableView.registerNibOf(DailyGankCell.self)
newTableView.registerNibOf(DailyGankLoadingCell.self)
}
}
fileprivate lazy var activityIndicatorView: UIActivityIndicatorView = {
let activityView = UIActivityIndicatorView(style: .white)
activityView.hidesWhenStopped = true
return activityView
}()
fileprivate lazy var coverHeaderView: CoverHeaderView = {
let headerView = CoverHeaderView.instanceFromNib()
headerView.frame = CGRect(x: 0, y: 0, width: GankConfig.getScreenWidth(), height: 235)
return headerView
}()
fileprivate lazy var noDataFooterView: NoDataFooterView = {
let noDataFooterView = NoDataFooterView.instanceFromNib()
noDataFooterView.reasonAction = { [weak self] in
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let networkViewController = storyboard.instantiateViewController(withIdentifier: "NetworkViewController")
self?.navigationController?.pushViewController(networkViewController , animated: true)
}
noDataFooterView.reloadAction = { [weak self] in
self?.updateNewView()
}
noDataFooterView.frame = CGRect(x: 0, y: 0, width: GankConfig.getScreenWidth(), height: GankConfig.getScreenHeight()-64)
return noDataFooterView
}()
fileprivate lazy var customFooterView: CustomFooterView = {
let footerView = CustomFooterView.instanceFromNib()
footerView.frame = CGRect(x: 0, y: 0, width: GankConfig.getScreenWidth(), height: 73)
return footerView
}()
fileprivate var isGankToday: Bool = true
fileprivate var meiziGank: Gank?
fileprivate var gankCategories: [String] = []
fileprivate var gankDictionary: [String: Array<Gank>] = [:]
deinit {
NotificationCenter.default.removeObserver(self)
newTableView?.delegate = nil
gankLog.debug("deinit NewViewController")
}
override func viewDidLoad() {
super.viewDidLoad()
updateNewView()
NotificationCenter.default.addObserver(self, selector: #selector(NewViewController.refreshUIWithNotification(_:)), name: GankConfig.NotificationName.chooseGank, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(NewViewController.refreshUIWithPush(_:)), name: GankConfig.NotificationName.push, object: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
guard let identifier = segue.identifier else {
return
}
switch identifier {
case "showDetail":
let vc = segue.destination as! GankDetailViewController
let url = sender as! String
vc.gankURL = url
default:
break
}
}
@IBAction func closeTip(_ sender: UIButton) {
tipView.isHidden = true
}
@IBAction func getNewGank(_ sender: UIBarButtonItem) {
updateNewView(mode: .today)
}
@IBAction func showCalendar(_ sender: UIBarButtonItem) {
self.performSegue(withIdentifier: "showCalendar", sender: nil)
}
@objc fileprivate func refreshUIWithNotification(_ notification: Notification) {
guard let date = notification.object as? String else {
return
}
updateNewView(mode: .date, isChoose: true, date: date)
}
@objc fileprivate func refreshUIWithPush(_ notification: Notification) {
updateNewView(mode: .today)
}
}
extension NewViewController {
fileprivate enum RightBarType {
case all
case only
case indicator
case none
}
fileprivate func setRightBarButtonItems(type: RightBarType) {
switch type {
case .only:
navigationItem.setRightBarButtonItems([calendarButton], animated: false)
case .indicator:
navigationItem.setRightBarButtonItems([calendarButton, UIBarButtonItem(customView: activityIndicatorView)], animated: false)
case .all:
navigationItem.setRightBarButtonItems([calendarButton, dailyGankButton], animated: false)
case .none:
navigationItem.setRightBarButtonItems(nil, animated: false)
}
}
fileprivate enum UpdateNewViewMode {
case lastest
case today
case date
}
fileprivate func updateNewView(mode: UpdateNewViewMode = .lastest, isChoose: Bool = false, date: String = "") {
isNoData = false
switch mode {
case .lastest:
setRightBarButtonItems(type: .none)
gankLog.debug("UpdateNewViewMode lastest")
case .date:
isGankToday = false
meiziGank = nil
gankCategories = []
gankDictionary = [:]
newTableView.isScrollEnabled = false
newTableView.separatorColor = .none
newTableView.tableFooterView = UIView()
newTableView.rowHeight = 158
newTableView.reloadData()
coverHeaderView.refresh()
tipView.isHidden = true
setRightBarButtonItems(type: .only)
gankLog.debug("UpdateNewViewMode date")
case .today:
GankConfig.heavyFeedbackEffectAction?()
activityIndicatorView.startAnimating()
setRightBarButtonItems(type: .indicator)
gankLog.debug("UpdateNewViewMode today")
}
let failureHandler: FailureHandler = { reason, message in
SafeDispatch.async { [weak self] in
self?.isNoData = true
self?.newTableView.tableHeaderView = UIView()
self?.newTableView.isScrollEnabled = false
self?.newTableView.tableFooterView = self?.noDataFooterView
self?.newTableView.reloadData()
gankLog.debug("加载失败")
}
}
switch mode {
case .lastest:
gankLatest(failureHandler: failureHandler, completion: { (isToday, meizi, categories, lastestGank) in
SafeDispatch.async { [weak self] in
self?.configureData(isToday, meizi, categories, lastestGank)
self?.makeUI()
}
})
case .today:
gankLatest(failureHandler: failureHandler, completion: { (isToday, meizi, categories, lastestGank) in
SafeDispatch.async { [weak self] in
self?.activityIndicatorView.stopAnimating()
guard isToday else {
self?.makeAlert()
return
}
self?.configureData(isToday, meizi, categories, lastestGank)
self?.makeUI()
}
})
case .date:
gankWithDay(date: date, failureHandler: failureHandler, completion: { (isToday, meizi, categories, lastestGank) in
SafeDispatch.async { [weak self] in
self?.configureData(isToday, meizi, categories, lastestGank)
self?.makeUI(isChoose:true)
}
})
}
}
fileprivate func configureData(_ isToday: Bool, _ meizi: Gank, _ categories: Array<String>, _ lastestGank: Dictionary<String, Array<Gank>>) {
isGankToday = isToday
meiziGank = meizi
gankCategories = categories
gankDictionary = lastestGank
}
fileprivate func makeUI(isChoose: Bool = false) {
newTableView.isScrollEnabled = true
newTableView.tableHeaderView = coverHeaderView
newTableView.tableFooterView = customFooterView
newTableView.estimatedRowHeight = 195.5
newTableView.rowHeight = UITableView.automaticDimension
let height = coverHeaderView.configure(meiziData: meiziGank)
coverHeaderView.frame.size = CGSize(width: GankConfig.getScreenWidth(), height: height)
newTableView.reloadData()
if isChoose == false {
tipView.isHidden = isGankToday
}
if isGankToday {
setRightBarButtonItems(type: .only)
return
}
setRightBarButtonItems(type: .all)
}
fileprivate func makeAlert() {
setRightBarButtonItems(type: .all)
guard GankNotificationService.shared.isAskAuthorization == true else {
GankAlert.confirmOrCancel(title: nil, message: String.messageOpenNotification, confirmTitle: String.promptConfirmOpenNotification, cancelTitle: String.promptCancelOpenNotification, inViewController: self, withConfirmAction: {
GankNotificationService.shared.checkAuthorization()
}, cancelAction: {})
return
}
GankAlert.alertKnown(title: nil, message: String.messageNoDailyGank, inViewController: self)
}
}
// MARK: - UITableViewDataSource, UITableViewDelegate
extension NewViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
guard !isNoData else {
return 0
}
return gankCategories.isEmpty ? 1 : gankCategories.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard !isNoData else {
return 0
}
guard !gankCategories.isEmpty else {
return 2
}
let key: String = gankCategories[section]
return gankDictionary[key]!.count
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
guard gankCategories.isEmpty || isNoData else {
return 56
}
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return CGFloat.leastNormalMagnitude
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard gankCategories.isEmpty else {
let headerView = GankHeaderView.instanceFromNib()
headerView.configure(titleString: gankCategories[section])
return headerView
}
return nil
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard gankCategories.isEmpty else {
let cell: DailyGankCell = tableView.dequeueReusableCell()
let key: String = gankCategories[indexPath.section]
let gankDetail: Gank = gankDictionary[key]![indexPath.row]
cell.configure(withGankDetail: gankDetail)
cell.selectionStyle = UITableViewCell.SelectionStyle.default
return cell
}
let cell: DailyGankLoadingCell = tableView.dequeueReusableCell()
cell.selectionStyle = UITableViewCell.SelectionStyle.none
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
defer {
tableView.deselectRow(at: indexPath, animated: true)
}
if !gankCategories.isEmpty {
let key: String = gankCategories[indexPath.section]
let gankDetail: Gank = gankDictionary[key]![indexPath.row]
self.performSegue(withIdentifier: "showDetail", sender: gankDetail.url)
}
}
}
| 892c52d33f3912d8b0a6b5176efe7950 | 34.40884 | 237 | 0.613746 | false | false | false | false |
xqz001/WWDC | refs/heads/master | WWDC/LiveEvent.swift | bsd-2-clause | 1 | //
// LiveEvent.swift
// WWDC
//
// Created by Guilherme Rambo on 16/05/15.
// Copyright (c) 2015 Guilherme Rambo. All rights reserved.
//
import Foundation
private let _dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'ZZZZ"
struct LiveEvent {
var id: Int
var title: String
var startsAt: NSDate
var description: String
var stream: NSURL?
var isLiveRightNow: Bool
private struct Keys {
static let id = "id"
static let title = "title"
static let description = "description"
static let stream = "stream"
static let startsAt = "starts_at"
static let isLiveRightNow = "isLiveRightNow"
}
init(jsonObject: JSON) {
id = jsonObject[Keys.id].intValue
title = jsonObject[Keys.title].string!
description = jsonObject[Keys.description].string!
stream = NSURL(string: jsonObject[Keys.stream].string!)
isLiveRightNow = jsonObject[Keys.isLiveRightNow].boolValue
let formatter = NSDateFormatter()
formatter.dateFormat = _dateFormat
startsAt = formatter.dateFromString(jsonObject[Keys.startsAt].string!)!
}
} | 9f0697a1f590fcb59e98161be83a1f02 | 27.243902 | 79 | 0.645635 | false | false | false | false |
mlilback/rc2SwiftClient | refs/heads/master | MacClient/Searchable.swift | isc | 1 | //
// Searchable.swift
//
// Copyright ©2016 Mark Lilback. This file is licensed under the ISC license.
//
import Cocoa
import ClientCore
protocol MacCodeEditor: CodeEditor, Searchable {}
protocol Searchable {
func performFind(action: NSTextFinder.Action)
var supportsSearchBar: Bool { get }
var searchBarVisible: Bool { get }
var searchableTextView: NSTextView? { get }
}
extension Searchable {
func performFind(action: NSTextFinder.Action) {
if let textView = searchableTextView {
let menuItem = NSMenuItem(title: "foo", action: #selector(NSTextView.performFindPanelAction(_:)), keyEquivalent: "")
menuItem.tag = action.rawValue
textView.performFindPanelAction(menuItem)
if action == .hideFindInterface {
textView.enclosingScrollView?.isFindBarVisible = false
}
}
}
var supportsSearchBar: Bool { return false }
var searchBarVisible: Bool { return searchableTextView?.enclosingScrollView?.isFindBarVisible ?? false }
var searchableTextView: NSTextView? { return nil }
}
| ba2a4785d5250b1f6542d49278df47f6 | 29.575758 | 119 | 0.755203 | false | false | false | false |
TLOpenSpring/TLTranstionLib-swift | refs/heads/master | TLTranstionLib-swift/Classes/Interactors/TLBaseSwipeInteraction.swift | mit | 1 | //
// TLBaseSwipeInteraction.swift
// Pods
//
// Created by Andrew on 16/8/8.
//
//
import UIKit
/*
UIPercentDrivenInteractiveTransition。这个类的对象会根据我们的手势,来决定我们的自定义过渡的完成度。我们把这些都放到手势识别器的 action 方法中去
当手势刚刚开始,我们创建一个 UIPercentDrivenInteractiveTransition 对象,然后让 navigationController 去把当前这个 viewController 弹出。
当手慢慢划入时,我们把总体手势划入的进度告诉 UIPercentDrivenInteractiveTransition 对象。
当手势结束,我们根据用户的手势进度来判断过渡是应该完成还是取消并相应的调用 finishInteractiveTransition 或者 cancelInteractiveTransition 方法.
*/
private let TLBaseSwipeInteractionDefaultCompletionPercentage:CGFloat = 0.3
public class TLBaseSwipeInteraction: UIPercentDrivenInteractiveTransition,TLTransitionInteractionProtocol,UIGestureRecognizerDelegate {
var fromViewController:UIViewController?
/// 滑动的手势
var gestureRecognizer:UIPanGestureRecognizer{
let gesture = UIPanGestureRecognizer(target: self, action: #selector(handlePanGesture(_:)))
gesture.delegate = self
return gesture
}
/// 当手势滑动的方向相反时是否触发手势
public var reverseGestureDirection:Bool = false
//MARK: - TLTransitionInteractionProtocol属性
public var isInteractive: Bool = true
public var shouldCompleteTransition: Bool = false
public var action: TLTranstionAction = TLTranstionAction.tl_Any
public var nextControllerDelegate: TLTransitionInteractionControllerDelegate?
public func attachViewController(viewController viewController: UIViewController, action: TLTranstionAction) {
self.fromViewController = viewController
self.action = action
//给当前控制器添加手势
self.attachGestureRecognizerToView((self.fromViewController?.view)!)
}
deinit{
self.gestureRecognizer.view?.removeGestureRecognizer(self.gestureRecognizer)
}
/**
添加手势
- parameter view:
*/
func attachGestureRecognizerToView(view:UIView) -> Void {
view.addGestureRecognizer(self.gestureRecognizer)
}
//MARK: - UIPercentDrivenInteractiveTransition
/**
Flag if the gesture is in the positive or negative direction
- parameter panGestureRecognizer: 滑动手势
- returns: Flag if the gesture is in the positive or negative direction
*/
func isGesturePositive(panGestureRecognizer:UIPanGestureRecognizer) -> Bool {
fatalError("子类必须实现这个方法\(isGesturePositive)")
return true
}
/**
当手势滑动的时候该方法会被触发
滑动手势的百分比
- parameter precent: 滑动的百分比
- returns: 距离完成手势操作的百分比
*/
func swipeCompletionPercent() -> CGFloat {
return TLBaseSwipeInteractionDefaultCompletionPercentage
}
/**
The translation percentage of the passed gesture recognizer
- parameter panGestureRecognizer:
- returns: 完成手势的百分比
*/
func translationPercentageWithPanGestureRecongizer(panGestureRecognizer panGestureRecognizer:UIPanGestureRecognizer) -> CGFloat {
fatalError("子类必须覆盖这个方法:\(translationPercentageWithPanGestureRecongizer))")
return 0
}
/**
The physical translation that is on the the view due to the panGestureRecognizer
- parameter panGestureRecognizer: 滑动手势
- returns: the translation that is currently on the view.
*/
func translationWithPanGestureRecongizer(panGestureRecognizer panGestureRecognizer:UIPanGestureRecognizer) -> CGFloat {
fatalError("子类必须覆盖这个方法:\(translationWithPanGestureRecongizer))")
return 0
}
//MARK: - UIPanGestureRecognizer Delegate
func handlePanGesture(panGestureRecognizer:UIPanGestureRecognizer) -> Void {
let percentage = self.translationPercentageWithPanGestureRecongizer(panGestureRecognizer: panGestureRecognizer)
//判断是否是正向还是逆向
let positiveDirection = self.reverseGestureDirection ? !self.isGesturePositive(panGestureRecognizer) : self.isGesturePositive(panGestureRecognizer)
switch panGestureRecognizer.state {
case .Began:
//允许用户交互
self.isInteractive = true
//如果是正向操作,并且下一个控制器实现了TLTransitionInteractionProtocol协议
if let nextDelegate = self.nextControllerDelegate{
if positiveDirection && nextDelegate is TLTransitionInteractionControllerDelegate{
//如果操作类型是 push
if action == TLTranstionAction.tl_Push{
self.fromViewController?.navigationController?.pushViewController((self.nextControllerDelegate?.nextViewControllerForInteractor(self))!, animated: true)
}else if (action == TLTranstionAction.tl_Present){
self.fromViewController?.presentViewController((self.nextControllerDelegate?.nextViewControllerForInteractor(self))!, animated: true, completion: nil)
}
}else{
//如果是逆向操作
if action == TLTranstionAction.tl_Pop{
self.fromViewController?.navigationController?.popViewControllerAnimated(true)
}else if action == TLTranstionAction.tl_Dismiss{
self.fromViewController?.dismissViewControllerAnimated(true, completion: nil)
}
}
}
case .Changed:
//如果是允许交互
if self.isInteractive{
self.shouldCompleteTransition = (percentage >= TLBaseSwipeInteractionDefaultCompletionPercentage)
self.updateInteractiveTransition(percentage)
}
break
case .Cancelled:
break
case .Ended:
if isInteractive{
//如果交互没有完成
if self.shouldCompleteTransition == false{
self.cancelInteractiveTransition()
}else{
self.finishInteractiveTransition()
}
}
self.isInteractive = false
break
default:
break
}
}
}
| 0d9eeee8022ed14ac3f47c086f381876 | 32.714286 | 176 | 0.655802 | false | false | false | false |
mcrollin/safecaster | refs/heads/master | safecaster/UIViewController+EmptyBackButton.swift | cc0-1.0 | 1 | //
// UIViewController+EmptyBackButton.swift
// safecaster
//
// Created by Marc Rollin on 7/24/15.
// Copyright (c) 2015 safecast. All rights reserved.
//
import UIKit
extension UIViewController {
// static var onceToken: dispatch_once_t = 0
//
// func load() {
// dispatch_once(&UIViewController.onceToken) {
// let method: Method = class_getInstanceMethod(object_getClass(self), "viewDidLoad")
// let swizzledMethod: Method = class_getInstanceMethod(object_getClass(self), "mob_viewDidLoad")
//
// method_exchangeImplementations(method, swizzledMethod)
// }
// }
//
// func mob_viewDidLoad() {
// self.viewDidLoad()
//
// let backButtonItem = UIBarButtonItem(title: nil, style: .Plain, target: nil, action: nil)
// self.navigationItem.backBarButtonItem = backButtonItem
// }
}
| d37e3ec5ce6188d1a94ddce3f0888811 | 29.517241 | 108 | 0.639548 | false | false | false | false |
DianQK/rx-sample-code | refs/heads/master | TwoWayBind/PushSetting/SelectTableViewHeaderFooterView.swift | mit | 1 | //
// SelectTableViewHeaderFooterView.swift
// RxDealCell
//
// Created by DianQK on 8/8/16.
// Copyright © 2016 T. All rights reserved.
//
import UIKit
import SnapKit
import RxSwift
import RxCocoa
class SelectTableViewHeaderFooterView: UITableViewHeaderFooterView {
static let reuseIdentifier = "SelectTableViewHeaderFooterView"
var name: String? {
get {
return nameLabel.text
}
set {
nameLabel.text = newValue
}
}
fileprivate lazy var selectSwitch = UISwitch()
private lazy var nameLabel = UILabel()
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
contentView.addSubview(nameLabel)
nameLabel.snp.makeConstraints { (make) in
make.leading.equalTo(self.contentView).offset(30)
make.centerY.equalTo(self.contentView)
}
contentView.addSubview(selectSwitch)
selectSwitch.snp.makeConstraints { (make) in
make.trailing.equalTo(self.contentView).offset(-30)
make.centerY.equalTo(self.contentView)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension Reactive where Base: UISwitch {
public var isOn: ControlProperty<Bool> {
let source = self.controlEvent(.valueChanged)
.map { [unowned uiSwitch = self.base] in uiSwitch.isOn }
let sink = UIBindingObserver<UISwitch, Bool>(UIElement: self.base) { uiSwitch, isOn in
guard uiSwitch.isOn != isOn else { return }
uiSwitch.setOn(isOn, animated: true)
}
return ControlProperty(values: source, valueSink: sink)
}
}
extension Reactive where Base: SelectTableViewHeaderFooterView {
var isSelected: ControlProperty<Bool> {
return base.selectSwitch.rx.isOn(animated: true)
}
}
| baa1900d89a817f10a90d48842663b1a | 27.597015 | 94 | 0.659186 | false | false | false | false |
qvacua/vimr | refs/heads/master | Commons/Sources/Commons/OSLogCommons.swift | mit | 1 | /**
* Tae Won Ha - http://taewon.de - @hataewon
* See LICENSE
*/
import Foundation
import os
public extension OSLog {
func trace<T>(
file: String = #file,
function: String = #function,
line: Int = #line,
_ msg: T
) {
#if TRACE
self.log(
type: .debug,
msg: "%{public}@",
"[\((file as NSString).lastPathComponent) - \(function):\(line)] [TRACE] \(msg)"
)
#endif
}
func debug(
file: String = #file,
function: String = #function,
line: Int = #line
) {
#if DEBUG
self.log(
type: .debug,
msg: "%{public}@",
"[\((file as NSString).lastPathComponent) - \(function):\(line)]"
)
#endif
}
func debug<T>(
file: String = #file,
function: String = #function,
line: Int = #line,
_ msg: T
) {
#if DEBUG
self.log(
type: .debug,
msg: "%{public}@",
"[\((file as NSString).lastPathComponent) - \(function):\(line)] \(msg)"
)
#endif
}
func info<T>(
file: String = #file,
function: String = #function,
line: Int = #line,
_ msg: T
) {
self.log(
type: .info,
msg: "%{public}@",
"[\((file as NSString).lastPathComponent) - \(function):\(line)] \(msg)"
)
}
func `default`<T>(
file: String = #file,
function: String = #function,
line: Int = #line,
_ msg: T
) {
self.log(
type: .default,
msg: "%{public}@",
"[\((file as NSString).lastPathComponent) - \(function):\(line)] \(msg)"
)
}
func error<T>(
file: String = #file,
function: String = #function,
line: Int = #line,
_ msg: T
) {
self.log(
type: .error,
msg: "%{public}@",
"[\((file as NSString).lastPathComponent) - \(function):\(line)] \(msg)"
)
}
func fault<T>(
file: String = #file,
function: String = #function,
line: Int = #line,
_ msg: T
) {
self.log(
type: .fault,
msg: "%{public}@",
"[\((file as NSString).lastPathComponent) - \(function):\(line)] \(msg)"
)
}
private func log(
type: OSLogType,
msg: StaticString,
_ object: CVarArg
) {
os_log(msg, log: self, type: type, object)
}
}
| d2a4f31201a4709cc72f99e33ad38f4b | 18.79646 | 88 | 0.502906 | false | false | false | false |
bitboylabs/selluv-ios | refs/heads/master | selluv-ios/selluv-ios/Classes/Base/Model/RealmModel/ClothingSizeConvert/BabyShoesSizeConvertInfo.swift | mit | 1 | //
// BabyShoesSizeConvertInfo.swift
// selluv-ios
//
// Created by 조백근 on 2016. 12. 8..
// Copyright © 2016년 BitBoy Labs. All rights reserved.
//
import RealmSwift
class BabyShoesSizeConvertInfo: Object {
dynamic var std = ""
dynamic var mm = ""
dynamic var us = ""
dynamic var eu = ""
dynamic var uk = ""
public func setupIndexes() {
self.std.indexTag = 0
self.mm.indexTag = 1
self.us.indexTag = 2
self.eu.indexTag = 3
self.uk.indexTag = 4
}
public static func displayNamesByTag() -> [String] {
return [SIZE_MM, SIZE_US, SIZE_EU, SIZE_UK]
}
public static func propertyName(displayName: String) -> String {
if displayName == SIZE_MM { return "mm"}
else if displayName == SIZE_US { return "us"}
else if displayName == SIZE_EU { return "eu"}
else if displayName == SIZE_UK { return "uk"}
return ""
}
public static func propertyIndex(displayName: String) -> String {
if displayName == SIZE_MM { return "0"}
else if displayName == SIZE_US { return "1"}
else if displayName == SIZE_EU { return "2"}
else if displayName == SIZE_UK { return "3"}
return "99"
}
public func sizeValues() -> [String] {
return [(self.mm.copy() as! String), (self.us.copy() as! String), (self.eu.copy() as! String), (self.uk.copy() as! String)]
}
override static func primaryKey() -> String? {
return "std"
}
}
| 101f770e284a2970c39621a2cf74302c | 27.018182 | 131 | 0.570409 | false | false | false | false |
jisudong/study | refs/heads/master | RxSwift-master/RxSwift/Traits/PrimitiveSequence.swift | mit | 1 | //
// PrimitiveSequence.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/5/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
/// Observable sequences containing 0 or 1 element.
public struct PrimitiveSequence<Trait, Element> {
fileprivate let source: Observable<Element>
init(raw: Observable<Element>) {
self.source = raw
}
}
/// Sequence containing exactly 1 element
public enum SingleTrait { }
/// Represents a push style sequence containing 1 element.
public typealias Single<Element> = PrimitiveSequence<SingleTrait, Element>
/// Sequence containing 0 or 1 elements
public enum MaybeTrait { }
/// Represents a push style sequence containing 0 or 1 element.
public typealias Maybe<Element> = PrimitiveSequence<MaybeTrait, Element>
/// Sequence containing 0 elements
public enum CompletableTrait { }
/// Represents a push style sequence containing 0 elements.
public typealias Completable = PrimitiveSequence<CompletableTrait, Swift.Never>
/// Observable sequences containing 0 or 1 element
public protocol PrimitiveSequenceType {
/// Additional constraints
associatedtype TraitType
/// Sequence element type
associatedtype ElementType
// Converts `self` to primitive sequence.
///
/// - returns: Observable sequence that represents `self`.
var primitiveSequence: PrimitiveSequence<TraitType, ElementType> { get }
}
extension PrimitiveSequence: PrimitiveSequenceType {
/// Additional constraints
public typealias TraitType = Trait
/// Sequence element type
public typealias ElementType = Element
// Converts `self` to primitive sequence.
///
/// - returns: Observable sequence that represents `self`.
public var primitiveSequence: PrimitiveSequence<TraitType, ElementType> {
return self
}
}
extension PrimitiveSequence: ObservableConvertibleType {
/// Type of elements in sequence.
public typealias E = Element
/// Converts `self` to `Observable` sequence.
///
/// - returns: Observable sequence that represents `self`.
public func asObservable() -> Observable<E> {
return source
}
}
// <Single>
public enum SingleEvent<Element> {
/// One and only sequence element is produced. (underlying observable sequence emits: `.next(Element)`, `.completed`)
case success(Element)
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
}
extension PrimitiveSequenceType where TraitType == SingleTrait {
public typealias SingleObserver = (SingleEvent<ElementType>) -> ()
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(subscribe: @escaping (@escaping SingleObserver) -> Disposable) -> PrimitiveSequence<TraitType, ElementType> {
let source = Observable<ElementType>.create { observer in
return subscribe { event in
switch event {
case .success(let element):
observer.on(.next(element))
observer.on(.completed)
case .error(let error):
observer.on(.error(error))
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (SingleEvent<ElementType>) -> ()) -> Disposable {
var stopped = false
return self.primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case .next(let element):
observer(.success(element))
case .error(let error):
observer(.error(error))
case .completed:
rxFatalErrorInDebug("Singles can't emit a completion event")
}
}
}
/**
Subscribes a success handler, and an error handler for this sequence.
- parameter onSuccess: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onSuccess: ((ElementType) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil) -> Disposable {
return self.primitiveSequence.subscribe { event in
switch event {
case .success(let element):
onSuccess?(element)
case .error(let error):
onError?(error)
}
}
}
}
// </Single>
// <Maybe>
public enum MaybeEvent<Element> {
/// One and only sequence element is produced. (underlying observable sequence emits: `.next(Element)`, `.completed`)
case success(Element)
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
/// Sequence completed successfully.
case completed
}
public extension PrimitiveSequenceType where TraitType == MaybeTrait {
public typealias MaybeObserver = (MaybeEvent<ElementType>) -> ()
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(subscribe: @escaping (@escaping MaybeObserver) -> Disposable) -> PrimitiveSequence<TraitType, ElementType> {
let source = Observable<ElementType>.create { observer in
return subscribe { event in
switch event {
case .success(let element):
observer.on(.next(element))
observer.on(.completed)
case .error(let error):
observer.on(.error(error))
case .completed:
observer.on(.completed)
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (MaybeEvent<ElementType>) -> ()) -> Disposable {
var stopped = false
return self.primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case .next(let element):
observer(.success(element))
case .error(let error):
observer(.error(error))
case .completed:
observer(.completed)
}
}
}
/**
Subscribes a success handler, an error handler, and a completion handler for this sequence.
- parameter onSuccess: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onSuccess: ((ElementType) -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil, onCompleted: (() -> Void)? = nil) -> Disposable {
return self.primitiveSequence.subscribe { event in
switch event {
case .success(let element):
onSuccess?(element)
case .error(let error):
onError?(error)
case .completed:
onCompleted?()
}
}
}
}
// </Maybe>
// <Completable>
public enum CompletableEvent {
/// Sequence terminated with an error. (underlying observable sequence emits: `.error(Error)`)
case error(Swift.Error)
/// Sequence completed successfully.
case completed
}
public extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Swift.Never {
public typealias CompletableObserver = (CompletableEvent) -> ()
/**
Creates an observable sequence from a specified subscribe method implementation.
- seealso: [create operator on reactivex.io](http://reactivex.io/documentation/operators/create.html)
- parameter subscribe: Implementation of the resulting observable sequence's `subscribe` method.
- returns: The observable sequence with the specified implementation for the `subscribe` method.
*/
public static func create(subscribe: @escaping (@escaping CompletableObserver) -> Disposable) -> PrimitiveSequence<TraitType, ElementType> {
let source = Observable<ElementType>.create { observer in
return subscribe { event in
switch event {
case .error(let error):
observer.on(.error(error))
case .completed:
observer.on(.completed)
}
}
}
return PrimitiveSequence(raw: source)
}
/**
Subscribes `observer` to receive events for this sequence.
- returns: Subscription for `observer` that can be used to cancel production of sequence elements and free resources.
*/
public func subscribe(_ observer: @escaping (CompletableEvent) -> ()) -> Disposable {
var stopped = false
return self.primitiveSequence.asObservable().subscribe { event in
if stopped { return }
stopped = true
switch event {
case .next:
rxFatalError("Completables can't emit values")
case .error(let error):
observer(.error(error))
case .completed:
observer(.completed)
}
}
}
/**
Subscribes a completion handler and an error handler for this sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- returns: Subscription object used to unsubscribe from the observable sequence.
*/
public func subscribe(onCompleted: (() -> Void)? = nil, onError: ((Swift.Error) -> Void)? = nil) -> Disposable {
return self.primitiveSequence.subscribe { event in
switch event {
case .error(let error):
onError?(error)
case .completed:
onCompleted?()
}
}
}
}
// </Completable>
extension PrimitiveSequence {
/**
Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
- seealso: [defer operator on reactivex.io](http://reactivex.io/documentation/operators/defer.html)
- parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence.
- returns: An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
public static func deferred(_ observableFactory: @escaping () throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.deferred {
try observableFactory().asObservable()
})
}
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: Element) -> PrimitiveSequence<Trait, ElementType> {
return PrimitiveSequence(raw: Observable.just(element))
}
/**
Returns an observable sequence that contains a single element.
- seealso: [just operator on reactivex.io](http://reactivex.io/documentation/operators/just.html)
- parameter element: Single element in the resulting observable sequence.
- parameter: Scheduler to send the single element on.
- returns: An observable sequence containing the single specified element.
*/
public static func just(_ element: Element, scheduler: ImmediateSchedulerType) -> PrimitiveSequence<Trait, ElementType> {
return PrimitiveSequence(raw: Observable.just(element, scheduler: scheduler))
}
/**
Returns an observable sequence that terminates with an `error`.
- seealso: [throw operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: The observable sequence that terminates with specified error.
*/
public static func error(_ error: Swift.Error) -> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.error(error))
}
/**
Returns a non-terminating observable sequence, which can be used to denote an infinite duration.
- seealso: [never operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence whose observers will never get called.
*/
public static func never() -> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.never())
}
/**
Time shifts the observable sequence by delaying the subscription with the specified relative time duration, using the specified scheduler to run timers.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the subscription.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: Time-shifted sequence.
*/
public func delaySubscription(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.delaySubscription(dueTime, scheduler: scheduler))
}
/**
Returns an observable sequence by the source observable sequence shifted forward in time by a specified delay. Error events from the source observable sequence are not delayed.
- seealso: [delay operator on reactivex.io](http://reactivex.io/documentation/operators/delay.html)
- parameter dueTime: Relative time shift of the source by.
- parameter scheduler: Scheduler to run the subscription delay timer on.
- returns: the source Observable shifted in time by the specified delay.
*/
public func delay(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.delay(dueTime, scheduler: scheduler))
}
/**
Invokes an action for each event in the observable sequence, and propagates all observer messages through the result sequence.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter onNext: Action to invoke for each element in the observable sequence.
- parameter onError: Action to invoke upon errored termination of the observable sequence.
- parameter onCompleted: Action to invoke upon graceful termination of the observable sequence.
- parameter onSubscribe: Action to invoke before subscribing to source observable sequence.
- parameter onSubscribed: Action to invoke after subscribing to source observable sequence.
- parameter onDispose: Action to invoke after subscription to source observable has been disposed for any reason. It can be either because sequence terminates for some reason or observer subscription being disposed.
- returns: The source sequence with the side-effecting behavior applied.
*/
public func `do`(onNext: ((E) throws -> Void)? = nil, onError: ((Swift.Error) throws -> Void)? = nil, onCompleted: (() throws -> Void)? = nil, onSubscribe: (() -> ())? = nil, onSubscribed: (() -> ())? = nil, onDispose: (() -> ())? = nil)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.do(
onNext: onNext,
onError: onError,
onCompleted: onCompleted,
onSubscribe: onSubscribe,
onSubscribed: onSubscribed,
onDispose: onDispose)
)
}
/**
Filters the elements of an observable sequence based on a predicate.
- seealso: [filter operator on reactivex.io](http://reactivex.io/documentation/operators/filter.html)
- parameter predicate: A function to test each source element for a condition.
- returns: An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
public func filter(_ predicate: @escaping (E) throws -> Bool)
-> Maybe<Element> {
return Maybe(raw: source.filter(predicate))
}
/**
Projects each element of an observable sequence into a new form.
- seealso: [map operator on reactivex.io](http://reactivex.io/documentation/operators/map.html)
- parameter transform: A transform function to apply to each source element.
- returns: An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
public func map<R>(_ transform: @escaping (E) throws -> R)
-> PrimitiveSequence<Trait, R> {
return PrimitiveSequence<Trait, R>(raw: source.map(transform))
}
/**
Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
- seealso: [flatMap operator on reactivex.io](http://reactivex.io/documentation/operators/flatmap.html)
- parameter selector: A transform function to apply to each element.
- returns: An observable sequence whose elements are the result of invoking the one-to-many transform function on each element of the input sequence.
*/
public func flatMap<R>(_ selector: @escaping (ElementType) throws -> PrimitiveSequence<Trait, R>)
-> PrimitiveSequence<Trait, R> {
return PrimitiveSequence<Trait, R>(raw: source.flatMap(selector))
}
/**
Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
This only invokes observer callbacks on a `scheduler`. In case the subscription and/or unsubscription
actions have side-effects that require to be run on a scheduler, use `subscribeOn`.
- seealso: [observeOn operator on reactivex.io](http://reactivex.io/documentation/operators/observeon.html)
- parameter scheduler: Scheduler to notify observers on.
- returns: The source sequence whose observations happen on the specified scheduler.
*/
public func observeOn(_ scheduler: ImmediateSchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.observeOn(scheduler))
}
/**
Wraps the source sequence in order to run its subscription and unsubscription logic on the specified
scheduler.
This operation is not commonly used.
This only performs the side-effects of subscription and unsubscription on the specified scheduler.
In order to invoke observer callbacks on a `scheduler`, use `observeOn`.
- seealso: [subscribeOn operator on reactivex.io](http://reactivex.io/documentation/operators/subscribeon.html)
- parameter scheduler: Scheduler to perform subscription and unsubscription actions on.
- returns: The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
public func subscribeOn(_ scheduler: ImmediateSchedulerType)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.subscribeOn(scheduler))
}
/**
Continues an observable sequence that is terminated by an error with the observable sequence produced by the handler.
- seealso: [catch operator on reactivex.io](http://reactivex.io/documentation/operators/catch.html)
- parameter handler: Error handler function, producing another observable sequence.
- returns: An observable sequence containing the source sequence's elements, followed by the elements produced by the handler's resulting observable sequence in case an error occurred.
*/
public func catchError(_ handler: @escaping (Swift.Error) throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.catchError { try handler($0).asObservable() })
}
/**
Repeats the source observable sequence the specified number of times in case of an error or until it successfully terminates.
If you encounter an error and want it to retry once, then you must use `retry(2)`
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter maxAttemptCount: Maximum number of times to repeat the sequence.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
public func retry(_ maxAttemptCount: Int)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retry(maxAttemptCount))
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType, Error: Swift.Error>(_ notificationHandler: @escaping (Observable<Error>) -> TriggerObservable)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retryWhen(notificationHandler))
}
/**
Repeats the source observable sequence on error when the notifier emits a next value.
If the source observable errors and the notifier completes, it will complete the source sequence.
- seealso: [retry operator on reactivex.io](http://reactivex.io/documentation/operators/retry.html)
- parameter notificationHandler: A handler that is passed an observable sequence of errors raised by the source observable and returns and observable that either continues, completes or errors. This behavior is then applied to the source observable.
- returns: An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully or is notified to error or complete.
*/
public func retryWhen<TriggerObservable: ObservableType>(_ notificationHandler: @escaping (Observable<Swift.Error>) -> TriggerObservable)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.retryWhen(notificationHandler))
}
/**
Prints received events for all observers on standard output.
- seealso: [do operator on reactivex.io](http://reactivex.io/documentation/operators/do.html)
- parameter identifier: Identifier that is printed together with event description to standard output.
- parameter trimOutput: Should output be trimmed to max 40 characters.
- returns: An observable sequence whose events are printed to standard output.
*/
public func debug(_ identifier: String? = nil, trimOutput: Bool = false, file: String = #file, line: UInt = #line, function: String = #function)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: source.debug(identifier, trimOutput: trimOutput, file: file, line: line, function: function))
}
/**
Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
- seealso: [using operator on reactivex.io](http://reactivex.io/documentation/operators/using.html)
- parameter resourceFactory: Factory function to obtain a resource object.
- parameter primitiveSequenceFactory: Factory function to obtain an observable sequence that depends on the obtained resource.
- returns: An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
public static func using<Resource: Disposable>(_ resourceFactory: @escaping () throws -> Resource, primitiveSequenceFactory: @escaping (Resource) throws -> PrimitiveSequence<Trait, Element>)
-> PrimitiveSequence<Trait, Element> {
return PrimitiveSequence(raw: Observable.using(resourceFactory, observableFactory: { (resource: Resource) throws -> Observable<E> in
return try primitiveSequenceFactory(resource).asObservable()
}))
}
}
extension PrimitiveSequenceType where ElementType: SignedInteger
{
/**
Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers.
- seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html)
- parameter dueTime: Relative time at which to produce the first value.
- parameter scheduler: Scheduler to run timers on.
- returns: An observable sequence that produces a value after due time has elapsed and then each period.
*/
public static func timer(_ dueTime: RxTimeInterval, scheduler: SchedulerType)
-> PrimitiveSequence<TraitType, ElementType> {
return PrimitiveSequence(raw: Observable<ElementType>.timer(dueTime, scheduler: scheduler))
}
}
extension PrimitiveSequenceType where TraitType == MaybeTrait {
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
public static func empty() -> PrimitiveSequence<MaybeTrait, ElementType> {
return PrimitiveSequence(raw: Observable.empty())
}
}
extension PrimitiveSequenceType where TraitType == CompletableTrait, ElementType == Never {
/**
Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message.
- seealso: [empty operator on reactivex.io](http://reactivex.io/documentation/operators/empty-never-throw.html)
- returns: An observable sequence with no elements.
*/
public static func empty() -> PrimitiveSequence<CompletableTrait, Never> {
return PrimitiveSequence(raw: Observable.empty())
}
/**
Concatenates the second observable sequence to `self` upon successful termination of `self`.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- parameter second: Second observable sequence.
- returns: An observable sequence that contains the elements of `self`, followed by those of the second sequence.
*/
public func concat(_ second: PrimitiveSequence<CompletableTrait, Never>) -> PrimitiveSequence<CompletableTrait, Never> {
return Completable.concat(primitiveSequence, second)
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<S: Sequence>(_ sequence: S) -> PrimitiveSequence<CompletableTrait, Never>
where S.Iterator.Element == PrimitiveSequence<CompletableTrait, Never> {
let source = Observable.concat(sequence.lazy.map { $0.asObservable() })
return PrimitiveSequence<CompletableTrait, Never>(raw: source)
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat<C: Collection>(_ collection: C) -> PrimitiveSequence<CompletableTrait, Never>
where C.Iterator.Element == PrimitiveSequence<CompletableTrait, Never> {
let source = Observable.concat(collection.map { $0.asObservable() })
return PrimitiveSequence<CompletableTrait, Never>(raw: source)
}
/**
Concatenates all observable sequences in the given sequence, as long as the previous observable sequence terminated successfully.
- seealso: [concat operator on reactivex.io](http://reactivex.io/documentation/operators/concat.html)
- returns: An observable sequence that contains the elements of each given sequence, in sequential order.
*/
public static func concat(_ sources: PrimitiveSequence<CompletableTrait, Never> ...) -> PrimitiveSequence<CompletableTrait, Never> {
let source = Observable.concat(sources.map { $0.asObservable() })
return PrimitiveSequence<CompletableTrait, Never>(raw: source)
}
/**
Merges elements from all observable sequences from collection into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge<C: Collection>(_ sources: C) -> PrimitiveSequence<CompletableTrait, Never>
where C.Iterator.Element == PrimitiveSequence<CompletableTrait, Never> {
let source = Observable.merge(sources.map { $0.asObservable() })
return PrimitiveSequence<CompletableTrait, Never>(raw: source)
}
/**
Merges elements from all observable sequences from array into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Array of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge(_ sources: [PrimitiveSequence<CompletableTrait, Never>]) -> PrimitiveSequence<CompletableTrait, Never> {
let source = Observable.merge(sources.map { $0.asObservable() })
return PrimitiveSequence<CompletableTrait, Never>(raw: source)
}
/**
Merges elements from all observable sequences into a single observable sequence.
- seealso: [merge operator on reactivex.io](http://reactivex.io/documentation/operators/merge.html)
- parameter sources: Collection of observable sequences to merge.
- returns: The observable sequence that merges the elements of the observable sequences.
*/
public static func merge(_ sources: PrimitiveSequence<CompletableTrait, Never>...) -> PrimitiveSequence<CompletableTrait, Never> {
let source = Observable.merge(sources.map { $0.asObservable() })
return PrimitiveSequence<CompletableTrait, Never>(raw: source)
}
}
extension ObservableType {
/**
The `asSingle` operator throws a `RxError.noElements` or `RxError.moreThanOneElement`
if the source Observable does not emit exactly one element before successfully completing.
- seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html)
- returns: An observable sequence that emits a single element or throws an exception if more (or none) of them are emitted.
*/
public func asSingle() -> Single<E> {
return PrimitiveSequence(raw: AsSingle(source: self.asObservable()))
}
/**
The `asMaybe` operator throws a ``RxError.moreThanOneElement`
if the source Observable does not emit at most one element before successfully completing.
- seealso: [single operator on reactivex.io](http://reactivex.io/documentation/operators/first.html)
- returns: An observable sequence that emits a single element, completes or throws an exception if more of them are emitted.
*/
public func asMaybe() -> Maybe<E> {
return PrimitiveSequence(raw: AsMaybe(source: self.asObservable()))
}
}
extension ObservableType where E == Never {
/**
- returns: An observable sequence that completes.
*/
public func asCompletable()
-> Completable {
return PrimitiveSequence(raw: self.asObservable())
}
}
| 32f74f981ae329f03f34a19c28e01fab | 43.826597 | 254 | 0.69516 | false | false | false | false |
TintPoint/Resource | refs/heads/master | Sources/Resources/LocalizedStringResource.swift | mit | 1 | //
// LocalizedStringResource.swift
// Resource
//
// Created by Justin Jia on 11/6/16.
// Copyright © 2016 TintPoint. MIT license.
//
/// A protocol that describes an item that can represent a localized string.
public protocol LocalizedStringDescribing {
/// The `String` that represents the key of the localized string.
var key: String { get }
/// The `String` that represents the table name of the localized string.
var tableName: String? { get }
/// The `Bundle` that represents the bundle of the localized string.
var bundle: Bundle { get }
/// The `String` that represents the value of the localized string.
var value: String { get }
/// The `String` that represents the comment of the localized string.
var comment: String { get }
/// The array of `Any` that represents the arguments of the localized string.
var arguments: [Any]? { get }
}
public extension LocalizedStringDescribing {
var tableName: String? {
return nil
}
var bundle: Bundle {
return .main
}
var value: String {
return ""
}
var comment: String {
return ""
}
var arguments: [Any]? {
return nil
}
}
/// A struct that describes an item that can represent a localized string.
public struct LocalizedStringDescription: LocalizedStringDescribing {
/// The `String` that represents the key of the localized string.
public let key: String
/// The `String` that represents the table name of the localized string.
public let tableName: String?
/// The `Bundle` that represents the bundle of the localized string.
public let bundle: Bundle
/// The `String` that represents the value of the localized string.
public let value: String
/// The `String` that represents the comment of the localized string.
public let comment: String
/// The array of `Any` that represents the arguments of the localized string.
public let arguments: [Any]?
public init(key: String, tableName: String? = nil, bundle: Bundle = .main, value: String = "", comment: String = "", arguments: [Any]? = nil) {
self.key = key
self.tableName = tableName
self.bundle = bundle
self.value = value
self.comment = comment
self.arguments = arguments
}
}
public extension Resource {
/// Returns a `String` that is represented by the item that conforms to `LocalizedStringDescribing`.
/// - Parameter describing: An item that conforms to `LocalizedStringDescribing`.
/// - Returns: A represented localized string.
static func of(_ describing: LocalizedStringDescribing) -> String {
let localizedString = NSLocalizedString(describing.key, tableName: describing.tableName, bundle: describing.bundle, value: describing.value, comment: describing.comment)
guard let arguments = describing.arguments as? [CVarArg] else {
return localizedString
}
return String(format: localizedString, arguments: arguments)
}
}
| 7f23e1d46006ad4d9750c938e856dbee | 31.795699 | 177 | 0.673115 | false | false | false | false |
MakeAWishFoundation/SwiftyMocky | refs/heads/master | SwiftyMocky-Example/Shared/AssociatedTypes/SuggestionRepository.swift | mit | 1 | //
// SuggestionRepository.swift
// SwiftyMocky
//
// Created by Andrzej Michnia on 11/11/2019.
// Copyright © 2019 CocoaPods. All rights reserved.
//
import Foundation
//sourcery: AutoMockable
//sourcery: typealias = "Entity = Suggestion"
protocol SuggestionRepository: Repository where Entity == Suggestion {}
//sourcery: AutoMockable
//sourcery: associatedtype = "Entity: SuggestionProtocol"
protocol SuggestionRepositoryConstrainedToProtocol: Repository where Entity: SuggestionProtocol {}
protocol Repository {
associatedtype Entity: EntityType
func save(entity: Entity) -> Bool
func save(entities: [Entity]) -> Bool
func find(
where predicate: NSPredicate,
sortedBy sortDescriptors: [NSSortDescriptor]
) -> [Entity]
func findOne(where predicate: NSPredicate) -> Entity
func delete(entity: Entity) -> Bool
func delete(entities: [Entity]) -> Bool
}
protocol EntityType {}
protocol SuggestionProtocol: EntityType, AutoMockable { }
class Suggestion: SuggestionProtocol {
init() {}
}
| 1a59a1b8a833768f7a949291816963f1 | 24.634146 | 98 | 0.727878 | false | false | false | false |
steelwheels/Coconut | refs/heads/master | CoconutData/Source/Value/CNStorageArray.swift | lgpl-2.1 | 1 | /**
* @file CNStorageArray.swift
* @brief Define CNStorageArray class
* @par Copyright
* Copyright (C) 2022 Steel Wheels Project
*/
import Foundation
public protocol CNArray
{
var count: Int { get }
var values: Array<CNValue> { get }
func value(at index: Int) -> CNValue?
func contains(value src: CNValue) -> Bool
func set(value src: CNValue, at index: Int) -> Bool
func append(value src: CNValue) -> Bool
}
public class CNStorageArray: CNArray
{
private var mPath: CNValuePath
private var mStorage: CNStorage
public init(path pth: CNValuePath, storage strg: CNStorage) {
mPath = pth
mStorage = strg
/* Check */
let _ = getArrayValue()
}
public var count: Int { get {
if let arr = getArrayValue() {
return arr.count
} else {
return 0
}
}}
public var values: Array<CNValue> { get {
if let arr = getArrayValue() {
return arr
} else {
return []
}
}}
public func value(at index: Int) -> CNValue? {
return mStorage.value(forPath: indexPath(index: index))
}
public func set(value src: CNValue, at index: Int) -> Bool {
return mStorage.set(value: src, forPath: indexPath(index: index))
}
public func append(value src: CNValue) -> Bool {
return mStorage.append(value: src, forPath: mPath)
}
public func contains(value src: CNValue) -> Bool {
if let vals = getArrayValue() {
for val in vals {
switch CNCompareValue(nativeValue0: src, nativeValue1: val) {
case .orderedAscending: // src < val[x]
break // continue
case .orderedSame: // src == vals[x]
return true
case .orderedDescending:
break // contibue
}
}
}
return false
}
private func indexPath(index idx: Int) -> CNValuePath {
return CNValuePath(path: mPath, subPath: [.index(idx)])
}
private func getArrayValue() -> Array<CNValue>? {
if let val = mStorage.value(forPath: mPath) {
switch val {
case .arrayValue(let arr):
return arr
default:
break
}
}
CNLog(logLevel: .error, message: "Not array value", atFunction: #function, inFile: #file)
return nil
}
}
| da2157d57905dc93ab86d79b5dcb2747 | 20.329897 | 91 | 0.659739 | false | false | false | false |
Restofire/Restofire | refs/heads/master | Sources/Extensions/Restofire+Logging.swift | mit | 1 | //
// Restofire+RequestLogging.swift
// Restofire
//
// Created by Rahul Katariya on 30/01/18.
// Copyright © 2018 Restofire. All rights reserved.
//
import Foundation
import Alamofire
extension Request {
func logRequestIfNeeded() {
if let argumentIndex = ProcessInfo.processInfo.arguments
.firstIndex(of: "-org.restofire.Restofire.Debug") {
let logLevel = ProcessInfo.processInfo.arguments[argumentIndex+1]
underlyingQueue.sync {
if logLevel == "1" {
print("/**************************************** Request ****************************************/")
print(self.cURLDescription())
print("/**************************************** RequestEnd ****************************************/")
}
}
}
}
func logDataRequestIfNeeded(result: DataResponse<Data?>) {
if let argumentIndex = ProcessInfo.processInfo.arguments
.firstIndex(of: "-org.restofire.Restofire.Debug") {
underlyingQueue.sync { [unowned self] in
let logLevel = ProcessInfo.processInfo.arguments[argumentIndex + 1]
if logLevel == "2" {
print("/**************************************** Response ****************************************/")
print(self.response.debugDescription)
print("/**************************************** ResponseEnd ****************************************/")
} else if logLevel == "3" {
print("/**************************************** Request ****************************************/")
print(self.cURLDescription())
print("/**************************************** RequestEnd ****************************************/")
print("")
print("/**************************************** Response ****************************************/")
print(self.response.debugDescription)
print("/**************************************** ResponseEnd ****************************************/")
let value = String(data: result.data ?? Data(), encoding: .utf8)
print("")
print("/**************************************** Result ****************************************/")
print(value ?? result.error.debugDescription)
print("/**************************************** ResultEnd ****************************************/")
}
}
}
}
func logDownloadRequestIfNeeded(result: DownloadResponse<URL?>) {
if let argumentIndex = ProcessInfo.processInfo.arguments
.firstIndex(of: "-org.restofire.Restofire.Debug") {
underlyingQueue.sync { [unowned self] in
let logLevel = ProcessInfo.processInfo.arguments[argumentIndex + 1]
if logLevel == "2" {
print("/**************************************** Response ****************************************/")
print(self.response.debugDescription)
print("/**************************************** ResponseEnd ****************************************/")
} else if logLevel == "3" {
print("/**************************************** Request ****************************************/")
print(self.cURLDescription())
print("/**************************************** RequestEnd ****************************************/")
print("/**************************************** Response ****************************************/")
print(self.response.debugDescription)
print("/**************************************** ResponseEnd ****************************************/")
print("/**************************************** Result ****************************************/")
print(result.fileURL ?? result.error.debugDescription)
print("/**************************************** ResultEnd ****************************************/")
}
}
}
}
}
| 0ec4697ab28e9d350235e3a1197bb6b6 | 55.805195 | 124 | 0.329218 | false | false | false | false |
pentateu/SwiftCrypt | refs/heads/master | SwiftCrypt/KeyPair.swift | mit | 1 | //
// KeyPairService.swift
// SwiftCrypt
//
// Created by Rafael Almeida on 12/10/14.
// Copyright (c) 2014 ISWE. All rights reserved.
//
import Foundation
class KeyPair: SecKeyBase {
let kSecPrivateKeyAttrsValue = kSecPrivateKeyAttrs.takeUnretainedValue() as! NSCopying
let kSecPublicKeyAttrsValue = kSecPublicKeyAttrs.takeUnretainedValue() as! NSCopying
//The example uses 512 . I was trying 1024
let keySize:CFNumberRef = 1024
var privateTag: NSData
var publicTag: NSData
var publicKeyRef: SecKeyRef?
var privateKeyRef: SecKeyRef?
init(privateTagIdentifier:String, pulicTagIdentifier:String){
privateTag = (privateTagIdentifier as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
publicTag = (pulicTagIdentifier as NSString).dataUsingEncoding(NSUTF8StringEncoding)!
super.init(keyType: kSecAttrKeyTypeRSA)
}
func createPublicKeyQueryParams() -> NSMutableDictionary {
return createBaiscKeyQueryParams(publicTag)
}
func createPrivateKeyQueryParams() -> NSMutableDictionary {
return createBaiscKeyQueryParams(privateTag)
}
func deleteKeyPair(){
deleteItem(createPrivateKeyQueryParams())
deleteItem(createPublicKeyQueryParams())
}
func generateKeyPair() {
deleteKeyPair()
// Set top level dictionary for the keypair.
let keyPairAttr: NSMutableDictionary = NSMutableDictionary()
keyPairAttr.setObject(keyType, forKey:kSecAttrKeyType as String)
keyPairAttr.setObject(keySize, forKey:kSecAttrKeySizeInBits as String)
// Set the private key dictionary.
let privateKeyAttr: NSMutableDictionary = NSMutableDictionary()
privateKeyAttr.setObject(NYES, forKey: kSecAttrIsPermanent as String)
privateKeyAttr.setObject(privateTag, forKey: kSecAttrApplicationTag as String)
// Set the public key dictionary.
let publicKeyAttr: NSMutableDictionary = NSMutableDictionary()
publicKeyAttr.setObject(NYES, forKey: kSecAttrIsPermanent as String)
publicKeyAttr.setObject(publicTag, forKey: kSecAttrApplicationTag as String)
// Set attributes to top level dictionary.
keyPairAttr.setObject(privateKeyAttr, forKey:kSecPrivateKeyAttrsValue)
keyPairAttr.setObject(publicKeyAttr, forKey:kSecPublicKeyAttrsValue)
var uPublicKeyRef: Unmanaged<SecKeyRef>?
var uPrivateKeyRef: Unmanaged<SecKeyRef>?
// SecKeyGeneratePair returns the SecKeyRefs just for educational purposes.
let sanityCheck = SecKeyGeneratePair(keyPairAttr as CFDictionaryRef, &uPublicKeyRef, &uPrivateKeyRef)
if(sanityCheck == noErr && uPublicKeyRef?.takeUnretainedValue() != nil && uPrivateKeyRef?.takeUnretainedValue() != nil){
println("Keys generated with success!");
publicKeyRef = uPublicKeyRef?.takeRetainedValue()
privateKeyRef = uPrivateKeyRef?.takeRetainedValue()
}
else{
println("Something really bad went wrong with generating the key pair.")
}
}
func getPublicKeyRef() -> SecKeyRef?{
if publicKeyRef == nil {
let query = createBaiscKeyQueryParams(publicTag)
query.setObject(NYES, forKey: kSecReturnRef as String)
var queryResult:AnyObject? = queryObject(query)
if let queryResultObj:AnyObject = queryResult {
publicKeyRef = queryResultObj as! SecKeyRef
}
}
return publicKeyRef
}
func getPrivateKeyRef() -> SecKeyRef?{
if privateKeyRef == nil {
let query = createBaiscKeyQueryParams(privateTag)
query.setObject(NYES, forKey: kSecReturnRef as String)
var queryResult:AnyObject? = queryObject(query)
if let queryResultObj:AnyObject = queryResult {
privateKeyRef = queryResultObj as! SecKeyRef
}
}
return privateKeyRef
}
func getPublicKeyBits() -> NSData? {
return getKeyBits(publicTag)
}
func getPrivateKeyBits() -> NSData? {
return getKeyBits(privateTag)
}
} | 614ba82c2b7e3dae032a3aae413c42af | 34.430894 | 128 | 0.65871 | false | false | false | false |
bugcoding/macOSCalendar | refs/heads/master | MacCalendar/PlanetData.swift | gpl-2.0 | 1 | //
// PlanetData.swift
// MacCalendar
//
// Created by bugcode on 16/8/19.
// // 本文件内容移植自<算法的乐趣>书中附带示例代码,源文件代码为c++,如有不妥请告知
//
import Foundation
// 行星数据
class PlanetData{
// VSOP_87
struct VSOP87_COEFFICIENT{
var A:Double
var B:Double
var C:Double
init(_ a:Double,_ b:Double,_ c:Double){
A = a
B = b
C = c
}
}
static let Earth_L0:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 175347046.0 , 0.0000000 , 000000.0000000 ) ,
VSOP87_COEFFICIENT( 3341656.0 , 4.6692568 , 6283.0758500 ) ,
VSOP87_COEFFICIENT( 34894.0 , 4.6261000 , 12566.1517000 ) ,
VSOP87_COEFFICIENT( 3497.0 , 2.7441000 , 5753.3849000 ) ,
VSOP87_COEFFICIENT( 3418.0 , 2.8289000 , 3.5231000 ) ,
VSOP87_COEFFICIENT( 3136.0 , 3.6277000 , 77713.7715000 ) ,
VSOP87_COEFFICIENT( 2676.0 , 4.4181000 , 7860.4194000 ) ,
VSOP87_COEFFICIENT( 2343.0 , 6.1352000 , 3930.2097000 ) ,
VSOP87_COEFFICIENT( 1324.0 , 0.7425000 , 11506.7698000 ) ,
VSOP87_COEFFICIENT( 1273.0 , 2.0371000 , 529.6910000 ) ,
VSOP87_COEFFICIENT( 1799.0 , 1.1096000 , 1577.3435000 ) ,
VSOP87_COEFFICIENT( 990.0 , 5.2330000 , 5884.9270000 ) ,
VSOP87_COEFFICIENT( 902.0 , 2.0450000 , 26.2980000 ) ,
VSOP87_COEFFICIENT( 857.0 , 3.5080000 , 398.1490000 ) ,
VSOP87_COEFFICIENT( 780.0 , 1.1790000 , 5223.6940000 ) ,
VSOP87_COEFFICIENT( 753.0 , 2.5330000 , 5507.5530000 ) ,
VSOP87_COEFFICIENT( 505.0 , 4.5830000 , 18849.2280000 ) ,
VSOP87_COEFFICIENT( 492.0 , 4.2050000 , 775.5230000 ) ,
VSOP87_COEFFICIENT( 357.0 , 2.9200000 , 000000.0670000 ) ,
VSOP87_COEFFICIENT( 317.0 , 5.8490000 , 11790.6290000 ) ,
VSOP87_COEFFICIENT( 284.0 , 1.8990000 , 796.2980000 ) ,
VSOP87_COEFFICIENT( 271.0 , 0.3150000 , 10977.0790000 ) ,
VSOP87_COEFFICIENT( 243.0 , 0.3450000 , 5486.7780000 ) ,
VSOP87_COEFFICIENT( 206.0 , 4.8060000 , 2544.3140000 ) ,
VSOP87_COEFFICIENT( 205.0 , 1.8690000 , 5573.1430000 ) ,
VSOP87_COEFFICIENT( 202.0 , 2.4580000 , 6069.7770000 ) ,
VSOP87_COEFFICIENT( 156.0 , 0.8330000 , 213.2990000 ) ,
VSOP87_COEFFICIENT( 132.0 , 3.4110000 , 2942.4630000 ) ,
VSOP87_COEFFICIENT( 126.0 , 1.0830000 , 20.7750000 ) ,
VSOP87_COEFFICIENT( 119.0 , 0.6450000 , 000000.9800000 ) ,
VSOP87_COEFFICIENT( 107.0 , 0.6360000 , 4694.0030000 ) ,
VSOP87_COEFFICIENT( 102.0 , 0.9760000 , 15720.8390000 ) ,
VSOP87_COEFFICIENT( 102.0 , 4.2670000 , 7.1140000 ) ,
VSOP87_COEFFICIENT( 99.0 , 6.2100000 , 2146.1700000 ) ,
VSOP87_COEFFICIENT( 98.0 , 0.6800000 , 155.4200000 ) ,
VSOP87_COEFFICIENT( 86.0 , 5.9800000 , 161000.6900000 ) ,
VSOP87_COEFFICIENT( 85.0 , 1.3000000 , 6275.9600000 ) ,
VSOP87_COEFFICIENT( 85.0 , 3.6700000 , 71430.7000000 ) ,
VSOP87_COEFFICIENT( 80.0 , 1.8100000 , 17260.1500000 ) ,
VSOP87_COEFFICIENT( 79.0 , 3.0400000 , 12036.4600000 ) ,
VSOP87_COEFFICIENT( 75.0 , 1.7600000 , 5088.6300000 ) ,
VSOP87_COEFFICIENT( 74.0 , 3.5000000 , 3154.6900000 ) ,
VSOP87_COEFFICIENT( 74.0 , 4.6800000 , 801.8200000 ) ,
VSOP87_COEFFICIENT( 70.0 , 0.8300000 , 9437.7600000 ) ,
VSOP87_COEFFICIENT( 62.0 , 3.9800000 , 8827.3900000 ) ,
VSOP87_COEFFICIENT( 61.0 , 1.8200000 , 7084.9000000 ) ,
VSOP87_COEFFICIENT( 57.0 , 2.7800000 , 6286.6000000 ) ,
VSOP87_COEFFICIENT( 56.0 , 4.3900000 , 14143.5000000 ) ,
VSOP87_COEFFICIENT( 56.0 , 3.4700000 , 6279.5500000 ) ,
VSOP87_COEFFICIENT( 52.0 , 0.1900000 , 12139.5500000 ) ,
VSOP87_COEFFICIENT( 52.0 , 1.3300000 , 1748.0200000 ) ,
VSOP87_COEFFICIENT( 51.0 , 0.2800000 , 5856.4800000 ) ,
VSOP87_COEFFICIENT( 49.0 , 0.4900000 , 1194.4500000 ) ,
VSOP87_COEFFICIENT( 41.0 , 5.3700000 , 8429.2400000 ) ,
VSOP87_COEFFICIENT( 41.0 , 2.4000000 , 19651.0500000 ) ,
VSOP87_COEFFICIENT( 39.0 , 6.1700000 , 10447.3900000 ) ,
VSOP87_COEFFICIENT( 37.0 , 6.0400000 , 10213.2900000 ) ,
VSOP87_COEFFICIENT( 37.0 , 2.5700000 , 1059.3800000 ) ,
VSOP87_COEFFICIENT( 36.0 , 1.7100000 , 2352.8700000 ) ,
VSOP87_COEFFICIENT( 36.0 , 1.7800000 , 6812.7700000 ) ,
VSOP87_COEFFICIENT( 33.0 , 0.5900000 , 17789.8500000 ) ,
VSOP87_COEFFICIENT( 30.0 , 0.4400000 , 83996.8500000 ) ,
VSOP87_COEFFICIENT( 30.0 , 2.7400000 , 1349.8700000 ) ,
VSOP87_COEFFICIENT( 25.0 , 3.1600000 , 4690.4800000 )
]
static let Earth_L1:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 628331966747.0 , 0.000000 , 00000.0000000 ) ,
VSOP87_COEFFICIENT( 206059.0 , 2.678235 , 6283.0758500 ) ,
VSOP87_COEFFICIENT( 4303.0 , 2.635100 , 12566.1517000 ) ,
VSOP87_COEFFICIENT( 425.0 , 1.590000 , 3.5230000 ) ,
VSOP87_COEFFICIENT( 119.0 , 5.796000 , 26.2980000 ) ,
VSOP87_COEFFICIENT( 109.0 , 2.966000 , 1577.3440000 ) ,
VSOP87_COEFFICIENT( 93.0 , 2.590000 , 18849.2300000 ) ,
VSOP87_COEFFICIENT( 72.0 , 1.140000 , 529.6900000 ) ,
VSOP87_COEFFICIENT( 68.0 , 1.870000 , 398.1500000 ) ,
VSOP87_COEFFICIENT( 67.0 , 4.410000 , 5507.5500000 ) ,
VSOP87_COEFFICIENT( 59.0 , 2.890000 , 5223.6900000 ) ,
VSOP87_COEFFICIENT( 56.0 , 2.170000 , 155.4200000 ) ,
VSOP87_COEFFICIENT( 45.0 , 0.400000 , 796.3000000 ) ,
VSOP87_COEFFICIENT( 36.0 , 0.470000 , 775.5200000 ) ,
VSOP87_COEFFICIENT( 29.0 , 2.650000 , 7.1100000 ) ,
VSOP87_COEFFICIENT( 21.0 , 5.340000 , 00000.9800000 ) ,
VSOP87_COEFFICIENT( 19.0 , 1.850000 , 5486.7800000 ) ,
VSOP87_COEFFICIENT( 19.0 , 4.970000 , 213.3000000 ) ,
VSOP87_COEFFICIENT( 17.0 , 2.990000 , 6275.9600000 ) ,
VSOP87_COEFFICIENT( 16.0 , 0.030000 , 2544.3100000 ) ,
VSOP87_COEFFICIENT( 16.0 , 1.430000 , 2146.1700000 ) ,
VSOP87_COEFFICIENT( 15.0 , 1.210000 , 10977.0800000 ) ,
VSOP87_COEFFICIENT( 12.0 , 2.830000 , 1748.0200000 ) ,
VSOP87_COEFFICIENT( 12.0 , 3.260000 , 5088.6300000 ) ,
VSOP87_COEFFICIENT( 12.0 , 5.270000 , 1194.4500000 ) ,
VSOP87_COEFFICIENT( 12.0 , 2.080000 , 4694.0000000 ) ,
VSOP87_COEFFICIENT( 11.0 , 0.770000 , 553.5700000 ) ,
VSOP87_COEFFICIENT( 10.0 , 1.300000 , 6286.6000000 ) ,
VSOP87_COEFFICIENT( 10.0 , 4.240000 , 1349.8700000 ) ,
VSOP87_COEFFICIENT( 9.0 , 2.700000 , 242.7300000 ) ,
VSOP87_COEFFICIENT( 9.0 , 5.640000 , 951.7200000 ) ,
VSOP87_COEFFICIENT( 8.0 , 5.300000 , 2352.8700000 ) ,
VSOP87_COEFFICIENT( 6.0 , 2.650000 , 9437.7600000 ) ,
VSOP87_COEFFICIENT( 6.0 , 4.670000 , 4690.4800000 )
]
static let Earth_L2:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 52919.0 , 0.0000 , 00000.0000 ) ,
VSOP87_COEFFICIENT( 8720.0 , 1.0721 , 6283.0758 ) ,
VSOP87_COEFFICIENT( 309.0 , 0.8670 , 12566.1520 ) ,
VSOP87_COEFFICIENT( 27.0 , 0.0500 , 3.5200 ) ,
VSOP87_COEFFICIENT( 16.0 , 5.1900 , 26.3000 ) ,
VSOP87_COEFFICIENT( 16.0 , 3.6800 , 155.4200 ) ,
VSOP87_COEFFICIENT( 10.0 , 0.7600 , 18849.2300 ) ,
VSOP87_COEFFICIENT( 9.0 , 2.0600 , 77713.7700 ) ,
VSOP87_COEFFICIENT( 7.0 , 0.8300 , 775.5200 ) ,
VSOP87_COEFFICIENT( 5.0 , 4.6600 , 1577.3400 ) ,
VSOP87_COEFFICIENT( 4.0 , 1.0300 , 7.1100 ) ,
VSOP87_COEFFICIENT( 4.0 , 3.4400 , 5573.1400 ) ,
VSOP87_COEFFICIENT( 3.0 , 5.1400 , 796.3000 ) ,
VSOP87_COEFFICIENT( 3.0 , 6.0500 , 5507.5500 ) ,
VSOP87_COEFFICIENT( 3.0 , 1.1900 , 242.7300 ) ,
VSOP87_COEFFICIENT( 3.0 , 6.1200 , 529.6900 ) ,
VSOP87_COEFFICIENT( 3.0 , 0.3100 , 398.1500 ) ,
VSOP87_COEFFICIENT( 3.0 , 2.2800 , 553.5700 ) ,
VSOP87_COEFFICIENT( 2.0 , 4.3800 , 5223.6900 ) ,
VSOP87_COEFFICIENT( 2.0 , 3.7500 , 00000.9800 )
]
static let Earth_L3:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 289.0 , 5.844 , 6283.076 ) ,
VSOP87_COEFFICIENT( 35.0 , 0.000 , 00000.000 ) ,
VSOP87_COEFFICIENT( 17.0 , 5.490 , 12566.150 ) ,
VSOP87_COEFFICIENT( 3.0 , 5.200 , 155.420 ) ,
VSOP87_COEFFICIENT( 1.0 , 4.720 , 3.520 ) ,
VSOP87_COEFFICIENT( 1.0 , 5.300 , 18849.230 ) ,
VSOP87_COEFFICIENT( 1.0 , 5.970 , 242.730 )
]
static let Earth_L4:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 114.0 , 3.142 , 00000.00 ) ,
VSOP87_COEFFICIENT( 8.0 , 4.130 , 6283.08 ) ,
VSOP87_COEFFICIENT( 1.0 , 3.840 , 12566.15 )
]
static let Earth_L5:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 1.0 , 3.14 , 0.0 )
]
static let Earth_B0:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 280.0 , 3.199 , 84334.662) ,
VSOP87_COEFFICIENT( 102.0 , 5.422 , 5507.553 ) ,
VSOP87_COEFFICIENT( 80.0 , 3.880 , 5223.690 ) ,
VSOP87_COEFFICIENT( 44.0 , 3.700 , 2352.870 ) ,
VSOP87_COEFFICIENT( 32.0 , 4.000 , 1577.340 )
]
static let Earth_B1:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 9.0 , 3.90 , 5507.55 ) ,
VSOP87_COEFFICIENT( 6.0 , 1.73 , 5223.69 )
]
static let Earth_B2:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 22378.0 , 3.38509 , 10213.28555 ) ,
VSOP87_COEFFICIENT( 282.0 , 0.00000 , 00000.00000 ) ,
VSOP87_COEFFICIENT( 173.0 , 5.25600 , 20426.57100 ) ,
VSOP87_COEFFICIENT( 27.0 , 3.87000 , 30639.86000 )
]
static let Earth_B3:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 647.0 , 4.992 , 10213.286 ) ,
VSOP87_COEFFICIENT( 20.0 , 3.140 , 00000.000 ) ,
VSOP87_COEFFICIENT( 6.0 , 0.770 , 20426.570 ) ,
VSOP87_COEFFICIENT( 3.0 , 5.440 , 30639.860 )
]
static let Earth_B4:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 14.0 , 0.32 , 10213.29 )
]
static let Earth_R0:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 100013989 , 0 , 0 ),
VSOP87_COEFFICIENT( 1670700 , 3.0984635 , 6283.0758500),
VSOP87_COEFFICIENT( 13956 , 3.05525 , 12566.15170 ),
VSOP87_COEFFICIENT( 3084 , 5.1985 , 77713.7715 ),
VSOP87_COEFFICIENT( 1628 , 1.1739 , 5753.3849 ),
VSOP87_COEFFICIENT( 1576 , 2.8469 , 7860.4194 ),
VSOP87_COEFFICIENT( 925 , 5.453 , 11506.770 ),
VSOP87_COEFFICIENT( 542 , 4.564 , 3930.210 ),
VSOP87_COEFFICIENT( 472 , 3.661 , 5884.927 ),
VSOP87_COEFFICIENT( 346 , 0.964 , 5507.553 ),
VSOP87_COEFFICIENT( 329 , 5.900 , 5223.694 ),
VSOP87_COEFFICIENT( 307 , 0.299 , 5573.143 ),
VSOP87_COEFFICIENT( 243 , 4.273 , 11790.629 ),
VSOP87_COEFFICIENT( 212 , 5.847 , 1577.344 ),
VSOP87_COEFFICIENT( 186 , 5.022 , 10977.079 ),
VSOP87_COEFFICIENT( 175 , 3.012 , 18849.228 ),
VSOP87_COEFFICIENT( 110 , 5.055 , 5486.778 ),
VSOP87_COEFFICIENT( 98 , 0.89 , 6069.78 ),
VSOP87_COEFFICIENT( 86 , 5.69 , 15720.84 ),
VSOP87_COEFFICIENT( 86 , 1.27 , 161000.69 ),
VSOP87_COEFFICIENT( 65 , 0.27 , 17260.15 ),
VSOP87_COEFFICIENT( 63 , 0.92 , 529.69 ),
VSOP87_COEFFICIENT( 57 , 2.01 , 83996.85 ),
VSOP87_COEFFICIENT( 56 , 5.24 , 71430.70 ),
VSOP87_COEFFICIENT( 49 , 3.25 , 2544.31 ),
VSOP87_COEFFICIENT( 47 , 2.58 , 775.52 ),
VSOP87_COEFFICIENT( 45 , 5.54 , 9437.76 ),
VSOP87_COEFFICIENT( 43 , 6.01 , 6275.96 ),
VSOP87_COEFFICIENT( 39 , 5.36 , 4694.00 ),
VSOP87_COEFFICIENT( 38 , 2.39 , 8827.39 ),
VSOP87_COEFFICIENT( 37 , 0.83 , 19651.05 ),
VSOP87_COEFFICIENT( 37 , 4.90 , 12139.55 ),
VSOP87_COEFFICIENT( 36 , 1.67 , 12036.46 ),
VSOP87_COEFFICIENT( 35 , 1.84 , 2942.46 ),
VSOP87_COEFFICIENT( 33 , 0.24 , 7084.90 ),
VSOP87_COEFFICIENT( 32 , 0.18 , 5088.63 ),
VSOP87_COEFFICIENT( 32 , 1.78 , 398.15 ),
VSOP87_COEFFICIENT( 28 , 1.21 , 6286.60 ),
VSOP87_COEFFICIENT( 28 , 1.90 , 6279.55 ),
VSOP87_COEFFICIENT( 26 , 4.59 , 10447.39 )
]
static let Earth_R1:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 103019 , 1.107490 , 6283.075850 ),
VSOP87_COEFFICIENT( 1721 , 1.0644 , 12566.1517 ),
VSOP87_COEFFICIENT( 702 , 3.142 , 0 ),
VSOP87_COEFFICIENT( 32 , 1.02 , 18849.23 ),
VSOP87_COEFFICIENT( 31 , 2.84 , 5507.55 ),
VSOP87_COEFFICIENT( 25 , 1.32 , 5223.69 ),
VSOP87_COEFFICIENT( 18 , 1.42 , 1577.34 ),
VSOP87_COEFFICIENT( 10 , 5.91 , 10977.08 ),
VSOP87_COEFFICIENT( 9 , 1.42 , 6275.96 ),
VSOP87_COEFFICIENT( 9 , 0.27 , 5486.78 )
]
static let Earth_R2:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 4359 , 5.7846 , 6283.0758 ),
VSOP87_COEFFICIENT( 124 , 5.579 , 12566.152 ),
VSOP87_COEFFICIENT( 12 , 3.14 , 0 ),
VSOP87_COEFFICIENT( 9 , 3.63 , 77713.77 ),
VSOP87_COEFFICIENT( 6 , 1.87 , 5573.14 ),
VSOP87_COEFFICIENT( 3 , 5.47 , 18849.23 )
]
static let Earth_R3:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 145 , 4.273 , 6283.076 ),
VSOP87_COEFFICIENT( 7 , 3.92 , 12566.15 )
]
static let Earth_R4:[VSOP87_COEFFICIENT] = [
VSOP87_COEFFICIENT( 4 , 2.56 , 6283.08 )
]
// elp2000
struct MOON_ECLIPTIC_LONGITUDE_COEFF{
var D:Double
var M:Double
var Mp:Double
var F:Double
var eiA:Double
var erA:Double
init(_ d:Double, _ m:Double, _ mp:Double, _ f:Double, _ eia:Double, _ era:Double){
D = d
M = m
Mp = mp
F = f
eiA = eia
erA = era
}
}
static let Moon_longitude:[MOON_ECLIPTIC_LONGITUDE_COEFF] = [
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 0, 1, 0, 6288744, -20905355 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 0, -1, 0, 1274027, -3699111 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 0, 0, 0, 658314, -2955968 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 0, 2, 0, 213618, -569925 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 1, 0, 0, -185116, 48888 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 0, 0, 2, -114332, -3149 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 0, -2, 0, 58793, 246158 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, -1, -1, 0, 57066, -152138 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 0, 1, 0, 53322, -170733 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, -1, 0, 0, 45758, -204586 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 1, -1, 0, -40923, -129620 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 1, 0, 0, 0, -34720, 108743 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 1, 1, 0, -30383, 104755 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 0, 0, -2, 15327, 10321 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 0, 1, 2, -12528, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 0, 1, -2, 10980, 79661 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 4, 0, -1, 0, 10675, -34782 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 0, 3, 0, 10034, -23210 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 4, 0, -2, 0, 8548, -21636 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 1, -1, 0, -7888, 24208 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 1, 0, 0, -6766, 30824 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 1, 0, -1, 0, -5163, -8379 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 1, 1, 0, 0, 4987, -16675 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, -1, 1, 0, 4036, -12831 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 0, 2, 0, 3994, -10445 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 4, 0, 0, 0, 3861, -11650 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 0, -3, 0, 3665, 14403 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 1, -2, 0, -2689, -7003 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 0, -1, 2, -2602, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, -1, -2, 0, 2390, 10056 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 1, 0, 1, 0, -2348, 6322 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, -2, 0, 0, 2236, -9884 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 1, 2, 0, -2120, 5751 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 2, 0, 0, -2069, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, -2, -1, 0, 2048, -4950 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 0, 1, -2, -1773, 4130 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 0, 0, 2, -1595, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 4, -1, -1, 0, 1215, -3958 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 0, 2, 2, -1110, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 3, 0, -1, 0, -892, 3258 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 1, 1, 0, -810, 2616 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 4, -1, -2, 0, 759, -1897 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 2, -1, 0, -713, -2117 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 2, -1, 0, -700, 2354 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 1, -2, 0, 691, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, -1, 0, -2, 596, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 4, 0, 1, 0, 549, -1423 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 0, 4, 0, 537, -1117 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 4, -1, 0, 0, 520, -1571 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 1, 0, -2, 0, -487, -1739 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 1, 0, -2, -399, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 0, 2, -2, -381, -4421 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 1, 1, 1, 0, 351, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 3, 0, -2, 0, -340, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 4, 0, -3, 0, 330, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, -1, 2, 0, 327, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 0, 2, 1, 0, -323, 1165 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 1, 1, -1, 0, 299, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 0, 3, 0, 294, 0 ),
MOON_ECLIPTIC_LONGITUDE_COEFF( 2, 0, -1, -2, 0, 8752 )
]
struct MOON_ECLIPTIC_LATITUDE_COEFF{
var D:Double
var M:Double
var Mp:Double
var F:Double
var eiA:Double
init(_ d:Double, _ m:Double, _ mp:Double, _ f:Double, _ eia:Double){
D = d
M = m
Mp = mp
F = f
eiA = eia
}
}
static let moon_Latitude:[MOON_ECLIPTIC_LATITUDE_COEFF] = [
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 0, 0, 1, 5128122 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 0, 1, 1, 280602 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 0, 1, -1, 277693 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 0, 0, -1, 173237 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 0, -1, 1, 55413 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 0, -1, -1, 46271 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 0, 0, 1, 32573 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 0, 2, 1, 17198 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 0, 1, -1, 9266 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 0, 2, -1, 8822 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, -1, 0, -1, 8216 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 0, -2, -1, 4324 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 0, 1, 1, 4200 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 1, 0, -1, -3359 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, -1, -1, 1, 2463 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, -1, 0, 1, 2211 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, -1, -1, -1, 2065 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 1, -1, -1, -1870 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 4, 0, -1, -1, 1828 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 1, 0, 1, -1794 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 0, 0, 3, -1749 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 1, -1, 1, -1565 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 1, 0, 0, 1, -1491 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 1, 1, 1, -1475 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 1, 1, -1, -1410 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 1, 0, -1, -1344 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 1, 0, 0, -1, -1335 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 0, 3, 1, 1107 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 4, 0, 0, -1, 1021 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 4, 0, -1, 1, 833 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 0, 1, -3, 777 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 4, 0, -2, 1, 671 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 0, 0, -3, 607 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 0, 2, -1, 596 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, -1, 1, -1, 491 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 0, -2, 1, -451 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 0, 3, -1, 439 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 0, 2, 1, 422 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 0, -3, -1, 421 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 1, -1, 1, -366 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 1, 0, 1, -351 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 4, 0, 0, 1, 331 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, -1, 1, 1, 315 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, -2, 0, -1, 302 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 0, 1, 3, -283 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 1, 1, -1, -229 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 1, 1, 0, -1, 223 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 1, 1, 0, 1, 223 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 1, -2, -1, -220 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, 1, -1, -1, -220 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 1, 0, 1, 1, -185 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, -1, -2, -1, 181 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 0, 1, 2, 1, -177 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 4, 0, -2, -1, 176 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 4, -1, -1, -1, 166 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 1, 0, 1, -1, -164 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 4, 0, 1, -1, 132 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 1, 0, -1, -1, -119 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 4, -1, 0, -1, 115 ),
MOON_ECLIPTIC_LATITUDE_COEFF( 2, -2, 0, 1, 107 )
]
}
| d47a9f351a6a6fad8e1ebba5ed2fa300 | 56.246575 | 90 | 0.498365 | false | false | false | false |
cliqz-oss/browser-ios | refs/heads/development | Client/Cliqz/Foundation/Networking/ConnectionManager.swift | mpl-2.0 | 2 | //
// ConnectionManager.swift
// Client
//
// Created by Mahmoud Adam on 11/4/15.
// Copyright © 2015 Cliqz. All rights reserved.
//
import Foundation
import Alamofire
enum ResponseType {
case jsonResponse
case stringResponse
}
class ConnectionManager {
//MARK: - Singltone
static let sharedInstance = ConnectionManager()
fileprivate init() {
}
//MARK: - Sending Requests
internal func sendRequest(_ method: Alamofire.HTTPMethod, url: String, parameters: [String: Any]?, responseType: ResponseType, queue: DispatchQueue, onSuccess: @escaping (Any) -> (), onFailure:@escaping (Data?, Error) -> ()) {
switch responseType {
case .jsonResponse:
Alamofire.request(url, method: method, parameters: parameters)
.responseJSON(queue: queue) {
response in
self.handelJSONResponse(response, onSuccess: onSuccess, onFailure: onFailure)
}
case .stringResponse:
Alamofire.request(url, method: method, parameters: parameters)
.responseString(queue: queue) {
response in
self.handelStringResponse(response, onSuccess: onSuccess, onFailure: onFailure)
}
}
}
internal func sendPostRequestWithBody(_ url: String, body: Any, responseType: ResponseType, enableCompression: Bool, queue: DispatchQueue, onSuccess: @escaping (Any) -> (), onFailure:@escaping (Data?, Error) -> ()) {
if JSONSerialization.isValidJSONObject(body) {
do {
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
let data = try JSONSerialization.data(withJSONObject: body, options: [])
if (enableCompression) {
request.setValue("gzip", forHTTPHeaderField: "Content-Encoding")
let compressedData : Data = try data.gzipped()
request.httpBody = compressedData
} else {
request.httpBody = data
}
switch responseType {
case .jsonResponse:
Alamofire.request(request)
.responseJSON(queue: queue) {
response in
self.handelJSONResponse(response, onSuccess: onSuccess, onFailure: onFailure)
}
case .stringResponse:
Alamofire.request(request)
.responseString(queue: queue) {
response in
self.handelStringResponse(response, onSuccess: onSuccess, onFailure: onFailure)
}
}
} catch let error as NSError {
print("sendPostRequestError: \(error.localizedDescription)")
}
} else {
print("sendPostRequestError")
}
}
// MARK: - Private methods
fileprivate func handelStringResponse(_ response: DataResponse<String>, onSuccess: (Any) -> (), onFailure:(Data?, Error) -> ()) {
switch response.result {
case .success(let string):
onSuccess(string)
case .failure(let error):
onFailure(response.data, error)
}
}
fileprivate func handelJSONResponse(_ response: Alamofire.DataResponse<Any>, onSuccess: (Any) -> (), onFailure:(Data?, Error) -> ()) {
switch response.result {
case .success(let json):
onSuccess(json)
case .failure(let error):
onFailure(response.data, error)
}
}
}
| 02b35271dbca1c9c1584417ccc5b42de | 34.045045 | 227 | 0.547044 | false | false | false | false |
fyl00/MonkeyKing | refs/heads/master | Sources/AnyActivity.swift | mit | 2 | //
// AnyActivity.swift
// MonkeyKing
//
// Created by NIX on 15/9/11.
// Copyright © 2015年 nixWork. All rights reserved.
//
import UIKit
open class AnyActivity: UIActivity {
fileprivate let type: UIActivityType
fileprivate let title: String
fileprivate let image: UIImage
fileprivate let message: MonkeyKing.Message
fileprivate let completionHandler: MonkeyKing.DeliverCompletionHandler
public init(type: UIActivityType, title: String, image: UIImage, message: MonkeyKing.Message, completionHandler: @escaping MonkeyKing.DeliverCompletionHandler) {
self.type = type
self.title = title
self.image = image
self.message = message
self.completionHandler = completionHandler
super.init()
}
override open class var activityCategory : UIActivityCategory {
return .share
}
override open var activityType: UIActivityType? {
return type
}
override open var activityTitle : String? {
return title
}
override open var activityImage : UIImage? {
return image
}
override open func canPerform(withActivityItems activityItems: [Any]) -> Bool {
return message.canBeDelivered
}
override open func perform() {
MonkeyKing.deliver(message, completionHandler: completionHandler)
activityDidFinish(true)
}
}
| c5561c98bf96463b3ac6b3e4b0cf3279 | 23.315789 | 165 | 0.683983 | false | false | false | false |
meantheory/octopus | refs/heads/master | strings.swift | apache-2.0 | 1 | import Cocoa
import Darwin
class Constant<T> : Parser {
let value: T
let str: String
init(value:T) {
self.value = value
self.str = "\(value)"
}
typealias Target = T
func parse(stream: CharStream) -> Target? {
if stream.startsWith(str) {
stream.advance(count(str))
return value
}
stream.error("Expected \(str)")
return nil
}
}
func const<T>(value:T) -> Constant<T> {
return Constant(value:value)
}
class Regex : Parser {
typealias Target = String
let pattern:String
init(pattern:String) {
self.pattern = pattern
}
func parse(stream:CharStream) -> Target? {
if let match = stream.startsWithRegex(pattern) {
stream.advance(count(match))
return match
}
return nil
}
}
func regex(pattern:String) -> Regex {
return Regex(pattern:pattern)
}
class Satisfy : Parser {
let condition: Character -> Bool
typealias Target = Character
init(condition:Character -> Bool) {
self.condition = condition
}
func parse(stream:CharStream) -> Target? {
if let ch = stream.head {
if condition(ch) {
stream.advance(1)
return ch
}
}
return nil
}
}
func satisfy(condition:Character->Bool) -> Satisfy {
return Satisfy(condition:condition)
}
class EndOfFile : Parser {
typealias Target = Void
func parse(stream:CharStream) -> Target? {
if stream.eof {
return Target()
} else {
return nil
}
}
}
func eof() -> EndOfFile {
return EndOfFile()
}
// Helpful versions which turn arrays of Characters into Strings
func arrayToString<T:Parser where T.Target==Array<Character>>
(parser: T) -> Pipe<T, String> {
return pipe(parser, {return String($0)})
}
func manychars<T:Parser where T.Target==Character>
(item:T) -> Pipe<Many<T>, String> {
return arrayToString(many(item))
}
func many1chars<T:Parser where T.Target==Character>
(item:T) -> Pipe<Many<T>, String> {
return arrayToString(many1(item))
}
// Overloaded followed-by operators
func >~ <T: Parser>(first: String, second: T) -> FollowedBySecond<Constant<String>,T> {
return FollowedBySecond(first: const(first), second: second)
}
func ~> <T: Parser>(first: T, second: String) -> FollowedByFirst<T,Constant<String>> {
return FollowedByFirst(first: first, second: const(second))
}
| ddb3279ede5237735a07aa82dc24119c | 19.385965 | 87 | 0.654045 | false | false | false | false |
watson-developer-cloud/ios-sdk | refs/heads/master | Sources/AssistantV1/Models/Example.swift | apache-2.0 | 1 | /**
* (C) Copyright IBM Corp. 2017, 2020.
*
* 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
/**
Example.
*/
public struct Example: Codable, Equatable {
/**
The text of a user input example. This string must conform to the following restrictions:
- It cannot contain carriage return, newline, or tab characters.
- It cannot consist of only whitespace characters.
*/
public var text: String
/**
An array of contextual entity mentions.
*/
public var mentions: [Mention]?
/**
The timestamp for creation of the object.
*/
public var created: Date?
/**
The timestamp for the most recent update to the object.
*/
public var updated: Date?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case text = "text"
case mentions = "mentions"
case created = "created"
case updated = "updated"
}
/**
Initialize a `Example` with member variables.
- parameter text: The text of a user input example. This string must conform to the following restrictions:
- It cannot contain carriage return, newline, or tab characters.
- It cannot consist of only whitespace characters.
- parameter mentions: An array of contextual entity mentions.
- returns: An initialized `Example`.
*/
public init(
text: String,
mentions: [Mention]? = nil
)
{
self.text = text
self.mentions = mentions
}
}
| a55aea78265e50f4c550d466d51199f3 | 27.739726 | 113 | 0.660629 | false | false | false | false |
felixjendrusch/Matryoshka | refs/heads/master | MatryoshkaPlayground/MatryoshkaPlayground/Networking/HTTPOperation.swift | mit | 1 | // Copyright (c) 2015 Felix Jendrusch. All rights reserved.
import Result
import ReactiveCocoa
import Matryoshka
public let HTTPOperationErrorDomain = "HTTPOperationErrorDomain"
public enum HTTPOperationErrorCode: Int {
case InvalidResponse = 1
}
public struct HTTPOperation: OperationType {
public var toURLRequest = { (baseURL: NSURL, request: HTTPRequest) -> Result<NSURLRequest, NSError> in
var mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: request.path, relativeToURL: baseURL)!)
mutableURLRequest.HTTPMethod = request.method.rawValue
mutableURLRequest.allHTTPHeaderFields = request.headerFields
let (URLRequest, error) = request.parameterEncoding.encode(mutableURLRequest, parameters: request.parameters)
if let error = error {
return .failure(error)
}
return .success(URLRequest)
}
public var toHTTPResponse = { (data: NSData, response: NSURLResponse) -> Result<HTTPResponse, NSError> in
let error = { NSError(domain: HTTPOperationErrorDomain, code: HTTPOperationErrorCode.InvalidResponse.rawValue, userInfo: nil) }
return Result((response as? NSHTTPURLResponse)?.statusCode, failWith: error()).map { statusCode in
return HTTPResponse(statusCode: HTTPStatusCode(rawValue: statusCode), data: data)
}
}
public var baseURL: NSURL
public var request: HTTPRequest
public init(baseURL: NSURL, request: HTTPRequest) {
self.baseURL = baseURL
self.request = request
}
public func execute(execute: NSURLRequest -> SignalProducer<(NSData, NSURLResponse), NSError>) -> SignalProducer<HTTPResponse, NSError> {
return SignalProducer(value: (baseURL: baseURL, request: request))
|> tryMap(toURLRequest)
|> map(execute) |> flatten(.Merge)
|> tryMap(toHTTPResponse)
}
}
public struct HTTPOperationFactory: OperationFactoryType {
public func create(input: (baseURL: NSURL, request: HTTPRequest)) -> HTTPOperation.Operation {
return Operation(HTTPOperation(baseURL: input.baseURL, request: input.request))
}
}
| d182aea689554ee128c6f1547e9f3240 | 39.490566 | 141 | 0.709692 | false | false | false | false |
Jaeandroid/actor-platform | refs/heads/master | actor-apps/app-ios/Actor/Controllers/Settings/SettingsPrivacyViewController.swift | mit | 31 | //
// Copyright (c) 2015 Actor LLC. <https://actor.im>
//
import UIKit
class SettingsPrivacyViewController: AATableViewController {
// MARK: -
// MARK: Private vars
private let CellIdentifier = "CellIdentifier"
private var authSessions: [APAuthSession]?
// MARK: -
// MARK: Constructors
init() {
super.init(style: UITableViewStyle.Grouped)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.title = NSLocalizedString("PrivacyTitle", comment: "Controller title")
tableView.registerClass(CommonCell.self, forCellReuseIdentifier: CellIdentifier)
tableView.backgroundColor = MainAppTheme.list.backyardColor
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
execute(MSG.loadSessionsCommand(), successBlock: { (val) -> Void in
var list = val as! JavaUtilList
self.authSessions = []
for i in 0..<list.size() {
self.authSessions!.append(list.getWithInt(jint(i)) as! APAuthSession)
}
self.tableView.reloadData()
}, failureBlock: nil)
}
// MARK: -
// MARK: Getters
private func terminateSessionsCell(indexPath: NSIndexPath) -> CommonCell {
var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell
cell.setContent(NSLocalizedString("PrivacyTerminate", comment: "Terminate action"))
cell.style = .Normal
cell.showTopSeparator()
cell.showBottomSeparator()
return cell
}
private func sessionsCell(indexPath: NSIndexPath) -> CommonCell {
var cell = tableView.dequeueReusableCellWithIdentifier(CellIdentifier, forIndexPath: indexPath) as! CommonCell
var session = authSessions![indexPath.row]
cell.setContent(session.getDeviceTitle())
cell.style = .Normal
if (indexPath.row == 0) {
cell.showTopSeparator()
} else {
cell.hideTopSeparator()
}
cell.showBottomSeparator()
return cell
}
// MARK: -
// MARK: UITableView Data Source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if authSessions != nil {
if count(authSessions!) > 0 {
return 2
}
}
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 1 {
return count(authSessions!)
}
return 1
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if indexPath.section == 0 && indexPath.row == 0 {
return terminateSessionsCell(indexPath)
} else if (indexPath.section == 1) {
return sessionsCell(indexPath)
}
return UITableViewCell()
}
func tableView(tableView: UITableView, titleForFooterInSection section: Int) -> String? {
if section > 0 { return nil }
return NSLocalizedString("PrivacyTerminateHint", comment: "Terminate hint")
}
// MARK: -
// MARK: UITableView Delegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
if indexPath.section == 0 {
execute(MSG.terminateAllSessionsCommand())
} else if (indexPath.section == 1) {
execute(MSG.terminateSessionCommandWithId(authSessions![indexPath.row].getId()), successBlock: { (val) -> Void in
self.execute(MSG.loadSessionsCommand(), successBlock: { (val) -> Void in
var list = val as! JavaUtilList
self.authSessions = []
for i in 0..<list.size() {
self.authSessions!.append(list.getWithInt(jint(i)) as! APAuthSession)
}
self.tableView.reloadData()
}, failureBlock: nil)
}, failureBlock: nil)
}
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel.textColor = MainAppTheme.list.sectionColor
}
func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
let header: UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView
header.textLabel.textColor = MainAppTheme.list.hintColor
}
}
| 9f4bd558bc57492269855978b832e762 | 34.235714 | 125 | 0.61788 | false | false | false | false |
JamesBirchall/udemyiossamples | refs/heads/master | TuppenceWeather/TuppenceWeather/Forecasts.swift | apache-2.0 | 1 | //
// Forecasts.swift
// TuppenceWeather
//
// Created by James Birchall on 22/07/2017.
// Copyright © 2017 James Birchall. All rights reserved.
//
import Foundation
import Alamofire
class Forecasts {
var forecastList = [Forecast]()
func downloadWeatherDetails(completed: @escaping () -> ()) {
let currentWeatherURL = URL(string: BASE_WEATHERFORECASTSURL)
Alamofire.request(currentWeatherURL!).responseJSON {
[weak self] response in
print("Request: \(String(describing: response.request))") // original url request
if let json = response.result.value as? Dictionary<String, Any> {
if let list = json["list"] as? [Dictionary<String, Any>] {
for item in list {
let currentForecast = Forecast()
// get min and max temp first
if let temp = item["temp"] as? Dictionary<String, Any> {
if let minTemp = temp["min"] as? Double {
let intVersion = Int(minTemp - 273.15)
currentForecast.lowTemp = "\(intVersion)"
}
if let maxTemp = temp["max"] as? Double {
let intVersion = Int(maxTemp - 273.15)
currentForecast.highTemp = "\(intVersion)"
}
}
// get weather Type
if let weather = item["weather"] as? [Dictionary<String, Any>] {
if let weatherType = weather.first?["main"] as? String {
currentForecast.weatherType = weatherType
}
}
// get date
if let date = item["dt"] as? Double {
let unixConvertableDate = Date(timeIntervalSince1970: date)
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
dateFormatter.dateFormat = "EEEE"
dateFormatter.timeStyle = .none
currentForecast.date = unixConvertableDate.dayOfWeek()
}
self?.forecastList.append(currentForecast)
}
}
}
// remove the first one - we already show todays in main view
self?.forecastList.removeFirst()
print("Completed forecast download and show")
print("We have set forecast variables.")
completed()
}
}
}
| 575f432bf0e2d2f2a55feb94d70d7934 | 40.542857 | 95 | 0.450138 | false | false | false | false |
tlax/looper | refs/heads/master | looper/Controller/Camera/CCameraRotate.swift | mit | 1 | import UIKit
class CCameraRotate:CController
{
weak var viewRotate:VCameraRotate!
weak var record:MCameraRecord!
init(record:MCameraRecord)
{
self.record = record
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
override func loadView()
{
let viewRotate:VCameraRotate = VCameraRotate(controller:self)
self.viewRotate = viewRotate
view = viewRotate
}
//MARK: private
private func asyncSave(orientation:UIImageOrientation)
{
var rotatedRecords:[MCameraRecordItem] = []
guard
let firstImage:UIImage = record.items.first?.image
else
{
return
}
let size:CGFloat = firstImage.size.width
let imageSize:CGSize = CGSize(
width:size,
height:size)
let drawingRect:CGRect = CGRect(
x:0,
y:0,
width:size,
height:size)
for rawItem:MCameraRecordItem in record.items
{
let originalImage:UIImage = rawItem.image
guard
let cgImage:CGImage = originalImage.cgImage
else
{
continue
}
let expectedImage:UIImage = UIImage(
cgImage:cgImage,
scale:originalImage.scale,
orientation:orientation)
UIGraphicsBeginImageContext(imageSize)
expectedImage.draw(in:drawingRect)
guard
let rotatedImage:UIImage = UIGraphicsGetImageFromCurrentImageContext()
else
{
UIGraphicsEndImageContext()
continue
}
UIGraphicsEndImageContext()
let rotatedItem:MCameraRecordItem = MCameraRecordItem(
image:rotatedImage)
rotatedRecords.append(rotatedItem)
}
record.items = rotatedRecords
DispatchQueue.main.async
{ [weak self] in
self?.saveFinished()
}
}
private func saveFinished()
{
parentController.pop(vertical:CParent.TransitionVertical.fromTop)
}
//MARK: public
func save()
{
viewRotate.startLoading()
let orientation:UIImageOrientation = viewRotate.orientation
if orientation == UIImageOrientation.up
{
saveFinished()
}
else
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.asyncSave(orientation:orientation)
}
}
}
}
| 7da7b714051a13feeeb7124f36e98dbc | 22.782258 | 86 | 0.498813 | false | false | false | false |
elefantel/TravelWish | refs/heads/master | TravelWish/ViewControllers/RegionsTableViewController.swift | mit | 1 | //
// RegionsTableViewController.swift
// TravelWish
//
// Created by Mpendulo Ndlovu on 2016/04/07.
// Copyright © 2016 Elefantel. All rights reserved.
//
import UIKit
class RegionsTableViewController: UITableViewController {
var _regions = NSMutableArray()
override func viewDidLoad()
{
super.viewDidLoad()
loadRegions()
}
private func loadRegions()
{
_regions.insertObject("Africa", atIndex: 0)
_regions.insertObject("Americas", atIndex: 1)
_regions.insertObject("Asia", atIndex: 2)
_regions.insertObject("Europe", atIndex: 3)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
switch (section)
{
case 0:
return _regions.count;
default:
return 0;
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("regionsCellIdentifier", forIndexPath: indexPath)
cell.textLabel!.text = _regions.objectAtIndex(indexPath.row) as? String
return cell
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
let indexPath = self.tableView.indexPathForSelectedRow;
let region = _regions.objectAtIndex(indexPath!.row) as? String;
let countriesTableViewController = segue.destinationViewController as? CountriesTableViewController;
countriesTableViewController!.region = region!;
}
}
| 1fcd7c126fbb50411b1657adbe24ac48 | 24.932432 | 116 | 0.648775 | false | false | false | false |
citrusbyte/Healthy-Baby | refs/heads/master | M2XDemo/TriggersViewController.swift | mit | 1 | //
// TriggersViewController.swift
// M2XDemo
//
// Created by Luis Floreani on 11/24/14.
// Copyright (c) 2014 citrusbyte.com. All rights reserved.
//
import Foundation
class TriggersViewController : HBBaseViewController, TriggerDetailViewControllerDelegate, UITableViewDataSource, UITableViewDelegate {
var deviceId: String?
private var triggers: [AnyObject]?
@IBOutlet private var tableView: UITableView!
@IBOutlet private var addTriggerButton: UIBarButtonItem!
@IBOutlet private var detailNoDataLabel: UILabel!
private var refreshTriggers: Bool = false
private var refreshControl: UIRefreshControl?
private var device: M2XDevice?
override func viewDidLoad() {
super.viewDidLoad()
assert(deviceId != nil, "deviceId can't be nil")
navigationItem.rightBarButtonItem = addTriggerButton
detailNoDataLabel.alpha = 0
detailNoDataLabel.textColor = Colors.grayColor
refreshControl = UIRefreshControl()
tableView.addSubview(refreshControl!)
refreshControl!.addTarget(self, action: "refreshData", forControlEvents: .ValueChanged)
var defaults = NSUserDefaults.standardUserDefaults()
let key = defaults.valueForKey("key") as? String
let client = M2XClient(apiKey: key)
self.device = M2XDevice(client: client, attributes: ["id": deviceId!])
loadData()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let dc = segue.destinationViewController as? TriggerDetailViewController {
dc.delegate = self
dc.device = self.device
if segue.identifier == "EditTriggerSegue" {
let indexPath = self.tableView.indexPathForSelectedRow()
let obj = self.triggers![indexPath!.row] as! M2XTrigger
dc.trigger = obj
}
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
ProgressHUD.cancelCBBProgress()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if refreshTriggers {
loadData()
refreshTriggers = false
}
}
func loadData() {
self.refreshControl?.beginRefreshing()
refreshData()
}
func refreshData() {
device?.triggersWithCompletionHandler { (objects: [AnyObject]!, response: M2XResponse!) -> Void in
self.refreshControl?.endRefreshing()
if response.error {
HBBaseViewController.handleErrorAlert(response.errorObject!)
} else {
self.triggers = objects
self.detailNoDataLabel.alpha = self.triggers?.count > 0 ? 0 : 1
self.tableView.reloadData()
}
}
}
// MARK: TriggerDetailViewControllerDelegate
func needsTriggersRefresh() {
refreshTriggers = true
}
// MARK: UITableViewDataSource
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 64.0
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return triggers?.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
let obj = triggers![indexPath.row] as! M2XTrigger
let stream = obj["conditions"].allKeys[0] as! String
let conditions = obj["conditions"][stream] as! NSDictionary
let condition = conditions.allKeys[0] as! String
let conditionSymbols = ["lt": "<", "lte": "<=", "eq": "=", "gt": ">", "gte": ">="]
cell.textLabel?.text = obj["name"] as? String
cell.detailTextLabel?.text = "\(conditionSymbols[condition]!) \(conditions[condition]!)"
return cell
}
@IBAction func dismissFromSegue(segue: UIStoryboardSegue) {
dismissViewControllerAnimated(true, completion: nil)
}
} | 673989de63ee0491942a2e826a4170c9 | 31.992366 | 134 | 0.62717 | false | false | false | false |
Sage-Bionetworks/MoleMapper | refs/heads/master | MoleMapper/Charts/Classes/Renderers/ChartXAxisRendererHorizontalBarChart.swift | bsd-3-clause | 1 | //
// ChartXAxisRendererHorizontalBarChart.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics
import UIKit
public class ChartXAxisRendererHorizontalBarChart: ChartXAxisRendererBarChart
{
public override init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!, chart: BarChartView)
{
super.init(viewPortHandler: viewPortHandler, xAxis: xAxis, transformer: transformer, chart: chart)
}
public override func computeAxis(xValAverageLength xValAverageLength: Double, xValues: [String?])
{
_xAxis.values = xValues
let longest = _xAxis.getLongestLabel() as NSString
let longestSize = longest.sizeWithAttributes([NSFontAttributeName: _xAxis.labelFont])
_xAxis.labelWidth = floor(longestSize.width + _xAxis.xOffset * 3.5)
_xAxis.labelHeight = longestSize.height
}
public override func renderAxisLabels(context context: CGContext?)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawLabelsEnabled || _chart.data === nil)
{
return
}
let xoffset = _xAxis.xOffset
if (_xAxis.labelPosition == .Top)
{
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left)
}
else if (_xAxis.labelPosition == .Bottom)
{
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right)
}
else if (_xAxis.labelPosition == .BottomInside)
{
drawLabels(context: context, pos: viewPortHandler.contentLeft + xoffset, align: .Left)
}
else if (_xAxis.labelPosition == .TopInside)
{
drawLabels(context: context, pos: viewPortHandler.contentRight - xoffset, align: .Right)
}
else
{ // BOTH SIDED
drawLabels(context: context, pos: viewPortHandler.contentLeft - xoffset, align: .Right)
drawLabels(context: context, pos: viewPortHandler.contentRight + xoffset, align: .Left)
}
}
/// draws the x-labels on the specified y-position
internal func drawLabels(context context: CGContext?, pos: CGFloat, align: NSTextAlignment)
{
let labelFont = _xAxis.labelFont
let labelTextColor = _xAxis.labelTextColor
// pre allocate to save performance (dont allocate in loop)
var position = CGPoint(x: 0.0, y: 0.0)
let bd = _chart.data as! BarChartData
let step = bd.dataSetCount
for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus)
{
let label = _xAxis.values[i]
if (label == nil)
{
continue
}
position.x = 0.0
position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace + bd.groupSpace / 2.0
// consider groups (center label for each group)
if (step > 1)
{
position.y += (CGFloat(step) - 1.0) / 2.0
}
transformer.pointValueToPixel(&position)
if (viewPortHandler.isInBoundsY(position.y))
{
ChartUtils.drawText(context: context, text: label!, point: CGPoint(x: pos, y: position.y - _xAxis.labelHeight / 2.0), align: align, attributes: [NSFontAttributeName: labelFont, NSForegroundColorAttributeName: labelTextColor])
}
}
}
private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderGridLines(context context: CGContext?)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawGridLinesEnabled || _chart.data === nil)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, _xAxis.gridColor.CGColor)
CGContextSetLineWidth(context, _xAxis.gridLineWidth)
if (_xAxis.gridLineDashLengths != nil)
{
CGContextSetLineDash(context, _xAxis.gridLineDashPhase, _xAxis.gridLineDashLengths, _xAxis.gridLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
var position = CGPoint(x: 0.0, y: 0.0)
let bd = _chart.data as! BarChartData
// take into consideration that multiple DataSets increase _deltaX
let step = bd.dataSetCount
for (var i = _minX, maxX = min(_maxX + 1, _xAxis.values.count); i < maxX; i += _xAxis.axisLabelModulus)
{
position.x = 0.0
position.y = CGFloat(i * step) + CGFloat(i) * bd.groupSpace - 0.5
transformer.pointValueToPixel(&position)
if (viewPortHandler.isInBoundsY(position.y))
{
_gridLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_gridLineSegmentsBuffer[0].y = position.y
_gridLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_gridLineSegmentsBuffer[1].y = position.y
CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2)
}
}
CGContextRestoreGState(context)
}
private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderAxisLine(context context: CGContext?)
{
if (!_xAxis.isEnabled || !_xAxis.isDrawAxisLineEnabled)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, _xAxis.axisLineColor.CGColor)
CGContextSetLineWidth(context, _xAxis.axisLineWidth)
if (_xAxis.axisLineDashLengths != nil)
{
CGContextSetLineDash(context, _xAxis.axisLineDashPhase, _xAxis.axisLineDashLengths, _xAxis.axisLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
if (_xAxis.labelPosition == .Top
|| _xAxis.labelPosition == .TopInside
|| _xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
if (_xAxis.labelPosition == .Bottom
|| _xAxis.labelPosition == .BottomInside
|| _xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
CGContextRestoreGState(context)
}
private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderLimitLines(context context: CGContext?)
{
var limitLines = _xAxis.limitLines
if (limitLines.count == 0)
{
return
}
CGContextSaveGState(context)
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for (var i = 0; i < limitLines.count; i++)
{
let l = limitLines[i]
position.x = 0.0
position.y = CGFloat(l.limit)
position = CGPointApplyAffineTransform(position, trans)
_limitLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_limitLineSegmentsBuffer[0].y = position.y
_limitLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_limitLineSegmentsBuffer[1].y = position.y
CGContextSetStrokeColorWithColor(context, l.lineColor.CGColor)
CGContextSetLineWidth(context, l.lineWidth)
if (l.lineDashLengths != nil)
{
CGContextSetLineDash(context, l.lineDashPhase, l.lineDashLengths!, l.lineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2)
let label = l.label
// if drawing the limit-value label is enabled
if (label.characters.count > 0)
{
let labelLineHeight = l.valueFont.lineHeight
let add = CGFloat(4.0)
let xOffset: CGFloat = add
let yOffset: CGFloat = l.lineWidth + labelLineHeight / 2.0
if (l.labelPosition == .Right)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentRight - xOffset,
y: position.y - yOffset - labelLineHeight),
align: .Right,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: viewPortHandler.contentLeft + xOffset,
y: position.y - yOffset - labelLineHeight),
align: .Left,
attributes: [NSFontAttributeName: l.valueFont, NSForegroundColorAttributeName: l.valueTextColor])
}
}
}
CGContextRestoreGState(context)
}
} | b723d12c5f2688cf62d54c8834593a72 | 36.451957 | 241 | 0.573601 | false | false | false | false |
rishi420/ENSwiftSideMenu | refs/heads/master | Library/ENSideMenu.swift | mit | 1 | //
// SideMenu.swift
// SwiftSideMenu
//
// Created by Evgeny on 24.07.14.
// Copyright (c) 2014 Evgeny Nazarov. All rights reserved.
//
import UIKit
@objc public protocol ENSideMenuDelegate {
optional func sideMenuWillOpen()
optional func sideMenuWillClose()
optional func sideMenuDidOpen()
optional func sideMenuDidClose()
optional func sideMenuShouldOpenSideMenu () -> Bool
}
@objc public protocol ENSideMenuProtocol {
var sideMenu : ENSideMenu? { get }
func setContentViewController(contentViewController: UIViewController)
}
public enum ENSideMenuAnimation : Int {
case None
case Default
}
/**
The position of the side view on the screen.
- Left: Left side of the screen
- Right: Right side of the screen
*/
public enum ENSideMenuPosition : Int {
case Left
case Right
}
public extension UIViewController {
/**
Changes current state of side menu view.
*/
public func toggleSideMenuView () {
sideMenuController()?.sideMenu?.toggleMenu()
}
/**
Hides the side menu view.
*/
public func hideSideMenuView () {
sideMenuController()?.sideMenu?.hideSideMenu()
}
/**
Shows the side menu view.
*/
public func showSideMenuView () {
sideMenuController()?.sideMenu?.showSideMenu()
}
/**
Returns a Boolean value indicating whether the side menu is showed.
:returns: BOOL value
*/
public func isSideMenuOpen () -> Bool {
let sieMenuOpen = self.sideMenuController()?.sideMenu?.isMenuOpen
return sieMenuOpen!
}
/**
* You must call this method from viewDidLayoutSubviews in your content view controlers so it fixes size and position of the side menu when the screen
* rotates.
* A convenient way to do it might be creating a subclass of UIViewController that does precisely that and then subclassing your view controllers from it.
*/
func fixSideMenuSize() {
if let navController = self.navigationController as? ENSideMenuNavigationController {
navController.sideMenu?.updateFrame()
}
}
/**
Returns a view controller containing a side menu
:returns: A `UIViewController`responding to `ENSideMenuProtocol` protocol
*/
public func sideMenuController () -> ENSideMenuProtocol? {
var iteration : UIViewController? = self.parentViewController
if (iteration == nil) {
return topMostController()
}
repeat {
if (iteration is ENSideMenuProtocol) {
return iteration as? ENSideMenuProtocol
} else if (iteration?.parentViewController != nil && iteration?.parentViewController != iteration) {
iteration = iteration!.parentViewController
} else {
iteration = nil
}
} while (iteration != nil)
return iteration as? ENSideMenuProtocol
}
internal func topMostController () -> ENSideMenuProtocol? {
var topController : UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController
if (topController is UITabBarController) {
topController = (topController as! UITabBarController).selectedViewController
}
while (topController?.presentedViewController is ENSideMenuProtocol) {
topController = topController?.presentedViewController
}
return topController as? ENSideMenuProtocol
}
}
public class ENSideMenu : NSObject, UIGestureRecognizerDelegate {
/// The width of the side menu view. The default value is 160.
public var menuWidth : CGFloat = 160.0 {
didSet {
needUpdateApperance = true
updateFrame()
}
}
private var menuPosition:ENSideMenuPosition = .Left
/// A Boolean value indicating whether the bouncing effect is enabled. The default value is TRUE.
public var bouncingEnabled :Bool = true
/// The duration of the slide animation. Used only when `bouncingEnabled` is FALSE.
public var animationDuration = 0.4
private let sideMenuContainerView = UIView()
private var menuViewController : UIViewController!
private var animator : UIDynamicAnimator!
private var sourceView : UIView!
private var needUpdateApperance : Bool = false
/// The delegate of the side menu
public weak var delegate : ENSideMenuDelegate?
private(set) var isMenuOpen : Bool = false
/// A Boolean value indicating whether the left swipe is enabled.
public var allowLeftSwipe : Bool = true
/// A Boolean value indicating whether the right swipe is enabled.
public var allowRightSwipe : Bool = true
/**
Initializes an instance of a `ENSideMenu` object.
:param: sourceView The parent view of the side menu view.
:param: menuPosition The position of the side menu view.
:returns: An initialized `ENSideMenu` object, added to the specified view.
*/
public init(sourceView: UIView, menuPosition: ENSideMenuPosition) {
super.init()
self.sourceView = sourceView
self.menuPosition = menuPosition
self.setupMenuView()
animator = UIDynamicAnimator(referenceView:sourceView)
animator.delegate = self
// Add right swipe gesture recognizer
let rightSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:")
rightSwipeGestureRecognizer.delegate = self
rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right
// Add left swipe gesture recognizer
let leftSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:")
leftSwipeGestureRecognizer.delegate = self
leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Left
if (menuPosition == .Left) {
sourceView.addGestureRecognizer(rightSwipeGestureRecognizer)
sideMenuContainerView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
else {
sideMenuContainerView.addGestureRecognizer(rightSwipeGestureRecognizer)
sourceView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
}
/**
Initializes an instance of a `ENSideMenu` object.
:param: sourceView The parent view of the side menu view.
:param: menuViewController A menu view controller object which will be placed in the side menu view.
:param: menuPosition The position of the side menu view.
:returns: An initialized `ENSideMenu` object, added to the specified view, containing the specified menu view controller.
*/
public convenience init(sourceView: UIView, menuViewController: UIViewController, menuPosition: ENSideMenuPosition) {
self.init(sourceView: sourceView, menuPosition: menuPosition)
self.menuViewController = menuViewController
self.menuViewController.view.frame = sideMenuContainerView.bounds
self.menuViewController.view.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
sideMenuContainerView.addSubview(self.menuViewController.view)
}
/*
public convenience init(sourceView: UIView, view: UIView, menuPosition: ENSideMenuPosition) {
self.init(sourceView: sourceView, menuPosition: menuPosition)
view.frame = sideMenuContainerView.bounds
view.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
sideMenuContainerView.addSubview(view)
}
*/
/**
Updates the frame of the side menu view.
*/
func updateFrame() {
var width:CGFloat
var height:CGFloat
(width, height) = adjustFrameDimensions( sourceView.frame.size.width, height: sourceView.frame.size.height)
let menuFrame = CGRectMake(
(menuPosition == .Left) ?
isMenuOpen ? 0 : -menuWidth-1.0 :
isMenuOpen ? width - menuWidth : width+1.0,
sourceView.frame.origin.y,
menuWidth,
height
)
sideMenuContainerView.frame = menuFrame
}
private func adjustFrameDimensions( width: CGFloat, height: CGFloat ) -> (CGFloat,CGFloat) {
if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1 &&
(UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.LandscapeRight ||
UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.LandscapeLeft) {
// iOS 7.1 or lower and landscape mode -> interchange width and height
return (height, width)
}
else {
return (width, height)
}
}
private func setupMenuView() {
// Configure side menu container
updateFrame()
sideMenuContainerView.backgroundColor = UIColor.clearColor()
sideMenuContainerView.clipsToBounds = false
sideMenuContainerView.layer.masksToBounds = false
sideMenuContainerView.layer.shadowOffset = (menuPosition == .Left) ? CGSizeMake(1.0, 1.0) : CGSizeMake(-1.0, -1.0)
sideMenuContainerView.layer.shadowRadius = 1.0
sideMenuContainerView.layer.shadowOpacity = 0.125
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath
sourceView.addSubview(sideMenuContainerView)
if (NSClassFromString("UIVisualEffectView") != nil) {
// Add blur view
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: .Light)) as UIVisualEffectView
visualEffectView.frame = sideMenuContainerView.bounds
visualEffectView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
sideMenuContainerView.addSubview(visualEffectView)
}
else {
// TODO: add blur for ios 7
}
}
private func toggleMenu (shouldOpen: Bool) {
if (shouldOpen && delegate?.sideMenuShouldOpenSideMenu?() == false) {
return
}
updateSideMenuApperanceIfNeeded()
isMenuOpen = shouldOpen
var width:CGFloat
var height:CGFloat
(width, height) = adjustFrameDimensions( sourceView.frame.size.width, height: sourceView.frame.size.height)
if (bouncingEnabled) {
animator.removeAllBehaviors()
var gravityDirectionX: CGFloat
var pushMagnitude: CGFloat
var boundaryPointX: CGFloat
var boundaryPointY: CGFloat
if (menuPosition == .Left) {
// Left side menu
gravityDirectionX = (shouldOpen) ? 1 : -1
pushMagnitude = (shouldOpen) ? 20 : -20
boundaryPointX = (shouldOpen) ? menuWidth : -menuWidth-2
boundaryPointY = 20
}
else {
// Right side menu
gravityDirectionX = (shouldOpen) ? -1 : 1
pushMagnitude = (shouldOpen) ? -20 : 20
boundaryPointX = (shouldOpen) ? width-menuWidth : width+menuWidth+2
boundaryPointY = -20
}
let gravityBehavior = UIGravityBehavior(items: [sideMenuContainerView])
gravityBehavior.gravityDirection = CGVectorMake(gravityDirectionX, 0)
animator.addBehavior(gravityBehavior)
let collisionBehavior = UICollisionBehavior(items: [sideMenuContainerView])
collisionBehavior.addBoundaryWithIdentifier("menuBoundary", fromPoint: CGPointMake(boundaryPointX, boundaryPointY),
toPoint: CGPointMake(boundaryPointX, height))
animator.addBehavior(collisionBehavior)
let pushBehavior = UIPushBehavior(items: [sideMenuContainerView], mode: UIPushBehaviorMode.Instantaneous)
pushBehavior.magnitude = pushMagnitude
animator.addBehavior(pushBehavior)
let menuViewBehavior = UIDynamicItemBehavior(items: [sideMenuContainerView])
menuViewBehavior.elasticity = 0.25
animator.addBehavior(menuViewBehavior)
}
else {
var destFrame :CGRect
if (menuPosition == .Left) {
destFrame = CGRectMake((shouldOpen) ? -2.0 : -menuWidth, 0, menuWidth, height)
}
else {
destFrame = CGRectMake((shouldOpen) ? width-menuWidth : width+2.0,
0,
menuWidth,
height)
}
UIView.animateWithDuration(
animationDuration,
animations: { () -> Void in
self.sideMenuContainerView.frame = destFrame
},
completion: { (Bool) -> Void in
if (self.isMenuOpen) {
self.delegate?.sideMenuDidOpen?()
} else {
self.delegate?.sideMenuDidClose?()
}
})
}
if (shouldOpen) {
delegate?.sideMenuWillOpen?()
} else {
delegate?.sideMenuWillClose?()
}
}
public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer is UISwipeGestureRecognizer {
let swipeGestureRecognizer = gestureRecognizer as! UISwipeGestureRecognizer
if !self.allowLeftSwipe {
if swipeGestureRecognizer.direction == .Left {
return false
}
}
if !self.allowRightSwipe {
if swipeGestureRecognizer.direction == .Right {
return false
}
}
}
return true
}
internal func handleGesture(gesture: UISwipeGestureRecognizer) {
toggleMenu((self.menuPosition == .Right && gesture.direction == .Left)
|| (self.menuPosition == .Left && gesture.direction == .Right))
}
private func updateSideMenuApperanceIfNeeded () {
if (needUpdateApperance) {
var frame = sideMenuContainerView.frame
frame.size.width = menuWidth
sideMenuContainerView.frame = frame
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath
needUpdateApperance = false
}
}
/**
Toggles the state of the side menu.
*/
public func toggleMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
else {
updateSideMenuApperanceIfNeeded()
toggleMenu(true)
}
}
/**
Shows the side menu if the menu is hidden.
*/
public func showSideMenu () {
if (!isMenuOpen) {
toggleMenu(true)
}
}
/**
Hides the side menu if the menu is showed.
*/
public func hideSideMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
}
}
extension ENSideMenu: UIDynamicAnimatorDelegate {
public func dynamicAnimatorDidPause(animator: UIDynamicAnimator) {
if (self.isMenuOpen) {
self.delegate?.sideMenuDidOpen?()
} else {
self.delegate?.sideMenuDidClose?()
}
}
public func dynamicAnimatorWillResume(animator: UIDynamicAnimator) {
print("resume")
}
}
| 26b123db494c6dcc3a11f126175f68fa | 36.229858 | 158 | 0.625485 | false | false | false | false |
Karumi/MarvelApiClient | refs/heads/master | MarvelApiClient/CharactersAPIClient.swift | apache-2.0 | 1 | //
// CharactersAPIClient.swift
// MarvelAPIClient
//
// Created by Pedro Vicente on 14/11/15.
// Copyright © 2015 GoKarumi S.L. All rights reserved.
//
import Foundation
import BothamNetworking
import Result
public class CharactersAPIClient {
private let apiClient: BothamAPIClient
private let parser: CharactersParser
init(apiClient: BothamAPIClient, parser: CharactersParser) {
self.parser = parser
self.apiClient = apiClient
}
public func getAll(offset: Int, limit: Int,
completion: @escaping (Result<GetCharactersDTO, BothamAPIClientError>) -> Void) {
assert(offset >= 0 && limit >= 0)
let params = [MarvelAPIParams.offset: "\(offset)", MarvelAPIParams.limit: "\(limit)"]
apiClient.GET("characters", parameters: params) { response in
completion(
response.mapJSON {
return self.parser.fromJSON(json: $0)
}
)
}
}
public func getById(id: String, completion: @escaping (Result<CharacterDTO, BothamAPIClientError>) -> Void) {
apiClient.GET("characters/\(id)") { response in
completion(
response.mapJSON {
return self.parser.characterDTOFromJSON(json: $0)
}
)
}
}
}
| d2cbb1d3036137dc1ac7fb4392d0de2a | 27.702128 | 113 | 0.59748 | false | false | false | false |
VeinGuo/VGPlayer | refs/heads/master | VGPlayer/Classes/UIButton+VGPlayer.swift | mit | 1 | //
// UIButton+VGPlayer.swift
// VGPlayer
//
// Created by Vein on 2017/6/12.
// Copyright © 2017年 Vein. All rights reserved.
// https://stackoverflow.com/questions/808503/uibutton-making-the-hit-area-larger-than-the-default-hit-area/13977921
import Foundation
fileprivate let minimumHitArea = CGSize(width: 50, height: 50)
extension UIButton {
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
// if the button is hidden/disabled/transparent it can't be hit
if self.isHidden || !self.isUserInteractionEnabled || self.alpha < 0.01 { return nil }
// increase the hit frame to be at least as big as `minimumHitArea`
let buttonSize = self.bounds.size
let widthToAdd = max(minimumHitArea.width - buttonSize.width, 0)
let heightToAdd = max(minimumHitArea.height - buttonSize.height, 0)
let largerFrame = self.bounds.insetBy(dx: -widthToAdd / 2, dy: -heightToAdd / 2)
// perform hit test on larger frame
return (largerFrame.contains(point)) ? super.hitTest(point, with: event) : nil
}
}
| a95a12a9851dacd385a2038337831f51 | 37.862069 | 117 | 0.673469 | false | true | false | false |
antonio081014/LeeCode-CodeBase | refs/heads/main | Swift/two-sum-iv-input-is-a-bst.swift | mit | 2 | /**
* https://leetcode.com/problems/two-sum-iv-input-is-a-bst/
*
*
*/
// Date: Mon Aug 23 09:34:50 PDT 2021
/**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init() { self.val = 0; self.left = nil; self.right = nil; }
* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }
* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {
* self.val = val
* self.left = left
* self.right = right
* }
* }
*/
class Solution {
func findTarget(_ root: TreeNode?, _ k: Int) -> Bool {
guard let root = root else { return false }
// if root.val < k { return findTarget(root.right, k) }
// if root.val > k { return findTarget(root.left, k) }
var target: Set<Int> = []
var queue = [root]
while queue.isEmpty == false {
let node = queue.removeFirst()
if target.contains(node.val) { return true }
target.insert(k - node.val)
if let left = node.left {
queue.append(left)
}
if let right = node.right {
queue.append(right)
}
}
return false
}
} | da3aa01306a4a3a9722c35259269af1f | 30.547619 | 85 | 0.522659 | false | false | false | false |
mvetoshkin/MVImagePicker | refs/heads/master | MVImagePicker/Classes/DataSources/PhotosDataSource.swift | mit | 1 | //
// PhotosDataSource.swift
// MVImagePicker
//
// Created by Mikhail Vetoshkin on 22/06/16.
// Copyright (c) 2016 Mikhail Vetoshkin. All rights reserved.
//
import Photos
import UIKit
@objc protocol ImagePickerPhotosDataSourceDelegate {
func imagePickerPhotosDataSourceHeaderDidTap(dataSource: ImagePickerPhotosDataSource, gesture: UITapGestureRecognizer)
func imagePickerAssetDidSelect(dataSource: ImagePickerPhotosDataSource, asset: PHAsset)
func imagePickerAssetDidDeselect(dataSource: ImagePickerPhotosDataSource, asset: PHAsset)
}
class ImagePickerPhotosDataSource: NSObject, UICollectionViewDataSource {
weak var delegate: ImagePickerPhotosDataSourceDelegate?
private var album: PHAssetCollection?
private let noPhotosCellIdentifier = NSStringFromClass(ImagePickerNoPhotosView.self)
private let photoCellIdentifier = NSStringFromClass(ImagePickerPhotoCell.self)
private let headerCellIdentifier = NSStringFromClass(ImagePickerPhotosHeaderCell.self)
var fetchResult: PHFetchResult?
var selectedAssets = [PHAsset]()
var multipleSelection = true
// MARK: Lazy init
lazy private var imageManager: PHImageManager = {
return PHImageManager()
}()
// MARK: UICollectionViewDataSource
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if let cnt = self.fetchResult?.count where cnt > 0 {
return cnt
}
return 1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
if self.fetchResult?.count > 0 {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(self.photoCellIdentifier, forIndexPath: indexPath)
as! ImagePickerPhotoCell
let currentTag = cell.tag + 1
cell.tag = currentTag
let scale = UIScreen.mainScreen().scale
let itemSize = (collectionView.collectionViewLayout as! UICollectionViewFlowLayout).itemSize
let thumbSize = CGSizeMake(itemSize.width * scale, itemSize.height * scale)
let asset = self.fetchResult![indexPath.item] as! PHAsset
self.imageManager.requestImageForAsset(asset, targetSize: thumbSize, contentMode: PHImageContentMode.AspectFill,
options: nil, resultHandler: { (image, _) -> Void in
if let img = image where cell.tag == currentTag {
cell.setThumbnail(img)
}
})
return cell
}
return collectionView.dequeueReusableCellWithReuseIdentifier(self.noPhotosCellIdentifier, forIndexPath: indexPath)
as! ImagePickerNoPhotosView
}
func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView {
if kind == UICollectionElementKindSectionHeader {
let header = collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader,
withReuseIdentifier: self.headerCellIdentifier, forIndexPath: indexPath) as! ImagePickerPhotosHeaderCell
let gesture = UITapGestureRecognizer(target: self, action: #selector(ImagePickerPhotosDataSource.headerDidTap(_:)))
gesture.numberOfTapsRequired = 1
header.addGestureRecognizer(gesture)
if let title = self.album?.localizedTitle {
header.setText(title)
}
return header
}
return UICollectionReusableView()
}
// MARK: Handlers
@objc private func headerDidTap(gesture: UITapGestureRecognizer) {
self.delegate?.imagePickerPhotosDataSourceHeaderDidTap(self, gesture: gesture)
}
// MARK: Public methods
class func fetchAssets(album: PHAssetCollection?, fetchLimit: Int? = nil) -> PHFetchResult {
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [
NSSortDescriptor(key: "creationDate", ascending: false)
]
if let limit = fetchLimit {
if #available(iOS 9.0, *) {
fetchOptions.fetchLimit = limit
}
}
if let alb = album {
fetchOptions.predicate = NSPredicate(format: "mediaType == %d", PHAssetMediaType.Image.rawValue)
return PHAsset.fetchAssetsInAssetCollection(alb, options: fetchOptions)
} else {
return PHAsset.fetchAssetsWithOptions(fetchOptions)
}
}
func registerReusableViews(collectionView: UICollectionView) {
collectionView.registerClass(ImagePickerNoPhotosView.self, forCellWithReuseIdentifier: self.noPhotosCellIdentifier)
collectionView.registerClass(ImagePickerPhotoCell.self, forCellWithReuseIdentifier: self.photoCellIdentifier)
collectionView.registerClass(ImagePickerPhotosHeaderCell.self,
forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: self.headerCellIdentifier)
}
func fetchData(album: PHAssetCollection) {
self.album = album
self.fetchResult = ImagePickerPhotosDataSource.fetchAssets(album)
}
func selectAsset(asset: PHAsset) {
if !self.multipleSelection {
self.selectedAssets.removeAll(keepCapacity: false)
}
self.selectedAssets.append(asset)
self.delegate?.imagePickerAssetDidSelect(self, asset: asset)
}
func deselectAsset(asset: PHAsset) {
if let idx = self.selectedAssets.indexOf(asset) {
self.selectedAssets.removeAtIndex(idx)
self.delegate?.imagePickerAssetDidDeselect(self, asset: asset)
}
}
}
| 6a12b5d642af59a7a3d1d7aed2b5e338 | 37.203947 | 171 | 0.698123 | false | false | false | false |
griff/metaz | refs/heads/develop | Plugins/TheTVDB3/src/Token.swift | mit | 1 | //
// Token.swift
// TheTVDB_NG
//
// Created by Brian Olsen on 21/02/2020.
//
import Foundation
import MetaZKit
class Token {
public static let API_KEY = "EC3E583524604886"
let value: String
let exp : Date
class TokenData : Codable {
public let exp: TimeInterval
}
public class TokenProvider {
private let tokenQueue : DispatchQueue
private var currentToken : Token?
init() {
tokenQueue = DispatchQueue(label: "io.metaz.TheTVDB3TokenQueue")
if let token = UserDefaults.standard.string(forKey: "TheTVDB3") {
currentToken = Token(token)
}
}
public var token: Token? {
get {
return tokenQueue.sync {
if let result = currentToken, result.valid() {
return result
} else if let result = login() {
UserDefaults.standard.set(result.value, forKey: "TheTVDB3")
currentToken = result
return result
} else {
return nil
}
}
}
}
private func login() -> Token? {
struct LoginResponse : Codable {
let token: String
}
struct Login : Codable {
let apiKey: String
}
guard let key = try? JSONEncoder().encode(Login(apiKey: Token.API_KEY))
else { return nil }
guard let url = URL(string: "\(Search.basePath)/login") else { return nil }
let headers = ["Content-Type": "application/json",
"Accept": "application/vnd.thetvdb.v3"]
guard let data_o = try? URLSession.dataSync(url: url,
method: "POST",
body: key,
headers: headers)
else { return nil }
guard let data = data_o else { return nil }
guard let token = try? JSONDecoder().decode(LoginResponse.self, from: data)
else { return nil }
return Token(token.token)
}
}
public static let shared = TokenProvider()
init(_ key: String) {
value = key
if let parsed = Token.parse(token: key) {
exp = parsed
} else {
exp = Date.distantPast
}
}
static func parse(token: String) -> Date? {
guard let data = token.split(separator: ".").safeGet(index: 1) else { return nil }
guard let jwt = Data(base64URLEncoded: String(data)) else { return nil }
guard let td = try? JSONDecoder().decode(TokenData.self, from: jwt) else { return nil }
return Date(timeIntervalSince1970: td.exp)
}
func valid() -> Bool {
return Date() < self.exp
}
}
| 8a8aa72ce3673fd11fe869a34756f1f5 | 31.595745 | 95 | 0.48107 | false | false | false | false |
EaglesoftZJ/actor-platform | refs/heads/master | actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Group/Cells/AAGroupMemberCell.swift | agpl-3.0 | 4 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import UIKit
open class AAGroupMemberCell: AATableViewCell {
// Views
open var nameLabel = UILabel()
open var onlineLabel = UILabel()
open var avatarView = AAAvatarView()
open var adminLabel = UILabel()
// Binder
open var binder = AABinder()
// Contstructors
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
adminLabel.text = AALocalized("GroupMemberAdmin")
adminLabel.sizeToFit()
contentView.addSubview(avatarView)
nameLabel.font = UIFont.systemFont(ofSize: 18.0)
nameLabel.textColor = appStyle.cellTextColor
contentView.addSubview(nameLabel)
onlineLabel.font = UIFont.systemFont(ofSize: 14.0)
contentView.addSubview(onlineLabel)
adminLabel.font = UIFont.systemFont(ofSize: 14.0)
adminLabel.textColor = appStyle.cellDestructiveColor
contentView.addSubview(adminLabel)
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// Binding
open func setUsername(_ username: String) {
nameLabel.text = username
}
open func bind(_ user: ACUserVM, isAdmin: Bool) {
// Bind name and avatar
let name = user.getNameModel().get()!
nameLabel.text = name
avatarView.bind(name, id: Int(user.getId()), avatar: user.getAvatarModel().get())
// Bind admin flag
adminLabel.isHidden = !isAdmin
// Bind onlines
if user.isBot() {
self.onlineLabel.textColor = self.appStyle.userOnlineColor
self.onlineLabel.text = "bot"
self.onlineLabel.alpha = 1
} else {
binder.bind(user.getPresenceModel()) { (value: ACUserPresence?) -> () in
if value != nil {
self.onlineLabel.showView()
self.onlineLabel.text = Actor.getFormatter().formatPresence(value!, with: user.getSex())
if value!.state.ordinal() == ACUserPresence_State.online().ordinal() {
self.onlineLabel.textColor = self.appStyle.userOnlineColor
} else {
self.onlineLabel.textColor = self.appStyle.userOfflineColor
}
} else {
self.onlineLabel.alpha = 0
self.onlineLabel.text = ""
}
}
}
}
open override func prepareForReuse() {
super.prepareForReuse()
binder.unbindAll()
}
// Layouting
open override func layoutSubviews() {
super.layoutSubviews()
let userAvatarViewFrameSize: CGFloat = CGFloat(44)
avatarView.frame = CGRect(x: 14.0, y: (contentView.bounds.size.height - userAvatarViewFrameSize) / 2.0, width: userAvatarViewFrameSize, height: userAvatarViewFrameSize)
var w: CGFloat = contentView.bounds.size.width - 65.0 - 8.0
if !adminLabel.isHidden {
adminLabel.frame = CGRect(x: contentView.width - adminLabel.width - 8, y: 5, width: adminLabel.width, height: 42)
w -= adminLabel.width + 8
}
nameLabel.frame = CGRect(x: 65.0, y: 5, width: w, height: 22)
onlineLabel.frame = CGRect(x: 65.0, y: 27, width: w, height: 16)
}
}
| 5db196aa6be25d8de65ab4b796c174e9 | 31.972727 | 176 | 0.575958 | false | false | false | false |
jphacks/TK_08 | refs/heads/master | iOS/AirMeet/AirMeet/ENSideMenu.swift | mit | 1 | //
// SideMenu.swift
// SwiftSideMenu
//
// Created by Evgeny on 24.07.14.
// Copyright (c) 2014 Evgeny Nazarov. All rights reserved.
//
import UIKit
@objc public protocol ENSideMenuDelegate {
optional func sideMenuWillOpen()
optional func sideMenuWillClose()
optional func sideMenuDidOpen()
optional func sideMenuDidClose()
optional func sideMenuShouldOpenSideMenu () -> Bool
}
@objc public protocol ENSideMenuProtocol {
var sideMenu : ENSideMenu? { get }
func setContentViewController(contentViewController: UIViewController)
}
public enum ENSideMenuAnimation : Int {
case None
case Default
}
/**
The position of the side view on the screen.
- Left: Left side of the screen
- Right: Right side of the screen
*/
public enum ENSideMenuPosition : Int {
case Left
case Right
}
public extension UIViewController {
/**
Changes current state of side menu view.
*/
public func toggleSideMenuView () {
sideMenuController()?.sideMenu?.toggleMenu()
}
/**
Hides the side menu view.
*/
public func hideSideMenuView () {
sideMenuController()?.sideMenu?.hideSideMenu()
}
/**
Shows the side menu view.
*/
public func showSideMenuView () {
sideMenuController()?.sideMenu?.showSideMenu()
}
/**
Returns a Boolean value indicating whether the side menu is showed.
:returns: BOOL value
*/
public func isSideMenuOpen () -> Bool {
let sieMenuOpen = self.sideMenuController()?.sideMenu?.isMenuOpen
return sieMenuOpen!
}
/**
* You must call this method from viewDidLayoutSubviews in your content view controlers so it fixes size and position of the side menu when the screen
* rotates.
* A convenient way to do it might be creating a subclass of UIViewController that does precisely that and then subclassing your view controllers from it.
*/
func fixSideMenuSize() {
if let navController = self.navigationController as? ENSideMenuNavigationController {
navController.sideMenu?.updateFrame()
}
}
/**
Returns a view controller containing a side menu
:returns: A `UIViewController`responding to `ENSideMenuProtocol` protocol
*/
public func sideMenuController () -> ENSideMenuProtocol? {
var iteration : UIViewController? = self.parentViewController
if (iteration == nil) {
return topMostController()
}
repeat {
if (iteration is ENSideMenuProtocol) {
return iteration as? ENSideMenuProtocol
} else if (iteration?.parentViewController != nil && iteration?.parentViewController != iteration) {
iteration = iteration!.parentViewController
} else {
iteration = nil
}
} while (iteration != nil)
return iteration as? ENSideMenuProtocol
}
internal func topMostController () -> ENSideMenuProtocol? {
var topController : UIViewController? = UIApplication.sharedApplication().keyWindow?.rootViewController
if (topController is UITabBarController) {
topController = (topController as! UITabBarController).selectedViewController
}
while (topController?.presentedViewController is ENSideMenuProtocol) {
topController = topController?.presentedViewController
}
return topController as? ENSideMenuProtocol
}
}
public class ENSideMenu : NSObject, UIGestureRecognizerDelegate {
/// The width of the side menu view. The default value is 160.
public var menuWidth : CGFloat = 160.0 {
didSet {
needUpdateApperance = true
updateFrame()
}
}
private var menuPosition:ENSideMenuPosition = .Left
private var blurStyle: UIBlurEffectStyle = .Light
/// A Boolean value indicating whether the bouncing effect is enabled. The default value is TRUE.
public var bouncingEnabled :Bool = true
/// The duration of the slide animation. Used only when `bouncingEnabled` is FALSE.
public var animationDuration = 0.4
private let sideMenuContainerView = UIView()
private(set) var menuViewController : UIViewController!
private var animator : UIDynamicAnimator!
private var sourceView : UIView!
private var needUpdateApperance : Bool = false
/// The delegate of the side menu
public weak var delegate : ENSideMenuDelegate?
private(set) var isMenuOpen : Bool = false
/// A Boolean value indicating whether the left swipe is enabled.
public var allowLeftSwipe : Bool = true
/// A Boolean value indicating whether the right swipe is enabled.
public var allowRightSwipe : Bool = true
public var allowPanGesture : Bool = true
private var panRecognizer : UIPanGestureRecognizer?
/**
Initializes an instance of a `ENSideMenu` object.
:param: sourceView The parent view of the side menu view.
:param: menuPosition The position of the side menu view.
:returns: An initialized `ENSideMenu` object, added to the specified view.
*/
public init(sourceView: UIView, menuPosition: ENSideMenuPosition, blurStyle: UIBlurEffectStyle = .Light) {
super.init()
self.sourceView = sourceView
self.menuPosition = menuPosition
self.blurStyle = blurStyle
self.setupMenuView()
animator = UIDynamicAnimator(referenceView:sourceView)
animator.delegate = self
self.panRecognizer = UIPanGestureRecognizer(target: self, action: "handlePan:")
panRecognizer!.delegate = self
sourceView.addGestureRecognizer(panRecognizer!)
// Add right swipe gesture recognizer
let rightSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:")
rightSwipeGestureRecognizer.delegate = self
rightSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Right
// Add left swipe gesture recognizer
let leftSwipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: "handleGesture:")
leftSwipeGestureRecognizer.delegate = self
leftSwipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Left
if (menuPosition == .Left) {
sourceView.addGestureRecognizer(rightSwipeGestureRecognizer)
sideMenuContainerView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
else {
sideMenuContainerView.addGestureRecognizer(rightSwipeGestureRecognizer)
sourceView.addGestureRecognizer(leftSwipeGestureRecognizer)
}
}
/**
Initializes an instance of a `ENSideMenu` object.
:param: sourceView The parent view of the side menu view.
:param: menuViewController A menu view controller object which will be placed in the side menu view.
:param: menuPosition The position of the side menu view.
:returns: An initialized `ENSideMenu` object, added to the specified view, containing the specified menu view controller.
*/
public convenience init(sourceView: UIView, menuViewController: UIViewController, menuPosition: ENSideMenuPosition, blurStyle: UIBlurEffectStyle = .Light) {
self.init(sourceView: sourceView, menuPosition: menuPosition, blurStyle: blurStyle)
self.menuViewController = menuViewController
self.menuViewController.view.frame = sideMenuContainerView.bounds
self.menuViewController.view.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
sideMenuContainerView.addSubview(self.menuViewController.view)
}
/*
public convenience init(sourceView: UIView, view: UIView, menuPosition: ENSideMenuPosition) {
self.init(sourceView: sourceView, menuPosition: menuPosition)
view.frame = sideMenuContainerView.bounds
view.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
sideMenuContainerView.addSubview(view)
}
*/
/**
Updates the frame of the side menu view.
*/
func updateFrame() {
var width:CGFloat
var height:CGFloat
(width, height) = adjustFrameDimensions( sourceView.frame.size.width, height: sourceView.frame.size.height)
let menuFrame = CGRectMake(
(menuPosition == .Left) ?
isMenuOpen ? 0 : -menuWidth-1.0 :
isMenuOpen ? width - menuWidth : width+1.0,
sourceView.frame.origin.y,
menuWidth,
height
)
sideMenuContainerView.frame = menuFrame
}
private func adjustFrameDimensions( width: CGFloat, height: CGFloat ) -> (CGFloat,CGFloat) {
if floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1 &&
(UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.LandscapeRight ||
UIApplication.sharedApplication().statusBarOrientation == UIInterfaceOrientation.LandscapeLeft) {
// iOS 7.1 or lower and landscape mode -> interchange width and height
return (height, width)
}
else {
return (width, height)
}
}
private func setupMenuView() {
// Configure side menu container
updateFrame()
sideMenuContainerView.backgroundColor = UIColor.clearColor()
sideMenuContainerView.clipsToBounds = false
sideMenuContainerView.layer.masksToBounds = false
sideMenuContainerView.layer.shadowOffset = (menuPosition == .Left) ? CGSizeMake(1.0, 1.0) : CGSizeMake(-1.0, -1.0)
sideMenuContainerView.layer.shadowRadius = 1.0
sideMenuContainerView.layer.shadowOpacity = 0.125
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath
sourceView.addSubview(sideMenuContainerView)
if (NSClassFromString("UIVisualEffectView") != nil) {
// Add blur view
let visualEffectView = UIVisualEffectView(effect: UIBlurEffect(style: blurStyle)) as UIVisualEffectView
visualEffectView.frame = sideMenuContainerView.bounds
visualEffectView.autoresizingMask = [.FlexibleHeight, .FlexibleWidth]
sideMenuContainerView.addSubview(visualEffectView)
}
else {
// TODO: add blur for ios 7
}
}
private func toggleMenu (shouldOpen: Bool) {
if (shouldOpen && delegate?.sideMenuShouldOpenSideMenu?() == false) {
return
}
updateSideMenuApperanceIfNeeded()
isMenuOpen = shouldOpen
var width:CGFloat
var height:CGFloat
(width, height) = adjustFrameDimensions( sourceView.frame.size.width, height: sourceView.frame.size.height)
if (bouncingEnabled) {
animator.removeAllBehaviors()
var gravityDirectionX: CGFloat
var pushMagnitude: CGFloat
var boundaryPointX: CGFloat
var boundaryPointY: CGFloat
if (menuPosition == .Left) {
// Left side menu
gravityDirectionX = (shouldOpen) ? 1 : -1
pushMagnitude = (shouldOpen) ? 20 : -20
boundaryPointX = (shouldOpen) ? menuWidth : -menuWidth-2
boundaryPointY = 20
}
else {
// Right side menu
gravityDirectionX = (shouldOpen) ? -1 : 1
pushMagnitude = (shouldOpen) ? -20 : 20
boundaryPointX = (shouldOpen) ? width-menuWidth : width+menuWidth+2
boundaryPointY = -20
}
let gravityBehavior = UIGravityBehavior(items: [sideMenuContainerView])
gravityBehavior.gravityDirection = CGVectorMake(gravityDirectionX, 0)
animator.addBehavior(gravityBehavior)
let collisionBehavior = UICollisionBehavior(items: [sideMenuContainerView])
collisionBehavior.addBoundaryWithIdentifier("menuBoundary", fromPoint: CGPointMake(boundaryPointX, boundaryPointY),
toPoint: CGPointMake(boundaryPointX, height))
animator.addBehavior(collisionBehavior)
let pushBehavior = UIPushBehavior(items: [sideMenuContainerView], mode: UIPushBehaviorMode.Instantaneous)
pushBehavior.magnitude = pushMagnitude
animator.addBehavior(pushBehavior)
let menuViewBehavior = UIDynamicItemBehavior(items: [sideMenuContainerView])
menuViewBehavior.elasticity = 0.25
animator.addBehavior(menuViewBehavior)
}
else {
var destFrame :CGRect
if (menuPosition == .Left) {
destFrame = CGRectMake((shouldOpen) ? -2.0 : -menuWidth, 0, menuWidth, height)
}
else {
destFrame = CGRectMake((shouldOpen) ? width-menuWidth : width+2.0,
0,
menuWidth,
height)
}
UIView.animateWithDuration(
animationDuration,
animations: { () -> Void in
self.sideMenuContainerView.frame = destFrame
},
completion: { (Bool) -> Void in
if (self.isMenuOpen) {
self.delegate?.sideMenuDidOpen?()
} else {
self.delegate?.sideMenuDidClose?()
}
})
}
if (shouldOpen) {
delegate?.sideMenuWillOpen?()
} else {
delegate?.sideMenuWillClose?()
}
}
public func gestureRecognizerShouldBegin(gestureRecognizer: UIGestureRecognizer) -> Bool {
if gestureRecognizer is UISwipeGestureRecognizer {
let swipeGestureRecognizer = gestureRecognizer as! UISwipeGestureRecognizer
if !self.allowLeftSwipe {
if swipeGestureRecognizer.direction == .Left {
return false
}
}
if !self.allowRightSwipe {
if swipeGestureRecognizer.direction == .Right {
return false
}
}
}
else if gestureRecognizer.isEqual(panRecognizer) {
if allowPanGesture == false {
return false
}
animator.removeAllBehaviors()
let touchPosition = gestureRecognizer.locationOfTouch(0, inView: sourceView)
if menuPosition == .Left {
if isMenuOpen {
if touchPosition.x < menuWidth {
return true
}
}
else {
if touchPosition.x < 25 {
return true
}
}
}
else {
if isMenuOpen {
if touchPosition.x > CGRectGetWidth(sourceView.frame) - menuWidth {
return true
}
}
else {
if touchPosition.x > CGRectGetWidth(sourceView.frame)-25 {
return true
}
}
}
return false
}
return true
}
internal func handleGesture(gesture: UISwipeGestureRecognizer) {
toggleMenu((self.menuPosition == .Right && gesture.direction == .Left)
|| (self.menuPosition == .Left && gesture.direction == .Right))
}
internal func handlePan(recognizer : UIPanGestureRecognizer){
let leftToRight = recognizer.velocityInView(recognizer.view).x > 0
switch recognizer.state {
case .Began:
break
case .Changed:
let translation = recognizer.translationInView(sourceView).x
let xPoint : CGFloat = sideMenuContainerView.center.x + translation + (menuPosition == .Left ? 1 : -1) * menuWidth / 2
if menuPosition == .Left {
if xPoint <= 0 || xPoint > CGRectGetWidth(self.sideMenuContainerView.frame) {
return
}
}else{
if xPoint <= sourceView.frame.size.width - menuWidth || xPoint >= sourceView.frame.size.width
{
return
}
}
sideMenuContainerView.center.x = sideMenuContainerView.center.x + translation
recognizer.setTranslation(CGPointZero, inView: sourceView)
default:
let shouldClose = menuPosition == .Left ? !leftToRight && CGRectGetMaxX(sideMenuContainerView.frame) < menuWidth : leftToRight && CGRectGetMinX(sideMenuContainerView.frame) > (sourceView.frame.size.width - menuWidth)
toggleMenu(!shouldClose)
}
}
private func updateSideMenuApperanceIfNeeded () {
if (needUpdateApperance) {
var frame = sideMenuContainerView.frame
frame.size.width = menuWidth
sideMenuContainerView.frame = frame
sideMenuContainerView.layer.shadowPath = UIBezierPath(rect: sideMenuContainerView.bounds).CGPath
needUpdateApperance = false
}
}
/**
Toggles the state of the side menu.
*/
public func toggleMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
else {
updateSideMenuApperanceIfNeeded()
toggleMenu(true)
}
}
/**
Shows the side menu if the menu is hidden.
*/
public func showSideMenu () {
if (!isMenuOpen) {
toggleMenu(true)
}
}
/**
Hides the side menu if the menu is showed.
*/
public func hideSideMenu () {
if (isMenuOpen) {
toggleMenu(false)
}
}
}
extension ENSideMenu: UIDynamicAnimatorDelegate {
public func dynamicAnimatorDidPause(animator: UIDynamicAnimator) {
if (self.isMenuOpen) {
self.delegate?.sideMenuDidOpen?()
} else {
self.delegate?.sideMenuDidClose?()
}
}
public func dynamicAnimatorWillResume(animator: UIDynamicAnimator) {
}
}
| 24687f8aae76f9f73cb9a665862dc467 | 36.402 | 229 | 0.607508 | false | false | false | false |
badoo/Chatto | refs/heads/master | Chatto/sources/ChatController/ChatMessages/New/ChatCollectionViewLayoutModelFactory.swift | mit | 1 | /*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
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 protocol ChatCollectionViewLayoutModelFactoryProtocol: AnyObject {
func createLayoutModel(items: ChatItemCompanionCollection,
collectionViewWidth: CGFloat) -> ChatCollectionViewLayoutModel
}
final class ChatCollectionViewLayoutModelFactory: ChatCollectionViewLayoutModelFactoryProtocol {
// MARK: - Type declarations
private struct HeightValue {
var value: CGFloat = 0
private let heightProvider: () -> CGFloat
init(_ heightProvider: @escaping () -> CGFloat) {
self.heightProvider = heightProvider
}
mutating func calculate() {
self.value = self.heightProvider()
}
}
// MARK: - Instantiation
init() {}
// MARK: - ChatCollectionViewLayoutUpdater
public func createLayoutModel(items: ChatItemCompanionCollection,
collectionViewWidth width: CGFloat) -> ChatCollectionViewLayoutModel {
var heights = items.map { companion in
HeightValue { companion.height(forMaxWidth: width) }
}
enum ExecutionContext { case this, main }
let isMainThread = Thread.isMainThread
let contexts: Indices<ExecutionContext> = Indices(of: items) {
isMainThread || $0.presenter.canCalculateHeightInBackground ? .this : .main
}
for index in contexts[.this] {
heights[index].calculate()
}
if !contexts[.main].isEmpty {
DispatchQueue.main.sync {
for index in contexts[.main] {
heights[index].calculate()
}
}
}
let heightValues = heights.map { $0.value }
let bottomMargins = items.map(\.bottomMargin)
let layoutData = Array(zip(heightValues, bottomMargins))
return ChatCollectionViewLayoutModel.createModel(width, itemsLayoutData: layoutData)
}
}
private extension ChatItemCompanion {
func height(forMaxWidth maxWidth: CGFloat) -> CGFloat {
self.presenter.heightForCell(maximumWidth: maxWidth,
decorationAttributes: self.decorationAttributes)
}
var bottomMargin: CGFloat { self.decorationAttributes?.bottomMargin ?? 0 }
}
private struct Indices<Key: Hashable> {
private let indicesByKey: [Key: Set<Int>]
init<C: Collection>(of collection: C, decide: (C.Element) -> Key) where C.Index == Int {
var indicesByKey: [Key: Set<Int>] = [:]
for (index, element) in collection.enumerated() {
indicesByKey[decide(element), default: []].insert(index)
}
self.indicesByKey = indicesByKey
}
subscript(_ key: Key) -> Set<Int> {
self.indicesByKey[key] ?? []
}
}
| 98ba6e9ca3d8293c914718e457e18d93 | 32 | 96 | 0.677545 | false | false | false | false |
openium/SwiftiumKit | refs/heads/master | Tests/SwiftiumKitTests/Additions/Foundation/StringExtensionsTests.swift | apache-2.0 | 1 | //
// String+SKAdditionsTests.swift
// SwiftiumKit
//
// Created by Richard Bergoin on 10/03/16.
// Copyright © 2016 Openium. All rights reserved.
//
import XCTest
class StringExtensionsTests: XCTestCase {
let stringToHash = "La chaine à hacher"
let emptyString = ""
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testMd5() {
// Given
// When
let hash = stringToHash.md5
// Expect
XCTAssertEqual(hash, "bbd5d80e828e166774b4c35076e5b1a6")
}
func testMd5_withEmptyString() {
// Given
// When
let hash = emptyString.md5
// Expect
XCTAssertEqual(hash, "d41d8cd98f00b204e9800998ecf8427e")
}
func testSha1() {
// Given
// When
let hash = stringToHash.sha1
// Expect
XCTAssertEqual(hash, "5ba4936fca2ab56482b310ddcf57dc8e87b96b54")
}
func testSha224() {
// Given
// When
let hash = stringToHash.sha224
// Expect
XCTAssertEqual(hash, "c875a5f938279f1eb0461582757bf101337292c5cab5dde31d25a1f5")
}
func testSha256() {
// Given
// When
let hash = stringToHash.sha256
// Expect
XCTAssertEqual(hash, "10aad976dbc9336d781821f8b1d87eebf1aff367a6c494646ce4ce7b725b66a4")
}
func testSha384() {
// Given
// When
let hash = stringToHash.sha384
// Expect
XCTAssertEqual(hash, "15bc03d7299d6edd7ed836bd1821cbab5ddb671c59b7ed6c3dd428e42996bebc47d40a594e97182a4e0fcd7beb6ba663")
}
func testSha512() {
// Given
// When
let hash = stringToHash.sha512
// Expect
XCTAssertEqual(hash, "4afd5988044494e55a91f26208849ce2221cd50e5b3e363c23f96ebc2f64c0679f5c85325cba71ae8d2df3a523795b2aefb2adb95030a4a4ddf519551e13cc8c")
}
func testHmacSHA1() {
// Given
let passmd5 = "5f4dcc3b5aa765d61d8327deb882cf99";
let strToSign = "GET\n1391863865\nparam=value¶m2=value2\n/path/to/api";
// When
let shaStr = strToSign.hmacSha1(passmd5)
// Expect
XCTAssertEqual(shaStr, "18835978a0297b5efca1e44d954f4f0c00b2b903")
}
// MARK: -
func testIntSubscript() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let thirdChar = someString[3]
let lastChar = someString[someString.count - 1]
// Expect
XCTAssertEqual(thirdChar, "d")
XCTAssertEqual(lastChar, "9")
}
func testIntSubscript_setCharacter_shouldReplace() {
// Given
var someString = "5f4dcc3b5aa765d61d8327deb882cf99";
let expected = "Af4dcc3b5aa765d61d8327deb882cf9A";
// When
someString[0] = "A"
someString[someString.count - 1] = "A"
// Expect
XCTAssertEqual(someString, expected)
}
func testIntSubscript_setString_shouldReplaceAndExtendString() {
// Given
var someString = "5f4dcc3b5aa765d61d8327deb882cf99";
let expected = "ABCDEFf4dcc3b5aa765d61d8327deb882cf99";
// When
someString[0] = "ABCDEF"
// Expect
XCTAssertEqual(someString, expected)
}
func testIntSubscript_setString_shouldReplaceAndShorterString() {
// Given
var someString = "5f4dcc3b5aa765d61d8327deb882cf99";
let expected = "f4dcc3b5aa765d61d8327deb882cf99";
// When
someString[0] = ""
// Expect
XCTAssertEqual(someString, expected)
}
func testIntSubscript_usingNegativeIndex() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let thirdLastChar = someString[-3]
let lastChart = someString[-1]
let firtChar = someString[-someString.count]
// Expect
XCTAssertEqual(thirdLastChar, "f")
XCTAssertEqual(lastChart, "9")
XCTAssertEqual(firtChar, "5")
}
func testIntSubscript_outOfRange_shouldReturnNil() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let outOfRangeChar = someString[someString.count]
// Expect
XCTAssertEqual(outOfRangeChar, nil)
}
func testIntSubscript_usingNegativeIndexOutOfRange_shouldReturnNil() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let outOfRangeChar = someString[-Int.max]
// Expect
XCTAssertEqual(outOfRangeChar, nil)
}
func testClosedRangeIntSubscript() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let first4Chars = someString[0...3]
// Expect
XCTAssertEqual(first4Chars, "5f4d")
}
func testClosedRangeIntSubscript_usingUpperOutOfRangeIndex_shouldReturnEmptyString() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let emptyString = someString[Int.max...Int.max]
// Expect
XCTAssertEqual(emptyString, "")
}
func testClosedRangeIntSubscript_usingSameLowerUpperIndex_shouldReturnEmptyString() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let thirdChar = someString[3...3]
// Expect
XCTAssertEqual(thirdChar, "d")
}
func testClosedRangeIntSubscript_outOfRangeUpperAndLower_shouldReturnFullString() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let fullString = someString[-1...someString.count]
// Expect
XCTAssertEqual(fullString, someString)
}
func testClosedRangeIntSubscript_outOfRange_shouldBounds() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let index = someString.count - 4
let last4Chars = someString[index...Int.max]
// Expect
XCTAssertEqual(last4Chars, "cf99")
}
func testRangeIntSubscript() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let first3Chars = someString[0..<3]
// Expect
XCTAssertEqual(first3Chars, "5f4")
}
func testRangeIntSubscript_outOfRange_shouldBounds() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let index = someString.count - 4
let last4Chars = someString[index..<Int.max]
// Expect
XCTAssertEqual(last4Chars, "cf99")
}
func testRangeIntSubscript_usingUpperOutOfRangeIndex_shouldReturnEmptyString() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let emptyString = someString[Int.max..<Int.max]
// Expect
XCTAssertEqual(emptyString, "")
}
func testRangeIntSubscript_usingSameLowerUpperIndex_shouldReturnEmptyString() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let emptyString = someString[4..<4]
// Expect
XCTAssertEqual(emptyString, "")
}
func testRangeIntSubscript_outOfRangeUpperAndLower_shouldReturnFullString() {
// Given
let someString = "5f4dcc3b5aa765d61d8327deb882cf99";
// When
let fullString = someString[-1..<someString.count]
// Expect
XCTAssertEqual(fullString, someString)
}
// MARK: - Disabled tests
func disabled_testIntSubscript_negativeIndex_shouldRaisePreconditionFailure() {
// Given
var someString = "5f4dcc3b5aa765d61d8327deb882cf99";
let expected = "f4dcc3b5aa765d61d8327deb882cf99";
// When
someString[-1] = ""
// Expect
XCTAssertEqual(someString, expected)
}
func disabled_testIntSubscript_outOfRangeIndex_shouldRaisePreconditionFailure() {
// Given
var someString = "5f4dcc3b5aa765d61d8327deb882cf99";
let expected = "f4dcc3b5aa765d61d8327deb882cf99";
// When
someString[someString.count] = ""
// Expect
XCTAssertEqual(someString, expected)
}
func disabled_testIntSubscript_nilNewValue_shouldRaisePreconditionFailure() {
// Given
var someString = "5f4dcc3b5aa765d61d8327deb882cf99";
let expected = "f4dcc3b5aa765d61d8327deb882cf99";
// When
someString[0] = nil
// Expect
XCTAssertEqual(someString, expected)
}
// MARK: -
func testFirstLowercased_withEmptyString_shouldReturnEmptyString() {
// Given
// When
let result = emptyString.firstLowercased()
// Expect
XCTAssertEqual(result, "")
}
func testFirstLowercased_withNonEmptyString_shouldReturnFirstCharLowercased() {
// Given
let sut = "Uppercase Words In String"
// When
let result = sut.firstLowercased()
// Expect
XCTAssertEqual(result, "uppercase Words In String")
}
// MARK: -
func testIsEmail_lowercase_valid() {
// Given
let email = "[email protected]"
// When
let isEmail = email.isEmail
// Expect
XCTAssertTrue(isEmail)
}
func testIsEmail_randomcase_valid() {
// Given
let email = "[email protected]"
// When
let isEmail = email.isEmail
// Expect
XCTAssertTrue(isEmail)
}
func testIsEmail_no_tld_invalid() {
// Given
let email = "fistname.lastname@domain"
// When
let isEmail = email.isEmail
// Expect
XCTAssertFalse(isEmail)
}
func testIsEmail_no_tld_ending_dot_invalid() {
// Given
let email = "fistname.lastname@domain."
// When
let isEmail = email.isEmail
// Expect
XCTAssertFalse(isEmail)
}
func testIsEmail_no_at_invalid() {
// Given
let email = "fistname.lastnamedomain.tld"
// When
let isEmail = email.isEmail
// Expect
XCTAssertFalse(isEmail)
}
func testIsEmail_no_name_invalid() {
// Given
let email = "@domain.tld"
// When
let isEmail = email.isEmail
// Expect
XCTAssertFalse(isEmail)
}
func testIsEmail_whitespace_name_invalid() {
// Given
let email = "fistname [email protected]"
// When
let isEmail = email.isEmail
// Expect
XCTAssertFalse(isEmail)
}
func testIsEmail_whitespace_domain_invalid() {
// Given
let email = "fistname.lastname@dom ain.tld"
// When
let isEmail = email.isEmail
// Expect
XCTAssertFalse(isEmail)
}
func testIsEmail_whitespace_tld_invalid() {
// Given
let email = "[email protected] ld"
// When
let isEmail = email.isEmail
// Expect
XCTAssertFalse(isEmail)
}
func testIsEmail_double_dot_name_invalid() {
// Given
let email = "[email protected]"
// When
let isEmail = email.isEmail
// Expect
XCTAssertFalse(isEmail)
}
func testIsEmail_double_email_valid() {
// Given
let email = "[email protected]"
// When
let isEmail = email.isEmail
// Expect
XCTAssertTrue(isEmail)
}
func testIsEmail_double_plus_email_valid() {
// Given
let email = "[email protected]"
// When
let isEmail = email.isEmail
// Expect
XCTAssertTrue(isEmail)
}
func testIsEmail_leading_whitespace_email_invalid() {
// Given
let email = " [email protected]"
// When
let isEmail = email.isEmail
// Expect
XCTAssertFalse(isEmail)
}
func testIsEmail_trailing_whitespace_email_invalid() {
// Given
let email = "[email protected] "
// When
let isEmail = email.isEmail
// Expect
XCTAssertFalse(isEmail)
}
// MARK: -
func testReplaceOccurrences_oneTime() {
// Given
var someString = "a lazy dog"
let expected = "a lazy cat"
// When
let replacedCount = someString.replaceOccurrences(of: "dog", with: "cat")
// Expect
XCTAssertEqual(replacedCount, 1)
XCTAssertEqual(someString, expected)
}
func testReplaceOccurrences_twoTimes() {
// Given
var someString = "blop blop"
let expected = "blip blip"
// When
let replacedCount = someString.replaceOccurrences(of: "blop", with: "blip")
// Expect
XCTAssertEqual(replacedCount, 2)
XCTAssertEqual(someString, expected)
}
func testReplaceOccurrences_ofMissingString_shouldReplaceNothing() {
// Given
var someString = "blop blop"
let expected = "blop blop"
// When
let replacedCount = someString.replaceOccurrences(of: "dog", with: "cat")
// Expect
XCTAssertEqual(replacedCount, 0)
XCTAssertEqual(someString, expected)
}
}
| b94e3abac5098c008de32f3ace630c4a | 24.495575 | 160 | 0.565359 | false | true | false | false |
mcgraw/tomorrow | refs/heads/master | Tomorrow/IGITaskReviewViewController.swift | bsd-2-clause | 1 | //
// IGITaskReviewViewController.swift
// Tomorrow
//
// Created by David McGraw on 1/24/15.
// Copyright (c) 2015 David McGraw. All rights reserved.
//
import UIKit
import Realm
import pop
class IGITaskReviewViewController: GAITrackedViewController {
@IBOutlet weak var titleLabel: IGILabel!
@IBOutlet weak var task1: IGILabel!
@IBOutlet weak var task2: IGILabel!
@IBOutlet weak var task3: IGILabel!
@IBOutlet weak var completeAction: IGIButton!
@IBOutlet weak var info: IGILabel!
var userObject: IGIUser?
override func viewDidLoad() {
super.viewDidLoad()
view.userInteractionEnabled = false
view.backgroundColor = UIColor.clearColor()
let users = IGIUser.allObjects()
if users.count > 0 {
userObject = users[0] as? IGIUser
} else {
assertionFailure("Something went wrong! User does not exist so we cannot add taskss!")
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
screenName = "Task Review Screen"
if let goal = userObject?.getCurrentGoalUnderEdit() {
var index = 0
let count = goal.tasks.count
for item in goal.tasks {
var task = item as! IGITask
let title = task.getTaskTitle()
if index == 0 {
task1?.text = title
} else if index == 1 {
task2?.text = title
} else if index == 2 {
task3?.text = title
}
index++
}
} else {
assertionFailure("A goal should exist! No goal with edit_completed == false found.")
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
playIntroductionAnimation()
}
@IBAction func completeActionPressed(sender: AnyObject) {
UIView.animateWithDuration(0.4, animations: {
self.titleLabel.alpha = 0.0
self.completeAction.alpha = 0.0
self.info.alpha = 0.0
})
// We're done editing this goal
if let goal = userObject?.getCurrentGoalUnderEdit() {
RLMRealm.defaultRealm().beginWriteTransaction()
goal.edit_completed = true
RLMRealm.defaultRealm().commitWriteTransaction()
}
let goals = IGIGoal.allObjects()
println("Goal count is \(goals.count)")
if goals.count > 1 {
UIView.animateWithDuration(0.5, animations: {
self.view.alpha = 0.0
}, completion: { (done) in
println("")
NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: "transitionToTimeline", userInfo: nil, repeats: false)
})
} else {
let build = GAIDictionaryBuilder.createEventWithCategory("milestone", action: "onboard_completed", label: nil, value: nil).build()
GAI.sharedInstance().defaultTracker.send(build as [NSObject: AnyObject])
// Jump the tasks before transitioning to the timeline
task1.jumpAnimationToConstant(-300, delayStart: 0)
task2.jumpAnimationToConstant(-300, delayStart: 0.3)
task3.jumpAnimationToConstant(-300, delayStart: 0.6)
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "kOnboardCompleted")
NSUserDefaults.standardUserDefaults().synchronize()
NSTimer.scheduledTimerWithTimeInterval(1.2, target: self, selector: "transitionToTimeline", userInfo: nil, repeats: false)
}
}
@IBAction func taskEditPressed(sender: AnyObject) {
var tag: Int = (sender.tag - 1000) - 1
userObject!.setTaskNeedsEdit(index: UInt(tag))
UIView.animateWithDuration(0.3, animations: {
self.titleLabel.alpha = 0.0
self.task1.alpha = 0.0
self.task2.alpha = 0.0
self.task3.alpha = 0.0
self.completeAction.alpha = 0.0
self.info.alpha = 0.0
}, completion: { (done) in
println("") // sigh..
self.performSegueWithIdentifier("unwindToTaskEdit", sender: self)
})
}
func transitionToTimeline() {
let total = userObject!.totalUserGoals()
if total == 1 {
performSegueWithIdentifier("completeTaskSegue", sender: self)
} else {
performSegueWithIdentifier("unwindToTimeline", sender: self)
}
}
// MARK: Animation
func playIntroductionAnimation() {
titleLabel.revealView(constant: 50)
var anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
anim.toValue = 1.0
anim.beginTime = CACurrentMediaTime() + 1.0
task1.pop_addAnimation(anim, forKey: "alpha")
anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
anim.toValue = 1.0
anim.beginTime = CACurrentMediaTime() + 2.0
task2.pop_addAnimation(anim, forKey: "alpha")
anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
anim.toValue = 1.0
anim.beginTime = CACurrentMediaTime() + 3.0
task3.pop_addAnimation(anim, forKey: "alpha")
completeAction.revealViewWithDelay(constant: 50, delay: 3.5)
info.revealViewWithDelay(constant: 25, delay: 3.8)
NSTimer.scheduledTimerWithTimeInterval(3.0, target: self, selector: "unlockView", userInfo: nil, repeats: false)
}
func unlockView() {
view.userInteractionEnabled = true
}
}
| 2e247eec7d1f54e5c890074da8ae7527 | 33.712575 | 142 | 0.586094 | false | false | false | false |
1457792186/JWSwift | refs/heads/develop | BabyTunes/Pods/RxSwift/RxSwift/Observers/TailRecursiveSink.swift | apache-2.0 | 38 | //
// TailRecursiveSink.swift
// RxSwift
//
// Created by Krunoslav Zaher on 3/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
enum TailRecursiveSinkCommand {
case moveNext
case dispose
}
#if DEBUG || TRACE_RESOURCES
public var maxTailRecursiveSinkStackSize = 0
#endif
/// This class is usually used with `Generator` version of the operators.
class TailRecursiveSink<S: Sequence, O: ObserverType>
: Sink<O>
, InvocableWithValueType where S.Iterator.Element: ObservableConvertibleType, S.Iterator.Element.E == O.E {
typealias Value = TailRecursiveSinkCommand
typealias E = O.E
typealias SequenceGenerator = (generator: S.Iterator, remaining: IntMax?)
var _generators: [SequenceGenerator] = []
var _isDisposed = false
var _subscription = SerialDisposable()
// this is thread safe object
var _gate = AsyncLock<InvocableScheduledItem<TailRecursiveSink<S, O>>>()
override init(observer: O, cancel: Cancelable) {
super.init(observer: observer, cancel: cancel)
}
func run(_ sources: SequenceGenerator) -> Disposable {
_generators.append(sources)
schedule(.moveNext)
return _subscription
}
func invoke(_ command: TailRecursiveSinkCommand) {
switch command {
case .dispose:
disposeCommand()
case .moveNext:
moveNextCommand()
}
}
// simple implementation for now
func schedule(_ command: TailRecursiveSinkCommand) {
_gate.invoke(InvocableScheduledItem(invocable: self, state: command))
}
func done() {
forwardOn(.completed)
dispose()
}
func extract(_ observable: Observable<E>) -> SequenceGenerator? {
rxAbstractMethod()
}
// should be done on gate locked
private func moveNextCommand() {
var next: Observable<E>? = nil
repeat {
guard let (g, left) = _generators.last else {
break
}
if _isDisposed {
return
}
_generators.removeLast()
var e = g
guard let nextCandidate = e.next()?.asObservable() else {
continue
}
// `left` is a hint of how many elements are left in generator.
// In case this is the last element, then there is no need to push
// that generator on stack.
//
// This is an optimization used to make sure in tail recursive case
// there is no memory leak in case this operator is used to generate non terminating
// sequence.
if let knownOriginalLeft = left {
// `- 1` because generator.next() has just been called
if knownOriginalLeft - 1 >= 1 {
_generators.append((e, knownOriginalLeft - 1))
}
}
else {
_generators.append((e, nil))
}
let nextGenerator = extract(nextCandidate)
if let nextGenerator = nextGenerator {
_generators.append(nextGenerator)
#if DEBUG || TRACE_RESOURCES
if maxTailRecursiveSinkStackSize < _generators.count {
maxTailRecursiveSinkStackSize = _generators.count
}
#endif
}
else {
next = nextCandidate
}
} while next == nil
guard let existingNext = next else {
done()
return
}
let disposable = SingleAssignmentDisposable()
_subscription.disposable = disposable
disposable.setDisposable(subscribeToNext(existingNext))
}
func subscribeToNext(_ source: Observable<E>) -> Disposable {
rxAbstractMethod()
}
func disposeCommand() {
_isDisposed = true
_generators.removeAll(keepingCapacity: false)
}
override func dispose() {
super.dispose()
_subscription.dispose()
_gate.dispose()
schedule(.dispose)
}
}
| 4650ba556b6424aa4ff9639ecd5c3b22 | 26.649007 | 111 | 0.571497 | false | false | false | false |
MjAbuz/SwiftHamcrest | refs/heads/master | Hamcrest/MetaMatchers.swift | bsd-3-clause | 1 | public func not<T>(matcher: Matcher<T>) -> Matcher<T> {
return Matcher("not \(matcher.description)") {value in !matcher.matches(value)}
}
public func not<T: Equatable>(expectedValue: T) -> Matcher<T> {
return not(equalToWithoutDescription(expectedValue))
}
public func describedAs<T>(description: String, _ matcher: Matcher<T>) -> Matcher<T> {
return Matcher(description) {matcher.matches($0) as MatchResult}
}
public func allOf<T>(matchers: Matcher<T>...) -> Matcher<T> {
return allOf(matchers)
}
public func allOf<S: SequenceType, T where S.Generator.Element == Matcher<T>>(matchers: S) -> Matcher<T> {
return Matcher(joinMatcherDescriptions(matchers)) {
(value: T) -> MatchResult in
var mismatchDescriptions: [String?] = []
for matcher in matchers {
switch delegateMatching(value, matcher, {
(mismatchDescription: String?) -> String? in
"mismatch: \(matcher.description)"
+ (mismatchDescription.map{" (\($0))"} ?? "")
}) {
case let .Mismatch(mismatchDescription):
mismatchDescriptions.append(mismatchDescription)
default:
break
}
}
return MatchResult(mismatchDescriptions.isEmpty, joinDescriptions(mismatchDescriptions))
}
}
public func && <T>(lhs: Matcher<T>, rhs: Matcher<T>) -> Matcher<T> {
return allOf(lhs, rhs)
}
public func anyOf<T>(matchers: Matcher<T>...) -> Matcher<T> {
return anyOf(matchers)
}
public func anyOf<S: SequenceType, T where S.Generator.Element == Matcher<T>>(matchers: S) -> Matcher<T> {
return Matcher(joinMatcherDescriptions(matchers, prefix: "any of")) {
(value: T) -> MatchResult in
let matchedMatchers = matchers.filter {$0.matches(value).boolValue}
return MatchResult(!matchedMatchers.isEmpty)
}
}
public func || <T>(lhs: Matcher<T>, rhs: Matcher<T>) -> Matcher<T> {
return anyOf(lhs, rhs)
} | ae9d59380cbe27cd763688472a475c66 | 35.109091 | 106 | 0.632242 | false | false | false | false |
JGiola/swift | refs/heads/main | test/decl/typealias/dependent_types.swift | apache-2.0 | 14 | // RUN: %target-typecheck-verify-swift
protocol P {
associatedtype Assoc = Self
}
struct X : P {
}
class Y<T: P> {
typealias Assoc = T.Assoc
}
func f<T: P>(_ x: T, y: Y<T>.Assoc) {
}
protocol P1 {
associatedtype A = Int
}
struct X1<T> : P1 {
init(_: X1.A) {
}
}
struct GenericStruct<T> { // expected-note 3{{generic type 'GenericStruct' declared here}}
typealias Alias = T
typealias MetaAlias = T.Type
typealias Concrete = Int
typealias ReferencesConcrete = Concrete
func methodOne() -> Alias.Type {}
func methodTwo() -> MetaAlias {}
func methodOne() -> Alias.BadType {}
// expected-error@-1 {{'BadType' is not a member type of type 'dependent_types.GenericStruct<T>.Alias'}}
func methodTwo() -> MetaAlias.BadType {}
// expected-error@-1 {{'BadType' is not a member type of type 'dependent_types.GenericStruct<T>.MetaAlias'}}
var propertyOne: Alias.BadType
// expected-error@-1 {{'BadType' is not a member type of type 'dependent_types.GenericStruct<T>.Alias' (aka 'T')}}
var propertyTwo: MetaAlias.BadType
// expected-error@-1 {{'BadType' is not a member type of type 'dependent_types.GenericStruct<T>.MetaAlias' (aka 'T.Type')}}
}
// This was accepted in Swift 3.0 and sort of worked... but we can't
// implement it correctly. In Swift 3.1 it triggered an assert.
// Make sure it's banned now with a proper diagnostic.
func foo() -> Int {}
func metaFoo() -> Int.Type {}
let _: GenericStruct.Alias = foo()
// expected-error@-1 {{reference to generic type 'GenericStruct' requires arguments in <...>}}
let _: GenericStruct.MetaAlias = metaFoo()
// expected-error@-1 {{reference to generic type 'GenericStruct' requires arguments in <...>}}
// ... but if the typealias has a fully concrete underlying type,
// we are OK.
let _: GenericStruct.Concrete = foo()
let _: GenericStruct.ReferencesConcrete = foo()
// expected-error@-1 {{reference to generic type 'GenericStruct' requires arguments in <...>}}
class SuperG<T, U> {
typealias Composed = (T, U)
}
class SubG<T> : SuperG<T, T> { }
typealias SubGX<T> = SubG<T?>
func checkSugar(gs: SubGX<Int>.Composed) {
let i4: Int = gs // expected-error{{cannot convert value of type 'SubGX<Int>.Composed' (aka '(Optional<Int>, Optional<Int>)') to specified type 'Int'}}
}
| bdb5012dba6280f94f0da8622d2c4f88 | 28.921053 | 153 | 0.682498 | false | false | false | false |
BalestraPatrick/Tweetometer | refs/heads/develop | Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/Models/ViewModels/DayViewModel.swift | apache-2.0 | 4 | /**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
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
FACEBOOK 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 IGListKit
final class DayViewModel {
let day: Int
let today: Bool
let selected: Bool
let appointments: Int
init(day: Int, today: Bool, selected: Bool, appointments: Int) {
self.day = day
self.today = today
self.selected = selected
self.appointments = appointments
}
}
extension DayViewModel: ListDiffable {
func diffIdentifier() -> NSObjectProtocol {
return day as NSObjectProtocol
}
func isEqual(toDiffableObject object: ListDiffable?) -> Bool {
if self === object { return true }
guard let object = object as? DayViewModel else { return false }
return today == object.today && selected == object.selected && appointments == object.appointments
}
}
| e9ef04ef9b7dc678560f10519135171f | 30.673913 | 106 | 0.712423 | false | false | false | false |
SunZhiC/LiveApp | refs/heads/master | SZCLiveApp/SZCLiveApp/Classes/Live/Controller/SZCLiveViewController.swift | mit | 1 | //
// SZCLiveViewController.swift
// SZCLiveApp
//
// Created by Sun on 2016/12/1.
// Copyright © 2016年 sunzhichao. All rights reserved.
//
import UIKit
import AFNetworking
import MJExtension
class SZCLiveViewController: UITableViewController {
fileprivate let httpManager = HttpTools.shareInstance
fileprivate var models: [SZCLiveModel] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "观看直播"
view.backgroundColor = UIColor.black
loadData()
tableView.register(UINib(nibName: "SZCLiveCell", bundle: nil), forCellReuseIdentifier: "cell")
tableView.separatorStyle = .none
}
}
extension SZCLiveViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.models.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> SZCLiveCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) as! SZCLiveCell
cell.liveModel = models[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 320
}
}
extension SZCLiveViewController {
func loadData() {
let url = "http://116.211.167.106/api/live/aggregation?uid=133825214&interest=1"
httpManager.sendDataRequest(url: url, success: {(dataTask: URLSessionDataTask, responseObject: Any?) -> Void in
guard let response = responseObject as? [String: Any] else { return }
guard let dataArray = response["lives"] as? [[String: Any]] else { return }
for data in dataArray {
self.models.append(SZCLiveModel(dict: data))
}
self.tableView.reloadData()
print(self.models)
}, failure: {(dataTask: URLSessionDataTask?, error: Error) -> Void in
print(error)
})
}
}
extension SZCLiveViewController {
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let creatorVc = SZCCreatorViewController()
creatorVc.liveModel = models[indexPath.row]
present(creatorVc, animated: true, completion: nil)
}
}
| 6a540813f1d3bfc3f18a785907405212 | 26.561798 | 119 | 0.625764 | false | false | false | false |
git-hushuai/MOMO | refs/heads/master | MMHSMeterialProject/LibaryFile/SQLiteDB/SQLiteDB.swift | mit | 1 | //
// SQLiteDB.swift
// TasksGalore
//
// Created by Fahim Farook on 12/6/14.
// Copyright (c) 2014 RookSoft Pte. Ltd. All rights reserved.
//
import Foundation
#if os(iOS)
import UIKit
#else
import AppKit
#endif
let SQLITE_DATE = SQLITE_NULL + 1
private let SQLITE_STATIC = unsafeBitCast(0, sqlite3_destructor_type.self)
private let SQLITE_TRANSIENT = unsafeBitCast(-1, sqlite3_destructor_type.self)
// MARK:- SQLiteDB Class - Does all the work
class SQLiteDB {
let DB_NAME = "data.db"
let QUEUE_LABEL = "SQLiteDB"
private var db:COpaquePointer = nil
private var queue:dispatch_queue_t
private var fmt = NSDateFormatter()
private var GROUP = ""
struct Static {
static var instance:SQLiteDB? = nil
static var token:dispatch_once_t = 0
}
class func sharedInstance() -> SQLiteDB! {
dispatch_once(&Static.token) {
Static.instance = self.init(gid:"")
}
return Static.instance!
}
class func sharedInstance(gid:String) -> SQLiteDB! {
dispatch_once(&Static.token) {
Static.instance = self.init(gid:gid)
}
return Static.instance!
}
required init(gid:String) {
assert(Static.instance == nil, "Singleton already initialized!")
GROUP = gid
// Set queue
queue = dispatch_queue_create(QUEUE_LABEL, nil)
fmt.timeZone = NSTimeZone(forSecondsFromGMT:0)
// Set up for file operations
let fm = NSFileManager.defaultManager()
let dbName:String = String.fromCString(DB_NAME)!
var docDir = ""
// Is this for an app group?
if GROUP.isEmpty {
// Get path to DB in Documents directory
docDir = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0]
} else {
// Get path to shared group folder
if let url = fm.containerURLForSecurityApplicationGroupIdentifier(GROUP) {
docDir = url.path!
} else {
assert(false, "Error getting container URL for group: \(GROUP)")
}
}
let path = (docDir as NSString).stringByAppendingPathComponent(dbName)
print("Database path: \(path)09090")
// Check if copy of DB is there in Documents directory
print("file existsAtPath :\(fm.fileExistsAtPath(path))");
if !(fm.fileExistsAtPath(path)) {
// The database does not exist, so copy to Documents directory
guard let rp = NSBundle.mainBundle().resourcePath else { return }
let from = (rp as NSString).stringByAppendingPathComponent(dbName)
do {
try fm.copyItemAtPath(from, toPath:path)
} catch let error as NSError {
print("SQLiteDB - failed to copy writable version of DB!")
print("Error - \(error.localizedDescription)")
return
}
}
// Open the DB
let cpath = path.cStringUsingEncoding(NSUTF8StringEncoding)
let error = sqlite3_open(cpath!, &db)
if error != SQLITE_OK {
// Open failed, close DB and fail
print("SQLiteDB - failed to open DB!")
sqlite3_close(db)
}
fmt.dateFormat = "YYYY-MM-dd HH:mm:ss"
}
deinit {
closeDatabase()
}
private func closeDatabase() {
if db != nil {
// Get launch count value
let ud = NSUserDefaults.standardUserDefaults()
var launchCount = ud.integerForKey("LaunchCount")
launchCount--
print("SQLiteDB - Launch count \(launchCount)")
var clean = false
if launchCount < 0 {
clean = true
launchCount = 500
}
ud.setInteger(launchCount, forKey: "LaunchCount")
ud.synchronize()
// Do we clean DB?
if !clean {
sqlite3_close(db)
return
}
// Clean DB
print("SQLiteDB - Optimize DB")
let sql = "VACUUM; ANALYZE"
if execute(sql) != SQLITE_OK {
print("SQLiteDB - Error cleaning DB")
}
sqlite3_close(db)
}
}
// Execute SQL with parameters and return result code
func execute(sql:String, parameters:[AnyObject]?=nil)->CInt {
var result:CInt = 0
dispatch_sync(queue) {
let stmt = self.prepare(sql, params:parameters)
if stmt != nil {
result = self.execute(stmt, sql:sql)
}
}
return result
}
// Run SQL query with parameters
func query(sql:String, parameters:[AnyObject]?=nil)->[[String:AnyObject]] {
var rows = [[String:AnyObject]]()
dispatch_sync(queue) {
let stmt = self.prepare(sql, params:parameters)
if stmt != nil {
rows = self.query(stmt, sql:sql)
}
}
return rows
}
// Show alert with either supplied message or last error
func alert(msg:String) {
dispatch_async(dispatch_get_main_queue()) {
#if os(iOS)
let alert = UIAlertView(title: "SQLiteDB", message:msg, delegate: nil, cancelButtonTitle: "OK")
alert.show()
#else
let alert = NSAlert()
alert.addButtonWithTitle("OK")
alert.messageText = "SQLiteDB"
alert.informativeText = msg
alert.alertStyle = NSAlertStyle.WarningAlertStyle
alert.runModal()
#endif
}
}
// Private method which prepares the SQL
private func prepare(sql:String, params:[AnyObject]?)->COpaquePointer {
var stmt:COpaquePointer = nil
let cSql = sql.cStringUsingEncoding(NSUTF8StringEncoding)
// Prepare
let result = sqlite3_prepare_v2(self.db, cSql!, -1, &stmt, nil)
if result != SQLITE_OK {
sqlite3_finalize(stmt)
if let error = String.fromCString(sqlite3_errmsg(self.db)) {
let msg = "SQLiteDB - failed to prepare SQL: \(sql), Error: \(error)"
print(msg)
}
return nil
}
// Bind parameters, if any
if params != nil {
// Validate parameters
let cntParams = sqlite3_bind_parameter_count(stmt)
let cnt = CInt(params!.count)
if cntParams != cnt {
let msg = "SQLiteDB - failed to bind parameters, counts did not match. SQL: \(sql), Parameters: \(params)"
print(msg)
return nil
}
var flag:CInt = 0
// Text & BLOB values passed to a C-API do not work correctly if they are not marked as transient.
for ndx in 1...cnt {
// println("Binding: \(params![ndx-1]) at Index: \(ndx)")
// Check for data types
if let txt = params![ndx-1] as? String {
flag = sqlite3_bind_text(stmt, CInt(ndx), txt, -1, SQLITE_TRANSIENT)
} else if let data = params![ndx-1] as? NSData {
flag = sqlite3_bind_blob(stmt, CInt(ndx), data.bytes, CInt(data.length), SQLITE_TRANSIENT)
} else if let date = params![ndx-1] as? NSDate {
let txt = fmt.stringFromDate(date)
flag = sqlite3_bind_text(stmt, CInt(ndx), txt, -1, SQLITE_TRANSIENT)
} else if let val = params![ndx-1] as? Double {
flag = sqlite3_bind_double(stmt, CInt(ndx), CDouble(val))
} else if let val = params![ndx-1] as? Int {
flag = sqlite3_bind_int(stmt, CInt(ndx), CInt(val))
} else {
flag = sqlite3_bind_null(stmt, CInt(ndx))
}
// Check for errors
if flag != SQLITE_OK {
sqlite3_finalize(stmt)
if let error = String.fromCString(sqlite3_errmsg(self.db)) {
let msg = "SQLiteDB - failed to bind for SQL: \(sql), Parameters: \(params), Index: \(ndx) Error: \(error)"
print(msg)
}
return nil
}
}
}
return stmt
}
// Private method which handles the actual execution of an SQL statement
private func execute(stmt:COpaquePointer, sql:String)->CInt {
// Step
var result = sqlite3_step(stmt)
if result != SQLITE_OK && result != SQLITE_DONE {
sqlite3_finalize(stmt)
if let err = String.fromCString(sqlite3_errmsg(self.db)) {
let msg = "SQLiteDB - failed to execute SQL: \(sql), Error: \(err)"
print(msg)
}
return 0
}
// Is this an insert
let upp = sql.uppercaseString
if upp.hasPrefix("INSERT ") {
// Known limitations: http://www.sqlite.org/c3ref/last_insert_rowid.html
let rid = sqlite3_last_insert_rowid(self.db)
result = CInt(rid)
} else if upp.hasPrefix("DELETE") || upp.hasPrefix("UPDATE") {
var cnt = sqlite3_changes(self.db)
if cnt == 0 {
cnt++
}
result = CInt(cnt)
} else {
result = 1
}
// Finalize
sqlite3_finalize(stmt)
return result
}
// Private method which handles the actual execution of an SQL query
private func query(stmt:COpaquePointer, sql:String)->[[String:AnyObject]] {
var rows = [[String:AnyObject]]()
var fetchColumnInfo = true
var columnCount:CInt = 0
var columnNames = [String]()
var columnTypes = [CInt]()
var result = sqlite3_step(stmt)
while result == SQLITE_ROW {
// Should we get column info?
if fetchColumnInfo {
columnCount = sqlite3_column_count(stmt)
for index in 0..<columnCount {
// Get column name
let name = sqlite3_column_name(stmt, index)
columnNames.append(String.fromCString(name)!)
// Get column type
columnTypes.append(self.getColumnType(index, stmt:stmt))
}
fetchColumnInfo = false
}
// Get row data for each column
var row = [String:AnyObject]()
for index in 0..<columnCount {
let key = columnNames[Int(index)]
let type = columnTypes[Int(index)]
if let val = getColumnValue(index, type:type, stmt:stmt) {
// println("Column type:\(type) with value:\(val)")
row[key] = val
}
}
rows.append(row)
// Next row
result = sqlite3_step(stmt)
}
sqlite3_finalize(stmt)
return rows
}
// Get column type
private func getColumnType(index:CInt, stmt:COpaquePointer)->CInt {
var type:CInt = 0
// Column types - http://www.sqlite.org/datatype3.html (section 2.2 table column 1)
let blobTypes = ["BINARY", "BLOB", "VARBINARY"]
let charTypes = ["CHAR", "CHARACTER", "CLOB", "NATIONAL VARYING CHARACTER", "NATIVE CHARACTER", "NCHAR", "NVARCHAR", "TEXT", "VARCHAR", "VARIANT", "VARYING CHARACTER"]
let dateTypes = ["DATE", "DATETIME", "TIME", "TIMESTAMP"]
let intTypes = ["BIGINT", "BIT", "BOOL", "BOOLEAN", "INT", "INT2", "INT8", "INTEGER", "MEDIUMINT", "SMALLINT", "TINYINT"]
let nullTypes = ["NULL"]
let realTypes = ["DECIMAL", "DOUBLE", "DOUBLE PRECISION", "FLOAT", "NUMERIC", "REAL"]
// Determine type of column - http://www.sqlite.org/c3ref/c_blob.html
let buf = sqlite3_column_decltype(stmt, index)
// println("SQLiteDB - Got column type: \(buf)")
if buf != nil {
var tmp = String.fromCString(buf)!.uppercaseString
// Remove brackets
let pos = tmp.positionOf("(")
if pos > 0 {
tmp = tmp.subStringTo(pos)
}
// Remove unsigned?
// Remove spaces
// Is the data type in any of the pre-set values?
// println("SQLiteDB - Cleaned up column type: \(tmp)")
if intTypes.contains(tmp) {
return SQLITE_INTEGER
}
if realTypes.contains(tmp) {
return SQLITE_FLOAT
}
if charTypes.contains(tmp) {
return SQLITE_TEXT
}
if blobTypes.contains(tmp) {
return SQLITE_BLOB
}
if nullTypes.contains(tmp) {
return SQLITE_NULL
}
if dateTypes.contains(tmp) {
return SQLITE_DATE
}
return SQLITE_TEXT
} else {
// For expressions and sub-queries
type = sqlite3_column_type(stmt, index)
}
return type
}
// Get column value
private func getColumnValue(index:CInt, type:CInt, stmt:COpaquePointer)->AnyObject? {
// Integer
if type == SQLITE_INTEGER {
let val = sqlite3_column_int(stmt, index)
return Int(val)
}
// Float
if type == SQLITE_FLOAT {
let val = sqlite3_column_double(stmt, index)
return Double(val)
}
// Text - handled by default handler at end
// Blob
if type == SQLITE_BLOB {
let data = sqlite3_column_blob(stmt, index)
let size = sqlite3_column_bytes(stmt, index)
let val = NSData(bytes:data, length: Int(size))
return val
}
// Null
if type == SQLITE_NULL {
return nil
}
// Date
if type == SQLITE_DATE {
// Is this a text date
let txt = UnsafePointer<Int8>(sqlite3_column_text(stmt, index))
if txt != nil {
if let buf = NSString(CString:txt, encoding:NSUTF8StringEncoding) {
let set = NSCharacterSet(charactersInString: "-:")
let range = buf.rangeOfCharacterFromSet(set)
if range.location != NSNotFound {
// Convert to time
var time:tm = tm(tm_sec: 0, tm_min: 0, tm_hour: 0, tm_mday: 0, tm_mon: 0, tm_year: 0, tm_wday: 0, tm_yday: 0, tm_isdst: 0, tm_gmtoff: 0, tm_zone:nil)
strptime(txt, "%Y-%m-%d %H:%M:%S", &time)
time.tm_isdst = -1
let diff = NSTimeZone.localTimeZone().secondsFromGMT
let t = mktime(&time) + diff
let ti = NSTimeInterval(t)
let val = NSDate(timeIntervalSince1970:ti)
return val
}
}
}
// If not a text date, then it's a time interval
let val = sqlite3_column_double(stmt, index)
let dt = NSDate(timeIntervalSince1970: val)
return dt
}
// If nothing works, return a string representation
let buf = UnsafePointer<Int8>(sqlite3_column_text(stmt, index))
let val = String.fromCString(buf)
return val
}
}
| 7d347c6f1d66dc054399eba49d3eb173 | 29.633005 | 169 | 0.659001 | false | false | false | false |
iOSWizards/AwesomeMedia | refs/heads/master | Example/Pods/AwesomeTracking/AwesomeTracking/Classes/Helpers/MixpanelHelper.swift | mit | 1 | //
// MixpanelHelper.swift
// AwesomeTracking
//
// Created by Leonardo Vinicius Kaminski Ferreira on 13/06/18.
//
import Foundation
import Mixpanel
struct MixpanelHelper {
static func track(_ eventName: String, with params: AwesomeTrackingDictionary) {
// typecast son of bitch from hell, because the mixpanel library choose to be different, they are cool ;)
var dic: Properties = [:]
for obj in params.stringLiteral() {
if let value = obj.value as? String {
dic[obj.key] = value
} else if let value = obj.value as? Int32 {
dic[obj.key] = Int(value)
} else if let value = obj.value as? Bool {
dic[obj.key] = value
}
}
Mixpanel.mainInstance().track(event: eventName, properties: dic)
}
}
| bf18548c54a14101e4f399d84526f0e4 | 25.84375 | 113 | 0.5844 | false | false | false | false |
rolandleth/LTHRadioButton | refs/heads/master | RadioButtonDemo/RadioButtonDemo/RadioCell.swift | mit | 1 | //
// RadioCell.swift
// RadioButtonDemo
//
// Created by Roland Leth on 19.10.2016.
// Copyright © 2016 Roland Leth. All rights reserved.
//
import UIKit
class RadioCell: UITableViewCell {
private let selectedColor = UIColor(red: 74/255, green: 144/255, blue: 226/255, alpha: 1.0)
private let deselectedColor = UIColor.lightGray
private lazy var radioButton: LTHRadioButton = {
let r = LTHRadioButton()
self.contentView.addSubview(r)
r.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
r.centerYAnchor.constraint(equalTo: self.contentView.centerYAnchor),
r.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 16),
r.heightAnchor.constraint(equalToConstant: r.frame.height),
r.widthAnchor.constraint(equalToConstant: r.frame.width)]
)
return r
}()
func update(with color: UIColor) {
backgroundColor = color
radioButton.selectedColor = color == .darkGray ? .white : selectedColor
radioButton.deselectedColor = color == .darkGray ? .lightGray : deselectedColor
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
return radioButton.select(animated: animated)
}
radioButton.deselect(animated: animated)
}
}
| 1989c9ab9b8a440ab1a1765edc3efe79 | 27.76087 | 94 | 0.732426 | false | false | false | false |
ObserveSocial/Observe | refs/heads/master | Sources/Observe.swift | mit | 2 | /**
Responsible for the executions of the tests.
*/
struct Observe {
static var reporter: Reportable? = DefaultReporter.sharedReporter
static var currentTest: ObserveTestable?
static func runTests() {
guard let currentTest = currentTest else {
// No more tests to run
return
}
guard currentTest.running == false else {
// Already Running
return
}
if currentTest.tested == false {
currentTest.runBeforeEachChild()
currentTest.runTest()
// TODO: Run the before, not before each, here
}
self.currentTest = nextTestInLine()
runTests()
}
/**
Get the next child test in line and remove it from the line.
If there are no more children tests, return the parent test.
If there is a child test, run the `beforeEach()` method before returning.
*/
private static func nextTestInLine() -> ObserveTestable? {
var test: ObserveTestable?
if let nextChild = currentTest?.popNextChild() {
test = nextChild
} else {
test = currentTest?.parent
}
return test
}
}
public func set(reporter: Reportable) {
Observe.reporter = reporter
}
public func defaultReporter() -> DefaultReporter {
return DefaultReporter.sharedReporter
}
| 7a1bd6add150eb3abe2edab945785f7c | 21.666667 | 76 | 0.650929 | false | true | false | false |
devcastid/iOS-Tutorials | refs/heads/master | Davcast-iOS/Pods/Material/Sources/MaterialButton.swift | mit | 1 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.io>.
* 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 Material 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
@objc(MaterialButton)
public class MaterialButton : UIButton {
/**
A CAShapeLayer used to manage elements that would be affected by
the clipToBounds property of the backing layer. For example, this
allows the dropshadow effect on the backing layer, while clipping
the image to a desired shape within the visualLayer.
*/
public private(set) lazy var visualLayer: CAShapeLayer = CAShapeLayer()
/**
A base delegate reference used when subclassing MaterialView.
*/
public weak var delegate: MaterialDelegate?
/// Sets whether the scaling animation should be used.
public lazy var pulseScale: Bool = true
/// The opcaity value for the pulse animation.
public var pulseColorOpacity: CGFloat = 0.25
/// The color of the pulse effect.
public var pulseColor: UIColor?
/**
This property is the same as clipsToBounds. It crops any of the view's
contents from bleeding past the view's frame. If an image is set using
the image property, then this value does not need to be set, since the
visualLayer's maskToBounds is set to true by default.
*/
public var masksToBounds: Bool {
get {
return layer.masksToBounds
}
set(value) {
layer.masksToBounds = value
}
}
/// A property that accesses the backing layer's backgroundColor.
public override var backgroundColor: UIColor? {
didSet {
layer.backgroundColor = backgroundColor?.CGColor
}
}
/// A property that accesses the layer.frame.origin.x property.
public var x: CGFloat {
get {
return layer.frame.origin.x
}
set(value) {
layer.frame.origin.x = value
}
}
/// A property that accesses the layer.frame.origin.y property.
public var y: CGFloat {
get {
return layer.frame.origin.y
}
set(value) {
layer.frame.origin.y = value
}
}
/**
A property that accesses the layer.frame.origin.width property.
When setting this property in conjunction with the shape property having a
value that is not .None, the height will be adjusted to maintain the correct
shape.
*/
public var width: CGFloat {
get {
return layer.frame.size.width
}
set(value) {
layer.frame.size.width = value
if .None != shape {
layer.frame.size.height = value
}
}
}
/**
A property that accesses the layer.frame.origin.height property.
When setting this property in conjunction with the shape property having a
value that is not .None, the width will be adjusted to maintain the correct
shape.
*/
public var height: CGFloat {
get {
return layer.frame.size.height
}
set(value) {
layer.frame.size.height = value
if .None != shape {
layer.frame.size.width = value
}
}
}
/// A property that accesses the backing layer's shadowColor.
public var shadowColor: UIColor? {
didSet {
layer.shadowColor = shadowColor?.CGColor
}
}
/// A property that accesses the backing layer's shadowOffset.
public var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set(value) {
layer.shadowOffset = value
}
}
/// A property that accesses the backing layer's shadowOpacity.
public var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set(value) {
layer.shadowOpacity = value
}
}
/// A property that accesses the backing layer's shadowRadius.
public var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set(value) {
layer.shadowRadius = value
}
}
/**
A property that sets the shadowOffset, shadowOpacity, and shadowRadius
for the backing layer. This is the preferred method of setting depth
in order to maintain consitency across UI objects.
*/
public var depth: MaterialDepth = .None {
didSet {
let value: MaterialDepthType = MaterialDepthToValue(depth)
shadowOffset = value.offset
shadowOpacity = value.opacity
shadowRadius = value.radius
}
}
/**
A property that sets the cornerRadius of the backing layer. If the shape
property has a value of .Circle when the cornerRadius is set, it will
become .None, as it no longer maintains its circle shape.
*/
public var cornerRadiusPreset: MaterialRadius = .None {
didSet {
if let v: MaterialRadius = cornerRadiusPreset {
cornerRadius = MaterialRadiusToValue(v)
if .Circle == shape {
shape = .None
}
}
}
}
/// A property that accesses the layer.cornerRadius.
public var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
/**
A property that manages the overall shape for the object. If either the
width or height property is set, the other will be automatically adjusted
to maintain the shape of the object.
*/
public var shape: MaterialShape = .None {
didSet {
if .None != shape {
if width < height {
frame.size.width = height
} else {
frame.size.height = width
}
}
}
}
/// A preset property to set the borderWidth.
public var borderWidthPreset: MaterialBorder = .None {
didSet {
borderWidth = MaterialBorderToValue(borderWidthPreset)
}
}
/// A property that accesses the layer.borderWith.
public var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
/// A property that accesses the layer.borderColor property.
public var borderColor: UIColor? {
didSet {
layer.borderColor = borderColor?.CGColor
}
}
/// A property that accesses the layer.position property.
public var position: CGPoint {
get {
return layer.position
}
set(value) {
layer.position = value
}
}
/// A property that accesses the layer.zPosition property.
public var zPosition: CGFloat {
get {
return layer.zPosition
}
set(value) {
layer.zPosition = value
}
}
/// A preset property for updated contentEdgeInsets.
public var contentEdgeInsetsPreset: MaterialEdgeInset {
didSet {
let value: UIEdgeInsets = MaterialEdgeInsetToValue(contentEdgeInsetsPreset)
contentEdgeInsets = UIEdgeInsetsMake(value.top, value.left, value.bottom, value.right)
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
contentEdgeInsetsPreset = .None
super.init(coder: aDecoder)
prepareView()
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
contentEdgeInsetsPreset = .None
super.init(frame: frame)
prepareView()
}
/// A convenience initializer.
public convenience init() {
self.init(frame: CGRectNull)
}
/// Overriding the layout callback for sublayers.
public override func layoutSublayersOfLayer(layer: CALayer) {
super.layoutSublayersOfLayer(layer)
if self.layer == layer {
layoutShape()
layoutVisualLayer()
}
}
/**
A method that accepts CAAnimation objects and executes them on the
view's backing layer.
- Parameter animation: A CAAnimation instance.
*/
public func animate(animation: CAAnimation) {
animation.delegate = self
if let a: CABasicAnimation = animation as? CABasicAnimation {
a.fromValue = (nil == layer.presentationLayer() ? layer : layer.presentationLayer() as! CALayer).valueForKeyPath(a.keyPath!)
}
if let a: CAPropertyAnimation = animation as? CAPropertyAnimation {
layer.addAnimation(a, forKey: a.keyPath!)
} else if let a: CAAnimationGroup = animation as? CAAnimationGroup {
layer.addAnimation(a, forKey: nil)
} else if let a: CATransition = animation as? CATransition {
layer.addAnimation(a, forKey: kCATransition)
}
}
/**
A delegation method that is executed when the backing layer starts
running an animation.
- Parameter anim: The currently running CAAnimation instance.
*/
public override func animationDidStart(anim: CAAnimation) {
(delegate as? MaterialAnimationDelegate)?.materialAnimationDidStart?(anim)
}
/**
A delegation method that is executed when the backing layer stops
running an animation.
- Parameter anim: The CAAnimation instance that stopped running.
- Parameter flag: A boolean that indicates if the animation stopped
because it was completed or interrupted. True if completed, false
if interrupted.
*/
public override func animationDidStop(anim: CAAnimation, finished flag: Bool) {
if anim is CAPropertyAnimation {
(delegate as? MaterialAnimationDelegate)?.materialAnimationDidStop?(anim, finished: flag)
} else if let a: CAAnimationGroup = anim as? CAAnimationGroup {
for x in a.animations! {
animationDidStop(x, finished: true)
}
}
layoutVisualLayer()
}
/**
A delegation method that is executed when the view has began a
touch event.
- Parameter touches: A set of UITouch objects.
- Parameter event: A UIEvent object.
*/
public override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesBegan(touches, withEvent: event)
pulseAnimation(layer.convertPoint(touches.first!.locationInView(self), fromLayer: layer))
}
/**
A delegation method that is executed when the view touch event has
ended.
- Parameter touches: A set of UITouch objects.
- Parameter event: A UIEvent object.
*/
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesEnded(touches, withEvent: event)
shrinkAnimation()
}
/**
A delegation method that is executed when the view touch event has
been cancelled.
- Parameter touches: A set of UITouch objects.
- Parameter event: A UIEvent object.
*/
public override func touchesCancelled(touches: Set<UITouch>?, withEvent event: UIEvent?) {
super.touchesCancelled(touches, withEvent: event)
shrinkAnimation()
}
/**
Triggers the pulse animation.
- Parameter point: A Optional point to pulse from, otherwise pulses
from the center.
*/
public func pulse(var point: CGPoint? = nil) {
if nil == point {
point = CGPointMake(CGFloat(width / 2), CGFloat(height / 2))
}
if let v: CFTimeInterval = pulseAnimation(point!) {
MaterialAnimation.delay(v) { [weak self] in
self?.shrinkAnimation()
}
}
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepareView method
to initialize property values and other setup operations.
The super.prepareView method should always be called immediately
when subclassing.
*/
public func prepareView() {
prepareVisualLayer()
pulseColor = MaterialColor.white
}
/// Prepares the visualLayer property.
internal func prepareVisualLayer() {
visualLayer.zPosition = 0
visualLayer.masksToBounds = true
layer.addSublayer(visualLayer)
}
/// Manages the layout for the visualLayer property.
internal func layoutVisualLayer() {
visualLayer.frame = bounds
visualLayer.position = CGPointMake(width / 2, height / 2)
visualLayer.cornerRadius = layer.cornerRadius
}
/// Manages the layout for the shape of the view instance.
internal func layoutShape() {
if .Circle == shape {
layer.cornerRadius = width / 2
}
}
/**
Triggers the pulse animation.
- Parameter point: A point to pulse from.
- Returns: A Ooptional CFTimeInternal if the point exists within
the view. The time internal represents the animation time.
*/
internal func pulseAnimation(point: CGPoint) -> CFTimeInterval? {
if true == layer.containsPoint(point) {
let r: CGFloat = (width < height ? height : width) / 2
let f: CGFloat = 3
let v: CGFloat = r / f
let d: CGFloat = 2 * f
let s: CGFloat = 1.05
var t: CFTimeInterval = CFTimeInterval(1.5 * width / UIScreen.mainScreen().bounds.width)
if 0.55 < t || 0.25 > t {
t = 0.55
}
t /= 1.3
if nil != pulseColor && 0 < pulseColorOpacity {
let pulseLayer: CAShapeLayer = CAShapeLayer()
pulseLayer.hidden = true
pulseLayer.zPosition = 1
pulseLayer.backgroundColor = pulseColor?.colorWithAlphaComponent(pulseColorOpacity).CGColor
visualLayer.addSublayer(pulseLayer)
MaterialAnimation.animationDisabled {
pulseLayer.bounds = CGRectMake(0, 0, v, v)
pulseLayer.position = point
pulseLayer.cornerRadius = r / d
pulseLayer.hidden = false
}
pulseLayer.addAnimation(MaterialAnimation.scale(3 * d, duration: t), forKey: nil)
MaterialAnimation.delay(t) { [weak self] in
if nil != self && nil != self!.pulseColor && 0 < self!.pulseColorOpacity {
MaterialAnimation.animateWithDuration(t, animations: {
pulseLayer.hidden = true
}) {
pulseLayer.removeFromSuperlayer()
}
}
}
}
if pulseScale {
layer.addAnimation(MaterialAnimation.scale(s, duration: t), forKey: nil)
return t
}
}
return nil
}
/// Executes the shrink animation for the pulse effect.
internal func shrinkAnimation() {
if pulseScale {
var t: CFTimeInterval = CFTimeInterval(1.5 * width / UIScreen.mainScreen().bounds.width)
if 0.55 < t || 0.25 > t {
t = 0.55
}
t /= 1.3
layer.addAnimation(MaterialAnimation.scale(1, duration: t), forKey: nil)
}
}
} | 84d72c22e55f55c5571d18c873c85471 | 27.922925 | 127 | 0.719011 | false | false | false | false |
kujenga/euler | refs/heads/main | 041/Sources/PandigitalPrimes/main.swift | gpl-3.0 | 1 | // https://projecteuler.net/problem=41
import Euler
var largest = 0;
for N in 1...9 {
// QuickPerm
// https://www.quickperm.org/
var a: [Int] = [];
// Pandigital set of digits, based on problem statement.
for d in 1...N {
a.append(d);
}
var p: [Int] = [];
for d in 0...N {
p.append(d);
}
var i = 1;
// Permute
while i < N {
// decrement p[i] by 1
p[i] -= 1
// if i is odd, then let j = p[i] otherwise let j = 0
let j = p[i]%2 != 0 ? p[i] : 0;
// swap(a[j], a[i])
a.swapAt(j, i)
// let i = 1
i = 1
// while (p[i] is equal to 0) do {
while p[i] == 0 {
// let p[i] = i
p[i] = i
// increment i by 1
i += 1
}
let x = digitsToInt(a)
if x.isPrime() {
print("is prime: \(x)")
if x > largest {
largest = x;
}
}
}
}
print("largest pandigital prime: \(largest)")
| 9e6899a05168f21487f6609d525cfd02 | 20.183673 | 61 | 0.407514 | false | false | false | false |
cjwirth/Tweets-InteractorExample | refs/heads/master | Tweets/Views/TweetTableViewCell.swift | mit | 1 | import UIKit
import Hakuba
class TweetCellModel: MYCellModel {
let name: String
let message: String
let image: UIImage
let retweeted: Bool
let liked: Bool
var didTapRetweet: (Void -> Void)?
var didTapLike: (Void -> Void)?
init(tweet: Tweet, retweeted: Bool = false, liked: Bool = false) {
name = tweet.author.name
message = tweet.message
image = tweet.author.image
self.retweeted = retweeted
self.liked = liked
super.init(cell: TweetTableViewCell.self, height: 100)
}
}
class TweetTableViewCell: MYTableViewCell {
@IBOutlet var iconView: UIImageView!
@IBOutlet var usernameLabel: UILabel!
@IBOutlet var messageLabel: UILabel!
@IBOutlet var retweetButton: UIButton!
@IBOutlet var likeButton: UIButton!
var didTapRetweet: (Void -> Void)?
var didTapLike: (Void -> Void)?
override func configureCell(cellModel: MYCellModel) {
super.configureCell(cellModel)
guard let model = cellModel as? TweetCellModel else {
return
}
let retweetImage = model.retweeted ? UIImage(named: "retweet-on")! : UIImage(named: "retweet")!
let likeImage = model.liked ? UIImage(named: "like-on")! : UIImage(named: "like")!
iconView.image = model.image
usernameLabel.text = model.name
messageLabel.text = model.message
retweetButton.setImage(retweetImage, forState: .Normal)
likeButton.setImage(likeImage, forState: .Normal)
didTapRetweet = model.didTapRetweet
didTapLike = model.didTapLike
}
@IBAction func retweetButtonTapped() {
didTapRetweet?()
}
@IBAction func likeButtonTapped() {
didTapLike?()
}
}
| 6df8eda628598e177e85c2fa64c4eb13 | 28.59322 | 103 | 0.651775 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/SILGen/minimum_foreach.swift | apache-2.0 | 34 | // RUN: %target-swift-emit-silgen -module-name Swift -parse-stdlib -parse-as-library %s
// This files contains a minimal implementation for Swift to emit foreach loops
// for a type. It acts partially as a guide for users and since it is in the
// form of a test, it ensures that we will always be able to get this test
// through the type checker.
precedencegroup AssignmentPrecedence { assignment: true }
public protocol ExpressibleByNilLiteral {
init(nilLiteral: ())
}
protocol IteratorProtocol {
associatedtype Element
mutating func next() -> Element?
}
protocol Sequence {
associatedtype Element
associatedtype Iterator : IteratorProtocol where Iterator.Element == Element
func makeIterator() -> Iterator
}
enum Optional<T> {
case none
case some(T)
}
func _diagnoseUnexpectedNilOptional(_filenameStart: Builtin.RawPointer,
_filenameLength: Builtin.Word,
_filenameIsASCII: Builtin.Int1,
_line: Builtin.Word) {
// This would usually contain an assert, but we don't need one since we are
// just emitting SILGen.
}
extension Optional : ExpressibleByNilLiteral {
public init(nilLiteral: ()) {
self = .none
}
}
class FakeCollection<T> {
}
struct FakeCollectionIterator<T> {
weak var collection: FakeCollection<T>?
init(_ newCollection: FakeCollection<T>) {
collection = newCollection
}
}
extension FakeCollectionIterator : IteratorProtocol {
public typealias Element = T
public mutating func next() -> Element? {
return .none
}
}
extension FakeCollection : Sequence {
public typealias Element = T
public typealias Iterator = FakeCollectionIterator<T>
public func makeIterator() -> FakeCollectionIterator<T> {
return FakeCollectionIterator(self)
}
}
func useT<T>(_ t: T) {}
func iterateFakeCollection<T>(_ x: FakeCollection<T>) {
for y in x {
useT(y)
}
}
| 83725c9e179b7797041ca4e9009d038a | 24.233766 | 87 | 0.692229 | false | false | false | false |
saeta/penguin | refs/heads/main | Tests/PenguinPipelineTests/FunctionGeneratorPipelineIteratorTests.swift | apache-2.0 | 1 | // Copyright 2020 Penguin Authors
//
// 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 PenguinPipeline
import struct PenguinStructures.Type
import XCTest
final class FunctionGeneratorPipelineIteratorTests: XCTestCase {
func testSimpleFunctionGenerator() {
var i = 0
var itr: FunctionGeneratorPipelineIterator<Int> = PipelineIterator.fromFunction {
if i >= 3 { return nil }
i += 1
return i
}
XCTAssertEqual(1, try! itr.next())
XCTAssertEqual(2, try! itr.next())
XCTAssertEqual(3, try! itr.next())
XCTAssertEqual(nil, try! itr.next())
}
func testSimpleInfiniteFunctionGenerator() {
var i = 0
var itr = PipelineIterator.fromFunction(Type<Int>()) {
i += 1
return i
}.take(3)
XCTAssertEqual(1, try! itr.next())
XCTAssertEqual(2, try! itr.next())
XCTAssertEqual(3, try! itr.next())
XCTAssertEqual(nil, try! itr.next())
}
func testThrowingFunctionGenerator() throws {
var i = 0
var itr: FunctionGeneratorPipelineIterator<Int> = PipelineIterator.fromFunction {
i += 1
if i == 2 {
throw TestErrors.silly
}
if i > 3 { return nil }
return i
}
XCTAssertEqual(1, try! itr.next())
do {
_ = try itr.next()
XCTFail("Should have thrown.")
} catch TestErrors.silly {
// Success
}
XCTAssertEqual(3, try! itr.next())
XCTAssertEqual(nil, try! itr.next())
}
static var allTests = [
("testSimpleFunctionGenerator", testSimpleFunctionGenerator),
("testSimpleInfiniteFunctionGenerator", testSimpleInfiniteFunctionGenerator),
("testThrowingFunctionGenerator", testThrowingFunctionGenerator),
]
}
fileprivate enum TestErrors: Error {
case silly
}
| f08f46bb3f1882b7133845a19e49f1f3 | 28.578947 | 85 | 0.682829 | false | true | false | false |
AutomationStation/BouncerBuddy | refs/heads/master | BouncerBuddy(version1.2)/BouncerBuddy/Rules/MinLengthRule.swift | apache-2.0 | 2 | //
// LengthRule.swift
// Validator
//
// Created by Jeff Potter on 3/6/15.
// Copyright (c) 2015 jpotts18. All rights reserved.
//
import Foundation
/**
`MinLengthRule` is a subclass of Rule that defines how minimum character length is validated.
*/
public class MinLengthRule: Rule {
/// Default minimum character length.
private var DEFAULT_LENGTH: Int = 3
/// Default error message to be displayed if validation fails.
private var message : String = "Must be at least 3 characters long"
/// - returns: An initialized `MinLengthRule` object, or nil if an object could not be created for some reason that would not result in an exception.
public init(){}
/**
Initializes a `MaxLengthRule` object that is to validate the length of the text of a text field
- parameter length: Minimum character length.
- parameter message: String of error message.
- returns: An initialized `MinLengthRule` object, or nil if an object could not be created for some reason that would not result in an exception.
*/
public init(length: Int, message : String = "Must be at least %ld characters long"){
self.DEFAULT_LENGTH = length
self.message = NSString(format: message, self.DEFAULT_LENGTH) as String
}
/**
Validates a text field.
- parameter value: String to checked for validation.
- returns: A boolean value. True if validation is successful; False if validation fails.
*/
public func validate(value: String) -> Bool {
return value.characters.count >= DEFAULT_LENGTH
}
/**
Displays error message when text field has failed validation.
- returns: String of error message.
*/
public func errorMessage() -> String {
return message
}
}
| 3f244fd684be6186305d291a35868356 | 34.372549 | 153 | 0.675721 | false | false | false | false |
piscoTech/MBLibrary | refs/heads/master | MBLibrary iOS/PullToRefreshView.swift | mit | 1 | //
// PullToRefresh.swift
// MBLibrary iOS
//
// Created by Marco Boschi on 12/07/2020.
// Original code by Loïs Di Qual (MIT Licence)
// https://github.com/siteline/SwiftUIRefresh/blob/master/Sources/PullToRefresh.swift
// Copyright © 2020 Marco Boschi. All rights reserved.
//
import SwiftUI
import UIKit
@available(iOS 13.0, *)
struct PullToRefresh: UIViewRepresentable {
let action: () -> Void
@Binding var isShowing: Bool
func makeUIView(context: Context) -> UIView {
let view = UIView(frame: .zero)
view.isHidden = true
view.isUserInteractionEnabled = false
return view
}
private func scrollView(root: UIView) -> UIScrollView? {
for subview in root.subviews {
if let scroll = subview as? UIScrollView {
return scroll
} else if let scroll = scrollView(root: subview) {
return scroll
}
}
return nil
}
func updateUIView(_ uiView: UIView, context: Context) {
DispatchQueue.main.async {
guard let viewHost = uiView.superview?.superview else {
return
}
guard let scroll = self.scrollView(root: viewHost) else {
return
}
if let refreshControl = scroll.refreshControl {
if self.isShowing {
refreshControl.beginRefreshing()
} else {
refreshControl.endRefreshing()
}
return
}
let refreshControl = UIRefreshControl()
refreshControl.addTarget(context.coordinator, action: #selector(Coordinator.onValueChanged), for: .valueChanged)
scroll.refreshControl = refreshControl
}
}
func makeCoordinator() -> Coordinator {
return Coordinator(self)
}
class Coordinator {
let view: PullToRefresh
init(_ view: PullToRefresh) {
self.view = view
}
@objc func onValueChanged() {
view.isShowing = true
view.action()
}
}
}
@available(iOS 13.0, *)
extension View {
public func pullToRefresh(isShowing: Binding<Bool>, onRefresh: @escaping () -> Void) -> some View {
VStack(spacing: 0) {
// Keep the original view first, a must to have nice animation with large titles
self
PullToRefresh(action: onRefresh, isShowing: isShowing).frame(width: 0, height: 0)
}
}
}
| c010dcac9bc787ccacbc0044246eb8dc | 21.612903 | 115 | 0.695197 | false | false | false | false |
suifengqjn/swiftDemo | refs/heads/master | Swift基本语法-黑马笔记/可选值/main.swift | apache-2.0 | 1 | //
// main.swift
// 可选值
//
// Created by 李南江 on 15/2/28.
// Copyright (c) 2015年 itcast. All rights reserved.
//
import Foundation
/*
可选值: optionals有两种状态:
1.有值 2.没有值, 没有值就是nil
*/
//有值:
var optValue1: Int? = 9
//没有值:
var optValue2: Int?
var optValue3: Int? = nil
/*
可选值可以利用if语句来进行判断
*/
var optValue4: Int?
if optValue4 != nil
{
print(optValue4)
}else
{
print(optValue4)
}
/*
提取可选类型的值(强制解析)
会将optValue中的整型值强制拿出来赋值给变量result, 换句话说就是告诉编译器optValue一定有值, 因为可选类型有两种状态有值和没有值, 所以需要告诉编译器到底有没有值
需要注意的是如果强制解析optValue, 但是optValue中没有值时会引发一个运行时错误
*/
var optValue5: Int? = 9
var result1: Int = optValue5!
print(result1)
//报错:
var optValue6: Int?
var result2: Int = optValue6!
print(result2)
/*
可选绑定:
为了更安全的解析可选类型的值, 一般情况下使用可选绑定
如果optValue没有值就不会做任何操作, 如果optValue有值会返回true并将optValue的值赋值给result执行大括号中的内容
*/
var optValue: Int? = 9
if let result3 = optValue
{
print(result3)
}
| 8980e0e91e95e4e6b1d8c6b59126f7f2 | 14.385965 | 92 | 0.72748 | false | false | false | false |
superk589/CGSSGuide | refs/heads/master | DereGuide/Model/Favorite/RemoteFavoriteChara.swift | mit | 2 | //
// RemoteFavoriteChara.swift
// DereGuide
//
// Created by zzk on 2017/7/26.
// Copyright © 2017 zzk. All rights reserved.
//
import UIKit
import CoreData
import CloudKit
struct RemoteFavoriteChara: RemoteRecord {
var id: String
var creatorID: String
var charaID: Int64
var localCreatedAt: Date
}
extension RemoteFavoriteChara {
static var recordType: String { return "FavoriteChara" }
init?(record: CKRecord) {
guard record.recordType == RemoteFavoriteChara.recordType else { return nil }
guard
let localCreatedAt = record["localCreatedAt"] as? Date,
let charaID = record["charaID"] as? NSNumber,
let creatorID = record.creatorUserRecordID?.recordName else {
return nil
}
self.id = record.recordID.recordName
self.creatorID = creatorID
self.localCreatedAt = localCreatedAt
self.charaID = charaID.int64Value
}
}
extension RemoteFavoriteChara {
func insert(into context: NSManagedObjectContext, completion: @escaping (Bool) -> ()) {
context.perform {
let chara = FavoriteChara.insert(into: context, charaID: Int(self.charaID))
chara.creatorID = self.creatorID
chara.remoteIdentifier = self.id
chara.createdAt = self.localCreatedAt
completion(true)
}
}
}
| c7e19260b9a105c53d44a6834dad02cb | 25.351852 | 91 | 0.632467 | false | false | false | false |
Isuru-Nanayakkara/Swift-Extensions | refs/heads/master | Swift+Extensions/Swift+Extensions/UIKit/UIButton+Extensions.swift | mit | 1 | //
// UIButton+Extensions.swift
// Swift+Extensions
//
// Created by Isuru Nanayakkara on 7/26/19.
// Copyright © 2019 BitInvent. All rights reserved.
//
import UIKit
extension UIButton {
public func setBackgroundColor(_ color: UIColor?, forState state: UIControl.State) {
guard let color = color else { return setBackgroundImage(nil, for: state) }
setBackgroundImage(UIImage.imageColored(color), for: state)
}
}
extension UIImage {
public class func imageColored(_ color: UIColor) -> UIImage! {
let onePixel = 1 / UIScreen.main.scale
let rect = CGRect(x: 0, y: 0, width: onePixel, height: onePixel)
UIGraphicsBeginImageContextWithOptions(rect.size, color.cgColor.alpha == 1, 0)
let context = UIGraphicsGetCurrentContext()
context!.setFillColor( color.cgColor)
context!.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
| 20bbb4dfa55ef93daf4165dec27f8e36 | 32.1 | 88 | 0.683787 | false | false | false | false |
HockeyWX/HockeySDK-iOSDemo-Swift | refs/heads/master | Classes/BITAppDelegate.swift | mit | 2 | //
// BITAppDelegate.swift
// HockeySDK-iOSDemo-Swift
//
// Created by Kevin Li on 18/10/2016.
//
import UIKit
@UIApplicationMain
class BITAppDelegate: UIResponder, UIApplicationDelegate,BITHockeyManagerDelegate {
var window: UIWindow?
var rootViewController: UIViewController?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
#if true //live
BITHockeyManager.shared().configure(withIdentifier: "7af641bbf9b644eb91a48995f084f458",delegate: self)
BITHockeyManager.shared().authenticator.authenticationSecret = "d7adc658f7168f3da93a5bd5c1947c00"
#else //warmup
BITHockeyManager.shared().configure(withIdentifier: "<#App ID#>",delegate: self)
BITHockeyManager.shared().authenticator.authenticationSecret = "<#Secret#>"
#endif
BITHockeyManager.shared().authenticator.identificationType = BITAuthenticatorIdentificationType.device
BITHockeyManager.shared().authenticator.restrictApplicationUsage = false
// optionally enable logging to get more information about states.
BITHockeyManager.shared().logLevel = BITLogLevel.verbose
BITHockeyManager.shared().start()
if didCrashInLastSessionOnStartup() {
waitingUI()
} else {
setupApplication()
}
return true
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return BITHockeyManager.shared().authenticator.handleOpen(url, sourceApplication: sourceApplication, annotation: annotation)
}
func waitingUI() {
// show intermediate UI
print("Please wait ...")
let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
let waitingViewController = storyboard.instantiateViewController(withIdentifier: "PleaseWait")
rootViewController = self.window?.rootViewController
self.window?.rootViewController = waitingViewController
}
func setupApplication() {
// setup your app specific code
if rootViewController != nil {
self.window?.rootViewController = rootViewController
}
BITHockeyManager.shared().authenticator.authenticateInstallation() // This line is obsolete in the crash only builds
}
func didCrashInLastSessionOnStartup() -> Bool {
return (BITHockeyManager.shared().crashManager.didCrashInLastSession && BITHockeyManager.shared().crashManager.timeIntervalCrashInLastSessionOccurred < 5)
}
// MARK: - BITHockeyManagerDelegate
/**
func userID(for hockeyManager: BITHockeyManager!, componentManager: BITHockeyBaseManager!) -> String! {
return "userID"
}
func userName(for hockeyManager: BITHockeyManager!, componentManager: BITHockeyBaseManager!) -> String! {
return "userName"
}
func userEmail(for hockeyManager: BITHockeyManager!, componentManager: BITHockeyBaseManager!) -> String! {
return "userEmail"
}
*/
// MARK: - BITCrashManagerDelegate
func applicationLog(for crashManager: BITCrashManager!) -> String! {
return "applicationLog"
}
/**
func attachment(for crashManager: BITCrashManager!) -> BITHockeyAttachment! {
let url = Bundle.main.url(forResource: "Default-568h@2x", withExtension: "png")
let data = NSData.init(contentsOf: url!)
let attachment = BITCrashAttachment.init(filename: "image.png", crashAttachmentData: data as Data!, contentType: "image/png")
return attachment!
}
*/
func crashManagerWillCancelSendingCrashReport(_ crashManager: BITCrashManager!) {
if didCrashInLastSessionOnStartup() {
setupApplication()
}
}
func crashManager(_ crashManager: BITCrashManager!, didFailWithError error: Error!) {
if didCrashInLastSessionOnStartup() {
setupApplication()
}
}
func crashManagerDidFinishSendingCrashReport(_ crashManager: BITCrashManager!) {
if didCrashInLastSessionOnStartup() {
setupApplication()
}
}
}
| 9bc1b054835adb879c5dcb8ae0c6469c | 35.848739 | 162 | 0.677081 | false | false | false | false |
Draveness/RbSwift | refs/heads/master | RbSwiftTests/String/String+RegexSpec.swift | mit | 1 | //
// Conversions.swift
// RbSwift
//
// Created by draveness on 19/03/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Quick
import Nimble
import RbSwift
class StringRegexSpec: BaseSpec {
override func spec() {
describe(".sub") {
it("returns a copy of str with the first occurrence of pattern replaced by the second argument") {
expect("hello".sub("l", "abc")).to(equal("heabclo"))
expect("hello".sub("le", "lll")).to(equal("hello"))
expect("hello".sub(".", "a")).to(equal("aello"))
}
}
describe(".subed") {
it("returns a copy of str with the first occurrence of pattern replaced by the second argument") {
var hello = "hello"
hello.subed("l", "abc")
expect(hello).to(equal("heabclo"))
}
}
describe(".gsub") {
it("returns a copy of str with the first occurrence of pattern replaced by the second argument") {
expect("hello".gsub("l", "abc")).to(equal("heabcabco"))
expect("hello".gsub("le", "lll")).to(equal("hello"))
expect("hello".gsub(".".literal, "lll")).to(equal("hello"))
expect("hello".gsub(".", "lll")).to(equal("lll" * 5))
expect("hello".gsub("^he", "lll")).to(equal("lllllo"))
expect("my name is draven".gsub("\\b(?<!['’`])[a-z]") { _ in
return "a"
}).to(equal("ay aame as araven"))
}
}
describe(".gsubed") {
it("mutates current string with gsub") {
var hello = "hello"
hello.gsubed("l", "abc")
expect(hello).to(equal("heabcabco"))
}
}
describe(".match(str:)") {
it("converts pattern to a NSRegularExpression, then invokes its match method on str") {
let matchData = "hello".match("(.)ll(o)")!
expect(matchData.match).to(equal("ello"))
expect(matchData.captures[0]).to(equal("e"))
expect(matchData.captures[1]).to(equal("o"))
}
it("retuns nil if matches nothing") {
let matchData = "hello".match("aha")
expect(matchData).to(beNil())
}
}
describe(".scan(str:)") {
it("returns all the match results in an array") {
let str = "abcxxabcxxsbc"
let scanResults = str.scan("(.)bc")
expect(scanResults[0].to_a).to(equal(["abc", "a"]))
expect(scanResults[1].to_a).to(equal(["abc", "a"]))
expect(scanResults[2].to_a).to(equal(["sbc", "s"]))
}
}
}
}
| ad8b44a71f7804f3b2c3e3fdf8e3a691 | 35.75641 | 110 | 0.477503 | false | false | false | false |
firebase/firebase-ios-sdk | refs/heads/master | FirebaseCore/Internal/Sources/HeartbeatLogging/RingBuffer.swift | apache-2.0 | 1 | // Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 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
/// A generic circular queue structure.
struct RingBuffer<Element>: Sequence {
/// An array of heartbeats treated as a circular queue and intialized with a fixed capacity.
private var circularQueue: [Element?]
/// The current "tail" and insert point for the `circularQueue`.
private var tailIndex: Array<Element?>.Index
/// Error types for `RingBuffer` operations.
enum Error: LocalizedError {
case outOfBoundsPush(pushIndex: Array<Element?>.Index, endIndex: Array<Element?>.Index)
var errorDescription: String {
switch self {
case let .outOfBoundsPush(pushIndex, endIndex):
return "Out-of-bounds push at index \(pushIndex) to ring buffer with" +
"end index of \(endIndex)."
}
}
}
/// Designated initializer.
/// - Parameter capacity: An `Int` representing the capacity.
init(capacity: Int) {
circularQueue = Array(repeating: nil, count: capacity)
tailIndex = circularQueue.startIndex
}
/// Pushes an element to the back of the buffer, returning the element (`Element?`) that was overwritten.
/// - Parameter element: The element to push to the back of the buffer.
/// - Returns: The element that was overwritten or `nil` if nothing was overwritten.
/// - Complexity: O(1)
@discardableResult
mutating func push(_ element: Element) throws -> Element? {
guard circularQueue.count > 0 else {
// Do not push if `circularQueue` is a fixed empty array.
return nil
}
guard circularQueue.indices.contains(tailIndex) else {
// We have somehow entered an invalid state (#10025).
throw Self.Error.outOfBoundsPush(
pushIndex: tailIndex,
endIndex: circularQueue.endIndex
)
}
let replaced = circularQueue[tailIndex]
circularQueue[tailIndex] = element
// Increment index, wrapping around to the start if needed.
tailIndex += 1
if tailIndex >= circularQueue.endIndex {
tailIndex = circularQueue.startIndex
}
return replaced
}
/// Pops an element from the back of the buffer, returning the element (`Element?`) that was popped.
/// - Returns: The element that was popped or `nil` if there was no element to pop.
/// - Complexity: O(1)
@discardableResult
mutating func pop() -> Element? {
guard circularQueue.count > 0 else {
// Do not pop if `circularQueue` is a fixed empty array.
return nil
}
// Decrement index, wrapping around to the back if needed.
tailIndex -= 1
if tailIndex < circularQueue.startIndex {
tailIndex = circularQueue.endIndex - 1
}
guard let popped = circularQueue[tailIndex] else {
return nil // There is no element to pop.
}
circularQueue[tailIndex] = nil
return popped
}
func makeIterator() -> IndexingIterator<[Element]> {
circularQueue
.compactMap { $0 } // Remove `nil` elements.
.makeIterator()
}
}
// MARK: - Codable
extension RingBuffer: Codable where Element: Codable {}
| 20bda5d9a091fd9116264e5b473e1acf | 31.954128 | 107 | 0.686804 | false | false | false | false |
KittenYang/Kingfisher | refs/heads/master | Kingfisher/KingfisherManager.swift | mit | 1 | //
// KingfisherManager.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/**
* RetrieveImageTask represents a task of image retrieving process.
* It contains an async task of getting image from disk and from network.
*/
public class RetrieveImageTask {
var diskRetrieveTask: RetrieveImageDiskTask?
var downloadTask: RetrieveImageDownloadTask?
/**
Cancel current task. If this task does not begin or already done, do nothing.
*/
public func cancel() {
if let diskRetrieveTask = diskRetrieveTask {
dispatch_block_cancel(diskRetrieveTask)
}
if let downloadTask = downloadTask {
downloadTask.cancel()
}
}
}
public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error"
private let instance = KingfisherManager()
/**
* Main manager class of Kingfisher
*/
public class KingfisherManager {
/**
* Options to control some downloader and cache behaviors.
*/
public typealias Options = (forceRefresh: Bool, lowPriority: Bool, cacheMemoryOnly: Bool, shouldDecode: Bool)
/// A preset option tuple with all value set to `false`.
public static var OptionsNone: Options = {
return (forceRefresh: false, lowPriority: false, cacheMemoryOnly: false, shouldDecode: false)
}()
/// Shared manager used by the extensions across Kingfisher.
public class var sharedManager: KingfisherManager {
return instance
}
/// Cache used by this manager
public var cache: ImageCache
/// Downloader used by this manager
public var downloader: ImageDownloader
/**
Default init method
:returns: A Kingfisher manager object with default cache and default downloader.
*/
public init() {
cache = ImageCache.defaultCache
downloader = ImageDownloader.defaultDownloader
}
/**
Get an image with URL as the key.
If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
If not found, it will download the image at URL and cache it.
These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
:param: URL The image URL.
:param: optionsInfo A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
:param: progressBlock Called every time downloaded data changed. This could be used as a progress UI.
:param: completionHandler Called when the whole retriving process finished.
:returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
*/
public func retrieveImageWithURL(URL: NSURL,
optionsInfo: KingfisherOptionsInfo?,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
func parseOptionsInfo(optionsInfo: KingfisherOptionsInfo?) -> (Options, ImageCache, ImageDownloader) {
let options: Options
if let optionsInOptionsInfo = optionsInfo?[.Options] as? KingfisherOptions {
options = (forceRefresh: (optionsInOptionsInfo & KingfisherOptions.ForceRefresh) != KingfisherOptions.None,
lowPriority: (optionsInOptionsInfo & KingfisherOptions.LowPriority) != KingfisherOptions.None,
cacheMemoryOnly: (optionsInOptionsInfo & KingfisherOptions.CacheMemoryOnly) != KingfisherOptions.None,
shouldDecode: (optionsInOptionsInfo & KingfisherOptions.BackgroundDecode) != KingfisherOptions.None)
} else {
options = (forceRefresh: false,
lowPriority: false,
cacheMemoryOnly: false,
shouldDecode: false)
}
let targetCache = optionsInfo?[.TargetCache] as? ImageCache ?? self.cache
let usedDownloader = optionsInfo?[.Downloader] as? ImageDownloader ?? self.downloader
return (options, targetCache, usedDownloader)
}
let task = RetrieveImageTask()
// There is a bug in Swift compiler which prevents to write `let (options, targetCache) = parseOptionsInfo(optionsInfo)`
// It will cause a compiler error.
let parsedOptions = parseOptionsInfo(optionsInfo)
let (options, targetCache, downloader) = (parsedOptions.0, parsedOptions.1, parsedOptions.2)
if let key = URL.absoluteString {
if options.forceRefresh {
downloadAndCacheImageWithURL(URL,
forKey: key,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: completionHandler,
options: options,
targetCache: targetCache,
downloader: downloader)
} else {
let diskTask = targetCache.retrieveImageForKey(key, options: options, completionHandler: { (image, cacheType) -> () in
if image != nil {
completionHandler?(image: image, error: nil, cacheType:cacheType, imageURL: URL)
} else {
self.downloadAndCacheImageWithURL(URL,
forKey: key,
retrieveImageTask: task,
progressBlock: progressBlock,
completionHandler: completionHandler,
options: options,
targetCache: targetCache,
downloader: downloader)
}
})
task.diskRetrieveTask = diskTask
}
}
return task
}
func downloadAndCacheImageWithURL(URL: NSURL,
forKey key: String,
retrieveImageTask: RetrieveImageTask,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?,
options: Options,
targetCache: ImageCache,
downloader: ImageDownloader)
{
downloader.downloadImageWithURL(URL, retrieveImageTask: retrieveImageTask, options: options, progressBlock: { (receivedSize, totalSize) -> () in
progressBlock?(receivedSize: receivedSize, totalSize: totalSize)
return
}) { (image, error, imageURL) -> () in
if let error = error where error.code == KingfisherError.NotModified.rawValue {
// Not modified. Try to find the image from cache.
// (The image should be in cache. It should be ensured by the framework users.)
targetCache.retrieveImageForKey(key, options: options, completionHandler: { (cacheImage, cacheType) -> () in
completionHandler?(image: cacheImage, error: nil, cacheType: cacheType, imageURL: URL)
})
return
}
if let image = image {
targetCache.storeImage(image, forKey: key, toDisk: !options.cacheMemoryOnly, completionHandler: nil)
}
completionHandler?(image: image, error: error, cacheType: .None, imageURL: URL)
}
}
}
// MARK: - Deprecated
public extension KingfisherManager {
@availability(*, deprecated=1.2, message="Use -retrieveImageWithURL:optionsInfo:progressBlock:completionHandler: instead.")
public func retrieveImageWithURL(URL: NSURL,
options: KingfisherOptions,
progressBlock: DownloadProgressBlock?,
completionHandler: CompletionHandler?) -> RetrieveImageTask
{
return retrieveImageWithURL(URL, optionsInfo: [.Options : options], progressBlock: progressBlock, completionHandler: completionHandler)
}
}
| c90efe9aafb3af408ff710eafcc91fbf | 42.420561 | 152 | 0.623978 | false | false | false | false |
phatblat/realm-cocoa | refs/heads/master | RealmSwift/RealmKeyedCollection.swift | apache-2.0 | 2 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2021 Realm 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
import Realm
/**
A homogenous key-value collection of `Object`s which can be retrieved, filtered, sorted, and operated upon.
*/
public protocol RealmKeyedCollection: Sequence, ThreadConfined, CustomStringConvertible {
/// The type of key associated with this collection
associatedtype Key: _MapKey
/// The type of value associated with this collection.
associatedtype Value: RealmCollectionValue
// MARK: Properties
/// The Realm which manages the map, or `nil` if the map is unmanaged.
var realm: Realm? { get }
/// Indicates if the map can no longer be accessed.
var isInvalidated: Bool { get }
/// Returns the number of key-value pairs in this map.
var count: Int { get }
/// A human-readable description of the objects contained in the Map.
var description: String { get }
// MARK: Mutation
/**
Updates the value stored in the dictionary for the given key, or adds a new key-value pair if the key does not exist.
- Note:If the value being added to the dictionary is an unmanaged object and the dictionary is managed
then that unmanaged object will be added to the Realm.
- warning: This method may only be called during a write transaction.
- parameter value: a value's key path predicate.
- parameter forKey: The direction to sort in.
*/
func updateValue(_ value: Value, forKey key: Key)
/**
Removes the given key and its associated object, only if the key exists in the dictionary. If the key does not
exist, the dictionary will not be modified.
- warning: This method may only be called during a write transaction.
*/
func removeObject(for key: Key)
/**
Removes all objects from the dictionary. The objects are not removed from the Realm that manages them.
- warning: This method may only be called during a write transaction.
*/
func removeAll()
/**
Returns the value for a given key, or sets a value for a key should the subscript be used for an assign.
- Note:If the value being added to the dictionary is an unmanaged object and the dictionary is managed
then that unmanaged object will be added to the Realm.
- Note:If the value being assigned for a key is `nil` then that key will be removed from the dictionary.
- warning: This method may only be called during a write transaction.
- parameter key: The key.
*/
subscript(key: Key) -> Value? { get set }
// MARK: KVC
/**
Returns a type of `Value` for a specified key if it exists in the map.
Note that when using key-value coding, the key must be a string.
- parameter key: The key to the property whose values are desired.
*/
func value(forKey key: String) -> AnyObject?
/**
Returns a type of `Value` for a specified key if it exists in the map.
- parameter keyPath: The key to the property whose values are desired.
*/
func value(forKeyPath keyPath: String) -> AnyObject?
/**
Adds a given key-value pair to the dictionary or updates a given key should it already exist.
- warning: This method can only be called during a write transaction.
- parameter value: The object value.
- parameter key: The name of the property whose value should be set on each object.
*/
func setValue(_ value: Any?, forKey key: String)
// MARK: Filtering
/**
Returns a `Results` containing all matching values in the dictionary with the given predicate.
- Note: This will return the values in the dictionary, and not the key-value pairs.
- parameter predicate: The predicate with which to filter the values.
*/
func filter(_ predicate: NSPredicate) -> Results<Value>
/**
Returns a Boolean value indicating whether the Map contains the key-value pair
satisfies the given predicate
- parameter where: a closure that test if any key-pair of the given map represents the match.
*/
func contains(where predicate: @escaping (_ key: Key, _ value: Value) -> Bool) -> Bool
// MARK: Sorting
/**
Returns a `Results` containing the objects in the dictionary, but sorted.
Objects are sorted based on their values. For example, to sort a dictionary of `Date`s from
neweset to oldest based, you might call `dates.sorted(ascending: true)`.
- parameter ascending: The direction to sort in.
*/
func sorted(ascending: Bool) -> Results<Value>
/**
Returns a `Results` containing the objects in the dictionary, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a dictionary of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: Dictionaries may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
func sorted(byKeyPath keyPath: String, ascending: Bool) -> Results<Value>
/**
Returns a `Results` containing the objects in the dictionary, but sorted.
- warning: Dictionaries may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- see: `sorted(byKeyPath:ascending:)`
*/
func sorted<S: Sequence>(by sortDescriptors: S) -> Results<Value>
where S.Iterator.Element == SortDescriptor
/// Returns all of the keys in this dictionary.
var keys: [Key] { get }
/// Returns all of the values in the dictionary.
var values: [Value] { get }
// MARK: Aggregate Operations
/**
Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
dictionary is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
func min<T: MinMaxType>(ofProperty property: String) -> T?
/**
Returns the maximum (highest) value of the given property among all the objects in the dictionary, or `nil` if the
dictionary is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter property: The name of a property whose minimum value is desired.
*/
func max<T: MinMaxType>(ofProperty property: String) -> T?
/**
Returns the sum of the given property for objects in the dictionary, or `nil` if the dictionary is empty.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter property: The name of a property conforming to `AddableType` to calculate sum on.
*/
func sum<T: AddableType>(ofProperty property: String) -> T
/**
Returns the average value of a given property over all the objects in the dictionary, or `nil` if
the dictionary is empty.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter property: The name of a property whose values should be summed.
*/
func average<T: AddableType>(ofProperty property: String) -> T?
// MARK: Notifications
/**
Registers a block to be called each time the dictionary changes.
The block will be asynchronously called with the initial dictionary, and then called again after each write
transaction which changes either any of the keys or values in the dictionary.
The `change` parameter that is passed to the block reports, in the form of keys within the dictionary, which of
the key-value pairs were added, removed, or modified during each write transaction.
At the time when the block is called, the dictionary will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
If no queue is given, notifications are delivered via the standard run loop, and so can't be delivered while the
run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When
notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification.
This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let myStringMap = myObject.stringMap
print("myStringMap.count: \(myStringMap?.count)") // => 0
let token = myStringMap.observe { changes in
switch changes {
case .initial(let myStringMap):
// Will print "myStringMap.count: 1"
print("myStringMap.count: \(myStringMap.count)")
print("Dog Name: \(myStringMap["nameOfDog"])") // => "Rex"
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
myStringMap["nameOfDog"] = "Rex"
}
// end of run loop execution context
```
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `invalidate()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter queue: The serial dispatch queue to receive notification on. If
`nil`, notifications are delivered to the current thread.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
func observe(on queue: DispatchQueue?,
_ block: @escaping (RealmMapChange<Self>) -> Void)
-> NotificationToken
/**
Registers a block to be called each time the dictionary changes.
The block will be asynchronously called with the initial dictionary, and then called again after each write
transaction which changes either any of the keys or values in the dictionary.
The `change` parameter that is passed to the block reports, in the form of keys within the dictionary, which of
the key-value pairs were added, removed, or modified during each write transaction.
At the time when the block is called, the dictionary will be fully evaluated and up-to-date, and as long as you do
not perform a write transaction on the same thread or explicitly call `realm.refresh()`, accessing it will never
perform blocking work.
If no queue is given, notifications are delivered via the standard run loop, and so can't be delivered while the
run loop is blocked by other activity. If a queue is given, notifications are delivered to that queue instead. When
notifications can't be delivered instantly, multiple notifications may be coalesced into a single notification.
This can include the notification with the initial collection.
For example, the following code performs a write transaction immediately after adding the notification block, so
there is no opportunity for the initial notification to be delivered first. As a result, the initial notification
will reflect the state of the Realm after the write transaction.
```swift
let myStringMap = myObject.stringMap
print("myStringMap.count: \(myStringMap?.count)") // => 0
let token = myStringMap.observe { changes in
switch changes {
case .initial(let myStringMap):
// Will print "myStringMap.count: 1"
print("myStringMap.count: \(myStringMap.count)")
print("Dog Name: \(myStringMap["nameOfDog"])") // => "Rex"
break
case .update:
// Will not be hit in this example
break
case .error:
break
}
}
try! realm.write {
myStringMap["nameOfDog"] = "Rex"
}
// end of run loop execution context
```
If no key paths are given, the block will be executed on any insertion,
modification, or deletion for all object properties and the properties of
any nested, linked objects. If a key path or key paths are provided,
then the block will be called for changes which occur only on the
provided key paths. For example, if:
```swift
class Dog: Object {
@Persisted var name: String
@Persisted var age: Int
@Persisted var toys: List<Toy>
}
// ...
let dogs = myObject.mapOfDogs
let token = dogs.observe(keyPaths: ["name"]) { changes in
switch changes {
case .initial(let dogs):
// ...
case .update:
// This case is hit:
// - after the token is intialized
// - when the name property of an object in the
// collection is modified
// - when an element is inserted or removed
// from the collection.
// This block is not triggered:
// - when a value other than name is modified on
// one of the elements.
case .error:
// ...
}
}
// end of run loop execution context
```
- If the observed key path were `["toys.brand"]`, then any insertion or
deletion to the `toys` list on any of the collection's elements would trigger the block.
Changes to the `brand` value on any `Toy` that is linked to a `Dog` in this
collection will trigger the block. Changes to a value other than `brand` on any `Toy` that
is linked to a `Dog` in this collection would not trigger the block.
Any insertion or removal to the `Dog` type collection being observed
would also trigger a notification.
- If the above example observed the `["toys"]` key path, then any insertion,
deletion, or modification to the `toys` list for any element in the collection
would trigger the block.
Changes to any value on any `Toy` that is linked to a `Dog` in this collection
would *not* trigger the block.
Any insertion or removal to the `Dog` type collection being observed
would still trigger a notification.
- note: Multiple notification tokens on the same object which filter for
separate key paths *do not* filter exclusively. If one key path
change is satisfied for one notification token, then all notification
token blocks for that object will execute.
You must retain the returned token for as long as you want updates to be sent to the block. To stop receiving
updates, call `invalidate()` on the token.
- warning: This method cannot be called during a write transaction, or when the containing Realm is read-only.
- parameter keyPaths: Only properties contained in the key paths array will trigger
the block when they are modified. If `nil`, notifications
will be delivered for any property change on the object.
String key paths which do not correspond to a valid a property
will throw an exception.
See description above for more detail on linked properties.
- note: The keyPaths parameter refers to object properties of the collection type and
*does not* refer to particular key/value pairs within the collection.
- parameter queue: The serial dispatch queue to receive notification on. If
`nil`, notifications are delivered to the current thread.
- parameter block: The block to be called whenever a change occurs.
- returns: A token which must be held for as long as you want updates to be delivered.
*/
func observe(keyPaths: [String]?,
on queue: DispatchQueue?,
_ block: @escaping (RealmMapChange<Self>) -> Void) -> NotificationToken
// MARK: Frozen Objects
/// Returns if this collection is frozen
var isFrozen: Bool { get }
/**
Returns a frozen (immutable) snapshot of this collection.
The frozen copy is an immutable collection which contains the same data as this collection
currently contains, but will not update when writes are made to the containing Realm. Unlike
live collections, frozen collections can be accessed from any thread.
- warning: This method cannot be called during a write transaction, or when the containing
Realm is read-only.
- warning: Holding onto a frozen collection for an extended period while performing write
transaction on the Realm may result in the Realm file growing to large sizes. See
`Realm.Configuration.maximumNumberOfActiveVersions` for more information.
*/
func freeze() -> Self
/**
Returns a live (mutable) version of this frozen collection.
This method resolves a reference to a live copy of the same frozen collection.
If called on a live collection, will return itself.
*/
func thaw() -> Self?
}
/**
Protocol for RealmKeyedCollections where the Value is of an Object type that
enables aggregatable operations.
*/
public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: ObjectBase, Value.Wrapped: RealmCollectionValue {
/**
Returns the minimum (lowest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter keyPath: The keyPath of a property whose minimum value is desired.
*/
func min<T: MinMaxType>(of keyPath: KeyPath<Value.Wrapped, T>) -> T? {
min(ofProperty: _name(for: keyPath))
}
/**
Returns the maximum (highest) value of the given property among all the objects in the collection, or `nil` if the
collection is empty.
- warning: Only a property whose type conforms to the `MinMaxType` protocol can be specified.
- parameter keyPath: The keyPath of a property whose minimum value is desired.
*/
func max<T: MinMaxType>(of keyPath: KeyPath<Value.Wrapped, T>) -> T? {
max(ofProperty: _name(for: keyPath))
}
/**
Returns the sum of the given property for objects in the collection, or `nil` if the collection is empty.
- warning: Only names of properties of a type conforming to the `AddableType` protocol can be used.
- parameter keyPath: The keyPath of a property conforming to `AddableType` to calculate sum on.
*/
func sum<T: AddableType>(of keyPath: KeyPath<Value.Wrapped, T>) -> T {
sum(ofProperty: _name(for: keyPath))
}
/**
Returns the average value of a given property over all the objects in the collection, or `nil` if
the collection is empty.
- warning: Only a property whose type conforms to the `AddableType` protocol can be specified.
- parameter keyPath: The keyPath of a property whose values should be summed.
*/
func average<T: AddableType>(of keyPath: KeyPath<Value.Wrapped, T>) -> T? {
average(ofProperty: _name(for: keyPath))
}
}
// MARK: Sortable
/**
Protocol for RealmKeyedCollections where the Value is of an Object type that
enables sortable operations.
*/
public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: ObjectBase, Value.Wrapped: RealmCollectionValue {
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on the values of the given key path. For example, to sort a collection of `Student`s from
youngest to oldest based on their `age` property, you might call
`students.sorted(byKeyPath: "age", ascending: true)`.
- warning: Collections may only be sorted by properties of boolean, `Date`, `NSDate`, single and double-precision
floating point, integer, and string types.
- parameter keyPath: The key path to sort by.
- parameter ascending: The direction to sort in.
*/
func sorted<T: Comparable>(by keyPath: KeyPath<Value.Wrapped, T>, ascending: Bool) -> Results<Value> {
sorted(byKeyPath: _name(for: keyPath), ascending: ascending)
}
}
public extension RealmKeyedCollection where Value: MinMaxType {
/**
Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
*/
func min() -> Value? {
return min(ofProperty: "self")
}
/**
Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
*/
func max() -> Value? {
return max(ofProperty: "self")
}
}
public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: MinMaxType {
/**
Returns the minimum (lowest) value of the collection, or `nil` if the collection is empty.
*/
func min() -> Value.Wrapped? {
return min(ofProperty: "self")
}
/**
Returns the maximum (highest) value of the collection, or `nil` if the collection is empty.
*/
func max() -> Value.Wrapped? {
return max(ofProperty: "self")
}
}
public extension RealmKeyedCollection where Value: AddableType {
/**
Returns the sum of the values in the collection, or `nil` if the collection is empty.
*/
func sum() -> Value {
return sum(ofProperty: "self")
}
/**
Returns the average of all of the values in the collection.
*/
func average<T: AddableType>() -> T? {
return average(ofProperty: "self")
}
}
public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: AddableType {
/**
Returns the sum of the values in the collection, or `nil` if the collection is empty.
*/
func sum() -> Value.Wrapped {
return sum(ofProperty: "self")
}
/**
Returns the average of all of the values in the collection.
*/
func average<T: AddableType>() -> T? {
return average(ofProperty: "self")
}
}
public extension RealmKeyedCollection where Value: Comparable {
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on their values. For example, to sort a collection of `Date`s from
neweset to oldest based, you might call `dates.sorted(ascending: true)`.
- parameter ascending: The direction to sort in.
*/
func sorted(ascending: Bool = true) -> Results<Value> {
return sorted(byKeyPath: "self", ascending: ascending)
}
}
public extension RealmKeyedCollection where Value: OptionalProtocol, Value.Wrapped: Comparable {
/**
Returns a `Results` containing the objects in the collection, but sorted.
Objects are sorted based on their values. For example, to sort a collection of `Date`s from
neweset to oldest based, you might call `dates.sorted(ascending: true)`.
- parameter ascending: The direction to sort in.
*/
func sorted(ascending: Bool = true) -> Results<Value> {
return sorted(byKeyPath: "self", ascending: ascending)
}
}
| dbf4d2371353c1ed73a6449dd26be0e9 | 40.289562 | 133 | 0.674386 | false | false | false | false |
EclipseSoundscapes/EclipseSoundscapes | refs/heads/master | EclipseSoundscapes/Features/About/Settings/Sections/Language/LanguageSettingItem.swift | gpl-3.0 | 1 | //
// LanguageSettingItem.swift
// EclipseSoundscapes
//
// Created by Arlindo on 12/26/20.
// Copyright © 2020 Eclipse Soundscapes. All rights reserved.
//
import RxCocoa
class LanguageSettingItem: SettingItem, ReactiveViewModel, EventViewModel {
let cellIdentifier: String = LanguageCell.identifier
let info: String = localizedString(key: "SettingsLanguageInstructions")
let setingsButtonTitle: String = localizedString(key: "SettingsLanguageButton")
let eventRelay = PublishRelay<Event>()
lazy var event: Signal<Event> = eventRelay.asSignal()
func react(to action: Action) {
switch action {
case .openDeviceSettings:
eventRelay.accept(.openDeviceSettings)
}
}
}
| 98340f4848ed9b9400c2004692fe37e8 | 29.833333 | 83 | 0.710811 | false | false | false | false |
v-andr/LakestoneCore | refs/heads/master | Source/HTTP.swift | apache-2.0 | 1 | //
// HTTP.swift
// LakestoneCore
//
// Created by Taras Vozniuk on 9/7/16.
// Copyright © 2016 GeoThings. All rights reserved.
//
// --------------------------------------------------------
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// HTTP-associated set of abstractions
//
#if COOPER
import java.net
import java.io
import android.util
#else
import Foundation
#if os(OSX) || os(Linux)
import PerfectCURL
import cURL
import PerfectThread
#endif
#endif
///
/// Designated class to perform a set of HTTP-related operations.
///
public class HTTP {
public class Request {
/// designated target of this requests
public let url: URL
public init(url: URL){
self.url = url
}
public var method: Method = .get
public var basicAuthentificationStringº: String? {
didSet {
if let basicAuthentificationString = basicAuthentificationStringº {
self.headers["Authorization"] = "Basic \(basicAuthentificationString)"
} else {
self.headers["Authorization"] = nil
}
}
}
public var headers = [String: String]()
public var dataº: Data?
public let queue: ThreadQueue = Threading.serialQueue(withLabel: "lakestonecore.http.request.queue")
#if os(iOS) || os(watchOS) || os(tvOS)
private var _downloadDelegateº: _DownloadDelegate?
#endif
// Silver is fragile with string-backed enums, plain enum in the meanwhile
public enum Method {
case get
case post
case put
#if os(OSX) || os(Linux)
public var methodCurlOption: CURLoption {
switch self {
case .get: return CURLOPT_HTTPGET
case .post: return CURLOPT_POST
case .put: return CURLOPT_PUT
}
}
#endif
}
public var methodString: String {
switch self.method {
case .get: return "GET"
case .post: return "POST"
case .put: return "PUT"
}
}
public class Error {
#if !COOPER
/// indicates the error in underlying invocation which results in both internally returned response objects and error being nil.
///
/// - remark: thrown when Foundation's session.dataTask(with:) callbacks with error and response both nil.
/// It is unlikely that this error will be ever thrown
static let Unknown = LakestoneError.with(stringRepresentation: "Internal unknown invocation error")
static let AddingPercentEncodingWithAllowedCharacterFailure = LakestoneError.with(stringRepresentation: "Adding percent encoding with allowed character set failed")
#endif
#if os(OSX) || os(Linux)
static let NotUTF8EncodedBytes = LakestoneError.with(stringRepresentation: "Received response data cannot be inferred as UTF8 string")
#endif
}
#if os(OSX) || os(Linux)
/// Error representable type that is backend by CURL error
public class CURLInvocationErrorType: ErrorRepresentable {
let curlCode: Int
let errorDetail: String
init(curlCode: Int, errorDetail: String){
self.curlCode = curlCode
self.errorDetail = errorDetail
}
public var detailMessage: String {
return self.errorDetail
}
}
#endif
public func addBasicAuthentification(with username: String, and password: String){
#if COOPER
self.basicAuthentificationStringº = Base64.encodeToString("\(username):\(password)".getBytes(), 0)
#else
self.basicAuthentificationStringº = Data.with(utf8EncodedString: "\(username):\(password)")?.base64EncodedString()
#endif
}
public func setFormURLEncodedData(with parameters:[String:Any]) throws {
#if !COOPER
var allowedCharacterSet = CharacterSet.urlQueryAllowed
//if '&' is present as part of value it needs to be escaped, since non escaped '&' will be treated as key=value pair seperator
allowedCharacterSet.remove(charactersIn: "&")
#endif
var urlEncodedString = String()
for (keyIndex, key) in parameters.keys.enumerated() {
guard let value = parameters[key] else {
continue
}
#if COOPER
let urlEncodedValue = URLEncoder.encode(String.derived(from: value), "UTF-8")
let urlEncodedKey = URLEncoder.encode(key, "UTF-8")
#else
guard let urlEncodedValue = String.derived(from: value).addingPercentEncoding(withAllowedCharacters: allowedCharacterSet),
let urlEncodedKey = key.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)
else {
throw Error.AddingPercentEncodingWithAllowedCharacterFailure
}
#endif
urlEncodedString += "\(urlEncodedKey)=\(urlEncodedValue)"
if (keyIndex < parameters.keys.count - 1){
urlEncodedString += "&"
}
}
guard let encodedData = Data.with(utf8EncodedString: urlEncodedString) else {
throw Data.Error.UTF8IncompatibleString
}
self.dataº = encodedData
self.headers["Content-Type"] = "application/x-www-form-urlencoded"
}
public func setMutlipartFormData(with parameters: [String: Any], mimeTypes: [String: String] = [:], fileNames: [String: String] = [:]) throws {
let boundary = "Boundary-\(UUID().uuidString)"
var multipartString = String()
var contentFragements = [Any]()
for (key, value) in parameters {
multipartString += "--\(boundary)\r\n"
multipartString += "Content-Disposition: form-data; name=\"\(key)\";"
if let filename = fileNames[key],value is Data {
multipartString += "; filename=\"\(filename)\""
}
multipartString += "\r\n"
if let mimeType = mimeTypes[key] {
multipartString += "Content-Type: \(mimeType)\r\n"
}
multipartString += "\r\n"
if let data = value as? Data {
contentFragements.append(multipartString)
contentFragements.append(data)
multipartString = String()
multipartString += "\r\n"
} else {
multipartString += "\(String.derived(from: value))\r\n"
}
}
multipartString += "--\(boundary)--\r\n"
var targetData = Data.empty
for contentFragement in contentFragements {
if let stringFragment = contentFragement as? String {
guard let encodedData = Data.with(utf8EncodedString: stringFragment) else {
throw Data.Error.UTF8IncompatibleString
}
targetData = targetData.appending(encodedData)
} else if let partialData = contentFragement as? Data {
targetData = targetData.appending(partialData)
} else {
#if COOPER
let contentType = contentFragement.Class
#else
let contentType = type(of: contentFragement)
#endif
print("WARNING: \(#function): Unexpected content fragment type: \(contentType). Fragment ignored")
}
}
guard let encodedRemainingFragment = Data.with(utf8EncodedString: multipartString) else {
throw Data.Error.UTF8IncompatibleString
}
self.dataº = targetData.appending(encodedRemainingFragment)
self.headers["Content-Type"] = "multipart/form-data; boundary=\(boundary)"
}
/// synchronous request invocation
/// - throws: **Java**:
/// `IOException` if an error occurs while opening/closing connection, reading/writing from/to designated remote.
/// **iOS**:
/// Wrapped `NSError` that indicates URLSession dataTask invocation error.
/// `HTTP.Request.Error.Unknown` when URLSession error was not provided.
/// **OSX/Linux**:
/// `LakestoneError` with CURLInvocationError contained object that contains curlError code and its description
/// `HTTP.Response.Error.UnexpectedEmptyHeaderData`, `HTTP.Response.Error.StatusLineFormatInvalid`
///
/// - returns: The response object carrying request status, http-headers, and optional data if providid
///
/// - warning: This will block the current thread until completed.
/// Therefore avoid calling it on the main thread.
#if COOPER
public func performSync() throws -> Response {
return try self._performSyncCore(with: nil)
}
private func _performSyncCore(with progressDelegateº: ((Double) -> Void)?) throws -> Response {
let currentConnection = self.url.openConnection() as! HttpURLConnection
do {
currentConnection.setDoOutput(false)
currentConnection.setUseCaches(false)
currentConnection.setRequestMethod(self.methodString)
currentConnection.setConnectTimeout(10 * 1000)
for (headerKey, headerValue) in self.headers {
currentConnection.setRequestProperty(headerKey, headerValue)
}
if self.method != .get {
currentConnection.setDoInput(true)
currentConnection.setDoOutput(true)
// writing off the data
if let data = self.dataº {
let outputStream = BufferedOutputStream(currentConnection.getOutputStream())
outputStream.write(data.plainBytes)
outputStream.close()
}
}
currentConnection.connect()
let responseCode = currentConnection.getResponseCode()
let responseHeaders = currentConnection.getHeaderFields()
let responseMessage = currentConnection.getResponseMessage()
let inputStream: InputStream
if responseCode >= 400 {
inputStream = BufferedInputStream(currentConnection.getErrorStream())
} else {
inputStream = BufferedInputStream(currentConnection.getInputStream())
}
let outputByteStream = ByteArrayOutputStream()
var readSize = currentConnection.getContentLength()
let batchReadSize = 16384
if progressDelegateº != nil && batchReadSize < readSize {
readSize = batchReadSize
} else if readSize < 0 {
readSize = batchReadSize
}
// reading the response
let bytes = java.lang.reflect.Array.newInstance(Byte.self, readSize) as! ByteStaticArray
var nRead: Int
var totalRead: Int = 0
while ( (nRead = inputStream.read(bytes, 0, readSize)) != -1){
outputByteStream.write(bytes, 0, nRead)
totalRead += nRead
let progress = Double(totalRead)/Double(currentConnection.getContentLength())
if progress < 1 {
progressDelegateº?(progress)
}
}
let completeData = Data.wrap(outputByteStream.toByteArray())
inputStream.close()
outputByteStream.close()
currentConnection.disconnect()
// header values are represented in List<String> for each individual key
// concatenate for unification-sake
//TODO: review whether this concatenation is neccesary
let targetPlainHeaderDict = [String: String]()
for entry in responseHeaders.entrySet() {
let key = entry.getKey()
var concatantedValues = String()
for individualValue in entry.getValue() {
concatantedValues = (concatantedValues.isEmpty()) ? individualValue : concatantedValues + ", \(individualValue)"
}
targetPlainHeaderDict[key] = concatantedValues
}
return HTTP.Response(url: self.url, statusCode: responseCode, statusMessage: responseMessage, headerFields: targetPlainHeaderDict, data: completeData)
} catch {
currentConnection.disconnect()
throw error
}
}
#else
public func performSync() throws -> Response {
#if os(OSX) || os(Linux)
let request = CURL(url: self.url.absoluteString)
var code = request.setOption(CURLOPT_FRESH_CONNECT, int: 1)
if (code != CURLE_OK) { throw LakestoneError(CURLInvocationErrorType(curlCode: Int(code.rawValue), errorDetail: request.strError(code: code))) }
if self.method == .put {
//curl put request modified.
// Setting method as PUT directly will for some reason will result in performFully() never return
code = request.setOption(CURLOPT_CUSTOMREQUEST, s: self.methodString)
} else {
code = request.setOption(self.method.methodCurlOption, int: 1)
if (code != CURLE_OK) { throw LakestoneError(CURLInvocationErrorType(curlCode: Int(code.rawValue), errorDetail: request.strError(code: code))) }
}
for (headerKey, headerValue) in self.headers {
code = request.setOption(CURLOPT_HTTPHEADER, s: "\(headerKey): \(headerValue)")
if (code != CURLE_OK) { throw LakestoneError(CURLInvocationErrorType(curlCode: Int(code.rawValue), errorDetail: request.strError(code: code))) }
}
if self.method != .get {
if let bytes = self.dataº?.bytes {
code = request.setOption(CURLOPT_POSTFIELDSIZE, int: bytes.count)
if (code != CURLE_OK) { throw LakestoneError(CURLInvocationErrorType(curlCode: Int(code.rawValue), errorDetail: request.strError(code: code))) }
code = request.setOption(CURLOPT_COPYPOSTFIELDS, v: UnsafeMutableRawPointer(mutating: bytes))
if (code != CURLE_OK) { throw LakestoneError(CURLInvocationErrorType(curlCode: Int(code.rawValue), errorDetail: request.strError(code: code))) }
}
}
let (invocationCode, headerBytes, bodyData) = request.performFully()
guard let headerString = String(bytes: headerBytes, encoding: String.Encoding.utf8) else {
throw HTTP.Request.Error.NotUTF8EncodedBytes
}
request.close()
if CURLcode(rawValue: UInt32(invocationCode)) != CURLE_OK {
throw LakestoneError(CURLInvocationErrorType(curlCode: invocationCode, errorDetail: request.strError(code: CURLcode(rawValue: UInt32(invocationCode)))))
}
var headerComponentsStrings = headerString.components(separatedBy: "\r\n").filter { !$0.isEmpty }
if headerComponentsStrings.isEmpty {
//curl invocation code is CURLE_OK however for header components are unexpectedly empty
throw HTTP.Response.Error.UnexpectedEmptyHeaderData
}
let statusComponents = headerComponentsStrings.removeFirst().components(separatedBy: " ")
guard statusComponents.count >= 3,
let statusCode = Int(statusComponents[1])
else {
throw HTTP.Response.Error.StatusLineFormatInvalid
}
let statusMessage = Array(statusComponents[2 ..< statusComponents.count]).joined(separator: " ")
let headerComponents = headerComponentsStrings.map { (headerComponentString: String) -> (String, String) in
var components = headerComponentString.components(separatedBy: ":")
if (components.count == 1){
return (components[0].trimmingCharacters(in: CharacterSet.whitespaces), String())
} else if (components.count == 2){
return (components[0].trimmingCharacters(in: CharacterSet.whitespaces), components[1].trimmingCharacters(in: CharacterSet.whitespaces))
} else if (components.count > 2){
//handling of case when : is a part of headerValue, thus we need to concatenate it back
let headerKey = components.removeFirst().trimmingCharacters(in: CharacterSet.whitespaces)
let headerValue = components.joined(separator: ":").trimmingCharacters(in: CharacterSet.whitespaces)
return (headerKey, headerValue)
} else {
return (String(), String())
}
}.filter { !$0.0.isEmpty }
var headerFields = [String: String]()
headerComponents.forEach { headerFields[$0.0] = $0.1 }
return HTTP.Response(url: self.url, statusCode: statusCode, statusMessage: statusMessage, headerFields: headerFields, data: Data(bytes: bodyData))
#else
var request = URLRequest(url: self.url)
request.httpMethod = self.methodString
for (headerKey, headerValue) in self.headers {
request.setValue(headerValue, forHTTPHeaderField: headerKey)
}
if self.method != .get {
request.httpBody = self.dataº
}
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: nil, delegateQueue: nil)
var targetDataº: Data?
var targetResponseº: URLResponse?
var targetErrorº: Swift.Error?
let semaphore = DispatchSemaphore(value: 0)
let dataTask = session.dataTask(with: request){ (dataº: Data?, responseº: URLResponse?, errorº: Swift.Error?) in
targetDataº = dataº
targetResponseº = responseº
targetErrorº = errorº
semaphore.signal()
}
dataTask.resume()
semaphore.wait()
if let targetError = targetErrorº {
throw targetError
}
// if response is nil and returned error is nil, error is not provided then
// this should never happen, but still handling this scenario
guard let response = targetResponseº as? HTTPURLResponse else {
throw Error.Unknown
}
var targetHeaderFields = [String: String]()
for (header, headerValue) in response.allHeaderFields {
guard let headerString = header as? String,
let headerValueString = headerValue as? String
else {
print("Header field entry is not a string literal")
continue
}
targetHeaderFields[headerString] = headerValueString
}
let statusMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode)
return HTTP.Response(url: self.url, statusCode: response.statusCode, statusMessage: statusMessage, headerFields: targetHeaderFields, data: targetDataº)
#endif
}
#endif
public func perform(with progressCallbackº:((Double) -> Void)? = nil, and completionHander: @escaping (ThrowableError?, Response?) -> Void){
#if os(iOS) || os(watchOS) || os(tvOS)
var request = URLRequest(url: self.url)
request.httpMethod = self.methodString
for (headerKey, headerValue) in self.headers {
request.setValue(headerValue, forHTTPHeaderField: headerKey)
}
if self.method != .get {
request.httpBody = self.dataº
}
_downloadDelegateº = _DownloadDelegate(invocationURL: self.url, progressDelegateº: progressCallbackº, completionHandler: completionHander)
let session = URLSession(configuration: URLSessionConfiguration.default, delegate: _downloadDelegateº, delegateQueue: nil)
let downloadTask = session.downloadTask(with: request)
downloadTask.resume()
#else
self.queue.dispatch {
do {
#if COOPER
let response = try self._performSyncCore(with: progressCallbackº)
#else
let response = try self.performSync()
#endif
completionHander(nil, response)
} catch {
#if COOPER
completionHander(error as! ThrowableError, nil)
#else
completionHander(error, nil)
#endif
}
}
#endif
}
}
/// Container that carries HTTP response entities
public class Response {
public class StatusCode {
public static let OK = 200
public static let BadRequest = 400
public static let Unauthorized = 401
public static let Forbidden = 403
public static let NotFound = 404
public static let MethodNotAllowed = 405
public static let NotAcceptable = 406
public static let UnsupportedMediaType = 415
}
public class Error {
#if os(OSX) || os(Linux)
/// indicates the empty headerData received while CURL invocation returned without error
/// Can only be thrown on Linux or OSX
static let UnexpectedEmptyHeaderData = LakestoneError.with(stringRepresentation: "Header data is empty when expected")
/// indicates the parsing failure of HTTP status line since it has invalid format
/// Can only be thrown on Linux or OSX
static let StatusLineFormatInvalid = LakestoneError.with(stringRepresentation: "HTTP Status line parsing failed: Invalid format")
#endif
}
/// origin of this responses
public let url: URL
public let statusCode: Int
public let statusMessage: String
public let headerFields: [String: String]
public let dataº: Data?
init(url: URL, statusCode: Int, statusMessage: String, headerFields: [String: String], data: Data? = nil){
self.url = url
self.statusCode = statusCode
self.statusMessage = statusMessage
self.headerFields = headerFields
self.dataº = data
}
public var jsonDictionaryDataº: [String: Any]? {
guard let data = self.dataº else {
return nil
}
return (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
}
public var jsonArrayDataº: [Any]? {
guard let data = self.dataº else {
return nil
}
return (try? JSONSerialization.jsonObject(with: data)) as? [Any]
}
}
#if os(iOS) || os(watchOS) || os(tvOS)
private class _DownloadDelegate: NSObject, URLSessionDownloadDelegate {
let invocationURL: URL
let progressDelegateº: ((Double) -> Void)?
let completionHandler: (ThrowableError?, Response?) -> Void
init(invocationURL: URL, progressDelegateº: ((Double) -> Void)?, completionHandler: @escaping (ThrowableError?, Response?) -> Void){
self.invocationURL = invocationURL
self.progressDelegateº = progressDelegateº
self.completionHandler = completionHandler
}
fileprivate func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
guard let response = downloadTask.response as? HTTPURLResponse else {
self.completionHandler(HTTP.Request.Error.Unknown, nil)
return
}
var targetHeaderFields = [String: String]()
for (header, headerValue) in response.allHeaderFields {
guard let headerString = header as? String,
let headerValueString = headerValue as? String
else {
print("Header field entry is not a string literal")
continue
}
targetHeaderFields[headerString] = headerValueString
}
let statusMessage = HTTPURLResponse.localizedString(forStatusCode: response.statusCode)
self.completionHandler(nil, HTTP.Response(url: self.invocationURL, statusCode: response.statusCode, statusMessage: statusMessage, headerFields: targetHeaderFields, data: FileManager.default.contents(atPath: location.path)
))
}
fileprivate func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
self.progressDelegateº?(Double(totalBytesWritten)/Double(totalBytesExpectedToWrite))
}
fileprivate func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
self.completionHandler(error, nil)
}
fileprivate func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
//the actual completion callback happens in URLSession(session:, downloadTask:, didFinishDownloadingToURL:), however the error callback is here
if let encounteredError = error {
self.completionHandler(encounteredError, nil)
}
}
}
#endif
}
| 40b9eb29b704d450cd7dffc5732e3421 | 32.381368 | 224 | 0.693542 | false | false | false | false |
alexandreblin/ios-car-dashboard | refs/heads/master | CarDash/RadioViewController.swift | mit | 1 | //
// RadioViewController.swift
// CarDash
//
// Created by Alexandre Blin on 12/06/2016.
// Copyright © 2016 Alexandre Blin. All rights reserved.
//
import UIKit
import MarqueeLabel
/// View controller displaying the current radio station.
class RadioViewController: CarObservingViewController {
@IBOutlet private weak var radioDescriptionVerticalSpaceConstraint: NSLayoutConstraint!
@IBOutlet private weak var nameLabel: UILabel!
@IBOutlet private weak var descriptionLabel: MarqueeLabel!
@IBOutlet private weak var frequencyLabel: UILabel!
@IBOutlet private weak var radioArtView: UIImageView!
private var radioArtFound = false
private let radioAliases = [
"virgin": "europe2",
"mfmradio": "mfm",
"cannesr": "razur",
"rcfnice": "rcf"
]
override func viewDidLoad() {
super.viewDidLoad()
// Add perspective to radioArtView
var rotationAndPerspectiveTransform = CATransform3DIdentity
rotationAndPerspectiveTransform.m34 = 1.0 / -500
rotationAndPerspectiveTransform = CATransform3DRotate(rotationAndPerspectiveTransform, 25.0 * CGFloat(M_PI) / 180.0, 0.0, 1.0, 0.0)
radioArtView.layer.transform = rotationAndPerspectiveTransform
radioArtView.layer.allowsEdgeAntialiasing = true
radioArtView.layer.minificationFilter = kCAFilterTrilinear
}
override func carInfoPropertyChanged(_ carInfo: CarInfo, property: CarInfo.Property) {
if property == .radioName || property == .radioFrequency || property == .radioBandName {
if property == .radioFrequency {
// When changing stations, remove current radio logo
radioArtFound = false
UIView.transition(with: radioArtView, duration: 0.2, options: .transitionCrossDissolve, animations: {
self.radioArtView.image = UIImage(named: "radioart_placeholder")
}, completion: nil)
}
updateRadioLabels()
} else if property == .radioDescription {
setRadioDescription(carInfo.radioDescription)
}
}
/// Sets and animate the radio description label.
///
/// - Parameter description: The description string to set
private func setRadioDescription(_ description: String?) {
if let description = description {
descriptionLabel.text = description
UIView.animate(withDuration: 0.5, animations: {
self.descriptionLabel.alpha = 1
self.radioDescriptionVerticalSpaceConstraint.constant = 32
self.view.layoutIfNeeded()
})
} else {
UIView.animate(withDuration: 0.5, animations: {
self.descriptionLabel.alpha = 0
self.radioDescriptionVerticalSpaceConstraint.constant = -78
self.view.layoutIfNeeded()
})
}
}
private func updateRadioLabels() {
if let radioName = carInfo.radioName, let frequency = carInfo.radioFrequency, let bandName = carInfo.radioBandName {
nameLabel.text = radioName
frequencyLabel.text = "\(frequency) MHz – FM \(bandName)"
let charactersToRemove = CharacterSet.alphanumerics.inverted
let strippedRadioName = carInfo.radioName?.lowercased().components(separatedBy: charactersToRemove).joined(separator: "")
if !radioArtFound {
// Try to find the station logo
if var strippedRadioName = strippedRadioName {
if let mapping = radioAliases[strippedRadioName] {
strippedRadioName = mapping
}
if let radioArt = UIImage(named: "radioart_\(strippedRadioName)") {
radioArtFound = true
UIView.transition(with: radioArtView, duration: 0.2, options: .transitionCrossDissolve, animations: {
self.radioArtView.image = radioArt
}, completion: nil)
}
}
}
} else {
// No station name found, display the frequency instead of the name
nameLabel.text = (carInfo.radioFrequency ?? "0.0") + " MHz"
frequencyLabel.text = "FM " + (carInfo.radioBandName ?? "")
// Force layout now because when changing frequency, we animate the hiding of the radio description
// but we don't want to animate the frequency label (it looks ugly)
view.layoutIfNeeded()
}
}
}
| da1be02571728f424aa566783adc659c | 39.849558 | 139 | 0.623267 | false | false | false | false |
LongPF/FaceTube | refs/heads/master | FaceTube/Tool/Capture/FTCameraOverlayView.swift | mit | 1 | //
// FTCameraOverlayView.swift
// FaceTube
//
// Created by 龙鹏飞 on 2017/4/19.
// Copyright © 2017年 https://github.com/LongPF/FaceTube. All rights reserved.
//
import UIKit
import SnapKit
@objc protocol FTCameraOverlayViewProtocol: NSObjectProtocol {
func close2back()
}
class FTCameraOverlayView: FTView {
var toolbar: FTVideoCaptureToolBar! //顶部的工具栏
var captureButton: FTCaptureButton! //拍摄按钮
fileprivate weak var camera: FTCamera! //弱引用一个camer来 方便 与 overlayview 的交互
fileprivate var filterPickerView: FTFiltersPickerView! //滤镜选择的pickerView
fileprivate var bottomMaskView: UIView! //底部的黑色半透明遮罩
var delegate: FTCameraOverlayViewProtocol?
//MARK: ************************ life cycle ************************
init(camera: FTCamera){
super.init(frame: CGRect.init())
self.camera = camera
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize();
}
fileprivate func initialize(){
self.toolbar = FTVideoCaptureToolBar()
self.toolbar.delegate = self
self.addSubview(self.toolbar)
self.captureButton = FTCaptureButton.init(model: FTCaptureButtonMode.FTCaptureButtonModeVideo)
self.captureButton.addTarget(self, action: #selector(FTCameraOverlayView.captureButtonClicked(button:)), for: .touchUpInside)
self.addSubview(self.captureButton)
self.filterPickerView = FTFiltersPickerView()
self.addSubview(self.filterPickerView)
self.bottomMaskView = UIView()
self.bottomMaskView.backgroundColor = UIColor.black
self.bottomMaskView.alpha = 0.4
self.insertSubview(self.bottomMaskView, belowSubview: self.captureButton)
self.toolbar.snp.makeConstraints { (make) in
make.leading.equalTo(self.snp.leading)
make.trailing.equalTo(self.snp.trailing)
make.top.equalTo(self.snp.top)
make.height.equalTo(40)
}
self.captureButton.snp.makeConstraints { (make) in
make.centerX.equalTo(self.snp.centerX)
make.bottom.equalTo(self.snp.bottom).offset(-15)
make.size.equalTo(CGSize.init(width: 68, height: 68))
}
self.filterPickerView.snp.makeConstraints { (make) in
make.leading.equalTo(self.snp.leading)
make.trailing.equalTo(self.snp.trailing)
make.bottom.equalTo(self.captureButton.snp.top).offset(-5)
make.height.equalTo(40)
}
self.bottomMaskView.snp.makeConstraints { (make) in
make.leading.equalTo(self.snp.leading)
make.trailing.equalTo(self.snp.trailing)
make.bottom.equalTo(self.snp.bottom)
make.top.equalTo(self.filterPickerView.snp.top).offset(-10)
}
}
//MARK: ************************ response methods ***************
func captureButtonClicked(button: UIButton){
if self.camera.recording {
self.camera.stopRecording()
}else{
self.camera.startRecording()
}
button.isSelected = !button.isSelected
}
}
extension FTCameraOverlayView: FTVideoCaptureToolBarDelegate
{
func videoCaptureToolBarClose(){
let sel: Selector! = NSSelectorFromString("close2back")
if (delegate != nil && (delegate?.responds(to: sel))!){
delegate?.close2back()
}
}
func videoCaptureToolBarBeauty(){
}
//MARK:闪光灯
func videoCaptureToolBarFlash(on: Bool) -> Bool{
if self.camera.activeCameraHasFlash() {
return self.camera.activeCameraSwitchFlash(on: on)
}
return false
}
//MARK:切换摄像头
func videoCaptureToolBarSwitch(){
if self.camera.canSwitchCameras() {
let success = self.camera.switchCamers()
if success
{
self.toolbar.flashButton.isEnabled = self.camera.activeCameraHasFlash()
//切换摄像头闪光灯为关闭
self.toolbar.setFlash(on: false)
self.toolbar.flash_on = true
}
}
}
}
| cd4ec644831588fd9cd9226d6be55808 | 30.144928 | 133 | 0.604933 | false | false | false | false |
hstdt/GodEye | refs/heads/master | Carthage/Checkouts/SystemEye/SystemEye/Classes/Hardware.swift | mit | 1 | //
// Hardware.swift
// Pods
//
// Created by zixun on 17/1/20.
//
//
import Foundation
open class Hardware: NSObject {
//--------------------------------------------------------------------------
// MARK: OPEN PROPERTY
//--------------------------------------------------------------------------
/// System uptime, you can get the components from the result
open static var uptime: Date {
get {
/// get the info about the process
let processsInfo = ProcessInfo.processInfo
/// get the uptime of the system
let timeInterval = processsInfo.systemUptime
/// create and return the date
return Date(timeIntervalSinceNow: -timeInterval)
}
}
/// model of the device, eg: "iPhone", "iPod touch"
open static let deviceModel: String = UIDevice.current.model
/// name of the device, eg: "My iPhone"
open static var deviceName: String = UIDevice.current.name
/// system name of the device, eg: "iOS"
open static let systemName: String = UIDevice.current.systemName
/// system version of the device, eg: "10.0"
open static let systemVersion: String = UIDevice.current.systemVersion
/// version code of device, eg: "iPhone7,1"
open static var deviceVersionCode: String {
get {
var systemInfo = utsname()
uname(&systemInfo)
let versionCode: String = String(validatingUTF8: NSString(bytes: &systemInfo.machine, length: Int(_SYS_NAMELEN), encoding: String.Encoding.ascii.rawValue)!.utf8String!)!
return versionCode
}
}
/// version of device, eg: "iPhone5"
open static var deviceVersion: String {
get {
switch self.deviceVersionCode {
/*** iPhone ***/
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone4"
case "iPhone4,1", "iPhone4,2", "iPhone4,3": return "iPhone4S"
case "iPhone5,1", "iPhone5,2": return "iPhone5"
case "iPhone5,3", "iPhone5,4": return "iPhone5C"
case "iPhone6,1", "iPhone6,2": return "iPhone5S"
case "iPhone7,2": return "iPhone6"
case "iPhone7,1": return "iPhone6Plus"
case "iPhone8,1": return "iPhone6S"
case "iPhone8,2": return "iPhone6SPlus"
case "iPhone8,4": return "iPhoneSE"
case "iPhone9,1", "iPhone9,3": return "iPhone7"
case "iPhone9,2", "iPhone9,4": return "iPhone7Plus"
/*** iPad ***/
case "iPad1,1": return "iPad1"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return "iPad2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPadAir"
case "iPad5,3", "iPad5,4": return "iPadAir2"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPadMini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPadMini2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPadMini3"
case "iPad5,1", "iPad5,2": return "iPadMini4"
case "iPad6,3", "iPad6,4", "iPad6,7", "iPad6,8": return "iPadPro"
/*** iPod ***/
case "iPod1,1": return "iPodTouch1Gen"
case "iPod2,1": return "iPodTouch2Gen"
case "iPod3,1": return "iPodTouch3Gen"
case "iPod4,1": return "iPodTouch4Gen"
case "iPod5,1": return "iPodTouch5Gen"
case "iPod7,1": return "iPodTouch6Gen"
/*** Simulator ***/
case "i386", "x86_64": return "Simulator"
default: return "Unknown"
}
}
}
/// get the screen width (x)
open static var screenWidth: CGFloat {
get {
return UIScreen.main.bounds.size.width
}
}
/// get the screen height (y)
open static var screenHeight: CGFloat {
get {
return UIScreen.main.bounds.size.height
}
}
/// get the brightness of screen
open static var screenBrightness: CGFloat {
get {
return UIScreen.main.brightness
}
}
open static var isMultitaskingSupported: Bool {
get {
return UIDevice.current.isMultitaskingSupported
}
}
/// is the debugger attached
open static var isDebuggerAttached: Bool {
get {
var info = kinfo_proc()
var mib : [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
var size = MemoryLayout.stride(ofValue: info)
let junk = sysctl(&mib, UInt32(mib.count), &info, &size, nil, 0)
assert(junk == 0, "sysctl failed")
return (info.kp_proc.p_flag & P_TRACED) != 0
}
}
/// is the device plugged in
open static var isPluggedIn: Bool {
get {
let preEnable = UIDevice.current.isBatteryMonitoringEnabled
UIDevice.current.isBatteryMonitoringEnabled = true
let batteryState = UIDevice.current.batteryState
UIDevice.current.isBatteryMonitoringEnabled = preEnable
return (batteryState == .charging || batteryState == .full)
}
}
/// is the device jailbrokened
open static var isJailbroken: Bool {
let cydiaURL = "/Applications/Cydia.app"
return FileManager.default.fileExists(atPath: cydiaURL)
}
}
| b33395a55f79a77eb76392de0ae1e5b9 | 41.684932 | 181 | 0.488126 | false | false | false | false |
chamander/Sampling-Reactive | refs/heads/master | Source/NetworkClients/WeatherClient.swift | mit | 2 | // Copyright © 2016 Gavan Chan. All rights reserved.
import Argo
import Foundation
import RxCocoa
import RxSwift
typealias WeatherProvidingClient = ClientProtocol & WeatherProviding
final class WeatherClient: WeatherProvidingClient {
enum Endpoint: String {
case weather = "weather"
}
let session: URLSession = .shared
var base: URL { return URL(string: baseURL)! }
private let baseURL: String = "http://api.openweathermap.org/data/2.5"
func weather(for cityID: City.Identifier, in unit: UnitTemperature = .celsius) -> Observable<Weather> {
var query: Dictionary<String, String> = [
"id": String(reflecting: cityID),
]
if let unit = unit.requestParameter { query.updateValue(unit, forKey: "units") }
let weather: Observable<Weather> = json(for: .weather, via: .get, withQuery: query)
.map(Weather.decode)
.flatMap { Observable<Weather>.from(decoded: $0) }
return weather
}
}
fileprivate extension UnitTemperature {
var requestParameter: String? {
switch self {
case UnitTemperature.celsius: return "metric"
case UnitTemperature.fahrenheit: return "imperial"
case UnitTemperature.kelvin: return nil
default: return nil
}
}
}
| 9751d40cde3ad9ea141e2e890267a27b | 26.111111 | 105 | 0.708197 | false | false | false | false |
PigDogBay/Food-Hygiene-Ratings | refs/heads/master | FoodHygieneRatingsTests/ObservablePropertyTest.swift | apache-2.0 | 1 | //
// ObservablePropertyTest.swift
// FoodHygieneRatingsTests
//
// Created by Mark Bailey on 20/09/2018.
// Copyright © 2018 MPD Bailey Technology. All rights reserved.
//
import XCTest
@testable import Food_Hygiene_Ratings
class ObservablePropertyTest: XCTestCase {
enum Fruit {
case apple, pear, banana, orange, blueberry
}
var intNewValue : Int?
var fruitNewValue : Fruit?
var callbackCount = 0
private func intChanged(owner : Any, newValue : Int){
intNewValue = newValue
}
private func fruitChanged(owner : Any, newValue : Fruit){
fruitNewValue = newValue
callbackCount = callbackCount + 1
}
override func setUp() {
super.setUp()
callbackCount = 0
}
func test_int_types() {
let target = ObservableProperty<Int>(42)
target.addObserver(named: "int", observer: intChanged)
target.value = 6
target.removeObserver(named: "int")
XCTAssertEqual(6, intNewValue)
}
func test_enum_types(){
let target = ObservableProperty<Fruit>(.apple)
target.addObserver(named: "fruit", observer: fruitChanged)
target.value = .blueberry
target.removeObserver(named: "fruit")
XCTAssertEqual(.blueberry, fruitNewValue)
}
func test_only_callback_on_change(){
let target = ObservableProperty<Fruit>(.apple)
target.addObserver(named: "fruit", observer: fruitChanged)
target.value = .blueberry
XCTAssertEqual(1, callbackCount)
target.value = .blueberry
XCTAssertEqual(1, callbackCount)
target.removeObserver(named: "fruit")
}
}
| ddca88f9547672bd73adb2df0ddd3735 | 27.844828 | 66 | 0.646145 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.