repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ccrama/Slide-iOS
|
Slide for Reddit/TextLinkCellView.swift
|
1
|
5475
|
//
// TextLinkCellView.swift
// Slide for Reddit
//
// Created by Carlos Crane on 6/25/17.
// Copyright © 2017 Haptic Apps. All rights reserved.
//
import Anchorage
import UIKit
final class TextLinkCellView: LinkCellView {
/*
// Only override draw() if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func draw(_ rect: CGRect) {
// Drawing code
}
*/
override func layoutForType() {
super.layoutForType()
let ceight = SettingValues.postViewMode == .COMPACT ? CGFloat(4) : CGFloat(8)
let ctwelve = SettingValues.postViewMode == .COMPACT ? CGFloat(8) : CGFloat(12)
constraintsForType = batch {
title.topAnchor == contentView.topAnchor + (ctwelve - 5)
if SettingValues.actionBarMode == .SIDE_RIGHT {
sideButtons.topAnchor == contentView.topAnchor + ctwelve
title.rightAnchor == sideButtons.leftAnchor - ceight
title.leftAnchor == contentView.leftAnchor + ctwelve
} else if SettingValues.actionBarMode == .SIDE {
sideButtons.topAnchor == contentView.topAnchor + ctwelve
title.leftAnchor == sideButtons.rightAnchor + ceight
title.rightAnchor == contentView.rightAnchor - ctwelve
} else {
title.horizontalAnchors == contentView.horizontalAnchors + ctwelve
}
if !SettingValues.actionBarMode.isFull() {
title.bottomAnchor == contentView.bottomAnchor - ctwelve
} else {
title.bottomAnchor <= box.topAnchor - ceight
}
subicon.topAnchor == title.topAnchor
subicon.leftAnchor == title.leftAnchor
subicon.widthAnchor == 24
subicon.heightAnchor == 24
}
}
override func layoutForContent() {
}
// override func doConstraints() {
// let target = CurrentType.text
//
// if(currentType == target && target != .banner){
// return //work is already done
// } else if(currentType == target && target == .banner && bigConstraint != nil){
// self.contentView.addConstraint(bigConstraint!)
// return
// }
//
// let metrics=["horizontalMargin":75,"top":0,"bottom":0,"separationBetweenLabels":0,"size": full ? 16 : 12, "labelMinHeight":75, "thumb": (SettingValues.largerThumbnail ? 75 : 50), "ctwelve": SettingValues.postViewMode == .COMPACT ? 8 : 12,"ceight": SettingValues.postViewMode == .COMPACT ? 4 : 8,"bannerHeight": submissionHeight] as [String: Int]
// let views=["label":title, "body": textView, "image": thumbImage, "info": b, "upvote": upvote, "downvote" : downvote, "score": score, "comments": comments, "banner": bannerImage, "buttons":buttons, "box": box] as [String : Any]
// var bt = "[buttons]-(ceight)-"
// var bx = "[box]-(ceight)-"
// if(SettingValues.hideButtonActionbar && !full){
// bt = "[buttons(0)]-4-"
// bx = "[box(0)]-4-"
// }
//
// self.contentView.removeConstraints(thumbConstraint)
// thumbConstraint = []
//
//
// thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-(ceight)-[image(0)]",
// options: NSLayoutFormatOptions(rawValue: 0),
// metrics: metrics,
// views: views))
//
//
// thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-(ctwelve)-[label]-(ctwelve)-|",
// options: NSLayoutFormatOptions(rawValue: 0),
// metrics: metrics,
// views: views))
//
// thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "H:|-(ctwelve)-[body]-(ctwelve)-|",
// options: NSLayoutFormatOptions(rawValue: 0),
// metrics: metrics,
// views: views))
//
// thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:|-(ctwelve)-[label]-5@1000-[body]-(ctwelve)-\(bx)|",
// options: NSLayoutFormatOptions(rawValue: 0),
// metrics: metrics,
// views: views))
// thumbConstraint.append(contentsOf: NSLayoutConstraint.constraints(withVisualFormat: "V:\(bt)|",
// options: NSLayoutFormatOptions(rawValue: 0),
// metrics: metrics,
// views: views))
// self.contentView.addConstraints(thumbConstraint)
// if(target == .banner && bigConstraint != nil){
// self.contentView.addConstraint(bigConstraint!)
// return
// }
// currentType = target
// }
}
|
apache-2.0
|
58d63cb429a8db3bef0f99f90b4c9997
| 48.315315 | 356 | 0.51973 | 5.003656 | false | false | false | false |
sora0077/RelayoutKit
|
RelayoutKitDemo/ViewController.swift
|
1
|
2745
|
//
// ViewController.swift
// RelayoutKitDemo
//
// Created by 林達也 on 2015/09/10.
// Copyright © 2015年 jp.sora0077. All rights reserved.
//
import UIKit
import RelayoutKit
class ATableViewCell: UITableViewCell {
}
extension ATableViewCell: TableRowRenderer {
static func register(tableView: UITableView) {
tableView.registerClass(self, forCellReuseIdentifier: self.identifier)
}
}
class TextTableRow<T: UITableViewCell where T: TableRowRenderer>: TableRow<T> {
let text: String
init(text: String) {
self.text = text
super.init()
canMove = true
if let n = Int(text) where n % 4 == 0 {
editingStyle = .Delete
previousSeparatorStyle = .Some(.None)
}
}
deinit {
print("deinit")
}
override func componentUpdate() {
super.componentUpdate()
renderer?.textLabel?.text = "\(text) row:\(indexPath!.row) section: \(indexPath!.section)"
}
override func componentDidMount() {
super.componentDidMount()
print(text, " did mount")
}
override func componentWillUnmount() {
super.componentDidMount()
print(text, " will unmount")
}
override func willDisplayCell() {
super.willDisplayCell()
}
override func didSelect(indexPath: NSIndexPath) {
super.didSelect(indexPath)
size.height = 100
}
}
class ViewController: UIViewController {
private var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let tableView = UITableView(frame: self.view.bounds, style: .Plain)
tableView.controller(self, sections: 1000)
tableView.extend((0..<1000).map {
TextTableRow<ATableViewCell>(text: "\($0)")
}, atSetcion: 0)
tableView[section: 0, row: 1] = TextTableRow<ATableViewCell>(text: "")
tableView[section: 0, row: 1] = nil
tableView[section: 0, row: 5] = nil
self.view.addSubview(tableView)
self.tableView = tableView
self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
self.tableView.setEditing(editing, animated: animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
aed2b44f15d180c37647833e40bc99f5
| 23.212389 | 98 | 0.594664 | 4.808436 | false | false | false | false |
shuoli84/RxSwift
|
RxExample/RxExample/Examples/WikipediaImageSearch/Views/WikipediaSearchCell.swift
|
2
|
1832
|
//
// WikipediaSearchCell.swift
// Example
//
// Created by Krunoslav Zaher on 3/28/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
import RxSwift
import RxCocoa
public class WikipediaSearchCell: UITableViewCell {
@IBOutlet var titleOutlet: UILabel!
@IBOutlet var URLOutlet: UILabel!
@IBOutlet var imagesOutlet: UICollectionView!
var disposeBag: DisposeBag!
let imageService = DefaultImageService.sharedImageService
public override func awakeFromNib() {
super.awakeFromNib()
self.imagesOutlet.registerNib(UINib(nibName: "WikipediaImageCell", bundle: nil), forCellWithReuseIdentifier: "ImageCell")
}
var viewModel: SearchResultViewModel! {
didSet {
let $ = viewModel.$
let disposeBag = DisposeBag()
self.titleOutlet.rx_subscribeTextTo(viewModel?.title ?? just("")) >- disposeBag.addDisposable
self.URLOutlet.text = viewModel.searchResult.URL.absoluteString ?? ""
viewModel.imageURLs
>- self.imagesOutlet.rx_subscribeItemsToWithCellIdentifier("ImageCell") { [unowned self] (_, URL, cell: CollectionViewImageCell) in
let loadingPlaceholder: UIImage? = nil
cell.image = self.imageService.imageFromURL(URL)
>- map { $0 as UIImage? }
>- catch(nil)
>- startWith(loadingPlaceholder)
}
>- disposeBag.addDisposable
self.disposeBag = disposeBag
}
}
public override func prepareForReuse() {
super.prepareForReuse()
self.disposeBag = nil
}
deinit {
}
}
|
mit
|
f858e98fff670f3c80affe2541266226
| 28.564516 | 147 | 0.593886 | 5.436202 | false | false | false | false |
codestergit/swift
|
test/SILGen/class_bound_protocols.swift
|
3
|
6336
|
// RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s
// -- Class-bound archetypes and existentials are *not* address-only and can
// be manipulated using normal reference type value semantics.
protocol NotClassBound {
func notClassBoundMethod()
}
protocol ClassBound : class {
func classBoundMethod()
}
protocol ClassBound2 : class {
func classBound2Method()
}
class ConcreteClass : NotClassBound, ClassBound, ClassBound2 {
func notClassBoundMethod() {}
func classBoundMethod() {}
func classBound2Method() {}
}
class ConcreteSubclass : ConcreteClass { }
// CHECK-LABEL: sil hidden @_T021class_bound_protocols0a1_B8_generic{{[_0-9a-zA-Z]*}}F
func class_bound_generic<T : ClassBound>(x: T) -> T {
var x = x
// CHECK: bb0([[X:%.*]] : $T):
// CHECK: [[X_ADDR:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ClassBound> { var τ_0_0 } <T>
// CHECK: [[PB:%.*]] = project_box [[X_ADDR]]
// CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]]
// CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]]
// CHECK: store [[X_COPY]] to [init] [[PB]]
return x
// CHECK: [[X1:%.*]] = load [copy] [[PB]]
// CHECK: destroy_value [[X_ADDR]]
// CHECK: destroy_value [[X]]
// CHECK: return [[X1]]
}
// CHECK-LABEL: sil hidden @_T021class_bound_protocols0a1_B10_generic_2{{[_0-9a-zA-Z]*}}F
func class_bound_generic_2<T : ClassBound & NotClassBound>(x: T) -> T {
var x = x
// CHECK: bb0([[X:%.*]] : $T):
// CHECK: [[X_ADDR:%.*]] = alloc_box $<τ_0_0 where τ_0_0 : ClassBound, τ_0_0 : NotClassBound> { var τ_0_0 } <T>
// CHECK: [[PB:%.*]] = project_box [[X_ADDR]]
// CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]]
// CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]]
// CHECK: store [[X_COPY]] to [init] [[PB]]
// CHECK: end_borrow [[BORROWED_X]] from [[X]]
return x
// CHECK: [[X1:%.*]] = load [copy] [[PB]]
// CHECK: return [[X1]]
}
// CHECK-LABEL: sil hidden @_T021class_bound_protocols0a1_B9_protocol{{[_0-9a-zA-Z]*}}F
func class_bound_protocol(x: ClassBound) -> ClassBound {
var x = x
// CHECK: bb0([[X:%.*]] : $ClassBound):
// CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound }
// CHECK: [[PB:%.*]] = project_box [[X_ADDR]]
// CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]]
// CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]]
// CHECK: store [[X_COPY]] to [init] [[PB]]
// CHECK: end_borrow [[BORROWED_X]] from [[X]]
return x
// CHECK: [[X1:%.*]] = load [copy] [[PB]]
// CHECK: return [[X1]]
}
// CHECK-LABEL: sil hidden @_T021class_bound_protocols0a1_B21_protocol_composition{{[_0-9a-zA-Z]*}}F
func class_bound_protocol_composition(x: ClassBound & NotClassBound)
-> ClassBound & NotClassBound {
var x = x
// CHECK: bb0([[X:%.*]] : $ClassBound & NotClassBound):
// CHECK: [[X_ADDR:%.*]] = alloc_box ${ var ClassBound & NotClassBound }
// CHECK: [[PB:%.*]] = project_box [[X_ADDR]]
// CHECK: [[BORROWED_X:%.*]] = begin_borrow [[X]]
// CHECK: [[X_COPY:%.*]] = copy_value [[BORROWED_X]]
// CHECK: store [[X_COPY]] to [init] [[PB]]
// CHECK: end_borrow [[BORROWED_X]] from [[X]]
return x
// CHECK: [[X1:%.*]] = load [copy] [[PB]]
// CHECK: return [[X1]]
}
// CHECK-LABEL: sil hidden @_T021class_bound_protocols0a1_B8_erasure{{[_0-9a-zA-Z]*}}F
func class_bound_erasure(x: ConcreteClass) -> ClassBound {
return x
// CHECK: [[PROTO:%.*]] = init_existential_ref {{%.*}} : $ConcreteClass, $ClassBound
// CHECK: return [[PROTO]]
}
// CHECK-LABEL: sil hidden @_T021class_bound_protocols0a1_B19_existential_upcastAA10ClassBound_pAaC_AA0F6Bound2p1x_tF :
func class_bound_existential_upcast(x: ClassBound & ClassBound2)
-> ClassBound {
return x
// CHECK: bb0([[ARG:%.*]] : $ClassBound & ClassBound2):
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[OPENED:%.*]] = open_existential_ref [[BORROWED_ARG]] : $ClassBound & ClassBound2 to [[OPENED_TYPE:\$@opened(.*) ClassBound & ClassBound2]]
// CHECK: [[OPENED_COPY:%.*]] = copy_value [[OPENED]]
// CHECK: [[PROTO:%.*]] = init_existential_ref [[OPENED_COPY]] : [[OPENED_TYPE]] : [[OPENED_TYPE]], $ClassBound
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
// CHECK: return [[PROTO]]
}
// CHECK: } // end sil function '_T021class_bound_protocols0a1_B19_existential_upcastAA10ClassBound_pAaC_AA0F6Bound2p1x_tF'
// CHECK-LABEL: sil hidden @_T021class_bound_protocols0a1_B30_to_unbound_existential_upcast{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[ARG0:%.*]] : $*NotClassBound, [[ARG1:%.*]] : $ClassBound & NotClassBound):
// CHECK: [[BORROWED_ARG1:%.*]] = begin_borrow [[ARG1]]
// CHECK: [[X_OPENED:%.*]] = open_existential_ref [[BORROWED_ARG1]] : $ClassBound & NotClassBound to [[OPENED_TYPE:\$@opened(.*) ClassBound & NotClassBound]]
// CHECK: [[PAYLOAD_ADDR:%.*]] = init_existential_addr [[ARG0]] : $*NotClassBound, [[OPENED_TYPE]]
// CHECK: [[X_OPENED_COPY:%.*]] = copy_value [[X_OPENED]]
// CHECK: store [[X_OPENED_COPY]] to [init] [[PAYLOAD_ADDR]]
// CHECK: end_borrow [[BORROWED_ARG1]] from [[ARG1]]
// CHECK: destroy_value [[ARG1]]
func class_bound_to_unbound_existential_upcast
(x: ClassBound & NotClassBound) -> NotClassBound {
return x
}
// CHECK-LABEL: sil hidden @_T021class_bound_protocols0a1_B7_method{{[_0-9a-zA-Z]*}}F
// CHECK: bb0([[ARG:%.*]] : $ClassBound):
func class_bound_method(x: ClassBound) {
var x = x
x.classBoundMethod()
// CHECK: [[XBOX:%.*]] = alloc_box ${ var ClassBound }, var, name "x"
// CHECK: [[XBOX_PB:%.*]] = project_box [[XBOX]]
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: store [[ARG_COPY]] to [init] [[XBOX_PB]]
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: [[X:%.*]] = load [copy] [[XBOX_PB]] : $*ClassBound
// CHECK: [[PROJ:%.*]] = open_existential_ref [[X]] : $ClassBound to $[[OPENED:@opened(.*) ClassBound]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #ClassBound.classBoundMethod!1
// CHECK: apply [[METHOD]]<[[OPENED]]>([[PROJ]])
// CHECK: destroy_value [[PROJ]]
// CHECK: destroy_value [[XBOX]]
// CHECK: destroy_value [[ARG]]
}
// CHECK: } // end sil function '_T021class_bound_protocols0a1_B7_methodyAA10ClassBound_p1x_tF'
|
apache-2.0
|
3f28b6e83c64f36e0c44dd020c0e5c94
| 42.951389 | 159 | 0.602939 | 3.161339 | false | false | false | false |
sebbean/ExSwift
|
ExSwift/Dictionary.swift
|
1
|
10540
|
//
// Dictionary.swift
// ExSwift
//
// Created by pNre on 04/06/14.
// Copyright (c) 2014 pNre. All rights reserved.
//
import Foundation
import Swift
public extension Dictionary {
/**
Difference of self and the input dictionaries.
Two dictionaries are considered equal if they contain the same [key: value] pairs.
- parameter dictionaries: Dictionaries to subtract
- returns: Difference of self and the input dictionaries
*/
public func difference <V: Equatable> (_ dictionaries: [Key: V]...) -> [Key: V] {
var result = [Key: V]()
each {
if let item = $1 as? V {
result[$0] = item
}
}
// Difference
for dictionary in dictionaries {
for (key, value) in dictionary {
if result.has(key) && result[key] == value {
result.removeValue(forKey: key)
}
}
}
return result
}
/**
Union of self and the input dictionaries.
- parameter dictionaries: Dictionaries to join
- returns: Union of self and the input dictionaries
*/
public func union (_ dictionaries: Dictionary...) -> Dictionary {
var result = self
dictionaries.each { (dictionary) -> Void in
dictionary.each { (key, value) -> Void in
_ = result.updateValue(value, forKey: key)
}
}
return result
}
/**
Intersection of self and the input dictionaries.
Two dictionaries are considered equal if they contain the same [key: value] copules.
- parameter values: Dictionaries to intersect
- returns: Dictionary of [key: value] couples contained in all the dictionaries and self
*/
public func intersection <K, V> (_ dictionaries: [K: V]...) -> [K: V] where K: Equatable, V: Equatable {
// Casts self from [Key: Value] to [K: V]
let filtered = mapFilter { (item, value) -> (K, V)? in
if (item is K) && (value is V) {
return (item as! K, value as! V)
}
return nil
}
// Intersection
return filtered.filter({ (key: K, value: V) -> Bool in
// check for [key: value] in all the dictionaries
dictionaries.all { $0.has(key) && $0[key] == value }
})
}
/**
Checks if a key exists in the dictionary.
- parameter key: Key to check
- returns: true if the key exists
*/
public func has (_ key: Key) -> Bool {
return index(forKey: key) != nil
}
/**
Creates an Array with values generated by running
each [key: value] of self through the mapFunction.
- parameter mapFunction:
- returns: Mapped array
*/
public func toArray <V> (_ map: (Key, Value) -> V) -> [V] {
var mapped = [V]()
each {
mapped.append(map($0, $1))
}
return mapped
}
/**
Creates a Dictionary with the same keys as self and values generated by running
each [key: value] of self through the mapFunction.
- parameter mapFunction:
- returns: Mapped dictionary
*/
public func mapValues <V> (_ map: (Key, Value) -> V) -> [Key: V] {
var mapped = [Key: V]()
each {
mapped[$0] = map($0, $1)
}
return mapped
}
/**
Creates a Dictionary with the same keys as self and values generated by running
each [key: value] of self through the mapFunction discarding nil return values.
- parameter mapFunction:
- returns: Mapped dictionary
*/
public func mapFilterValues <V> (_ map: (Key, Value) -> V?) -> [Key: V] {
var mapped = [Key: V]()
each {
if let value = map($0, $1) {
mapped[$0] = value
}
}
return mapped
}
/**
Creates a Dictionary with keys and values generated by running
each [key: value] of self through the mapFunction discarding nil return values.
- parameter mapFunction:
- returns: Mapped dictionary
*/
public func mapFilter <K, V> (_ map: (Key, Value) -> (K, V)?) -> [K: V] {
var mapped = [K: V]()
each {
if let value = map($0, $1) {
mapped[value.0] = value.1
}
}
return mapped
}
/**
Creates a Dictionary with keys and values generated by running
each [key: value] of self through the mapFunction.
- parameter mapFunction:
- returns: Mapped dictionary
*/
public func map <K, V> (_ map: (Key, Value) -> (K, V)) -> [K: V] {
var mapped = [K: V]()
self.each({
let (_key, _value) = map($0, $1)
mapped[_key] = _value
})
return mapped
}
/**
Loops trough each [key: value] pair in self.
- parameter eachFunction: Function to inovke on each loop
*/
public func each (_ each: (Key, Value) -> ()) {
for (key, value) in self {
each(key, value)
}
}
/**
Constructs a dictionary containing every [key: value] pair from self
for which testFunction evaluates to true.
- parameter testFunction: Function called to test each key, value
- returns: Filtered dictionary
*/
public func filter (_ test: (Key, Value) -> Bool) -> Dictionary {
var result = Dictionary()
for (key, value) in self {
if test(key, value) {
result[key] = value
}
}
return result
}
/**
Creates a dictionary composed of keys generated from the results of
running each element of self through groupingFunction. The corresponding
value of each key is an array of the elements responsible for generating the key.
- parameter groupingFunction:
- returns: Grouped dictionary
*/
public func groupBy <T> (_ group: (Key, Value) -> T) -> [T: [Value]] {
var result = [T: [Value]]()
for (key, value) in self {
let groupKey = group(key, value)
// If element has already been added to dictionary, append to it. If not, create one.
if result.has(groupKey) {
result[groupKey]! += [value]
} else {
result[groupKey] = [value]
}
}
return result
}
/**
Similar to groupBy. Doesn't return a list of values, but the number of values for each group.
- parameter groupingFunction: Function called to define the grouping key
- returns: Grouped dictionary
*/
public func countBy <T> (_ group: (Key, Value) -> (T)) -> [T: Int] {
var result = [T: Int]()
for (key, value) in self {
let groupKey = group(key, value)
// If element has already been added to dictionary, append to it. If not, create one.
if result.has(groupKey) {
result[groupKey]! += 1
} else {
result[groupKey] = 1
}
}
return result
}
/**
Checks if test evaluates true for all the elements in self.
- parameter test: Function to call for each element
- returns: true if test returns true for all the elements in self
*/
public func all (_ test: (Key, Value) -> (Bool)) -> Bool {
for (key, value) in self {
if !test(key, value) {
return false
}
}
return true
}
/**
Checks if test evaluates true for any element of self.
- parameter test: Function to call for each element
- returns: true if test returns true for any element of self
*/
public func any (_ test: (Key, Value) -> (Bool)) -> Bool {
for (key, value) in self {
if test(key, value) {
return true
}
}
return false
}
/**
Returns the number of elements which meet the condition
- parameter test: Function to call for each element
- returns: the number of elements meeting the condition
*/
public func countWhere (_ test: (Key, Value) -> (Bool)) -> Int {
var result = 0
for (key, value) in self {
if test(key, value) {
result += 1
}
}
return result
}
/**
Returns a copy of self, filtered to only have values for the whitelisted keys.
- parameter keys: Whitelisted keys
- returns: Filtered dictionary
*/
public func pick (_ keys: [Key]) -> Dictionary {
return filter { (key: Key, _) -> Bool in
return keys.contains(key)
}
}
/**
Returns a copy of self, filtered to only have values for the whitelisted keys.
- parameter keys: Whitelisted keys
- returns: Filtered dictionary
*/
public func pick (_ keys: Key...) -> Dictionary {
return pick(unsafeBitCast(keys, to: [Key].self))
}
/**
Returns a copy of self, filtered to only have values for the whitelisted keys.
- parameter keys: Keys to get
- returns: Dictionary with the given keys
*/
public func at (_ keys: Key...) -> Dictionary {
return pick(keys)
}
/**
Removes a (key, value) pair from self and returns it as tuple.
If the dictionary is empty returns nil.
- returns: (key, value) tuple
*/
public mutating func shift () -> (Key, Value)? {
if let key = keys.first {
return (key, removeValue(forKey: key)!)
}
return nil
}
}
/**
Difference operator
*/
public func - <K, V: Equatable> (first: [K: V], second: [K: V]) -> [K: V] {
return first.difference(second)
}
/**
Intersection operator
*/
public func & <K, V: Equatable> (first: [K: V], second: [K: V]) -> [K: V] {
return first.intersection(second)
}
/**
Union operator
*/
public func | <K: Hashable, V> (first: [K: V], second: [K: V]) -> [K: V] {
return first.union(second)
}
|
bsd-2-clause
|
7e521e0f080eac96c9ee85ba7463167f
| 24.770171 | 108 | 0.523624 | 4.502349 | false | false | false | false |
vector-im/vector-ios
|
Riot/Routers/RootRouter.swift
|
1
|
3151
|
/*
Copyright 2020 New Vector Ltd
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
/// `RootRouter` is a concrete implementation of RootRouterType.
final class RootRouter: RootRouterType {
// MARK: - Constants
// `rootViewController` animation constants
private enum RootViewControllerUpdateAnimation {
static let duration: TimeInterval = 0.3
static let options: UIView.AnimationOptions = .transitionCrossDissolve
}
// MARK: - Properties
private var presentedModule: Presentable?
let window: UIWindow
/// The root view controller currently presented
var rootViewController: UIViewController? {
return self.window.rootViewController
}
// MARK: - Setup
init(window: UIWindow) {
self.window = window
}
// MARK: - Public methods
func setRootModule(_ module: Presentable) {
self.updateRootViewController(rootViewController: module.toPresentable(), animated: false, completion: nil)
self.window.makeKeyAndVisible()
}
func dismissRootModule(animated: Bool, completion: (() -> Void)?) {
self.updateRootViewController(rootViewController: nil, animated: animated, completion: completion)
}
func presentModule(_ module: Presentable, animated: Bool, completion: (() -> Void)?) {
let viewControllerPresenter = self.rootViewController?.presentedViewController ?? self.rootViewController
viewControllerPresenter?.present(module.toPresentable(), animated: animated, completion: completion)
self.presentedModule = module
}
func dismissModule(animated: Bool, completion: (() -> Void)?) {
self.presentedModule?.toPresentable().dismiss(animated: animated, completion: completion)
}
// MARK: - Private methods
private func updateRootViewController(rootViewController: UIViewController?, animated: Bool, completion: (() -> Void)?) {
if animated {
UIView.transition(with: window, duration: RootViewControllerUpdateAnimation.duration, options: RootViewControllerUpdateAnimation.options, animations: {
let oldState: Bool = UIView.areAnimationsEnabled
UIView.setAnimationsEnabled(false)
self.window.rootViewController = rootViewController
UIView.setAnimationsEnabled(oldState)
}, completion: { (finished: Bool) -> Void in
completion?()
})
} else {
self.window.rootViewController = rootViewController
completion?()
}
}
}
|
apache-2.0
|
f671ef460fb4085bb6f86035f1b5a0f8
| 35.218391 | 163 | 0.677245 | 5.547535 | false | false | false | false |
bryancmiller/rockandmarty
|
Text Adventure/Text Adventure/CGFloatExtensions.swift
|
1
|
980
|
//
// CGFloatExtensions.swift
// Text Adventure
//
// Created by Bryan Miller on 9/9/17.
// Copyright © 2017 Bryan Miller. All rights reserved.
//
import Foundation
import UIKit
extension CGFloat {
static func convertHeight(h: CGFloat, screenSize: CGRect) -> CGFloat {
// iPhone 5 height is 568 and designed on iPhone 5
let iPhone5Height: CGFloat = 568.0
let currentPhoneHeight: CGFloat = screenSize.height
// calculate ratio between iPhone 5 and current
let phoneRatio: CGFloat = currentPhoneHeight / iPhone5Height
return (h * phoneRatio)
}
static func convertWidth(w: CGFloat, screenSize: CGRect) -> CGFloat {
// iPhone 5 width is 320
let iPhone5Width: CGFloat = 320.0
let currentPhoneWidth: CGFloat = screenSize.width
// calculate ratio between iPhone 5 and current
let phoneRatio: CGFloat = currentPhoneWidth / iPhone5Width
return (w * phoneRatio)
}
}
|
apache-2.0
|
2255423feb57df200b91fdd1b5abf5b1
| 31.633333 | 74 | 0.670072 | 4.40991 | false | false | false | false |
swift-lang/swift-k
|
tests/language-behaviour/associative_array/foreach5.swift
|
1
|
281
|
// THIS-SCRIPT-SHOULD-FAIL
// ... because structs are not valid index types
type mystruct{
int a;
int b;
}
int array[int][mystruct];
mystruct xx,yy;
xx.a = 1;
xx.b = 2;
yy.a = 101;
yy.b = 202;
array[1][xx] = 55;
array[1][yy] = 11;
foreach v in array[1]{
trace(v);
}
|
apache-2.0
|
bda6d82b254a43a9490c615bda38fb85
| 10.75 | 48 | 0.597865 | 2.361345 | false | false | false | false |
Hout/SwiftDate
|
Tests/SwiftDateTests/TestSwiftDate.swift
|
2
|
1600
|
//
// SwiftDate
// Parse, validate, manipulate, and display dates, time and timezones in Swift
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
//
import SwiftDate
import XCTest
class TestSwiftDate: XCTestCase {
func testAutoFormats() {
let builtInAutoFormats = SwiftDate.autoFormats
XCTAssert((SwiftDate.autoFormats.isEmpty == false), "No auto formats available")
let newFormats = [DateFormats.altRSS, DateFormats.extended, DateFormats.httpHeader]
SwiftDate.autoFormats = newFormats
XCTAssert( (SwiftDate.autoFormats == newFormats), "Failed to set new auto formats")
SwiftDate.resetAutoFormats()
XCTAssert( (SwiftDate.autoFormats == builtInAutoFormats), "Failed to reset auto formats")
}
func testUTCZone() {
SwiftDate.defaultRegion = Region(calendar: Calendars.gregorian, zone: Zones.asiaShanghai, locale: Locales.current)
// DO NOT recognized the right timezone
// The timezone should be UTC
let wrongZone = "2020-03-13T05:40:48.000Z"
let wrongZoneDate = Date.init(wrongZone)
print(wrongZoneDate!.description)
XCTAssert("2020-03-13 05:40:48 +0000" == wrongZoneDate!.description)
let iso8601Time = "2020-03-13T05:40:48+00:00"
let iso8601Date = Date.init(iso8601Time)
print(iso8601Date!.description)
XCTAssert("2020-03-13 05:40:48 +0000" == iso8601Date!.description)
}
}
|
mit
|
9f0af68a39db38f8cb898d301f5aaa4c
| 36.186047 | 122 | 0.703565 | 3.890511 | false | true | false | false |
WangCrystal/actor-platform
|
actor-apps/app-ios/ActorApp/Controllers/Settings/SettingsViewController.swift
|
4
|
15762
|
//
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import UIKit
import MobileCoreServices
class SettingsViewController: AATableViewController {
// MARK: -
// MARK: Private vars
private let UserInfoCellIdentifier = "UserInfoCellIdentifier"
private let TitledCellIdentifier = "TitledCellIdentifier"
private let TextCellIdentifier = "TextCellIdentifier"
private var tableData: UATableData!
private let uid: Int
private var user: ACUserVM?
private var binder = Binder()
private var phones: JavaUtilArrayList?
// MARK: -
// MARK: Constructors
init() {
uid = Int(Actor.myUid())
super.init(style: UITableViewStyle.Plain)
var title = "";
if (MainAppTheme.tab.showText) {
title = NSLocalizedString("TabSettings", comment: "Settings Title")
}
tabBarItem = UITabBarItem(title: title,
image: MainAppTheme.tab.createUnselectedIcon("TabIconSettings"),
selectedImage: MainAppTheme.tab.createSelectedIcon("TabIconSettingsHighlighted"))
if (!MainAppTheme.tab.showText) {
tabBarItem.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: -
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = MainAppTheme.list.bgColor
edgesForExtendedLayout = UIRectEdge.Top
automaticallyAdjustsScrollViewInsets = false
user = Actor.getUserWithUid(jint(uid))
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.backgroundColor = MainAppTheme.list.backyardColor
tableView.clipsToBounds = false
tableView.tableFooterView = UIView()
tableData = UATableData(tableView: tableView)
tableData.registerClass(UserPhotoCell.self, forCellReuseIdentifier: UserInfoCellIdentifier)
tableData.registerClass(TitledCell.self, forCellReuseIdentifier: TitledCellIdentifier)
tableData.registerClass(TextCell.self, forCellReuseIdentifier: TextCellIdentifier)
tableData.tableScrollClosure = { (tableView: UITableView) -> () in
self.applyScrollUi(tableView)
}
// Avatar
let profileInfoSection = tableData.addSection(true)
.setFooterHeight(15)
profileInfoSection.addCustomCell { (tableView, indexPath) -> UITableViewCell in
let cell: UserPhotoCell = tableView.dequeueReusableCellWithIdentifier(self.UserInfoCellIdentifier, forIndexPath: indexPath) as! UserPhotoCell
cell.contentView.superview?.clipsToBounds = false
if self.user != nil {
cell.setUsername(self.user!.getNameModel().get())
}
self.applyScrollUi(tableView, cell: cell)
return cell
}.setHeight(avatarHeight)
// Nick
profileInfoSection
.addCustomCell { (tableView, indexPath) -> UITableViewCell in
let cell: TitledCell = tableView.dequeueReusableCellWithIdentifier(self.TitledCellIdentifier, forIndexPath: indexPath) as! TitledCell
cell.enableNavigationIcon()
if let nick = self.user!.getNickModel().get() {
cell.setTitle(localized("ProfileUsername"), content: "@\(nick)")
cell.setAction(false)
} else {
cell.setTitle(localized("ProfileUsername"), content: localized("SettingsUsernameNotSet"))
cell.setAction(true)
}
return cell
}
.setHeight(55)
.setAction { () -> () in
self.textInputAlert("SettingsUsernameTitle", content: self.user!.getNickModel().get(), action: "AlertSave", tapYes: { (nval) -> () in
var nNick: String? = nval.trim()
if nNick?.length == 0 {
nNick = nil
}
self.execute(Actor.editMyNickCommandWithNick(nNick))
})
}
var about = self.user!.getAboutModel().get()
if about == nil {
about = localized("SettingsAboutNotSet")
}
let aboutCell = profileInfoSection
.addTextCell(localized("ProfileAbout"), text: about)
.setEnableNavigation(true)
if self.user!.getAboutModel().get() == nil {
aboutCell.setIsAction(true)
}
aboutCell.setAction { () -> () in
var text = self.user!.getAboutModel().get()
if text == nil {
text = ""
}
let controller = EditTextController(title: localized("SettingsChangeAboutTitle"), actionTitle: localized("NavigationSave"), content: text, completition: { (newText) -> () in
var updatedText: String? = newText.trim()
if updatedText?.length == 0 {
updatedText = nil
}
self.execute(Actor.editMyAboutCommandWithNick(updatedText))
})
let navigation = AANavigationController(rootViewController: controller)
self.presentViewController(navigation, animated: true, completion: nil)
}
// Phones
profileInfoSection
.addCustomCells(55, countClosure: { () -> Int in
if (self.phones != nil) {
return Int(self.phones!.size())
}
return 0
}) { (tableView, index, indexPath) -> UITableViewCell in
let cell: TitledCell = tableView.dequeueReusableCellWithIdentifier(self.TitledCellIdentifier, forIndexPath: indexPath) as! TitledCell
if let phone = self.phones!.getWithInt(jint(index)) as? ACUserPhone {
cell.setTitle(phone.getTitle(), content: "+\(phone.getPhone())")
}
return cell
}.setAction { (index) -> () in
let phoneNumber = (self.phones?.getWithInt(jint(index)).getPhone())!
let hasPhone = UIApplication.sharedApplication().canOpenURL(NSURL(string: "tel://")!)
if (!hasPhone) {
UIPasteboard.generalPasteboard().string = "+\(phoneNumber)"
self.alertUser("NumberCopied")
} else {
self.showActionSheet(["CallNumber", "CopyNumber"],
cancelButton: "AlertCancel",
destructButton: nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if (index == 0) {
UIApplication.sharedApplication().openURL(NSURL(string: "tel://+\(phoneNumber)")!)
} else if index == 1 {
UIPasteboard.generalPasteboard().string = "+\(phoneNumber)"
self.alertUser("NumberCopied")
}
})
}
}
// Profile
let topSection = tableData.addSection(true)
topSection.setHeaderHeight(15)
topSection.setFooterHeight(15)
// Profile: Set Photo
topSection.addActionCell("SettingsSetPhoto", actionClosure: { () -> () in
let hasCamera = UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera)
self.showActionSheet(hasCamera ? ["PhotoCamera", "PhotoLibrary"] : ["PhotoLibrary"],
cancelButton: "AlertCancel",
destructButton: self.user!.getAvatarModel().get() != nil ? "PhotoRemove" : nil,
sourceView: self.view,
sourceRect: self.view.bounds,
tapClosure: { (index) -> () in
if index == -2 {
self.confirmUser("PhotoRemoveGroupMessage",
action: "PhotoRemove",
cancel: "AlertCancel",
sourceView: self.view,
sourceRect: self.view.bounds,
tapYes: { () -> () in
Actor.removeMyAvatar()
})
} else if index >= 0 {
let takePhoto: Bool = (index == 0) && hasCamera
self.pickAvatar(takePhoto, closure: { (image) -> () in
Actor.changeOwnAvatar(image)
})
}
})
})
// Profile: Set Name
topSection.addActionCell("SettingsChangeName", actionClosure: { () -> () in
let alertView = UIAlertView(title: nil,
message: NSLocalizedString("SettingsEditHeader", comment: "Title"),
delegate: nil,
cancelButtonTitle: NSLocalizedString("AlertCancel", comment: "Cancel Title"))
alertView.addButtonWithTitle(NSLocalizedString("AlertSave", comment: "Save Title"))
alertView.alertViewStyle = UIAlertViewStyle.PlainTextInput
alertView.textFieldAtIndex(0)!.autocapitalizationType = UITextAutocapitalizationType.Words
alertView.textFieldAtIndex(0)!.text = self.user!.getNameModel().get()
alertView.textFieldAtIndex(0)?.keyboardAppearance = MainAppTheme.common.isDarkKeyboard ? UIKeyboardAppearance.Dark : UIKeyboardAppearance.Light
alertView.tapBlock = { (alertView, buttonIndex) -> () in
if (buttonIndex == 1) {
let textField = alertView.textFieldAtIndex(0)!
if textField.text!.length > 0 {
self.execute(Actor.editMyNameCommandWithName(textField.text))
}
}
}
alertView.show()
})
// Settings
let actionsSection = tableData.addSection(true)
.setHeaderHeight(15)
.setFooterHeight(15)
// Settings: Notifications
actionsSection.addNavigationCell("SettingsNotifications", actionClosure: { () -> () in
self.navigateNext(SettingsNotificationsViewController(), removeCurrent: false)
})
// Settings: Privacy
actionsSection.addNavigationCell("SettingsSecurity", actionClosure: { () -> () in
self.navigateNext(SettingsPrivacyViewController(), removeCurrent: false)
})
// Support
let supportSection = tableData.addSection(true)
.setHeaderHeight(15)
.setFooterHeight(15)
// Support: Ask Question
supportSection.addNavigationCell("SettingsAskQuestion", actionClosure: { () -> () in
self.execute(Actor.findUsersCommandWithQuery("75551234567"), successBlock: { (val) -> Void in
var user:ACUserVM!
if let users = val as? IOSObjectArray {
if Int(users.length()) > 0 {
if let tempUser = users.objectAtIndex(0) as? ACUserVM {
user = tempUser
}
}
}
self.navigateDetail(ConversationViewController(peer: ACPeer.userWithInt(user.getId())))
}, failureBlock: { (val) -> Void in
// TODO: Implement
})
})
// Support: Ask Question
supportSection.addNavigationCell("SettingsAbout", actionClosure: { () -> () in
UIApplication.sharedApplication().openURL(NSURL(string: "https://actor.im")!)
})
// Support: App version
let version = NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String
supportSection.addCommonCell()
.setContent(NSLocalizedString("SettingsVersion", comment: "Version").stringByReplacingOccurrencesOfString("{version}", withString: version, options: NSStringCompareOptions(), range: nil))
.setStyle(.Hint)
// Bind
tableView.reloadData()
binder.bind(user!.getNameModel()!, closure: { (value: String?) -> () in
if value == nil {
return
}
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell {
cell.setUsername(value!)
}
})
binder.bind(user!.getAboutModel(), closure: { (value: String?) -> () in
var about = self.user!.getAboutModel().get()
if about == nil {
about = localized("SettingsAboutNotSet")
aboutCell.setIsAction(true)
} else {
aboutCell.setIsAction(false)
}
aboutCell.setContent(localized("ProfileAbout"), text: about)
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 2, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
})
binder.bind(user!.getNickModel(), closure: { (value: String?) -> () in
self.tableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 1, inSection: 0)], withRowAnimation: UITableViewRowAnimation.Automatic)
})
binder.bind(Actor.getOwnAvatarVM().getUploadState(), valueModel2: user!.getAvatarModel()) { (upload: ACAvatarUploadState?, avatar: ACAvatar?) -> () in
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell {
if (upload != nil && upload!.isUploading().boolValue) {
cell.userAvatarView.bind(self.user!.getNameModel().get(), id: jint(self.uid), fileName: upload?.getDescriptor())
cell.setProgress(true)
} else {
cell.userAvatarView.bind(self.user!.getNameModel().get(), id: jint(self.uid), avatar: avatar, clearPrev: false)
cell.setProgress(false)
}
}
}
binder.bind(user!.getPresenceModel(), closure: { (presence: ACUserPresence?) -> () in
let presenceText = Actor.getFormatter().formatPresence(presence, withSex: self.user!.getSex())
if presenceText != nil {
if let cell = self.tableView.cellForRowAtIndexPath(NSIndexPath(forItem: 0, inSection: 0)) as? UserPhotoCell {
cell.setPresence(presenceText)
}
}
})
binder.bind(user!.getPhonesModel(), closure: { (phones: JavaUtilArrayList?) -> () in
if phones != nil {
self.phones = phones
self.tableView.reloadData()
}
})
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
Actor.onProfileOpenWithUid(jint(uid))
MainAppTheme.navigation.applyStatusBar()
navigationController?.navigationBar.shadowImage = UIImage()
applyScrollUi(tableView)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
Actor.onProfileClosedWithUid(jint(uid))
navigationController?.navigationBar.lt_reset()
}
}
|
mit
|
dc5de20107a57ec7f1cc7f3096cf9107
| 42.065574 | 199 | 0.556655 | 5.56175 | false | false | false | false |
terflogag/FacebookImagePicker
|
GBHFacebookImagePicker/Classes/Controller/ContentStateViewController/ContentStateViewController.swift
|
1
|
1309
|
//
// ContentStateViewController.swift
// SkyBreathe
//
// Created by Florian Gabach on 25/10/2018.
// Copyright © 2018 OpenAirlines. All rights reserved.
//
import UIKit
final class ContentStateViewController: UIViewController {
// MARK: - Var
private var state: State?
private var shownViewController: UIViewController?
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
if state == nil {
self.transition(to: .loading)
}
}
// MARK: - Action
func transition(to newState: State) {
self.shownViewController?.remove()
let viewCtrl = viewController(for: newState)
self.add(viewCtrl)
self.shownViewController = viewCtrl
self.state = newState
}
}
private extension ContentStateViewController {
func viewController(for state: State) -> UIViewController {
switch state {
case .loading:
return LoadingViewController()
case .failed:
return LoadingViewController()
case .render(let viewController):
return viewController
}
}
}
extension ContentStateViewController {
public enum State {
case loading
case failed(Error)
case render(UIViewController)
}
}
|
mit
|
b238c05f07915f08f01556ff18d50c6d
| 20.8 | 63 | 0.631498 | 4.880597 | false | false | false | false |
gnachman/iTerm2
|
sources/VT100SavedColors.swift
|
2
|
4017
|
//
// VT100SavedColors.swift
// iTerm2SharedARC
//
// Created by George Nachman on 10/6/21.
//
import Foundation
@objcMembers
@objc(VT100SavedColors)
final class SavedColors: NSObject {
static let capacity = 256
private(set) var used = 0
private(set) var last = 0
private(set) var slots = [Int: Slot]()
override var debugDescription: String {
return "<\(Self.self): \(it_addressString) \(repDescr)>"
}
var repDescr: String {
let slotStrings = slots.keys.sorted().map { (i: Int) -> String in
let description = slots[i]?.debugDescription ?? "(nil)"
return "\(i): \(description)"
}
let joined = slotStrings.joined(separator: " ")
return "used=\(used) last=\(last) slots=[\(joined)]"
}
func push(_ slot: Slot) {
set(slot, at: used)
/// xterm only updates its `last` variable on a regular push, not on direct assignment to a slot.
/// I'm not thrilled about this, but I think it's better to replicate the bug than create a fork.
last = max(last, used)
}
@objc(setSlot:at:) func set(_ slot: Slot, at index: Int) {
guard index >= 0 && index < Self.capacity else {
return
}
slots[index] = slot
used = index + 1
}
func pop() -> Slot? {
return slot(used - 1)
}
@objc(slotAt:) func slot(_ index: Int) -> Slot? {
guard index >= 0 && index < Self.capacity else {
return nil
}
guard let slot = slots[index] else {
return nil
}
/// This is intentional. xterm updates `used` on pop, even when directly accessing by index.
used = index
return slot
}
func peek(_ index: Int) -> Slot? {
guard index >= 0 && index < Self.capacity else {
return nil
}
return slots[index]
}
}
extension SavedColors: Encodable {
var plist: Data? {
return try? PropertyListEncoder().encode(self)
}
}
extension SavedColors: Decodable {
static func from(data: Data?) -> SavedColors? {
guard let data = data else {
return nil
}
return try? PropertyListDecoder().decode(self, from: data)
}
}
extension SavedColors {
@objcMembers
@objc(VT100SavedColorsSlot)
class Slot: NSObject, Codable {
private static let numberOfIndexedColors = 256
private let _text: CodableColor
var text: NSColor { return _text.color }
private let _background: CodableColor
var background: NSColor { return _background.color }
private let _selectionText: CodableColor
var selectionText: NSColor { return _selectionText.color }
private let _selectionBackground: CodableColor
var selectionBackground: NSColor { return _selectionBackground.color }
private let _indexedColors: [CodableColor]
var indexedColors: [NSColor] { return _indexedColors.map { $0.color } }
override var debugDescription: String {
return "<Slot text=\(text) background=\(background) selectionText=\(selectionText) selectionBackground=\(selectionBackground) indexedColors=\(indexedColors.map { $0.debugDescription }.joined(separator: ","))>"
}
@objc(initWithTextColor:backgroundColor:selectionTextColor:selectionBackgroundColor:indexedColorProvider:)
init(text: NSColor,
background: NSColor,
selectionText: NSColor,
selectionBackground: NSColor,
indexedColorProvider: (Int) -> (NSColor)) {
let indexedColors = (0..<Self.numberOfIndexedColors).map {
CodableColor(indexedColorProvider($0))
}
_text = CodableColor(text)
_background = CodableColor(background)
_selectionText = CodableColor(selectionText)
_selectionBackground = CodableColor(selectionBackground)
_indexedColors = indexedColors
}
}
}
|
gpl-2.0
|
8cac9c7ee1d608c41fc529446b556c2a
| 30.880952 | 221 | 0.607916 | 4.438674 | false | false | false | false |
ajjnix/Remember
|
Remember/TaskListCollectionViewCell.swift
|
1
|
2428
|
import UIKit
final class TaskListCollectionViewCell: BaseCollectionViewCell {
fileprivate let title: UILabel = UILabel(frame: .zero)
}
extension TaskListCollectionViewCell {
override func setupUI() {
contentView.addSubview(title)
title.addConstraintFrame(to: contentView)
title.translatesAutoresizingMaskIntoConstraints = false
}
}
extension TaskListCollectionViewCell {
func update(_ model: TaskListCellModel) {
title.text = model.task.title
update(model.mode)
}
fileprivate func update(_ mode: TaskListCellModel.Mode) {
if mode == .front {
title.backgroundColor = UIColor.lightGray
} else {
title.backgroundColor = UIColor.green.withAlphaComponent(0.3)
}
}
}
extension TaskListCollectionViewCell {
func rotate(to mode: TaskListCellModel.Mode) {
prepareForAnimation()
startRotate(to: mode)
}
private func prepareForAnimation() {
layer.shouldRasterize = true
layer.rasterizationScale = UIScreen.main.scale
}
private func startRotate(to mode: TaskListCellModel.Mode) {
let firstAnimation = makeFirstRotateAnimation(for: mode)
let secondAnimation = makeSecondRoteteAnimation(for: mode)
layer.add(firstAnimation, onStop: { [weak self] _ in
self?.update(mode)
self?.layer.add(secondAnimation)
})
}
private func makeFirstRotateAnimation(for mode: TaskListCellModel.Mode) -> CAAnimation {
return makeRotateAnimation(.pi/2)
}
private func makeSecondRoteteAnimation(for mode: TaskListCellModel.Mode) -> CAAnimation {
let angel: CGFloat = (mode == .back ? .pi : 0)
return makeRotateAnimation(angel)
}
private func makeRotateAnimation(_ angle: CGFloat) -> CAAnimation {
let animation = CABasicAnimation(keyPath: "transform")
animation.duration = 0.3
animation.toValue = makeTransform(angle: angle)
animation.fillMode = kCAFillModeForwards
animation.isRemovedOnCompletion = false
return animation
}
private func makeTransform(angle: CGFloat) -> CATransform3D {
var transform = CATransform3DIdentity
transform.m34 = -1.0/1000
let rotate = CATransform3DRotate(transform, angle, 0, 1, 0)
return CATransform3DTranslate(rotate, 0, 0, 0)
}
}
|
mit
|
4a0c8f5bf36019925a288b0ff27a963a
| 31.810811 | 93 | 0.665568 | 4.846307 | false | false | false | false |
saeta/penguin
|
Sources/PenguinStructures/AnyArrayBuffer.swift
|
1
|
6188
|
// 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.
extension AnyArrayBuffer where Dispatch == AnyObject {
/// Creates an instance containing the same elements as `src`.
public init<Element>(_ src: ArrayBuffer<Element>) {
self.storage = src.storage.object
self.dispatch = Void.self as AnyObject
}
/// Creates an instance containing the same elements as `src`.
public init<OtherDispatch>(_ src: AnyArrayBuffer<OtherDispatch>) {
self.storage = src.storage
self.dispatch = src.dispatch
}
}
extension AnyArrayBuffer {
/// Creates an instance containing the same elements as `src`, failing if
/// `src` is not dispatched by a `Dispatch` or a subclass thereof.
public init?<OtherDispatch>(_ src: AnyArrayBuffer<OtherDispatch>) {
guard let d = src.dispatch as? Dispatch else { return nil }
self.storage = src.storage
self.dispatch = d
}
/// Creates an instance containing the same elements as `src`.
///
/// - Requires: `src.dispatch is Dispatch.Type`.
public init<OtherDispatch>(unsafelyCasting src: AnyArrayBuffer<OtherDispatch>)
{
self.storage = src.storage
self.dispatch = unsafeDowncast(src.dispatch, to: Dispatch.self)
}
}
/// A type-erased array that is not statically known to support any operations.
public typealias AnyElementArrayBuffer = AnyArrayBuffer<AnyObject>
/// A resizable, value-semantic buffer of homogenous elements of
/// statically-unknown type.
public struct AnyArrayBuffer<Dispatch: AnyObject> {
public typealias Storage = AnyArrayStorage
/// A bounded contiguous buffer comprising all of `self`'s storage.
public var storage: Storage?
/// A “vtable” of functions implementing type-erased operations that depend on the Element type.
public let dispatch: Dispatch
public init<Element>(storage: ArrayStorage<Element>, dispatch: Dispatch) {
self.storage = storage.object
self.dispatch = dispatch
}
/// Creates a buffer with elements from `src`.
public init(_ src: AnyArrayBuffer) {
self.storage = src.storage
self.dispatch = src.dispatch
}
/// Returns `true` iff an element of type `e` can be appended to `self`.
public func canAppendElement(ofType e: TypeID) -> Bool {
storage.unsafelyUnwrapped.isUsable(forElementType: e)
}
/// Returns the result of invoking `body` on a typed alias of `self`, if
/// `self.canStoreElement(ofType: Type<Element>.id)`; returns `nil` otherwise.
public mutating func mutate<Element, R>(
ifElementType _: Type<Element>,
_ body: (_ me: inout ArrayBuffer<Element>)->R
) -> R? {
// TODO: check for spurious ARC traffic
guard var me = ArrayBuffer<Element>(self) else { return nil }
self.storage = nil
defer { self.storage = me.storage.object }
return body(&me)
}
/// Returns the result of invoking `body` on a typed alias of `self`.
///
/// - Requires: `self.elementType == Element.self`.
@available(*, deprecated, message: "use subscript(unsafelyAssumingElementType:) instead.")
public mutating func unsafelyMutate<Element, R>(
assumingElementType _: Type<Element>,
_ body: (_ me: inout ArrayBuffer<Element>)->R
) -> R {
body(&self[unsafelyAssumingElementType: Type<Element>()])
}
}
extension AnyArrayBuffer {
/// The number of stored elements.
public var count: Int { storage.unsafelyUnwrapped.count }
/// The number of elements that can be stored in `self` without reallocation,
/// provided its representation is not shared with other instances.
public var capacity: Int { storage.unsafelyUnwrapped.capacity }
}
extension AnyArrayBuffer {
/// Accesses `self` as an `ArrayBuffer<Element>` if `Element.self == elementType`.
///
/// - Writing `nil` removes all elements of `self`.
/// - Where `Element.self != elementType`:
/// - reading returns `nil`.
/// - writing changes the type of elements stored in `self`.
///
public subscript<Element>(elementType _: Type<Element>) -> ArrayBuffer<Element>? {
get {
ArrayBuffer<Element>(self)
}
_modify {
// TODO: check for spurious ARC traffic
var me = ArrayBuffer<Element>(self)
if me != nil {
// Don't retain an additional reference during this mutation, to prevent needless CoW.
self.storage = nil
}
defer {
if let written = me {
self.storage = written.storage.object
}
}
yield &me
}
}
/// Accesses `self` as an `ArrayBuffer<Element>`.
///
/// - Requires: `Element.self == elementType`.
public subscript<Element>(existingElementType _: Type<Element>) -> ArrayBuffer<Element> {
get {
ArrayBuffer<Element>(self)!
}
_modify {
// TODO: check for spurious ARC traffic
var me = ArrayBuffer<Element>(self)!
// Don't retain an additional reference during this mutation, to prevent needless CoW.
self.storage = nil
defer { self.storage = me.storage.object }
yield &me
}
}
/// Accesses `self` as an `ArrayBuffer<Element>` unsafely assuming `Element.self == elementType`.
///
/// - Requires: `self.storage!.isUsable(forElementType: Type<Element>)`.
public subscript<Element>(unsafelyAssumingElementType _: Type<Element>) -> ArrayBuffer<Element> {
get {
ArrayBuffer<Element>(unsafelyDowncasting: self)
}
_modify {
// TODO: check for spurious ARC traffic
var me = ArrayBuffer<Element>(unsafelyDowncasting: self)
// Don't retain an additional reference during this mutation, to prevent needless CoW.
self.storage = nil
defer { self.storage = me.storage.object }
yield &me
}
}
}
|
apache-2.0
|
9bc45f6dca0066832a297b39f28d10d4
| 34.337143 | 99 | 0.683053 | 4.276625 | false | false | false | false |
tinypass/piano-sdk-for-ios
|
Sources/OAuth/OAuth/PianoIDApplicationDelegate.swift
|
1
|
1858
|
import UIKit
@objcMembers
public class PianoIDApplicationDelegate: NSObject {
public static let shared = PianoIDApplicationDelegate()
public func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {
facebookApplication(application, didFinishLaunchingWithOptions: launchOptions)
appleApplication(application, didFinishLaunchingWithOptions: launchOptions)
return true
}
public func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
var handled = PianoID.shared.handleUrl(url)
if (!handled) {
handled = googleApplication(application, handleOpen: url)
}
return handled
}
public func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
var handled = PianoID.shared.handleUrl(url)
if (!handled) {
handled = googleApplication(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
if (!handled) {
handled = facebookApplication(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
return handled
}
public func application(_ application: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
var handled = PianoID.shared.handleUrl(url)
if (!handled) {
handled = googleApplication(application, open: url, options: options)
}
if (!handled) {
handled = facebookApplication(application, open: url, options: options)
}
return handled
}
}
|
apache-2.0
|
588a79578bc18cc8d2c436896f486ec7
| 35.431373 | 167 | 0.643165 | 5.699387 | false | false | false | false |
jaropawlak/Signal-iOS
|
Signal/src/contact/SystemContactsFetcher.swift
|
1
|
18910
|
//
// Copyright (c) 2017 Open Whisper Systems. All rights reserved.
//
import Foundation
import Contacts
import ContactsUI
enum Result<T, ErrorType> {
case success(T)
case error(ErrorType)
}
protocol ContactStoreAdaptee {
var authorizationStatus: ContactStoreAuthorizationStatus { get }
var supportsContactEditing: Bool { get }
func requestAccess(completionHandler: @escaping (Bool, Error?) -> Void)
func fetchContacts() -> Result<[Contact], Error>
func startObservingChanges(changeHandler: @escaping () -> Void)
}
@available(iOS 9.0, *)
class ContactsFrameworkContactStoreAdaptee: ContactStoreAdaptee {
let TAG = "[ContactsFrameworkContactStoreAdaptee]"
private let contactStore = CNContactStore()
private var changeHandler: (() -> Void)?
private var initializedObserver = false
private var lastSortOrder: CNContactSortOrder?
let supportsContactEditing = true
private let allowedContactKeys: [CNKeyDescriptor] = [
CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactThumbnailImageDataKey as CNKeyDescriptor, // TODO full image instead of thumbnail?
CNContactPhoneNumbersKey as CNKeyDescriptor,
CNContactEmailAddressesKey as CNKeyDescriptor,
CNContactViewController.descriptorForRequiredKeys()
]
var authorizationStatus: ContactStoreAuthorizationStatus {
switch CNContactStore.authorizationStatus(for: CNEntityType.contacts) {
case .notDetermined:
return .notDetermined
case .restricted:
return .restricted
case .denied:
return .denied
case .authorized:
return .authorized
}
}
func startObservingChanges(changeHandler: @escaping () -> Void) {
// should only call once
assert(self.changeHandler == nil)
self.changeHandler = changeHandler
self.lastSortOrder = CNContactsUserDefaults.shared().sortOrder
NotificationCenter.default.addObserver(self, selector: #selector(runChangeHandler), name: .CNContactStoreDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: .UIApplicationDidBecomeActive, object: nil)
}
@objc
func didBecomeActive() {
let currentSortOrder = CNContactsUserDefaults.shared().sortOrder
guard currentSortOrder != self.lastSortOrder else {
// sort order unchanged
return
}
Logger.info("\(TAG) sort order changed: \(String(describing: self.lastSortOrder)) -> \(String(describing: currentSortOrder))")
self.lastSortOrder = currentSortOrder
self.runChangeHandler()
}
@objc
func runChangeHandler() {
guard let changeHandler = self.changeHandler else {
owsFail("\(TAG) trying to run change handler before it was registered")
return
}
changeHandler()
}
func requestAccess(completionHandler: @escaping (Bool, Error?) -> Void) {
self.contactStore.requestAccess(for: .contacts, completionHandler: completionHandler)
}
func fetchContacts() -> Result<[Contact], Error> {
var systemContacts = [CNContact]()
do {
let contactFetchRequest = CNContactFetchRequest(keysToFetch: self.allowedContactKeys)
contactFetchRequest.sortOrder = .userDefault
try self.contactStore.enumerateContacts(with: contactFetchRequest) { (contact, _) -> Void in
systemContacts.append(contact)
}
} catch let error as NSError {
owsFail("\(self.TAG) Failed to fetch contacts with error:\(error)")
return .error(error)
}
let contacts = systemContacts.map { Contact(systemContact: $0) }
return .success(contacts)
}
}
let kAddressBookContactStoreDidChangeNotificationName = NSNotification.Name("AddressBookContactStoreAdapteeDidChange")
/**
* System contact fetching compatible with iOS8
*/
class AddressBookContactStoreAdaptee: ContactStoreAdaptee {
let TAG = "[AddressBookContactStoreAdaptee]"
private var addressBook: ABAddressBook = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()
private var changeHandler: (() -> Void)?
let supportsContactEditing = false
var authorizationStatus: ContactStoreAuthorizationStatus {
switch ABAddressBookGetAuthorizationStatus() {
case .notDetermined:
return .notDetermined
case .restricted:
return .restricted
case .denied:
return .denied
case .authorized:
return .authorized
}
}
@objc
func runChangeHandler() {
guard let changeHandler = self.changeHandler else {
owsFail("\(TAG) trying to run change handler before it was registered")
return
}
changeHandler()
}
func startObservingChanges(changeHandler: @escaping () -> Void) {
// should only call once
assert(self.changeHandler == nil)
self.changeHandler = changeHandler
NotificationCenter.default.addObserver(self, selector: #selector(runChangeHandler), name: kAddressBookContactStoreDidChangeNotificationName, object: nil)
let callback: ABExternalChangeCallback = { (_, _, _) in
// Ideally we'd just call the changeHandler here, but because this is a C style callback in swift,
// we can't capture any state in the closure, so we use a notification as a trampoline
NotificationCenter.default.postNotificationNameAsync(kAddressBookContactStoreDidChangeNotificationName, object: nil)
}
ABAddressBookRegisterExternalChangeCallback(addressBook, callback, nil)
}
func requestAccess(completionHandler: @escaping (Bool, Error?) -> Void) {
ABAddressBookRequestAccessWithCompletion(addressBook, completionHandler)
}
func fetchContacts() -> Result<[Contact], Error> {
// Changes are not reflected unless we create a new address book
self.addressBook = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()
let allPeople = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(addressBook, nil, ABPersonGetSortOrdering()).takeRetainedValue() as [ABRecord]
let contacts = allPeople.map { self.buildContact(abRecord: $0) }
return .success(contacts)
}
private func buildContact(abRecord: ABRecord) -> Contact {
let addressBookRecord = OWSABRecord(abRecord: abRecord)
var firstName = addressBookRecord.firstName
let lastName = addressBookRecord.lastName
let phoneNumbers = addressBookRecord.phoneNumbers
if firstName == nil && lastName == nil {
if let companyName = addressBookRecord.companyName {
firstName = companyName
} else {
firstName = phoneNumbers.first
}
}
return Contact(contactWithFirstName: firstName,
andLastName: lastName,
andUserTextPhoneNumbers: phoneNumbers,
andImage: addressBookRecord.image,
andContactID: addressBookRecord.recordId)
}
}
/**
* Wrapper around ABRecord for easy property extraction.
* Some code lifted from:
* https://github.com/SocialbitGmbH/SwiftAddressBook/blob/c1993fa/Pod/Classes/SwiftAddressBookPerson.swift
*/
struct OWSABRecord {
public struct MultivalueEntry<T> {
public var value: T
public var label: String?
public let id: Int
public init(value: T, label: String?, id: Int) {
self.value = value
self.label = label
self.id = id
}
}
let abRecord: ABRecord
init(abRecord: ABRecord) {
self.abRecord = abRecord
}
var firstName: String? {
return self.extractProperty(kABPersonFirstNameProperty)
}
var lastName: String? {
return self.extractProperty(kABPersonLastNameProperty)
}
var companyName: String? {
return self.extractProperty(kABPersonOrganizationProperty)
}
var recordId: ABRecordID {
return ABRecordGetRecordID(abRecord)
}
// We don't yet support labels for our iOS8 users.
var phoneNumbers: [String] {
if let result: [MultivalueEntry<String>] = extractMultivalueProperty(kABPersonPhoneProperty) {
return result.map { $0.value }
} else {
return []
}
}
var image: UIImage? {
guard ABPersonHasImageData(abRecord) else {
return nil
}
guard let data = ABPersonCopyImageData(abRecord)?.takeRetainedValue() else {
return nil
}
return UIImage(data: data as Data)
}
private func extractProperty<T>(_ propertyName: ABPropertyID) -> T? {
let value: AnyObject? = ABRecordCopyValue(self.abRecord, propertyName)?.takeRetainedValue()
return value as? T
}
fileprivate func extractMultivalueProperty<T>(_ propertyName: ABPropertyID) -> Array<MultivalueEntry<T>>? {
guard let multivalue: ABMultiValue = extractProperty(propertyName) else { return nil }
var array = Array<MultivalueEntry<T>>()
for i: Int in 0..<(ABMultiValueGetCount(multivalue)) {
let value: T? = ABMultiValueCopyValueAtIndex(multivalue, i).takeRetainedValue() as? T
if let v: T = value {
let id: Int = Int(ABMultiValueGetIdentifierAtIndex(multivalue, i))
let optionalLabel = ABMultiValueCopyLabelAtIndex(multivalue, i)?.takeRetainedValue()
array.append(MultivalueEntry(value: v,
label: optionalLabel == nil ? nil : optionalLabel! as String,
id: id))
}
}
return !array.isEmpty ? array : nil
}
}
enum ContactStoreAuthorizationStatus {
case notDetermined,
restricted,
denied,
authorized
}
class ContactStoreAdapter: ContactStoreAdaptee {
let adaptee: ContactStoreAdaptee
init() {
if #available(iOS 9.0, *) {
self.adaptee = ContactsFrameworkContactStoreAdaptee()
} else {
self.adaptee = AddressBookContactStoreAdaptee()
}
}
var supportsContactEditing: Bool {
return self.adaptee.supportsContactEditing
}
var authorizationStatus: ContactStoreAuthorizationStatus {
return self.adaptee.authorizationStatus
}
func requestAccess(completionHandler: @escaping (Bool, Error?) -> Void) {
return self.adaptee.requestAccess(completionHandler: completionHandler)
}
func fetchContacts() -> Result<[Contact], Error> {
return self.adaptee.fetchContacts()
}
func startObservingChanges(changeHandler: @escaping () -> Void) {
self.adaptee.startObservingChanges(changeHandler: changeHandler)
}
}
@objc protocol SystemContactsFetcherDelegate: class {
func systemContactsFetcher(_ systemContactsFetcher: SystemContactsFetcher, updatedContacts contacts: [Contact])
}
@objc
class SystemContactsFetcher: NSObject {
private let TAG = "[SystemContactsFetcher]"
var lastContactUpdateHash: Int?
var lastDelegateNotificationDate: Date?
let contactStoreAdapter: ContactStoreAdapter
public weak var delegate: SystemContactsFetcherDelegate?
public var authorizationStatus: ContactStoreAuthorizationStatus {
return contactStoreAdapter.authorizationStatus
}
public var isAuthorized: Bool {
guard self.authorizationStatus != .notDetermined else {
owsFail("should have called `requestOnce` before checking authorization status.")
return false
}
return self.authorizationStatus == .authorized
}
private var systemContactsHaveBeenRequestedAtLeastOnce = false
private var hasSetupObservation = false
override init() {
self.contactStoreAdapter = ContactStoreAdapter()
}
var supportsContactEditing: Bool {
return self.contactStoreAdapter.supportsContactEditing
}
private func setupObservationIfNecessary() {
AssertIsOnMainThread()
guard !hasSetupObservation else {
return
}
hasSetupObservation = true
self.contactStoreAdapter.startObservingChanges { [weak self] in
DispatchQueue.main.async {
self?.updateContacts(completion: nil, alwaysNotify: false)
}
}
}
/**
* Ensures we've requested access for system contacts. This can be used in multiple places,
* where we might need contact access, but will ensure we don't wastefully reload contacts
* if we have already fetched contacts.
*
* @param completion completion handler is called on main thread.
*/
public func requestOnce(completion completionParam: ((Error?) -> Void)?) {
AssertIsOnMainThread()
// Ensure completion is invoked on main thread.
let completion = { error in
DispatchMainThreadSafe({
completionParam?(error)
})
}
guard !systemContactsHaveBeenRequestedAtLeastOnce else {
completion(nil)
return
}
setupObservationIfNecessary()
switch authorizationStatus {
case .notDetermined:
if UIApplication.shared.applicationState == .background {
Logger.error("\(self.TAG) do not request contacts permission when app is in background")
completion(nil)
return
}
self.contactStoreAdapter.requestAccess { (granted, error) in
if let error = error {
Logger.error("\(self.TAG) error fetching contacts: \(error)")
completion(error)
return
}
guard granted else {
// This case should have been caught be the error guard a few lines up.
owsFail("\(self.TAG) declined contact access.")
completion(nil)
return
}
DispatchQueue.main.async {
self.updateContacts(completion: completion)
}
}
case .authorized:
self.updateContacts(completion: completion)
case .denied, .restricted:
Logger.debug("\(TAG) contacts were \(self.authorizationStatus)")
completion(nil)
}
}
public func fetchOnceIfAlreadyAuthorized() {
AssertIsOnMainThread()
guard authorizationStatus == .authorized else {
return
}
guard !systemContactsHaveBeenRequestedAtLeastOnce else {
return
}
updateContacts(completion: nil, alwaysNotify: false)
}
public func fetchIfAlreadyAuthorizedAndAlwaysNotify() {
AssertIsOnMainThread()
guard authorizationStatus == .authorized else {
return
}
updateContacts(completion: nil, alwaysNotify: true)
}
private func updateContacts(completion completionParam: ((Error?) -> Void)?, alwaysNotify: Bool = false) {
AssertIsOnMainThread()
// Ensure completion is invoked on main thread.
let completion = { error in
DispatchMainThreadSafe({
completionParam?(error)
})
}
systemContactsHaveBeenRequestedAtLeastOnce = true
setupObservationIfNecessary()
DispatchQueue.global().async {
Logger.info("\(self.TAG) fetching contacts")
var fetchedContacts: [Contact]?
switch self.contactStoreAdapter.fetchContacts() {
case .success(let result):
fetchedContacts = result
case .error(let error):
completion(error)
return
}
guard let contacts = fetchedContacts else {
owsFail("\(self.TAG) contacts was unexpectedly not set.")
completion(nil)
}
let contactsHash = HashableArray(contacts).hashValue
DispatchQueue.main.async {
var shouldNotifyDelegate = false
if self.lastContactUpdateHash != contactsHash {
Logger.info("\(self.TAG) contact hash changed. new contactsHash: \(contactsHash)")
shouldNotifyDelegate = true
} else if alwaysNotify {
Logger.info("\(self.TAG) ignoring debounce.")
shouldNotifyDelegate = true
} else {
// If nothing has changed, only notify delegate (to perform contact intersection) every N hours
if let lastDelegateNotificationDate = self.lastDelegateNotificationDate {
let kDebounceInterval = TimeInterval(12 * 60 * 60)
let expiresAtDate = Date(timeInterval: kDebounceInterval, since: lastDelegateNotificationDate)
if Date() > expiresAtDate {
Logger.info("\(self.TAG) debounce interval expired at: \(expiresAtDate)")
shouldNotifyDelegate = true
} else {
Logger.info("\(self.TAG) ignoring since debounce interval hasn't expired")
}
} else {
Logger.info("\(self.TAG) first contact fetch. contactsHash: \(contactsHash)")
shouldNotifyDelegate = true
}
}
guard shouldNotifyDelegate else {
Logger.info("\(self.TAG) no reason to notify delegate.")
completion(nil)
return
}
self.lastDelegateNotificationDate = Date()
self.lastContactUpdateHash = contactsHash
self.delegate?.systemContactsFetcher(self, updatedContacts: contacts)
completion(nil)
}
}
}
}
struct HashableArray<Element: Hashable>: Hashable {
var elements: [Element]
init(_ elements: [Element]) {
self.elements = elements
}
var hashValue: Int {
// random generated 32bit number
let base = 224712574
var position = 0
return elements.reduce(base) { (result, element) -> Int in
// Make sure change in sort order invalidates hash
position += 1
return result ^ element.hashValue + position
}
}
static func == (lhs: HashableArray, rhs: HashableArray) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
|
gpl-3.0
|
9b38f779d75e5fffd05336f78a756710
| 33.697248 | 161 | 0.62771 | 5.379801 | false | false | false | false |
yannickl/FlowingMenu
|
Sources/FlowingMenuTransitionManager.swift
|
1
|
9111
|
/*
* FlowingMenu
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
import UIKit
import QuartzCore
/**
The `FlowingMenuTransitionManager` is a concrete subclass of
`UIPercentDrivenInteractiveTransition` which aims to drive the transition between
two views by providing an flowing/elastic and bouncing animation effect.
You must adopt the `FlowingMenuDelegate` if you want to make the transition
interactive.
*/
public final class FlowingMenuTransitionManager: UIPercentDrivenInteractiveTransition {
// MARK: - Specifying the Delegate
/**
The delegate for the flowing transition manager.
The delegate must adopt the `FlowingMenuDelegate` protocol and implement the
required methods to manage the interactive animations.
*/
public weak var delegate: FlowingMenuDelegate?
// MARK: - Managing the Animation Mode
/// Defines the animation mode of the transition.
enum AnimationMode {
/// Present the menu mode.
case presentation
/// Dismiss the menu mode.
case dismissal
}
/// The current animation mode.
var animationMode = AnimationMode.presentation
// MARK: - Defining Interactive Components
/// Flag to know when whether the transition is interactive.
var interactive = false
/// Control views aims to build the elastic shape.
let controlViews = (0 ..< 8).map { _ in UIView() }
/// Shaper layer used to draw the elastic view.
let shapeLayer = CAShapeLayer()
/// Mask to used to create the bubble effect.
let shapeMaskLayer = CAShapeLayer()
/// The display link used to create the bouncing effect.
lazy var displayLink: CADisplayLink = {
let displayLink = CADisplayLink(target: self, selector: #selector(FlowingMenuTransitionManager.updateShapeLayer))
displayLink.isPaused = true
displayLink.add(to: RunLoop.main, forMode: RunLoop.Mode.default)
return displayLink
}()
/// Flag to pause/run the display link.
var animating = false {
didSet {
displayLink.isPaused = !animating
}
}
// MARK: - Working with Animations
/// Present menu animation.
func presentMenu(_ menuView: UIView, otherView: UIView, containerView: UIView, status: FlowingMenuTransitionStatus, duration: TimeInterval, completion: @escaping () -> Void) {
// Composing the view
guard let ov = otherView.snapshotView(afterScreenUpdates: true) else { return }
ov.autoresizingMask = [.flexibleWidth, .flexibleHeight]
containerView.addSubview(ov)
containerView.addSubview(menuView)
// Add the tap gesture
addTapGesture(ov)
// Add a mask to the menu to create the bubble effect
let maskLayer = CAShapeLayer()
menuView.layer.mask = maskLayer
let source = delegate ?? self
let menuWidth = source.flowingMenu(self, widthOfMenuView: menuView)
let maxSideSize = max(menuView.bounds.width, menuView.bounds.height)
let beginRect = CGRect(x: 1, y: menuView.bounds.height / 2 - 1, width: 2, height: 2)
let middleRect = CGRect(x: -menuWidth, y: 0, width: menuWidth * 2, height: menuView.bounds.height)
let endRect = CGRect(x: -maxSideSize, y: menuView.bounds.height / 2 - maxSideSize, width: maxSideSize * 2, height: maxSideSize * 2)
let beginPath = UIBezierPath(rect: menuView.bounds)
beginPath.append(UIBezierPath(ovalIn: beginRect).reversing())
let middlePath = UIBezierPath(rect: menuView.bounds)
middlePath.append(UIBezierPath(ovalIn: middleRect).reversing())
let endPath = UIBezierPath(rect: menuView.bounds)
endPath.append(UIBezierPath(ovalIn: endRect).reversing())
// Defining the menu frame
var menuFrame = menuView.frame
menuFrame.size.width = menuWidth
menuView.frame = menuFrame
// Start the animations
if !interactive {
let bubbleAnim = CAKeyframeAnimation(keyPath: "path")
bubbleAnim.values = [beginRect, middleRect, endRect].map { UIBezierPath(ovalIn: $0).cgPath }
bubbleAnim.keyTimes = [0, 0.4, 1]
bubbleAnim.duration = duration
bubbleAnim.isRemovedOnCompletion = false
bubbleAnim.fillMode = CAMediaTimingFillMode.forwards
maskLayer.add(bubbleAnim, forKey: "bubbleAnim")
}
else {
// Last control points help us to know the menu height
controlViews[7].center = CGPoint(x: 0, y: menuView.bounds.height)
// Be sure there is no animation running
shapeMaskLayer.removeAllAnimations()
// Retrieve the shape color
let shapeColor = source.colorOfElasticShapeInFlowingMenu(self) ?? menuView.backgroundColor ?? .black
shapeMaskLayer.path = UIBezierPath(rect: ov.bounds).cgPath
shapeLayer.actions = ["position" : NSNull(), "bounds" : NSNull(), "path" : NSNull()]
shapeLayer.backgroundColor = shapeColor.cgColor
shapeLayer.fillColor = shapeColor.cgColor
// Add the mask to create the bubble effect
shapeLayer.mask = shapeMaskLayer
// Add the shape layer to container view
containerView.layer.addSublayer(shapeLayer)
// If the container view change,@objc @objc we update the control points parent
for view in controlViews {
view.removeFromSuperview()
containerView.addSubview(view)
}
}
containerView.isUserInteractionEnabled = false
UIView.animate(withDuration: duration, animations: {
menuFrame.origin.x = 0
menuView.frame = menuFrame
otherView.alpha = 0
ov.alpha = 0.4
}) { _ in
if self.interactive && !status.transitionWasCancelled() {
self.interactive = false
let bubbleAnim = CAKeyframeAnimation(keyPath: "path")
bubbleAnim.values = [beginRect, middleRect, endRect].map { UIBezierPath(ovalIn: $0).cgPath }
bubbleAnim.keyTimes = [0, 0.4, 1]
bubbleAnim.duration = duration
bubbleAnim.isRemovedOnCompletion = false
bubbleAnim.fillMode = CAMediaTimingFillMode.forwards
maskLayer.add(bubbleAnim, forKey: "bubbleAnim")
let anim = CAKeyframeAnimation(keyPath: "path")
anim.values = [beginPath, middlePath, endPath].map { $0.cgPath }
anim.keyTimes = [0, 0.4, 1]
anim.duration = duration
anim.isRemovedOnCompletion = false
anim.fillMode = CAMediaTimingFillMode.forwards
self.shapeMaskLayer.add(anim, forKey: "bubbleAnim")
UIView.animate(withDuration: duration, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0, options: [], animations: {
for view in self.controlViews {
view.center.x = menuWidth
}
}, completion: { _ in
self.shapeLayer.removeFromSuperlayer()
containerView.isUserInteractionEnabled = true
menuView.layer.mask = nil
self.animating = false
completion()
})
}
else {
menuView.layer.mask = nil
self.animating = false
containerView.isUserInteractionEnabled = true
completion()
}
}
}
/// Dismiss menu animation.
func dismissMenu(_ menuView: UIView, otherView: UIView, containerView: UIView, status: FlowingMenuTransitionStatus, duration: TimeInterval, completion: @escaping () -> Void) {
otherView.frame = containerView.bounds
let ov = otherView.snapshotView(afterScreenUpdates: true)
var menuFrame = menuView.frame
containerView.addSubview(otherView)
containerView.addSubview(ov!)
containerView.addSubview(menuView)
otherView.alpha = 0
ov?.alpha = 0.4
UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseOut], animations: {
menuFrame.origin.x = -menuFrame.width
menuView.frame = menuFrame
otherView.alpha = 1
ov?.alpha = 1
}) { _ in
completion()
}
}
}
|
mit
|
004c95454c05ec5a912ff57a3eee69a6
| 36.64876 | 177 | 0.678081 | 4.693972 | false | false | false | false |
nttcom/SkyWay-DrivingVehicle
|
DrivingVehicle/DrivingVehicle/controllers/MainController.swift
|
1
|
4581
|
//
// MainController.swift
// DrivingVehicle
//
import UIKit
import Foundation
import AVFoundation
class MainController: UIViewController, NWObserver ,AVAudioPlayerDelegate{
private var _skyway: Skyway!
private var _vehicle: VehicleTemplate!
private var _videoView: VideoViewManager!
private var cannonPlayer : AVAudioPlayer!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
self.vehicleInit()
_videoView = VideoViewManager(parentView: self.view)
_skyway.videoDisplayProtocol = _videoView
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func vehicleInit(){
#if Romo
let peerId = "Romo-" + UIDevice.currentDevice().name
self._skyway = Skyway(peerId: peerId)
self._vehicle = RomoDrive(socket: self._skyway)
#elseif Double
let peerId = "Double-" + UIDevice.currentDevice().name
self._skyway = Skyway(peerId: peerId)
self._vehicle = DoubleDrive(socket: self._skyway)
#endif
_skyway.delegates.append(self)
_skyway.delegates.append(_vehicle)
let cannonFilePath : NSString = NSBundle.mainBundle().pathForResource("cannon", ofType: "mp3")!
let cannonfileURL: NSURL = NSURL(fileURLWithPath: cannonFilePath as String)
cannonPlayer = try? AVAudioPlayer(contentsOfURL: cannonfileURL)
cannonPlayer.delegate = self
cannonPlayer.prepareToPlay()
}
// MARK: RomoFaceDisplay
#if Romo
private var romoView = RMCharacter.Romo()
private var romoViewFlag : Bool = false
func addRomoView(){
self.dispatch_async_main {
self.romoViewFlag = true
self.romoView.addToSuperview(self.view)
}
}
func removeRomoView(){
self.dispatch_async_main {
self.romoViewFlag = false
self.romoView.removeFromSuperview()
self.romoView = RMCharacter.Romo()
}
}
func dispatch_async_main(block: () -> ()) {
dispatch_async(dispatch_get_main_queue(), block)
}
func onMessage(dict: Dictionary<String, AnyObject>){
let type = dict["type"] as! String!
if(type != nil){
let flag = dict["flag"] as! Bool! == true
switch type{
case "Romo":
if(flag){
self.addRomoView()
}else{
self.removeRomoView()
}
case "GetCamera":
if(flag){
_skyway.sendCameraPosition()
}
case "SwitchCamera":
if(flag){
_skyway.switchCamera()
}
case "Shot":
if(flag){
if(cannonPlayer != nil){
if (cannonPlayer.playing == true) {
cannonPlayer.currentTime = 0;
}
cannonPlayer.play()
}
}
default:
return
}
}
}
#elseif Double
func onMessage(dict: Dictionary<String, AnyObject>){
let type = dict["type"] as! String!
if(type != nil){
let flag = dict["flag"] as! Bool! == true
switch type{
case "GetCamera":
if(flag){
_skyway.sendCameraPosition()
}
case "SwitchCamera":
if(flag){
_skyway.switchCamera()
}
case "Shot":
if(flag){
if(cannonPlayer != nil){
if (cannonPlayer.playing == true) {
cannonPlayer.currentTime = 0;
}
cannonPlayer.play()
}
}
default:
return
}
}
}
#endif
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
}
}
|
mit
|
9f4e89ad6f937f6e77dc1f0ec58fe357
| 28.554839 | 103 | 0.485484 | 5.129899 | false | false | false | false |
anddygon/RxTest
|
RxTest/NetEngine/Observable.swift
|
1
|
2608
|
//
// Observable.swift
// StyleWe
//
// Created by xiaoP on 16/8/18.
// Copyright © 2016年 Chicv. All rights reserved.
//
import Foundation
import ObjectMapper
import Alamofire
import RxSwift
private let mappingError = NSError(domain: "", code: -1, userInfo: [NSLocalizedFailureReasonErrorKey:"Mapping Failed"])
extension ObservableType where E == (AnyObject?, HTTPURLResponse?) {
func mapObject<T: Mappable>(_ type: T.Type, keyPath: String? = nil)-> Observable<T> {
return observeOn(SerialDispatchQueueScheduler(qos: .background))
.flatMap{ (anyObject, response) -> Observable<T> in
let waitMapObject: AnyObject?
if let keyPath = keyPath , !keyPath.isEmpty {
waitMapObject = (anyObject as! NSObject).value(forKeyPath: keyPath) as AnyObject?
} else {
waitMapObject = anyObject
}
if let object = Mapper<T>().map(JSONObject:waitMapObject) {
return Observable.just(object)
} else {
return Observable.error(mappingError)
}
}
.observeOn(MainScheduler.instance)
}
/**
- parameter type: 返回的数据需要解析成的模型类型
- parameter keyPath: 对应的JSON路径
- returns: 会发送对应的Object以及对应的数量
比如productIndex接口 如果参数配置return-filter=1服务器返回的是一个下面形式的JSON
{
list: [xxxx]
filter: {} //filter对象
}
这样的接口返回的第二个Bool是list是不是还有更多数据待加载
*/
func mapArray<T: Mappable>(_ type: T.Type, keyPath: String? = nil)-> Observable<[T]> {
return observeOn(SerialDispatchQueueScheduler(qos: .background))
.flatMap{ (anyObject, response) -> Observable<[T]> in
let waitMapObject: AnyObject?
if let keyPath = keyPath , !keyPath.isEmpty {
waitMapObject = (anyObject as! NSObject).value(forKeyPath: keyPath) as AnyObject?
} else {
waitMapObject = anyObject
}
if let object = Mapper<T>().mapArray(JSONObject: waitMapObject) {
return Observable.just(object)
} else {
return Observable.error(mappingError)
}
}
.observeOn(MainScheduler.instance)
}
}
|
mit
|
fcb2796305e920b9ac082a439accee84
| 32.410959 | 119 | 0.553916 | 4.820158 | false | false | false | false |
haskelash/DragSelectCollectionView
|
DragSelectCollectionView/DragSelectCollectionView.swift
|
1
|
13533
|
//
// DragSelectCollectionView.swift
// DragSelectCollectionView
//
// Created by Haskel Ash on 9/9/16.
// Copyright © 2016 Haskel Ash. All rights reserved.
//
import UIKit
/**
A `UICollectionView` subclass that enables contiuous selection of cells while dragging.
Use this class as you would use a regular instance of `UICollectionView`, i.e. with a
`UICollectionViewDataSource` and a `UICollectionViewDelegate`. Call `beginDragSelection(at:)` when
you want to start a continuous selection event starting at a particular `IndexPath`. Throughout the selection
process, this class will ask its `delegate` if it should select / deselect each cell it encounters.
*/
public class DragSelectCollectionView: UICollectionView {
//MARK: Public Properties
/**
Sets a maximum number of cells that may be selected, `nil` by default.
Setting this value to a value of `0` or lower effectively disables selection.
Setting this value to `nil` removes any upper limit to selection.
If when setting a new value, the collection view already has a greater number
of cells selected, then the apporpriate number of cells will be deselected from the end of the list.
*/
public var selectionLimit: Int? {
get {
return selectionManager.maxSelectionCount
}
set {
selectionManager.maxSelectionCount = newValue
}
}
/**
Height of top and bottom hotspots for auto scrolling.
Defaults to `100`. Set this to `0` to disable auto scrolling.
*/
public var hotspotHeight: CGFloat = 100 {
didSet { updateHotspotViews() }
}
///Padding between top of collection view and top hotspot. Defaults to `0`.
public var hotspotOffsetTop: CGFloat = 0 {
didSet { updateHotspotViews() }
}
///Padding between bottom of collection view and bottom hotspot. Defaults to `0`.
public var hotspotOffsetBottom: CGFloat = 0 {
didSet { updateHotspotViews() }
}
/**
Used to calculate auto scroll speed. Defaults to `0.5`.
Auto scroll speed is calculated as `baseAutoScrollVelocity` times however many points
into the hotspot the user has touched, per `0.025` seconds. For example, if the user has
traversed `5` points from the middle of the screen into either of the hotspot, and this value is `0.5`,
then the velocity will be `0.5 * 5 / 0.025 = 100` points/second.
*/
public var baseAutoScrollVelocity: CGFloat = 0.5
/// :nodoc:
public override var bounds: CGRect {
didSet {
updateHotspotViews()
}
}
///Toggles selection and scrolling information output to console. Defaults to `false`.
public static var logging = false
/**
Toggles whether to show a faded green view where the hotspots are.
Defaults to `false`. Useful for debugging.
*/
public var showHotspots = false { didSet {
if showHotspots {
if oldValue == true { return }
updateHotspotViews()
addSubview(hotspotTopView)
addSubview(hotspotBottomView)
} else {
if oldValue == false { return }
hotspotTopView.removeFromSuperview()
hotspotBottomView.removeFromSuperview()
}
}}
//MARK: Public Methods
/// :nodoc:
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
selectionManager = DragSelectionManager(collectionView: self)
allowsMultipleSelection = true
}
/// :nodoc:
public override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
super.init(frame: frame, collectionViewLayout: layout)
selectionManager = DragSelectionManager(collectionView: self)
allowsMultipleSelection = true
}
/**
Attempts to begin drag selection at the provided index path.
- Parameter selection: the index path at which to begin drag selection.
- Returns: `false` if drag selection is alreay in progress or `selection` cannot
be selected (decided by the `UICollectionViewDelegate`), `true` otherwise.
*/
@discardableResult public func beginDragSelection(at selection: IndexPath) -> Bool {
if dragSelectActive {
DragSelectCollectionView.LOG("Drag selection is already active.")
return false
}
//negative hotspotHeight denotes no hotspots, skip this part
if hotspotHeight > -1 {
DragSelectCollectionView.LOG("CollectionView height = %0.2f",
args: bounds.size.height)
DragSelectCollectionView.LOG("Hotspot top bound = %0.2f to %0.2f",
args: hotspotTopBoundStart, hotspotTopBoundEnd)
DragSelectCollectionView.LOG("Hotspot bottom bound = %0.2f to %0.2f",
args: hotspotBottomBoundStart, hotspotBottomBoundEnd)
if showHotspots {
setNeedsDisplay()
}
}
//if initial selection can't be selected, don't start drag selecting
if delegate?.collectionView?(self, shouldSelectItemAt: selection) == false {
dragSelectActive = false
initialSelection = nilIndexPath
lastDraggedIndex = nilIndexPath
minReached = nilIndexPath
maxReached = nilIndexPath
DragSelectCollectionView.LOG("Index [%i, %i] is not selectable.",
args: selection.section, selection.item)
return false
}
//all good - start drag selecting
selectionManager.setSelected(true, for: selection)
dragSelectActive = true
initialSelection = selection
lastDraggedIndex = selection
minReached = selection
maxReached = selection
DragSelectCollectionView.LOG("Drag selection initialized, starting at index [%i, %i].",
args: selection.section, selection.item)
return true
}
/// :nodoc:
public override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesMoved(touches, with: event)
if !dragSelectActive { return }
guard let pointInBounds = event?.allTouches?.first?.location(in: self) else { return }
let point = CGPoint(x: pointInBounds.x, y: pointInBounds.y - contentOffset.y)
let pathAtPoint = getItemAtPosition(point: pointInBounds)
// Check for auto-scroll hotspot
if (hotspotHeight > -1) {
if point.y >= hotspotTopBoundStart && point.y <= hotspotTopBoundEnd {
inBottomHotspot = false
if !inTopHotspot {
inTopHotspot = true
DragSelectCollectionView.LOG("Now in TOP hotspot")
autoScrollTimer.invalidate()
autoScrollTimer = Timer.scheduledTimer(
timeInterval: autoScrollDelay,
target: self, selector: #selector(autoScroll),
userInfo: nil, repeats: true)
}
autoScrollVelocity = baseAutoScrollVelocity * (hotspotTopBoundEnd - point.y)
DragSelectCollectionView.LOG("Auto scroll velocity = %0.2f", args: autoScrollVelocity)
} else if point.y >= hotspotBottomBoundStart && point.y <= hotspotBottomBoundEnd {
inTopHotspot = false
if !inBottomHotspot {
inBottomHotspot = true
DragSelectCollectionView.LOG("Now in BOTTOM hotspot")
autoScrollTimer.invalidate()
autoScrollTimer = Timer.scheduledTimer(
timeInterval: autoScrollDelay,
target: self, selector: #selector(autoScroll),
userInfo: nil, repeats: true)
}
autoScrollVelocity = baseAutoScrollVelocity * (point.y - hotspotBottomBoundStart)
DragSelectCollectionView.LOG("Auto scroll velocity = %0.2f", args: autoScrollVelocity)
} else if inTopHotspot || inBottomHotspot {
DragSelectCollectionView.LOG("Left the hotspot")
autoScrollTimer.invalidate()
inTopHotspot = false
inBottomHotspot = false
}
}
// Drag selection logic
if pathAtPoint != nilIndexPath && pathAtPoint != lastDraggedIndex {
lastDraggedIndex = pathAtPoint
maxReached = max(maxReached, lastDraggedIndex)
minReached = min(minReached, lastDraggedIndex)
selectionManager.selectRange(
from: initialSelection,
to: lastDraggedIndex,
min: minReached,
max: maxReached)
DragSelectCollectionView.LOG(
"Selecting from: [%i, %i], to: [%i, %i], min: [%i, %i], max: [%i, %i]",
args: initialSelection.section, initialSelection.item,
lastDraggedIndex.section, lastDraggedIndex.item,
minReached.section, minReached.item,
maxReached.section, maxReached.item)
if initialSelection == lastDraggedIndex {
minReached = initialSelection
maxReached = initialSelection
}
}
}
/// :nodoc:
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
if !dragSelectActive { return }
//edge case - if user drags back to initial selection, keep that selected
//it gets deselected by super.touchesEnded() above
if initialSelection == lastDraggedIndex {
selectionManager.setSelected(true, for: initialSelection)
}
dragSelectActive = false
inTopHotspot = false
inBottomHotspot = false
autoScrollTimer.invalidate()
}
/**
Attempts to select all items, starting from the first item in the collection.
If an item cannot be selected (decided by the `UICollectionViewDelegate`), the item is skipped.
If `selectionLimit` is reached, this method terminates.
The `collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath)`
method of the `UICollectionViewDelegate` is called for each selected item.
*/
public func selectAll() {
selectionManager.selectAll()
}
/**
Deselects all selected items.
The `collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath)`
method of the `UICollectionViewDelegate` is called for each deselected item.
*/
public func deselectAll() {
selectionManager.deselectAll()
}
//MARK: PRIVATE PROPERTIES
private var selectionManager: DragSelectionManager!
private var dragSelectActive = false
private var nilIndexPath = IndexPath(item: -1, section: -1)
private var initialSelection = IndexPath(item: -1, section: -1)
private var lastDraggedIndex = IndexPath(item: -1, section: -1)
private var minReached = IndexPath(item: -1, section: -1)
private var maxReached = IndexPath(item: -1, section: -1)
private var autoScrollTimer = Timer()
private var autoScrollVelocity: CGFloat = 0
private let autoScrollDelay: TimeInterval = 0.025
private var inTopHotspot = false
private var inBottomHotspot = false
private var hotspotTopBoundStart: CGFloat {
get {
return hotspotOffsetTop
}
}
private var hotspotTopBoundEnd: CGFloat {
get {
return hotspotOffsetTop + hotspotHeight
}
}
private var hotspotBottomBoundStart: CGFloat {
get {
return bounds.size.height - hotspotOffsetBottom - hotspotHeight
}
}
private var hotspotBottomBoundEnd: CGFloat {
get {
return bounds.size.height - hotspotOffsetBottom
}
}
//MARK: PRIVATE METHODS
private static func LOG(_ message: String, args: CVarArg...) {
if !logging { return }
print("DragSelectCollectionView, " + String(format: message, arguments: args))
}
private func getItemAtPosition(point: CGPoint) -> IndexPath {
let path = indexPathForItem(at: point)
return path ?? nilIndexPath
}
@objc private func autoScroll() {
if !autoScrollTimer.isValid { return }
if inTopHotspot {
contentOffset.y -= autoScrollVelocity
} else if inBottomHotspot {
contentOffset.y += autoScrollVelocity
}
contentOffset.y = max(min(contentOffset.y, self.contentSize.height - self.bounds.size.height), 0)
}
//MARK: HOTSPOT DEBUGGING
private var hotspotTopView = DragSelectCollectionView.newHotspotView()
private var hotspotBottomView = DragSelectCollectionView.newHotspotView()
private class func newHotspotView() -> UIView {
let view = UIView()
view.backgroundColor = UIColor.green
view.alpha = 0.5
return view
}
private func updateHotspotViews() {
hotspotTopView.frame = CGRect(x: 0, y: contentOffset.y+hotspotTopBoundStart, width: bounds.width, height: hotspotHeight)
hotspotBottomView.frame = CGRect(x: 0, y: contentOffset.y+hotspotBottomBoundStart, width: bounds.width, height: hotspotHeight)
}
}
|
mit
|
41802fb8844906750132e190b13f390f
| 37.885057 | 134 | 0.632353 | 4.998892 | false | false | false | false |
roger-tan/FoodTracker
|
FoodTracker/AppDelegate.swift
|
1
|
4558
|
//
// AppDelegate.swift
// FoodTracker
//
// Created by Roger TAN on 5/1/17.
// Copyright © 2017 Roger TAN. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "FoodTracker")
container.loadPersistentStores(completionHandler: { (_, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
mit
|
0dbefac8558e8bb6e8798b60e7f957ad
| 49.076923 | 285 | 0.687294 | 5.819923 | false | false | false | false |
peferron/algo
|
EPI/Searching/Find the min and max simultaneously/swift/main.swift
|
1
|
622
|
public func minMax<T: Comparable>(_ elements: [T]) -> (min: T, max: T) {
var result = (min: elements[0], max: elements[0])
for i in stride(from: 1, to: elements.count, by: 2) {
let pair: (min: T, max: T)
if i == elements.count - 1 {
pair = (min: elements[i], max: elements[i])
} else if elements[i] < elements[i + 1] {
pair = (min: elements[i], max: elements[i + 1])
} else {
pair = (min: elements[i + 1], max: elements[i])
}
result = (min: min(result.min, pair.min), max: max(result.max, pair.max))
}
return result
}
|
mit
|
9b70ff1ec64db5d1b7842e74d88649bd
| 31.736842 | 81 | 0.516077 | 3.189744 | false | false | false | false |
TheHolyGrail/Historian
|
ELCache/URLCache.swift
|
2
|
5744
|
//
// URLCache.swift
// ELCache
//
// Created by Sam Grover on 12/7/15.
// Copyright © 2015 WalmartLabs. All rights reserved.
//
import Foundation
import ELWebService
public typealias FetchURLCompletionClosure = (MemoryCacheable?, NSError?) -> Void
@objc
public class URLCache: NSObject {
internal var activeServiceTasks: [String: ServiceTask]
internal let memoryCache = MemoryCache.sharedMemoryCache
public static let sharedURLCache = URLCache()
override init() {
activeServiceTasks = [String: ServiceTask]()
super.init()
}
/// Cleans out from storage the entire shared URL cache managed by `NSURLCache`
public func flushStorageCache() {
NSURLCache.sharedURLCache().removeAllCachedResponses()
}
/// Cleans out the memory cache
public func flushMemoryCache() {
memoryCache.flush()
}
/// Cleans out both memory cache and storage cache. Basically calls `flushMemoryCache` and `flushStorageCache`.
public func flushCache() {
memoryCache.flush()
flushStorageCache()
}
/**
Fetches the resource at the URL. If it has been fetched before, its validity is checked in storage cache.
Looks at memory cache, storage cache, and goes out to network if not found in those two.
- parameter URL: The URL being fetched.
- parameter cacheOnly: If `true`, then only look in cache. Defaults to `false`.
- parameter completion: The completion block to call with the results of the fetch.
*/
public func fetch(URL: NSURL, cacheOnly: Bool = false, completion: FetchURLCompletionClosure) {
var found = false
let valid = validInCache(URL)
if valid {
found = fetchFromMemory(URL, completion: completion)
if !found {
found = fetchFromStorage(URL, completion: completion)
}
}
if !found {
if cacheOnly {
// TODO: Insert proper error
completion(nil, nil)
} else {
fetchFromNetwork(URL, completion: completion)
}
}
}
/// Checks if the resource at the URL exists and is valid in cache.
public func validInCache(URL: NSURL) -> Bool {
return fetchFromStorage(URL) {_,_ in }
}
/// Returns `true` is the URL is being fetched from the network, `false` otherwise.
public func isNetworkFetching(URL: NSURL) -> Bool {
return activeServiceTasks[URL.absoluteString] != nil
}
/// Cancels the network fetch of a URL if it is currently in progress.
public func cancelFetch(URL: NSURL) {
if let aTask = self.activeServiceTasks.removeValueForKey(URL.absoluteString) {
aTask.cancel()
}
}
/// Remove the URL from memory and storage cache, cancelling any ongoing fetches if necessary.
public func remove(URL: NSURL) {
cancelFetch(URL)
memoryCache.remove(URL.absoluteString)
NSURLCache.sharedURLCache().removeCachedResponseForRequest(NSURLRequest(URL: URL))
}
func fetchFromMemory(URL: NSURL, completion: FetchURLCompletionClosure) -> Bool {
if let resource = memoryCache.fetch(URL.absoluteString) {
completion(resource, nil)
return true
}
return false
}
func fetchFromStorage(URL: NSURL, completion: FetchURLCompletionClosure) -> Bool {
var success = false
let request = NSURLRequest(URL: URL)
if let cachedResponse = NSURLCache.sharedURLCache().validCachedResponseForRequest(request, timeToLive: 60, removeIfInvalid: true) {
didFetch(cachedResponse.data, URL: URL, error: nil, completion: completion)
success = true
}
return success
}
func fetchFromNetwork(URL: NSURL, completion: FetchURLCompletionClosure) {
let aTask = WebService(baseURLString: "").GET(URL.absoluteString)
activeServiceTasks[URL.absoluteString] = aTask
var error: NSError? = nil
aTask
.response { (data: NSData?, response: NSURLResponse?) -> ServiceTaskResult in
self.activeServiceTasks.removeValueForKey(URL.absoluteString)
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode >= 400 {
error = NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: nil)
}
if let data = data {
self.didFetch(data, URL: URL, error: error, completion: completion)
}
}
return .Empty
}
.responseError {_ in
let error = NSError(domain: NSURLErrorDomain, code: NSURLErrorBadURL, userInfo: nil)
self.didFetch(nil, URL: URL, error: error, completion: completion)
}
.resume()
}
// Called when something is fetched from storage or network so that it can be added to the memory cache
func didFetch(data: NSData?, URL: NSURL, error: NSError?, completion: FetchURLCompletionClosure) {
if let data = data {
if let imageFromData = UIImage(data: data) {
if let finalImage = UIImage.decompressed(imageFromData) {
memoryCache.store(finalImage, key: URL.absoluteString)
completion(finalImage, error)
}
} else {
memoryCache.store(data, key: URL.absoluteString)
completion(data, error)
}
}
}
}
|
mit
|
6732ccda8574be377eeab6c5a7d4fc9d
| 35.348101 | 139 | 0.607522 | 5.123104 | false | true | false | false |
nineteen-apps/themify
|
Sources/Color+Extension.swift
|
1
|
4720
|
// -*-swift-*-
// The MIT License (MIT)
//
// Copyright (c) 2017 - Nineteen
//
// 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.
//
// Created: 2017-04-17 by Ronaldo Faria Lima
// This file purpose: Convenience extension for UIColor class
import Foundation
import UIKit
// MARK: - UIColor Extension
extension UIColor {
typealias ColorComponents = (red: CGFloat, green: CGFloat, blue: CGFloat, alpha: CGFloat)
enum ColorType: Int {
case fullRgb = 6
case rgb = 3
case fullRgba = 8
case rgba = 4
}
/// Creates a UIColor based on a string hexadecimal RGB value.
///
/// - Parameters:
/// - hex: hexadecimal string
/// - alpha: alpha for the new color. 1.0 is full opaque, 0.0 is full transparent.
convenience init?(hex: String, alpha: CGFloat) {
if let colorComps = UIColor.colorComponents(from: hex) {
self.init(red: colorComps.red, green: colorComps.green, blue: colorComps.blue, alpha: alpha)
return
}
return nil
}
/// Creates a UIColor based on a RGB or RGBA hexadecimal values
///
/// - Parameters:
/// - hex: hexadecimal string containing RGB or RGBA on complete or simple representations
convenience init?(hex: String) {
if let colorComps = UIColor.colorComponents(from: hex) {
self.init(red: colorComps.red, green: colorComps.green, blue: colorComps.blue, alpha: colorComps.alpha)
return
}
return nil
}
/// Do the heavy lifting of parsing an hex string
///
/// - Parameters:
/// - hexString: String containing both RGB or RGBA strings, on both simple or complete form.
/// - Returns:
/// - A tuple of color components on success
/// - nil if provided hex string is invalid
fileprivate static func colorComponents(from hexString: String) -> ColorComponents? {
var components = ColorComponents(0, 0, 0, CGFloat(0xff))
var rawHex = hexString
if let i = hexString.index(of: "#") {
rawHex = String(hexString[hexString.index(i, offsetBy: 1)..<hexString.endIndex])
}
let colorType = ColorType(rawValue: rawHex.count)
if colorType == nil {
// Invalid hex value provided
return nil
}
let scanner = Scanner(string: rawHex)
var rgba = UInt64(0)
scanner.scanHexInt64(&rgba)
switch colorType! {
case .fullRgb:
components.red = CGFloat((rgba >> 0x10) & 0xff)
components.green = CGFloat((rgba >> 0x8) & 0xff)
components.blue = CGFloat(rgba & 0xff)
case .rgb:
components.red = CGFloat(rgba >> 0x8 | (rgba & 0xf00) >> 0x4)
components.green = CGFloat((rgba & 0xf0) | (rgba & 0xf0) >> 0x4)
components.blue = CGFloat((rgba & 0xf) | (rgba & 0xf) << 0x4)
case .fullRgba:
components.red = CGFloat(rgba >> 0x18)
components.green = CGFloat((rgba >> 0x10) & 0xff)
components.blue = CGFloat((rgba >> 0x8) & 0xff)
components.alpha = CGFloat(rgba & 0xff)
case .rgba:
components.red = CGFloat((rgba & 0xf000) >> 0x8 | (rgba & 0xf000) >> 0xC)
components.green = CGFloat((rgba & 0xf00) >> 0x4 | (rgba & 0xf00) >> 0x8)
components.blue = CGFloat(rgba & 0xf0 | (rgba & 0xf0) >> 0x4)
components.alpha = CGFloat(rgba & 0xf | (rgba & 0xf) << 0x4)
}
components.red /= CGFloat(0xff)
components.green /= CGFloat(0xff)
components.blue /= CGFloat(0xff)
components.alpha /= CGFloat(0xff)
return components
}
}
|
mit
|
c8929e8c7a33caefd591c6b8a64a35a4
| 40.769912 | 115 | 0.629449 | 4.115083 | false | false | false | false |
benjaminsnorris/SharedHelpers
|
Sources/UIViewController+TopMost.swift
|
1
|
1220
|
/*
| _ ____ ____ _
| | |‾| ⚈ |-| ⚈ |‾| |
| | | ‾‾‾‾| |‾‾‾‾ | |
| ‾ ‾ ‾
*/
import UIKit
extension UIViewController {
@objc open var topMostViewController: UIViewController {
if presentedViewController == nil {
return self
}
if let navigation = presentedViewController as? UINavigationController {
if let visible = navigation.visibleViewController {
return visible.topMostViewController
}
if let top = navigation.topViewController {
return top.topMostViewController
}
return navigation.topMostViewController
}
if let tab = presentedViewController as? UITabBarController {
if let selectedTab = tab.selectedViewController {
return selectedTab.topMostViewController
}
return tab.topMostViewController
}
return presentedViewController!.topMostViewController
}
}
public extension UIApplication {
var topMostViewController: UIViewController? {
return keyWindow?.rootViewController?.topMostViewController
}
}
|
mit
|
61aa4592464e610b62164b31fa2e7538
| 27.333333 | 80 | 0.584034 | 6.197917 | false | false | false | false |
josmas/swiftFizzBuzz
|
FizzBuzzTests/ViewControllerUnitTests.swift
|
1
|
1394
|
//
// ViewControllerUnitTests.swift
// FizzBuzz
//
// Created by Jose Dominguez on 16/01/2016.
// Copyright © 2016 Jos. All rights reserved.
//
import XCTest
@testable import FizzBuzz
class ViewControllerUnitTests: XCTestCase {
var viewController : ViewController!
var game = Game()
override func setUp() {
super.setUp()
let storyboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
viewController = storyboard.instantiateViewControllerWithIdentifier("ViewController") as! ViewController
UIApplication.sharedApplication().keyWindow!.rootViewController = viewController
let _ = viewController.view
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testHasAGame() {
XCTAssertNotNil(viewController.game)
}
func testPlayShouldReturnIfMoveRight() {
let response = game.play(Move.Number)
XCTAssertNotNil(response.right)
}
func testPlayShouldReturnNewScore() {
let response = game.play(Move.Number)
XCTAssertNotNil(response.score)
}
func testOnWrongMoveScoreNotIncremented() {
viewController.play(Move.Fizz)
let newScore = viewController.gameScore
XCTAssertEqual(newScore, 0)
}
}
|
mit
|
e5d8b88a661f44906cc05e20c1eb2d3a
| 25.788462 | 112 | 0.681263 | 4.90493 | false | true | false | false |
JohnEstropia/CoreStore
|
Sources/CoreStoreManagedObject.swift
|
1
|
2259
|
//
// CoreStoreManagedObject.swift
// CoreStore
//
// Copyright © 2018 John Rommel Estropia
//
// 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 CoreData
import Foundation
// MARK: - CoreStoreManagedObject
@objc internal class CoreStoreManagedObject: NSManagedObject {
internal typealias CustomGetter = @convention(block) (_ rawObject: Any) -> Any?
internal typealias CustomSetter = @convention(block) (_ rawObject: Any, _ newValue: Any?) -> Void
internal typealias CustomInitializer = @convention(block) (_ rawObject: Any) -> Void
internal typealias CustomGetterSetter = (getter: CustomGetter?, setter: CustomSetter?)
@nonobjc @inline(__always)
internal static func cs_subclassName(for entity: DynamicEntity, in modelVersion: ModelVersion) -> String {
return "_\(NSStringFromClass(CoreStoreManagedObject.self))__\(modelVersion)__\(NSStringFromClass(entity.type))__\(entity.entityName)"
}
}
// MARK: - Private
private enum Static {
static let queue = DispatchQueue.concurrent("com.coreStore.coreStoreManagerObjectBarrierQueue", qos: .userInteractive)
static var cache: [ObjectIdentifier: [KeyPathString: Set<KeyPathString>]] = [:]
}
|
mit
|
6cf9e2afc4f3e6abccc01af1ca4bd3bf
| 41.603774 | 141 | 0.737821 | 4.617587 | false | false | false | false |
sigmonky/hearthechanges
|
iHearChangesSwift/User Interface/InfoViewController.swift
|
1
|
1547
|
//
// InfoViewController.swift
// iHearChangesSwift
//
// Created by Weinstein, Randy - Nick.com on 6/26/17.
// Copyright © 2017 fakeancient. All rights reserved.
//
import UIKit
class InfoViewController: UIViewController {
var infoText:String = ""
@IBOutlet weak var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
//textView.text = infoText
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func updateInfo() {
//textView.text = infoText
if let rtfPath = Bundle.main.url(forResource: infoText, withExtension: "rtf") {
do {
let attributedStringWithRtf = try NSAttributedString(url: rtfPath, options: [NSDocumentTypeDocumentAttribute:NSRTFTextDocumentType], documentAttributes: nil)
textView.attributedText = attributedStringWithRtf
} catch {
print("No rtf content found!")
}
}
}
/*
// 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.
}
*/
}
|
mit
|
7629a42c97269acafd9fe78b5133e6c8
| 27.109091 | 173 | 0.633894 | 4.987097 | false | false | false | false |
jotaninwater/yeahbuoy
|
YeahBuoy/Settings.swift
|
1
|
818
|
//
// Settings.swift
// YeahBuoy
//
// Created by Jonathan on 7/16/16.
// Copyright © 2016 Jonathan Domasig. All rights reserved.
//
import Foundation
// TODO: Make this persistent
class Settings {
static let instance:Settings = Settings() // Our singleton
var latitude:String = "40N"
var longitude:String = "73W"
var radius:Int = 100
var modified:Bool = false // Keep track if the settings is modified so we dont have to resync.
private var base_url:String = "http://www.ndbc.noaa.gov/rss/ndbc_obs_search.php?"
func getFeedUrl() -> String {
// Build our url.
// TODO: Do validation on the values.
let retUrl = "\(self.base_url)lat=\(self.latitude)&lon=\(self.longitude)&radius=\(self.radius)"
return retUrl
}
}
|
gpl-3.0
|
63c9bb1f979c8ca5f294f036b77ec105
| 27.206897 | 104 | 0.625459 | 3.696833 | false | false | false | false |
nifti/CinchKit
|
CinchKit/Serializers/PollsResponseSerializer.swift
|
1
|
17936
|
//
// PollsResponseSerializer.swift
// CinchKit
//
// Created by Ryan Fitzgerald on 2/12/15.
// Copyright (c) 2015 cinch. All rights reserved.
//
import Foundation
import SwiftyJSON
class PollsResponseSerializer : JSONObjectSerializer {
let accountsSerializer = AccountsSerializer()
let linkSerializer = LinksSerializer()
let commentsSerializer = CommentsSerializer()
func jsonToObject(json: SwiftyJSON.JSON) -> CNHPollsResponse? {
return self.parseResponse(json)
}
func parseResponse(json : JSON) -> CNHPollsResponse? {
let polls = self.parsePollsResponse(json)
var nextLink : CNHApiLink?
if let href = json["links"]["next"].URL {
nextLink = CNHApiLink(id: nil, href: href, type: "polls")
}
let selfLink = CNHApiLink(id: nil, href: json["links"]["self"].URL!, type: "polls")
return CNHPollsResponse(selfLink : selfLink, nextLink : nextLink, polls: polls)
}
func parsePollsResponse(json : JSON) -> [CNHPoll]? {
var accountIndex : [String : CNHAccount]?
if let accounts = accountsSerializer.jsonToObject(json["linked"]["accounts"]) {
accountIndex = self.indexById(accounts)
}
return json["discussions"].array?.map { self.decodePoll(accountIndex, json: $0) }
}
func decodePoll(accounts : [String : CNHAccount]?, json : JSON) -> CNHPoll {
var candidates = json["candidates"].array?.map(self.decodeCandidate)
var account : CNHAccount?
if let authorId = json["links"]["author"]["id"].string {
account = accounts?[authorId]
}
let links = linkSerializer.jsonToObject(json["links"])
let comments = commentsSerializer.jsonToObject(json["recentComments"])
if candidates == nil {
candidates = []
}
let displayAt : NSDate
if let displayStr = json["displayAt"].string {
displayAt = CinchKitDateTools.dateFromISOString(displayStr)
} else {
displayAt = CinchKitDateTools.dateFromISOString(json["created"].stringValue)
}
// -----
var recentVoters = [CNHAccount]()
if let accs = accounts, let arr = json["recentVoters"].array {
for acc in arr {
if let voter = accs[acc.stringValue] {
recentVoters.append(voter)
}
}
}
// -----
return CNHPoll(
id: json["id"].stringValue,
href : json["href"].stringValue,
topic : json["topic"].stringValue,
type : json["type"].stringValue,
shortLink : json["shortLink"].URL,
votesTotal : json["votesTotal"].intValue,
messagesTotal : json["messagesTotal"].intValue,
isPublic : json["public"].boolValue,
categoryId: json["category"].stringValue,
created : CinchKitDateTools.dateFromISOString(json["created"].stringValue),
updated : CinchKitDateTools.dateFromISOString(json["updated"].stringValue),
displayAt : displayAt,
author : account,
candidates : candidates!,
comments : comments,
links : links,
recentVoters : recentVoters
)
}
func decodeCandidate(json : JSON) -> CNHPollCandidate {
var images : [PictureVersion : NSURL]?
if let imgArray = json["images"].array {
images = self.decodePollImages(imgArray)
}
return CNHPollCandidate(
id: json["id"].stringValue,
href : json["href"].stringValue,
image : json["image"].stringValue,
votes : json["votes"].intValue,
created : CinchKitDateTools.dateFromISOString(json["created"].stringValue),
voters : json["voters"].array?.map({ $0.stringValue }),
type : json["type"].stringValue,
option : json["option"].string,
images : images
)
}
private func decodePollImages(images : [JSON]) -> [PictureVersion : NSURL] {
return images.reduce([PictureVersion : NSURL](), combine: { (memo, json) -> [PictureVersion : NSURL] in
var result = memo
if let url = json["url"].URL {
if let version = PictureVersion(rawValue: json["name"].stringValue) {
result[version] = url
}
}
return result
})
}
internal func indexById(data : [CNHAccount]) -> [String : CNHAccount] {
var result = [String : CNHAccount]()
for item in data {
result[item.id] = item
}
return result
}
}
class PollVotesSerializer : JSONObjectSerializer {
let accountsSerializer = AccountsSerializer()
func jsonToObject(json: SwiftyJSON.JSON) -> CNHVotesResponse? {
var nextLink : CNHApiLink?
if let href = json["links"]["next"].URL {
nextLink = CNHApiLink(id: nil, href: href, type: "votes")
}
let selfLink = CNHApiLink(id: nil, href: json["links"]["self"].URL!, type: "votes")
let votes = json["votes"].array?.map(self.decodeVote)
return CNHVotesResponse(selfLink : selfLink, nextLink : nextLink, votes : votes)
}
private func decodeVote(json : JSON) -> CNHVote {
let account = accountsSerializer.decodeAccount(json["account"])
return CNHVote(
id: json["photoId"].string,
photoURL: json["photoURL"].URL,
created : CinchKitDateTools.dateFromISOString(json["created"].stringValue),
updated : CinchKitDateTools.dateFromISOString(json["updated"].stringValue),
account : account
)
}
}
class FollowersSerializer : JSONObjectSerializer {
let accountsSerializer = AccountsSerializer()
func jsonToObject(json: SwiftyJSON.JSON) -> CNHFollowersResponse? {
var nextLink : CNHApiLink?
if let href = json["links"]["next"].URL {
nextLink = CNHApiLink(id: nil, href: href, type: "followers")
}
let selfLink = CNHApiLink(id: nil, href: json["links"]["self"].URL!, type: "followers")
let accounts = accountsSerializer.jsonToObject(json["accounts"])
return CNHFollowersResponse(selfLink : selfLink, nextLink : nextLink, followers : accounts)
}
}
class CommentsSerializer : JSONObjectSerializer {
let accountsSerializer = AccountsSerializer()
let linkSerializer = LinksSerializer()
func jsonToObject(json: SwiftyJSON.JSON) -> [CNHComment]? {
return json.array?.map(self.decodeComment)
}
func decodeComment(json : JSON) -> CNHComment {
let author = accountsSerializer.decodeAccount(json["author"])
let type : CNHCommentType
if let t = CNHCommentType(rawValue: json["type"].stringValue) {
type = t
} else {
type = CNHCommentType.Comment
}
let links = linkSerializer.jsonToObject(json["links"])
return CNHComment(
id: json["id"].stringValue,
href: json["href"].URL!,
created :CinchKitDateTools.dateFromISOString(json["created"].stringValue),
message : json["message"].stringValue,
author : author,
type : type,
links : links
)
}
}
class CommentsResponseSerializer : JSONObjectSerializer {
let commentsSerializer = CommentsSerializer()
func jsonToObject(json: SwiftyJSON.JSON) -> CNHCommentsResponse? {
var nextLink : CNHApiLink?
if let href = json["links"]["next"].URL {
nextLink = CNHApiLink(id: nil, href: href, type: "comments")
}
let selfLink = CNHApiLink(id: nil, href: json["links"]["self"].URL!, type: "comments")
let comments = commentsSerializer.jsonToObject(json["messages"])
return CNHCommentsResponse(selfLink : selfLink, nextLink : nextLink, comments : comments)
}
}
class NotificationsResponseSerializer : JSONObjectSerializer {
let accountsSerializer = AccountsSerializer()
let pollsSerializer = PollsResponseSerializer()
let categoriesSerializer = CategoriesSerializer()
func jsonToObject(json: SwiftyJSON.JSON) -> CNHNotificationsResponse? {
var nextLink : CNHApiLink?
if let href = json["links"]["next"].URL {
nextLink = CNHApiLink(id: nil, href: href, type: "notifications")
}
let selfLink = CNHApiLink(id: nil, href: json["links"]["self"].URL!, type: "notifications")
var accountIndex : [String : CNHAccount]?
if let accounts = accountsSerializer.jsonToObject(json["linked"]["accounts"]) {
accountIndex = self.indexById(accounts)
}
var pollIndex : [String : CNHPoll]?
if let polls = json["linked"]["polls"].array?.map( { self.pollsSerializer.decodePoll(accountIndex, json: $0) } ) {
pollIndex = self.indexById(polls)
}
var categoryIndex : [String : CNHCategory]?
if let categories = categoriesSerializer.jsonToObject(json["linked"]) {
categoryIndex = self.indexById(categories)
}
let notifications = json["notifications"].array?.map {
self.decodeNotification(accountIndex, polls : pollIndex, categories: categoryIndex, json: $0)
}
return CNHNotificationsResponse(selfLink : selfLink, nextLink : nextLink, notifications : notifications)
}
func decodeNotification(accounts : [String : CNHAccount]?, polls : [String : CNHPoll]?, categories : [String : CNHCategory]?, json : JSON) -> CNHNotification {
var senderAccount : CNHAccount?
var recipientAccount : CNHAccount?
var resourcePoll : CNHPoll?
var resourceAccount : CNHAccount?
var resourceCategory : CNHCategory?
var extraCategory : CNHCategory?
var extraCandidate : CNHPollCandidate?
var extraAccount : CNHAccount?
if let acc = accounts?[json["senderId"].stringValue] {
senderAccount = acc
}
if let acc = accounts?[json["recipientId"].stringValue] {
recipientAccount = acc
}
if json["resourceType"].stringValue == "poll", let poll = polls?[json["resourceId"].stringValue] {
resourcePoll = poll
if let extra = json["extra"].dictionaryObject, let candId = extra["candidateId"] as? String {
for candidate in poll.candidates {
if candidate.id == candId {
extraCandidate = candidate
}
}
}
} else if json["resourceType"].stringValue == "account", let acc = accounts?[json["resourceId"].stringValue] {
resourceAccount = acc
} else if json["resourceType"].stringValue == "category", let cat = categories?[json["resourceId"].stringValue] {
resourceCategory = cat
}
if let extra = json["extra"].dictionaryObject {
if let catId = extra["categoryId"] as? String, let cat = categories?[catId] {
extraCategory = cat
}
if let accId = extra["accountId"] as? String, let acc = accounts?[accId] {
extraAccount = acc
}
}
return CNHNotification(
id: json["id"].stringValue,
href : json["href"].URL!,
created : CinchKitDateTools.dateFromISOString(json["createdAt"].stringValue),
action : json["action"].stringValue,
senderAccount : senderAccount,
recipientAccount : recipientAccount,
resourcePoll : resourcePoll,
resourceAccount : resourceAccount,
resourceCategory : resourceCategory,
extraCategory : extraCategory,
extraCandidate : extraCandidate,
extraAccount : extraAccount
)
}
internal func indexById(data : [CNHAccount]) -> [String : CNHAccount] {
var result = [String : CNHAccount]()
for item in data {
result[item.id] = item
}
return result
}
internal func indexById(data : [CNHPoll]) -> [String : CNHPoll] {
var result = [String : CNHPoll]()
for item in data {
result[item.id] = item
}
return result
}
internal func indexById(data : [CNHCategory]) -> [String : CNHCategory] {
var result = [String : CNHCategory]()
for item in data {
result[item.id] = item
}
return result
}
}
class CategoriesSerializer : JSONObjectSerializer {
let linkSerializer = LinksSerializer()
func jsonToObject(json: SwiftyJSON.JSON) -> [CNHCategory]? {
return json["categories"].array?.map(self.decodeCategory)
}
private func decodeCategory(json : JSON) -> CNHCategory {
let links = linkSerializer.jsonToObject(json["links"])
var icons = [NSURL]()
for iconLink in json["images"].arrayValue {
icons.append(iconLink.URL!)
}
return CNHCategory(
id: json["id"].stringValue,
name: json["name"].stringValue,
hideWhenCreating: json["hideWhenCreating"].boolValue,
links: links,
icons: icons,
position: json["position"].intValue
)
}
}
class PurchaseSerializer: JSONObjectSerializer {
let accountsSerializer = AccountsSerializer()
let pollsSerializer = PollsResponseSerializer()
func jsonToObject(json: SwiftyJSON.JSON) -> CNHPurchase? {
var accountIndex = [String: CNHAccount]()
if let accounts = accountsSerializer.jsonToObject(json["linked"]["accounts"]) {
accountIndex = self.indexById(accounts)
}
var pollIndex = [String: CNHPoll]()
if let polls = json["linked"]["polls"].array?.map({ self.pollsSerializer.decodePoll(accountIndex, json: $0) }) {
pollIndex = self.indexById(polls)
}
return json["purchases"].array?.map({ self.decodePurchase(accountIndex, polls: pollIndex, json: $0) }).first
}
private func decodePurchase(accounts: [String: CNHAccount], polls: [String: CNHPoll], json: JSON) -> CNHPurchase {
var poll: CNHPoll?
let product = CNHPurchaseProduct(rawValue: json["productId"].stringValue)!
let account: CNHAccount = accounts[json["accountId"].stringValue]!
if product == CNHPurchaseProduct.BumpPoll {
poll = polls[json["metadata"]["pollId"].stringValue]
}
return CNHPurchase(
id: json["id"].stringValue,
product: product,
transactionId: json["transactionId"].stringValue,
account: account,
poll: poll
)
}
internal func indexById(data: [CNHAccount]) -> [String: CNHAccount] {
var result = [String: CNHAccount]()
for item in data {
result[item.id] = item
}
return result
}
internal func indexById(data: [CNHPoll]) -> [String: CNHPoll] {
var result = [String: CNHPoll]()
for item in data {
result[item.id] = item
}
return result
}
}
// -----
class LeaderboardSerializer: JSONObjectSerializer {
let accountsSerializer = AccountsSerializer()
func jsonToObject(json: SwiftyJSON.JSON) -> [CNHLeaderAccount]? {
var accountIndex = [String: CNHAccount]()
if let accounts = accountsSerializer.jsonToObject(json["linked"]["accounts"]) {
accountIndex = self.indexById(accounts)
}
return json["leaders"].array?.map({ self.decodeLeader(accountIndex, json: $0) })
}
private func decodeLeader(accounts: [String: CNHAccount], json: JSON) -> CNHLeaderAccount {
return CNHLeaderAccount(
account: accounts[json["id"].stringValue]!,
rank: json["rank"].intValue,
votesTotal: json["votesTotal"].intValue,
movement: CNHLeaderMovement(rawValue: json["movement"].stringValue) ?? CNHLeaderMovement.Up
)
}
internal func indexById(data: [CNHAccount]) -> [String: CNHAccount] {
var result = [String: CNHAccount]()
for item in data {
result[item.id] = item
}
return result
}
}
class LeaderboardResponseSerializer: JSONObjectSerializer {
let leaderboardSerializer = LeaderboardSerializer()
func jsonToObject(json: SwiftyJSON.JSON) -> CNHLeaderboardResponse? {
var nextLink : CNHApiLink?
if let href = json["links"]["next"].URL {
nextLink = CNHApiLink(id: nil, href: href, type: "leaderboard")
}
let selfLink = CNHApiLink(id: nil, href: json["links"]["self"].URL!, type: "leaderboard")
let leaders = leaderboardSerializer.jsonToObject(json)
return CNHLeaderboardResponse(selfLink: selfLink, nextLink: nextLink, leaders: leaders)
}
}
class DeeplinksSerializer : JSONObjectSerializer {
let linkSerializer = LinksSerializer()
func jsonToObject(json: SwiftyJSON.JSON) -> [CNHApiLink]? {
return json.array?.map({ (json: JSON) -> CNHApiLink in
return CNHApiLink(id: nil, href: json.URL!, type: "deeplink")
})
}
}
// -----
class EmptyResponseSerializer : JSONObjectSerializer {
func jsonToObject(json: SwiftyJSON.JSON) -> String? {
return "OK"
}
}
|
mit
|
22ffbc3f4570f0e5c73d9e5951df6bbf
| 32.33829 | 163 | 0.589429 | 4.528149 | false | false | false | false |
taketo1024/SwiftyAlgebra
|
Sources/SwmCore/Extensions/Sequence.swift
|
1
|
3905
|
//
// Sequence.swift
// SwiftyMath
//
// Created by Taketo Sano on 2017/05/19.
// Copyright © 2017年 Taketo Sano. All rights reserved.
//
import Algorithms
public extension Sequence {
@inlinable
var isEmpty: Bool {
anyElement == nil
}
@inlinable
var anyElement: Element? {
first { _ in true }
}
@inlinable
var count: Int {
count { _ in true }
}
@inlinable
func count(where predicate: (Element) -> Bool) -> Int {
self.reduce(into: 0) { (c, x) in
if predicate(x) { c += 1 }
}
}
@inlinable
func exclude(_ isExcluded: (Self.Element) throws -> Bool) rethrows -> [Self.Element] {
try self.filter{ try !isExcluded($0) }
}
func reduce<Result>(_ initialResult: Result, while shouldContinue: (Result, Self.Element) -> Bool, _ nextPartialResult: (Result, Self.Element) throws -> Result) rethrows -> Result {
var res = initialResult
for e in self {
if !shouldContinue(res, e) { break }
res = try nextPartialResult(res, e)
}
return res
}
func reduce<Result>(into initialResult: Result, while shouldContinue: (Result, Self.Element) -> Bool, _ updateAccumulatingResult: (inout Result, Self.Element) throws -> ()) rethrows -> Result {
var res = initialResult
for e in self {
if !shouldContinue(res, e) { break }
try updateAccumulatingResult(&res, e)
}
return res
}
@inlinable
func sorted<C: Comparable>(by indexer: (Element) -> C) -> [Element] {
self.sorted{ (e1, e2) in indexer(e1) < indexer(e2) }
}
@inlinable
func max<C: Comparable>(by indexer: (Element) -> C) -> Element? {
self.max{ (e1, e2) in indexer(e1) < indexer(e2) }
}
@inlinable
func min<C: Comparable>(by indexer: (Element) -> C) -> Element? {
self.min{ (e1, e2) in indexer(e1) < indexer(e2) }
}
@inlinable
func group<U: Hashable>(by keyGenerator: (Element) -> U) -> [U: [Element]] {
Dictionary(grouping: self, by: keyGenerator)
}
func split(by predicate: (Element) -> Bool) -> ([Element], [Element]) {
var T: [Element] = []
var F: [Element] = []
for e in self {
if predicate(e) {
T.append(e)
} else {
F.append(e)
}
}
return (T, F)
}
func toArray() -> [Element] {
Array(self)
}
func toDictionary() -> [Int: Element] {
Dictionary(self.enumerated().map{ (i, a) in (i, a) } )
}
static func *<S: Sequence>(s1: Self, s2: S) -> Product2<Self, S> {
product(s1, s2)
}
}
public extension Sequence where Element: Hashable {
var isUnique: Bool {
var bucket = Set<Element>()
return self.allSatisfy{ bucket.insert($0).inserted }
}
@available(*, deprecated, message: "use uniqued()")
func unique() -> [Element] {
var bucket = Set<Element>()
return self.filter { bucket.insert($0).inserted }
}
func subtract(_ set: Set<Element>) -> [Element] {
return self.filter{ !set.contains($0) }
}
func isDisjoint<S: Sequence>(with other: S) -> Bool where S.Element == Element {
Set(self).isDisjoint(with: other)
}
func countMultiplicities() -> [Element : Int] {
self.group{ $0 }.mapValues{ $0.count }
}
func makeIndexer() -> (Element) -> Int? {
let dict = Dictionary(self.enumerated().map{ ($1, $0) })
return { dict[$0] }
}
}
public extension Sequence where Element: Comparable {
var closureRange: ClosedRange<Element>? {
if let m = self.min(), let M = self.max() {
return m ... M
} else {
return nil
}
}
}
|
cc0-1.0
|
5ddb59f7ffc091126099f713a5963120
| 26.673759 | 197 | 0.538698 | 3.840551 | false | false | false | false |
SquidKit/SquidKit
|
SquidKit/DispatchTimer.swift
|
1
|
3651
|
//
// DispatchTimer.swift
// SquidKit
//
// Created by Mike Leavy on 9/7/18.
// Copyright © 2018-2019 Squid Store, LLC. All rights reserved.
//
import Foundation
// callback parameters: TimeInterval - the current relative playback time;
// Bool - completed flag - true if a duration has been set by the caller, and the duration has been reached.
public typealias DispatchTimerFiredCallback = (TimeInterval, Bool) -> Void
public class DispatchTimer {
private enum State {
case idle
case running
case paused
}
private var state: State = .idle
private var timer: DispatchSourceTimer!
private var repeatInterval: TimeInterval?
private var deadline: TimeInterval!
private var deadlineReached = false
private var callback: DispatchTimerFiredCallback?
private var isRepeating: Bool {
return repeatInterval != nil
}
public var timeOffset: TimeInterval = 0
public var duration: TimeInterval?
public var isRunning: Bool {
return state == .running
}
public var isIdle: Bool {
return state == .idle
}
deinit {
callback = nil
// timer doesn't like being destructed while in a suspended state, so...
if !isRunning {
start()
}
}
public init(_ deadline: TimeInterval, repeatInterval: TimeInterval?, duration: TimeInterval?, callback: @escaping DispatchTimerFiredCallback) {
self.repeatInterval = repeatInterval
self.duration = duration
self.deadline = deadline
self.callback = callback
timer = DispatchSource.makeTimerSource(flags: .strict, queue: DispatchQueue(label: "com.squidstore.dispatch.timer"))
configure()
}
public func configure() {
guard state == .idle else {return}
deadlineReached = false
timer.setEventHandler { [weak self] in
guard let unwrapped = self else {return}
if !unwrapped.deadlineReached {
unwrapped.deadlineReached = true
unwrapped.timeOffset += unwrapped.deadline
}
else {
unwrapped.timeOffset += unwrapped.repeatInterval ?? 0
}
var completed = false
if let duration = unwrapped.duration {
completed = unwrapped.timeOffset >= duration
}
DispatchQueue.main.async {
unwrapped.callback?(unwrapped.timeOffset, completed)
}
}
}
public func start() {
switch state {
case .idle:
let dispatchDeadline: DispatchTime = DispatchTime.now() + DispatchTimeInterval.milliseconds(Int(deadline * 1000))
if isRepeating {
let dispatchRepeatInterval = DispatchTimeInterval.milliseconds(Int((repeatInterval ?? 0) * 1000))
timer.schedule(deadline: dispatchDeadline, repeating: dispatchRepeatInterval)
}
else {
timer.schedule(deadline: dispatchDeadline)
}
timer.resume()
case .paused:
timer.resume()
case .running:
break
}
state = .running
}
public func pause() {
guard state == .running else {return}
timer.suspend()
state = .paused
}
public func stop() {
switch state {
case .idle, .paused:
break
case .running:
timer.suspend()
}
state = .idle
timeOffset = 0
deadlineReached = false
}
}
|
mit
|
6ddba6f2f6d98f7ca9dc4c901f300b93
| 25.071429 | 147 | 0.585205 | 5.305233 | false | false | false | false |
oisdk/JSONParser
|
JSONParser/FromString.swift
|
1
|
5928
|
func uChr(n: UInt8) -> Character { return Character(UnicodeScalar(n)) }
func uStr(s: [UInt8]) -> String { return String(s.lazy.map(uChr)) }
extension GeneratorType where Element == UInt8 {
private mutating func error(lit lit: String) -> JSONError {
return JSONError.Lit(expecting: lit, found: uStr(peek(5)))
}
private mutating func numError(soFar: [UInt8]) -> JSONError {
return JSONError.Number(uStr(soFar) + uStr(peek(5)))
}
private mutating func closingDelim(soFar: String) -> JSONError {
return JSONError.NoClosingDelimString(soFar: soFar, found: uStr(peek(5)))
}
private mutating func closingDelim(soFar: [JSON]) -> JSONError {
let desc = soFar
.map { i in String(String(i).characters.prefix(5)) + "..."}
.joinWithSeparator("\n ")
return JSONError.NoClosingDelimArray(
soFar: "\n " + desc,
found: uStr(peek(5)))
}
private mutating func closingDelim(soFar: [String:JSON]) -> JSONError {
let desc = soFar
.map { (k,_) in k + ": ..."}
.joinWithSeparator("\n ")
return JSONError.NoClosingDelimObject(
soFar: "\n " + desc,
found: uStr(peek(5))
)
}
}
extension GeneratorType where Element == UInt8 {
private mutating func decodeNull() -> Result<JSON,JSONError> {
guard next() == Code.u else { return .None(error(lit: "null")) }
guard next() == Code.l else { return .None(error(lit: "null")) }
guard next() == Code.l else { return .None(error(lit: "null")) }
return .Some(JSON.null)
}
private mutating func decodeTrue() -> Result<JSON,JSONError> {
guard next() == Code.r else { return .None(error(lit: "true")) }
guard next() == Code.u else { return .None(error(lit: "true")) }
guard next() == Code.e else { return .None(error(lit: "true")) }
return .Some(JSON.JBool(true))
}
private mutating func decodeFalse() -> Result<JSON,JSONError> {
guard next() == Code.a else { return .None(error(lit: "false")) }
guard next() == Code.l else { return .None(error(lit: "false")) }
guard next() == Code.s else { return .None(error(lit: "false")) }
guard next() == Code.e else { return .None(error(lit: "false")) }
return .Some(JSON.JBool(false))
}
private mutating func decodeNum(n: UInt8) -> Result<JSON,JSONError> {
var isDouble = false
var arr: [UInt8] = [n]
while let i = next() {
switch i {
case Code.e, Code.E, Code.fullst:
isDouble = true
fallthrough
case Code.Zero...Code.Nine, Code.plus, Code.hyphen: arr.append(i)
default:
if let n = isDouble ?
Double(uStr(arr)).map(JSON.JFloat) :
Int(uStr(arr)).map(JSON.JInt) {
return .Some(n)
}
return .None(numError(arr))
}
}
return .None(numError(arr))
}
private mutating func decodeString() -> Result<String,JSONError> {
var res = ""
while let n = next() {
switch n {
case Code.quot: return .Some(res)
case Code.bslash:
switch decodeEscaped() {
case let a?: res.appendContentsOf(a)
case let .None(e): return .None(e)
}
case let c: res.append(Character(UnicodeScalar(c)))
}
}
return .None(closingDelim(res))
}
private mutating func decodeEscaped() -> Result<String,JSONError> {
switch next() {
case Code.quot? : return .Some("\"")
case Code.fslash?: return .Some("/")
case Code.b? : return .Some("\u{8}")
case Code.f? : return .Some("\u{12}")
case Code.n? : return .Some("\n")
case Code.r? : return .Some("\r")
case Code.t? : return .Some("\t")
case Code.u?:
guard let a = next(), b = next(), c = next(), d = next() else {
fallthrough
}
guard let s = UInt32(uStr([a,b,c,d]), radix: 16)
.map({String(Character(UnicodeScalar($0)))}) else {
fallthrough
}
return .Some(s)
default: return .None(error(lit: "Unicode"))
}
}
private mutating func skipMany(sep: UInt8) -> Result<UInt8,JSONError> {
while let i = next() {
switch i {
case Code.space, Code.tab, Code.ret, Code.newlin, sep: continue
default: return .Some(i)
}
}
return .None(.NoDivider(expecting: String(uChr(sep)), found: ""))
}
private mutating func decodeArr() -> Result<JSON,JSONError> {
var res: [JSON] = []
while let i = skipMany(Code.comma) {
if i == Code.squarC { return .Some(.JArray(res)) }
switch decode(i) {
case let a?: res.append(a)
case let .None(e): return .None(e)
}
}
return .None(closingDelim(res))
}
private mutating func decodeObj() -> Result<JSON,JSONError> {
var res: [String:JSON] = [:]
while let i = skipMany(Code.comma) {
if i == Code.curliC { return .Some(.JObject(res)) }
let (key,val): (String,JSON)
switch decodeString() {
case let s?: key = s
case let .None(e): return .None(e)
}
guard let i = skipMany(Code.colon) else {
return .None(closingDelim(res))
}
switch decode(i) {
case let v?: val = v
case let .None(e): return .None(e)
}
res[key] = val
}
return .None(closingDelim(res))
}
private mutating func decode(i: UInt8) -> Result<JSON,JSONError> {
switch i {
case Code.squarO: return decodeArr()
case Code.curliO: return decodeObj()
case Code.quot : return decodeString().map(JSON.JString)
case Code.n : return decodeNull()
case Code.t : return decodeTrue()
case Code.f : return decodeFalse()
default : return decodeNum(i)
}
}
public mutating func asJSON() -> Result<JSON,JSONError> {
guard let i = next() else { return .None(.Empty) }
return decode(i)
}
}
extension String {
public func asJSON() -> Result<JSON,JSONError> {
var g = utf8.generate()
return g.asJSON()
}
}
|
mit
|
83c3c2b9539b5c9c99382337b6e3a7f2
| 31.398907 | 77 | 0.588057 | 3.452533 | false | false | false | false |
wesj/firefox-ios-1
|
Sync/SyncMeta.swift
|
1
|
2385
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
// Equivalent to Android Sync's EngineSettings, but here
// we use them for meta/global itself.
public struct EngineMeta {
let version: Int
let syncID: String
public static func fromJSON(json: JSON) -> EngineMeta? {
if let syncID = json["syncID"].asString {
if let version = json["version"].asInt {
return EngineMeta(version: version, syncID: syncID)
}
}
return nil
}
public static func mapFromJSON(map: [String: JSON]?) -> [String: EngineMeta]? {
if let map = map {
return optFilter(mapValues(map, EngineMeta.fromJSON))
}
return nil
}
}
public struct MetaGlobal {
let syncID: String
let storageVersion: Int
let engines: [String: EngineMeta]? // Is this really optional?
let declined: [String]?
public static func fromPayload(string: String) -> MetaGlobal? {
return fromPayload(JSON(string: string))
}
// TODO: is it more useful to support partial globals?
// TODO: how do we return error states here?
public static func fromPayload(json: JSON) -> MetaGlobal? {
if json.isError {
return nil
}
if let syncID = json["syncID"].asString {
if let storageVersion = json["storageVersion"].asInt {
let engines = EngineMeta.mapFromJSON(json["engines"].asDictionary)
let declined = json["declined"].asArray
return MetaGlobal(syncID: syncID,
storageVersion: storageVersion,
engines: engines,
declined: jsonsToStrings(declined))
}
}
return nil
}
}
public class GlobalEnvelope: EnvelopeJSON {
public lazy var global: MetaGlobal? = {
return MetaGlobal.fromPayload(self.payload)
}()
}
/**
* Encapsulates a meta/global, identity-derived keys, and keys.
*/
public class SyncMeta {
let syncKey: KeyBundle
var keys: Keys?
var global: MetaGlobal?
public init(syncKey: KeyBundle) {
self.syncKey = syncKey
}
}
|
mpl-2.0
|
d30feadabf5f8575e5152e0157b46bae
| 29.189873 | 83 | 0.602935 | 4.640078 | false | false | false | false |
cplaverty/KeitaiWaniKani
|
WaniKaniStudyQueueWidget/TodayViewController.swift
|
1
|
5493
|
//
// TodayViewController.swift
// WaniKaniStudyQueueWidget
//
// Copyright © 2017 Chris Laverty. All rights reserved.
//
import NotificationCenter
import os
import UIKit
import WaniKaniKit
struct ApplicationURL {
static let dashboard = URL(string: "kwk://launch/dashboard")!
static let launchReviews = URL(string: "kwk://launch/reviews")!
}
class TodayViewController: UITableViewController {
private enum ReuseIdentifier: String {
case studyQueue = "StudyQueue"
case notLoggedIn = "NotLoggedIn"
}
// MARK: - Properties
private var studyQueue: StudyQueue? {
didSet {
DispatchQueue.main.async {
self.tableView.reloadData()
self.preferredContentSize = self.tableView.contentSize
}
}
}
// MARK: - View Controller Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
let nc = CFNotificationCenterGetDarwinNotifyCenter()
let observer = UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque())
let callback: CFNotificationCallback = { (_, observer, name, _, _) in
os_log("Got notification for %@", type: .debug, name?.rawValue as String? ?? "<none>")
let mySelf = Unmanaged<TodayViewController>.fromOpaque(observer!).takeUnretainedValue()
_ = try? mySelf.updateStudyQueue()
}
CFNotificationCenterAddObserver(nc, observer, callback, CFNotificationName.waniKaniAssignmentsDidChange.rawValue, nil, .deliverImmediately)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
_ = try? updateStudyQueue()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
preferredContentSize = tableView.contentSize
}
deinit {
let nc = CFNotificationCenterGetDarwinNotifyCenter()
let observer = UnsafeRawPointer(Unmanaged.passUnretained(self).toOpaque())
CFNotificationCenterRemoveEveryObserver(nc, observer)
}
// MARK: - Implementation
private func latestStudyQueue() throws -> StudyQueue? {
let databaseManager = DatabaseManager(factory: AppGroupDatabaseConnectionFactory())
guard databaseManager.open(readOnly: true) else {
return nil
}
let resourceRepository = ResourceRepositoryReader(databaseManager: databaseManager)
guard try resourceRepository.hasStudyQueue() else {
return nil
}
return try resourceRepository.studyQueue()
}
private func updateStudyQueue() throws -> Bool {
let studyQueue = try latestStudyQueue()
guard studyQueue != self.studyQueue else {
return false
}
self.studyQueue = studyQueue
return true
}
// MARK: - UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let studyQueue = self.studyQueue else {
return tableView.dequeueReusableCell(withIdentifier: ReuseIdentifier.notLoggedIn.rawValue, for: indexPath)
}
let cell = tableView.dequeueReusableCell(withIdentifier: ReuseIdentifier.studyQueue.rawValue, for: indexPath) as! StudyQueueTableViewCell
cell.studyQueue = studyQueue
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let studyQueue = self.studyQueue, studyQueue.reviewsAvailable > 0 {
self.extensionContext?.open(ApplicationURL.launchReviews, completionHandler: nil)
} else {
self.extensionContext?.open(ApplicationURL.dashboard, completionHandler: nil)
}
}
}
// MARK: - NCWidgetProviding
extension TodayViewController: NCWidgetProviding {
func widgetPerformUpdate(completionHandler: @escaping (NCUpdateResult) -> Void) {
do {
let changed = try updateStudyQueue()
if changed {
os_log("Study queue updated", type: .debug)
completionHandler(.newData)
} else {
os_log("Study queue not updated", type: .debug)
completionHandler(.noData)
}
} catch ResourceRepositoryError.noDatabase {
os_log("Database does not exist", type: .info)
self.studyQueue = nil
completionHandler(.noData)
} catch {
os_log("Error when refreshing study queue from today widget in completion handler: %@", type: .error, error as NSError)
self.studyQueue = nil
completionHandler(.failed)
}
}
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
os_log("widgetActiveDisplayModeDidChange: activeDisplayMode = %i, maxSize = %@", type: .debug, activeDisplayMode.rawValue, maxSize.debugDescription)
if activeDisplayMode == .compact {
tableView.rowHeight = maxSize.height
preferredContentSize = maxSize
}
}
}
|
mit
|
1b71f321ddecdb174905fed6da6a7cc3
| 33.759494 | 156 | 0.641114 | 5.42152 | false | false | false | false |
ollieatkinson/Expectation
|
Tests/Source/Matchers/Expectation+BeLessThanOrEqualTo_Spec.swift
|
1
|
1182
|
//
// Expectation+BeLessThanOrEqualTo_Spec.swift
// Expectation
//
// Created by Atkinson, Oliver (Developer) on 23/02/2016.
// Copyright © 2016 Oliver. All rights reserved.
//
import XCTest
@testable import Expectation
class Expectation_BeLessThanOrEqualTo_Spec: XCTestCase {
override func tearDown() {
super.tearDown()
ExpectationAssertFunctions.assertTrue = ExpectationAssertFunctions.ExpectationAssertTrue
ExpectationAssertFunctions.assertFalse = ExpectationAssertFunctions.ExpectationAssertFalse
ExpectationAssertFunctions.assertNil = ExpectationAssertFunctions.ExpectationAssertNil
ExpectationAssertFunctions.assertNotNil = ExpectationAssertFunctions.ExpectationAssertNotNil
ExpectationAssertFunctions.fail = ExpectationAssertFunctions.ExpectationFail
}
func testBeLessThanOrEqualToPass() {
assertTrueValidate(True) {
expect(1).to.beLessThanOrEqualTo(2)
}
assertTrueValidate(True) {
expect(1).to.beLessThanOrEqualTo(1)
}
}
func testBeLessThanOrEqualToFail() {
assertTrueValidate(False) {
expect(2).to.beLessThanOrEqualTo(1)
}
}
}
|
mit
|
a5e657029b1354b286df10c37f1f0f62
| 25.244444 | 96 | 0.736664 | 5.417431 | false | true | false | false |
psharanda/vmc2
|
5. MVP+Routing+Bindings/VIPER/Context.swift
|
1
|
913
|
//
// Created by Pavel Sharanda on 20.11.16.
// Copyright © 2016 psharanda. All rights reserved.
//
import UIKit
typealias AppContext = TextLoaderContainer & MainModuleContainer & NavigationControllerContainer & WindowContainer
class ProductionContext: AppContext {
//internal singleton
private static let textLoader = TextLoader()
func makeTextLoader() -> TextLoaderProtocol {
return ProductionContext.textLoader
}
func makeMainModule() -> (MainPresenter, MainViewProtocol) {
let view = MainViewController()
let presenter = MainPresenter(textLoader: makeTextLoader(), view: view)
view.presenter = presenter
return (presenter, view)
}
func makeNavigationView() -> NavigationView {
return UINavigationController()
}
func makeWindow() -> Window {
return UIWindow(frame: UIScreen.main.bounds)
}
}
|
mit
|
e378cc0e055210fb73bab681a4815982
| 26.636364 | 114 | 0.686404 | 4.983607 | false | false | false | false |
chrisamanse/Stopwatch
|
Stopwatch/Timer.swift
|
1
|
2017
|
//
// Timer.swift
// Stopwatch
//
// Created by Chris Amanse on 12/8/15.
// Copyright © 2015 Joe Christopher Paul Amanse. All rights reserved.
//
import Foundation
public class Timer: Stopwatch {
internal var targetTimer: NSTimer?
public weak var timerDelegate: TimerDelegate? {
didSet {
if active {
if oldValue == nil && timerDelegate != nil {
createTargetTimer()
} else if timerDelegate == nil {
destroyTargetTimer()
}
}
}
}
public let targetTimeInterval: NSTimeInterval
public init(targetTimeInterval: NSTimeInterval) {
self.targetTimeInterval = targetTimeInterval
}
public var timeLeft: NSTimeInterval {
return targetTimeInterval - timePassed
}
public override func start() {
createTargetTimer()
super.start()
}
public override func pause() {
destroyTargetTimer()
super.pause()
}
public override func stop() {
destroyTargetTimer()
super.stop()
}
private func createTargetTimer() {
destroyTargetTimer() // Destroy old target timer
// Only create when timer delegate is not nil
guard timerDelegate != nil else {
return
}
let newTimer = NSTimer(timeInterval: timeLeft, target: self, selector: #selector(triggerTargetReached(_:)), userInfo: nil, repeats: false)
targetTimer = newTimer
NSRunLoop.mainRunLoop().addTimer(newTimer, forMode: NSRunLoopCommonModes)
}
private func destroyTargetTimer() {
targetTimer?.invalidate()
targetTimer = nil
}
public func triggerTargetReached(sender: AnyObject?) {
timerDelegate?.timerDidReachTargetTimeInterval(self)
}
}
public protocol TimerDelegate: class {
func timerDidReachTargetTimeInterval(timer: Timer)
}
|
mit
|
9ed6b17b683bc76828095bd9f0ce9c55
| 24.846154 | 146 | 0.596726 | 5.277487 | false | false | false | false |
cailingyun2010/swift-weibo
|
微博-S/Classes/Home/StatusPictureView.swift
|
1
|
5329
|
//
// StatusPictureView.swift
// 微博-S
//
// Created by nimingM on 16/3/29.
// Copyright © 2016年 蔡凌云. All rights reserved.
//
import UIKit
import SDWebImage
class StatusPictureView: UICollectionView {
var status: Status? {
didSet {
reloadData()
}
}
private var pictureLayout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
init() {
super.init(frame: CGRectZero, collectionViewLayout: pictureLayout)
// 注册cell
registerClass(PictureViewCell.self, forCellWithReuseIdentifier: XMGPictureViewCellReuseIdentifier)
dataSource = self
delegate = self
pictureLayout.minimumInteritemSpacing = 10
pictureLayout.minimumLineSpacing = 10
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// 初始化配图相关属性
private func setupPictureView() {
}
/**
计算配图的尺寸
*/
func calculateImageSize() -> CGSize
{
// 1.取出配图个数
let count = status?.storedPicURLS?.count
// 2.如果没有配图zero
if count == 0 || count == nil
{
return CGSizeZero
}
// 3.如果只有一张配图, 返回图片的实际大小
if count == 1
{
// 3.1取出缓存的图片
let key = status?.storedPicURLS!.first?.absoluteString
let image = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(key!)
pictureLayout.itemSize = image.size
// 3.2返回缓存图片的尺寸
return image.size
}
// 4.如果有4张配图, 计算田字格的大小
let width = 90
let margin = 10
pictureLayout.itemSize = CGSize(width: width, height: width)
if count == 4
{
let viewWidth = width * 2 + margin
return CGSize(width: viewWidth, height: viewWidth)
}
// 5.如果是其它(多张), 计算九宫格的大小
// 5.1计算列数
let colNumber = 3
// 5.2计算行数
let rowNumber = (count! - 1) / 3 + 1
// 宽度 = 列数 * 图片的宽度 + (列数 - 1) * 间隙
let viewWidth = colNumber * width + (colNumber - 1) * margin
// 高度 = 行数 * 图片的高度 + (行数 - 1) * 间隙
let viewHeight = rowNumber * width + (rowNumber - 1) * margin
return CGSize(width: viewWidth, height: viewHeight)
}
}
class PictureViewCell: UICollectionViewCell {
// 定义接收外界属性的数据
var imageUrl:NSURL? {
didSet {
iconImageView.sd_setImageWithURL(imageUrl)
if ((imageUrl?.absoluteString)! as NSString).pathExtension.lowercaseString == "gif" {
gitImageView.hidden = false
} else {
gitImageView.hidden = true
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
// 添加子控件
contentView.addSubview(iconImageView)
// 布局子控件
iconImageView.xmg_Fill(contentView)
}
// MARK: - 懒加载
private lazy var iconImageView: UIImageView = {
let icon = UIImageView()
icon.userInteractionEnabled = true
return icon
}()
private lazy var gitImageView: UIImageView = {
let iv = UIImageView(image: UIImage(named: "avatar_vgirl"))
iv.hidden = true
return iv
}()
}
// MARK: - 通知名
/// 选中图片的通知名称
let XMGStatusPictureViewSelected = "XMGStatusPictureViewSelected"
/// 当前选中图片的索引对应的key
let XMGStatusPictureViewIndexKey = "XMGStatusPictureViewIndexKey"
/// 需要展示的所有图片对应的key
let XMGStatusPictureViewURLsKey = "XMGStatusPictureViewURLsKey"
extension StatusPictureView: UICollectionViewDataSource,UICollectionViewDelegate {
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(XMGPictureViewCellReuseIdentifier, forIndexPath: indexPath) as! PictureViewCell
cell.imageUrl = status?.storedPicURLS![indexPath.item]
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return status?.storedPicURLS?.count ?? 0
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let info = [XMGStatusPictureViewIndexKey : indexPath, XMGStatusPictureViewURLsKey : status!.LargePictureURLS!]
NSNotificationCenter.defaultCenter().postNotificationName(XMGStatusPictureViewSelected, object: self, userInfo: info)
}
}
|
apache-2.0
|
0c515ab8d703bca6d0f9d038799acb6c
| 29.331288 | 152 | 0.59729 | 5.050051 | false | false | false | false |
Marguerite-iOS/Marguerite
|
Marguerite/StopTableViewCell.swift
|
1
|
1611
|
//
// StopTableViewCell.swift
// Marguerite
//
// Created by Andrew Finke on 6/30/15.
// Copyright © 2015 Andrew Finke. All rights reserved.
//
import UIKit
class StopTableViewCell: UITableViewCell {
/*
Cell used in main stops table view for displaying stop name and all route images
*/
@IBOutlet private weak var stopNameLabel: UILabel!
@IBOutlet private weak var routesImageView: UIImageView!
var stop: ShuttleStop? {
didSet {
if let stop = stop {
routesImageView.image = stop.getRouteBubblesImage(frame.width)
stopNameLabel.text = stop.name
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateTheme", name: Notification.UpdatedTheme.rawValue, object: nil)
selectedBackgroundView = UIView()
updateTheme()
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/**
Updates the UI colors
*/
func updateTheme() {
if ShuttleSystem.sharedInstance.nightModeEnabled {
backgroundColor = UIColor.darkModeCellColor()
stopNameLabel.textColor = UIColor.whiteColor()
selectedBackgroundView?.backgroundColor = UIColor.darkModeCellSelectionColor()
} else {
backgroundColor = UIColor.whiteColor()
stopNameLabel.textColor = UIColor.blackColor()
selectedBackgroundView?.backgroundColor = UIColor.cellSelectionColor()
}
}
}
|
mit
|
6ec84f1663d04765a0dba1943490f840
| 28.814815 | 142 | 0.640994 | 5.296053 | false | false | false | false |
BoomTownROI/SSASideMenu
|
SSASideMenuExample/SSASideMenuExample/RightMenuViewController.swift
|
1
|
3161
|
//
// RightMenuViewController.swift
// SSASideMenuExample
//
// Created by Sebastian S. Andersen on 06/03/15.
// Copyright (c) 2015 SebastianAndersen. All rights reserved.
//
import Foundation
import UIKit
import SSASideMenu
class RightMenuViewController: UIViewController {
lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.separatorStyle = .None
tableView.frame = CGRectMake(180, (self.view.frame.size.height - 54 * 2) / 2.0, self.view.frame.size.width, 54 * 2)
tableView.autoresizingMask = .FlexibleTopMargin | .FlexibleBottomMargin | .FlexibleWidth
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")
tableView.opaque = false
tableView.backgroundColor = UIColor.clearColor()
tableView.backgroundView = nil
tableView.bounces = false
return tableView
}()
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK : TableViewDataSource & Delegate Methods
extension RightMenuViewController: UITableViewDelegate, UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 2
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 54
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! UITableViewCell
let titles: [String] = ["Home", "Calendar"]
cell.backgroundColor = UIColor.clearColor()
cell.textLabel?.font = UIFont(name: "HelveticaNeue", size: 21)
cell.textLabel?.textColor = UIColor.whiteColor()
cell.textLabel?.text = titles[indexPath.row]
cell.selectionStyle = .None
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
switch indexPath.row {
case 0:
sideMenuViewController?.contentViewController = UINavigationController(rootViewController: FirstViewController())
sideMenuViewController?.hideMenuViewController()
break
case 1:
sideMenuViewController?.contentViewController = UINavigationController(rootViewController: SecondViewController())
sideMenuViewController?.hideMenuViewController()
break
default:
break
}
}
}
|
mit
|
d61b3eb89d938726f7bb46cb86f34708
| 29.403846 | 126 | 0.648845 | 5.964151 | false | false | false | false |
tomekc/R.swift
|
R.swift/values.swift
|
2
|
10178
|
//
// values.swift
// R.swift
//
// Created by Mathijs Kadijk on 31-01-15.
// From: https://github.com/mac-cain13/R.swift
// License: MIT License
//
let ResourceFilename = "R.generated.swift"
let Header = [
"// This is a generated file, do not edit!",
"// Generated by R.swift, see https://github.com/mac-cain13/R.swift",
].joinWithSeparator("\n")
let Imports = [
"import UIKit",
].joinWithSeparator("\n")
let ReuseIdentifier = Struct(
type: Type(name: "ReuseIdentifier", genericType: Type(name: "T")),
implements: [Type(name: "CustomStringConvertible")],
lets: [
Let(
name: "identifier",
type: Type(name: "String")
)
],
vars: [
Var(
isStatic: false,
name: "description",
type: Type(name: "String"),
getter: "return identifier"
)
],
functions: [],
structs: [])
let NibResourceProtocol = Protocol(
type: Type(name: "NibResource"),
typealiasses: [],
vars: [
Var(isStatic: false, name: "name", type: Type._String, getter: "get"),
Var(isStatic: false, name: "instance", type: Type._UINib, getter: "get")
]
)
let ReusableProtocol = Protocol(
type: Type(name: "Reusable"),
typealiasses: [
Typealias(alias: Type(name: "T"), type: nil)
],
vars: [
Var(isStatic: false, name: "reuseIdentifier", type: ReuseIdentifier.type, getter: "get")
]
)
let NibUIViewControllerExtension = Extension(
type: Type._UIViewController,
functions: [
Initializer(
type: .Convenience,
parameters: [
Function.Parameter(name: "nib", type: Type(name: "NibResource"))
],
body: "self.init(nibName: nib.name, bundle: nil)"
) as Func
]
)
let ReuseIdentifierUITableViewExtension = Extension(
type: Type._UITableView,
functions: [
Function(
isStatic: false,
name: "dequeueReusableCellWithIdentifier",
generics: "T : \(Type._UITableViewCell)",
parameters: [
Function.Parameter(name: "identifier", type: ReuseIdentifier.type),
Function.Parameter(name: "forIndexPath", localName: "indexPath", type: Type._NSIndexPath.asOptional())
],
returnType: Type(name: "T", genericType: nil, optional: true),
body: "if let indexPath = indexPath {\n return dequeueReusableCellWithIdentifier(identifier.identifier, forIndexPath: indexPath) as? T\n}\nreturn dequeueReusableCellWithIdentifier(identifier.identifier) as? T"
),
Function(
isStatic: false,
name: "dequeueReusableCellWithIdentifier",
generics: "T : \(Type._UITableViewCell)",
parameters: [
Function.Parameter(name: "identifier", type: ReuseIdentifier.type),
],
returnType: Type(name: "T", genericType: nil, optional: true),
body: "return dequeueReusableCellWithIdentifier(identifier.identifier) as? T"
),
Function(
isStatic: false,
name: "dequeueReusableHeaderFooterViewWithIdentifier",
generics: "T : \(Type._UITableViewHeaderFooterView)",
parameters: [
Function.Parameter(name: "identifier", type: ReuseIdentifier.type),
],
returnType: Type(name: "T", genericType: nil, optional: true),
body: "return dequeueReusableHeaderFooterViewWithIdentifier(identifier.identifier) as? T"
),
Function(
isStatic: false,
name: "registerNib",
generics: "T: \(NibResourceProtocol.type) where T: \(ReusableProtocol.type), T.T: UITableViewCell",
parameters: [
Function.Parameter(name: "nibResource", type: Type(name: "T"))
],
returnType: Type._Void,
body: "registerNib(nibResource.instance, forCellReuseIdentifier: nibResource.reuseIdentifier.identifier)"
),
Function(
isStatic: false,
name: "registerNibs",
generics: "T: \(NibResourceProtocol.type) where T: \(ReusableProtocol.type), T.T: UITableViewCell",
parameters: [
Function.Parameter(name: "nibResources", type: Type(name: "[T]"))
],
returnType: Type._Void,
body: "nibResources.forEach(registerNib)"
),
Function(
isStatic: false,
name: "registerNibForHeaderFooterView",
generics: "T: \(NibResourceProtocol.type) where T: \(ReusableProtocol.type), T.T: UIView",
parameters: [
Function.Parameter(name: "nibResource", type: Type(name: "T"))
],
returnType: Type._Void,
body: "registerNib(nibResource.instance, forHeaderFooterViewReuseIdentifier: nibResource.reuseIdentifier.identifier)"
)
]
)
let ReuseIdentifierUICollectionViewExtension = Extension(
type: Type._UICollectionView,
functions: [
Function(
isStatic: false,
name: "dequeueReusableCellWithReuseIdentifier",
generics: "T: \(Type._UICollectionViewCell)",
parameters: [
Function.Parameter(name: "identifier", type: ReuseIdentifier.type),
Function.Parameter(name: "forIndexPath", localName: "indexPath", type: Type._NSIndexPath)
],
returnType: Type(name: "T", genericType: nil, optional: true),
body: "return dequeueReusableCellWithReuseIdentifier(identifier.identifier, forIndexPath: indexPath) as? T"
),
Function(
isStatic: false,
name: "dequeueReusableSupplementaryViewOfKind",
generics: "T: \(Type._UICollectionReusableView)",
parameters: [
Function.Parameter(name: "elementKind", type: Type._String),
Function.Parameter(name: "withReuseIdentifier", localName: "identifier", type: ReuseIdentifier.type),
Function.Parameter(name: "forIndexPath", localName: "indexPath", type: Type._NSIndexPath)
],
returnType: Type(name: "T", genericType: nil, optional: true),
body: "return dequeueReusableSupplementaryViewOfKind(elementKind, withReuseIdentifier: identifier.identifier, forIndexPath: indexPath) as? T"
),
Function(
isStatic: false,
name: "registerNib",
generics: "T: \(NibResourceProtocol.type) where T: \(ReusableProtocol.type), T.T: UICollectionViewCell",
parameters: [
Function.Parameter(name: "nibResource", type: Type(name: "T"))
],
returnType: Type._Void,
body: "registerNib(nibResource.instance, forCellWithReuseIdentifier: nibResource.reuseIdentifier.identifier)"
),
Function(
isStatic: false,
name: "registerNibs",
generics: "T: \(NibResourceProtocol.type) where T: \(ReusableProtocol.type), T.T: UICollectionViewCell",
parameters: [
Function.Parameter(name: "nibResources", type: Type(name: "[T]"))
],
returnType: Type._Void,
body: "nibResources.forEach(registerNib)"
),
Function(
isStatic: false,
name: "registerNib",
generics: "T: \(NibResourceProtocol.type) where T: \(ReusableProtocol.type), T.T: UICollectionReusableView",
parameters: [
Function.Parameter(name: "nibResource", type: Type(name: "T")),
Function.Parameter(name: "forSupplementaryViewOfKind", localName: "kind", type: Type._String)
],
returnType: Type._Void,
body: "registerNib(nibResource.instance, forSupplementaryViewOfKind: kind, withReuseIdentifier: nibResource.reuseIdentifier.identifier)"
),
Function(
isStatic: false,
name: "registerNibs",
generics: "T: \(NibResourceProtocol.type) where T: \(ReusableProtocol.type), T.T: UICollectionReusableView",
parameters: [
Function.Parameter(name: "nibResources", type: Type(name: "[T]")),
Function.Parameter(name: "forSupplementaryViewOfKind", localName: "kind", type: Type._String)
],
returnType: Type._Void,
body: "nibResources.forEach { self.registerNib($0, forSupplementaryViewOfKind: kind) }"
),
]
)
let IndentationString = " "
let Ordinals = [
(number: 1, word: "first"),
(number: 2, word: "second"),
(number: 3, word: "third"),
(number: 4, word: "fourth"),
(number: 5, word: "fifth"),
(number: 6, word: "sixth"),
(number: 7, word: "seventh"),
(number: 8, word: "eighth"),
(number: 9, word: "ninth"),
(number: 10, word: "tenth"),
(number: 11, word: "eleventh"),
(number: 12, word: "twelfth"),
(number: 13, word: "thirteenth"),
(number: 14, word: "fourteenth"),
(number: 15, word: "fifteenth"),
(number: 16, word: "sixteenth"),
(number: 17, word: "seventeenth"),
(number: 18, word: "eighteenth"),
(number: 19, word: "nineteenth"),
(number: 20, word: "twentieth"),
]
// Extensions
let AssetFolderExtensions: Set<String> = ["xcassets"]
let AssetExtensions: Set<String> = ["launchimage", "imageset"] // Note: "appiconset" is not loadable by default, so it's not included here
let ImageExtensions: Set<String> = ["tiff", "tif", "jpg", "jpeg", "gif", "png", "bmp", "bmpf", "ico", "cur", "xbm"] // See "Supported Image Formats" on https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/
let FontExtensions: Set<String> = ["otf", "ttf"]
let StoryboardExtensions: Set<String> = ["storyboard"]
let NibExtensions: Set<String> = ["xib"]
let CompiledResourcesExtensions: Set<String> = AssetFolderExtensions.union(StoryboardExtensions).union(NibExtensions)
let ElementNameToTypeMapping = [
"viewController": Type._UIViewController,
"tableViewCell": Type(name: "UITableViewCell"),
"tabBarController": Type(name: "UITabBarController"),
"glkViewController": Type(name: "GLKViewController"),
"pageViewController": Type(name: "UIPageViewController"),
"tableViewController": Type(name: "UITableViewController"),
"splitViewController": Type(name: "UISplitViewController"),
"navigationController": Type(name: "UINavigationController"),
"avPlayerViewController": Type(name: "AVPlayerViewController"),
"collectionViewController": Type(name: "UICollectionViewController"),
]
let SwiftKeywords = ["class", "deinit", "enum", "extension", "func", "import", "init", "internal", "let", "operator", "private", "protocol", "public", "static", "struct", "subscript", "typealias", "var", "break", "case", "continue", "default", "do", "else", "fallthrough", "for", "if", "in", "return", "switch", "where", "while", "as", "dynamicType", "false", "is", "nil", "self", "Self", "super", "true", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__"]
|
mit
|
5de2dc0a965c5e879f640d23003246eb
| 36.557196 | 459 | 0.662999 | 4.058214 | false | false | false | false |
txstate-etc/mobile-tracs-ios
|
mobile-tracs-ios/Data/Notification.swift
|
1
|
1588
|
//
// Notification.swift
// mobile-tracs-ios
//
// Created by Nick Wing on 3/19/17.
// Copyright © 2017 Texas State University. All rights reserved.
//
import Foundation
class Notification : Equatable {
public var id: String?
public var provider_id: String?
public var user_id: String?
public var object_type: String?
public var object_id: String?
public var object: TRACSObject?
public var notification_type: String?
public var site_id: String?
public var tool_id: String?
public var notify_after: Date?
public var seen: Bool
public var read: Bool
init(dict:[String:Any]) {
id = dict["id"] as? String
if let keys:[String:Any] = dict["keys"] as? [String:Any] {
notification_type = keys["notification_type"] as? String
object_type = keys["object_type"] as? String
object_id = keys["object_id"] as? String
user_id = keys["user_id"] as? String
provider_id = keys["provider_id"] as? String
}
if let otherkeys:[String:Any] = dict["other_keys"] as? [String:Any] {
site_id = otherkeys["site_id"] as? String
tool_id = otherkeys["tool_id"] as? String
}
notify_after = dict["notify_after"] as? Date
seen = dict["seen"] as? Bool ?? false
read = dict["read"] as? Bool ?? false
}
func isRead() -> Bool {
return read || object?.read ?? false
}
static func ==(lhs: Notification, rhs: Notification) -> Bool {
return lhs.id != nil && lhs.id == rhs.id
}
}
|
mit
|
87dbcd792343f3ec53a0891990b9ef96
| 30.74 | 77 | 0.589162 | 3.742925 | false | false | false | false |
superk589/CGSSGuide
|
DereGuide/Toolbox/Gacha/Detail/View/GachaDetailLoadingCell.swift
|
2
|
1368
|
//
// GachaDetailLoadingCell.swift
// DereGuide
//
// Created by zzk on 19/01/2018.
// Copyright © 2018 zzk. All rights reserved.
//
import UIKit
class GachaDetailLoadingCell: UITableViewCell {
let leftLabel = UILabel()
let loadingView = LoadingView()
weak var delegate: LoadingViewDelegate? {
didSet {
loadingView.delegate = delegate
}
}
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
leftLabel.font = UIFont.systemFont(ofSize: 16)
leftLabel.text = NSLocalizedString("模拟抽卡", comment: "")
contentView.addSubview(leftLabel)
leftLabel.snp.makeConstraints { (make) in
make.left.equalTo(readableContentGuide)
make.top.equalTo(10)
}
contentView.addSubview(loadingView)
loadingView.snp.makeConstraints { (make) in
make.top.equalTo(leftLabel.snp.bottom).offset(8)
make.left.equalTo(readableContentGuide)
make.right.equalTo(readableContentGuide)
make.bottom.equalTo(-20)
}
selectionStyle = .none
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
2083035ceb9bfd256370bd06680f7cfc
| 26.734694 | 79 | 0.621045 | 4.702422 | false | false | false | false |
EaglesoftZJ/actor-platform
|
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Contacts/ContactsController.swift
|
1
|
14555
|
//
// ContactsController.swift
// ActorSDK
//
// Created by dingjinming on 2018/1/11.
// Copyright © 2018年 Steve Kite. All rights reserved.
//
import UIKit
class ContactsController: AAContactsListContentController,UITableViewDelegate,UITableViewDataSource,UISearchDisplayDelegate,UISearchBarDelegate {
func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
searchArray.removeAll()
for contact in contactsArray
{
if contact.name.contains(searchText){
searchArray.append(contact)
}
}
}
func numberOfSections(in tableView: UITableView) -> Int {
if tableView == searchDisplay.searchResultsTableView {
return 1
}
return displayList.count + 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == searchDisplay.searchResultsTableView {
return searchArray.count
}
if section == 0 {
return 3
}
let dic = displayList[section-1] as? NSDictionary
let arr = dic?.object(forKey: "sectionArray") as! Array<ACContact>
return arr.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if tableView == searchDisplay.searchResultsTableView {
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ContactsGroupCell
let contact = searchArray[indexPath.row]
cell.nameLabel.text = contact.name
cell.avatarView.bind(contact.name, id: Int(contact.uid), avatar: contact.avatar)
return cell
}
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: "tableCell", for: indexPath)
tableCell(row: indexPath.row, cell: cell)
return cell
}
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! ContactsGroupCell
let dic = displayList[indexPath.section-1] as! NSDictionary
let arr = dic["sectionArray"] as! Array<ACContact>
let data = arr[indexPath.row]
cell.nameLabel.text = data.name
cell.avatarView.bind(data.name, id: Int(data.uid), avatar: data.avatar)
return cell
}
//创建三个自定义cell
func tableCell(row: Int,cell: UITableViewCell){
let imageList = ["ic_create_channel","ic_chats_outline","ic_add_user"]
let textList = ["组织架构","群组","创建群组"]
cell.imageView?.image = UIImage.bundled(imageList[row])
cell.textLabel?.text = textList[row]
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if tableView == searchDisplay.searchResultsTableView{
return nil
}
if section == 0 {
return "联系人"
}
let dic = displayList[section-1] as! NSDictionary
let text = dic["sectionTitle"] as! String
return text
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
if tableView == table{
var list = Array<String>()
for dic in displayList {
let text = (dic as! NSDictionary)["sectionTitle"] as! String
list.append(text)
}
return list
}
return nil
}
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
if tableView == table{
return index+1
}
return 0
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
if tableView == searchDisplay.searchResultsTableView {
let contact = searchArray[indexPath.row]
if let customController = ActorSDK.sharedActor().delegate.actorControllerForConversation(ACPeer_userWithInt_(contact.uid)) {
navigateDetail(customController)
} else {
navigateDetail(ConversationViewController(peer: ACPeer_userWithInt_(contact.uid)))
}
}
else{
if indexPath.section == 0 {
if indexPath.row == 0{self.navigateDetail(ZZJGTableViewController())}
if indexPath.row == 1{self.navigateNext(ContactsGroupController())}
if indexPath.row == 2{self.navigateNext(AAGroupCreateViewController(isChannel: false), removeCurrent: false)}
}
else{
let dic = displayList[indexPath.section-1] as! NSDictionary
let arr = dic["sectionArray"] as! Array<ACContact>
let contact = arr[indexPath.row]
if let customController = ActorSDK.sharedActor().delegate.actorControllerForConversation(ACPeer_userWithInt_(contact.uid)) {
navigateDetail(customController)
} else {
navigateDetail(ConversationViewController(peer: ACPeer_userWithInt_(contact.uid)))
}
}
}
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 56
}
let table = UITableView()
var displayList = NSMutableArray()
let sortList = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","#"]
var searchDisplay = UISearchDisplayController()
var searchArray = [ACContact]()
var contactsArray = [ACContact]()
var isReload:Bool = false
public override init() {
super.init()
tabBarItem = UITabBarItem(title: "TabPeople", img: "TabIconContacts", selImage: "TabIconContactsHighlighted")
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.add, target: self, action: #selector(findContact))
}
public required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
removeAllFatherView()
self.edgesForExtendedLayout = UIRectEdge(rawValue: 0)
self.automaticallyAdjustsScrollViewInsets = false
self.title = "联系人"
view.backgroundColor = .white
createList()
createSearchDisplay()
}
func tableReload()
{
isReload = true
self.hidePlaceholder()
self.table.showView()
let list:ARBindedDisplayList! = ActorSDK.sharedActor().contactsList
for charTmp in sortList {
let array = NSMutableArray()
for i in 0...Int(list.size())-1
{
let data = list.item(with: jint(i)) as! ACContact
let pinyin = data.pyShort
if charTmp == "#" && !pureLetters(pinyin!){
array.add(data)
}
else if charTmp == pinyin {
array.add(data)
}
}
let dic = NSMutableDictionary()
if array.count != 0
{
dic["sectionArray"] = array
dic["sectionTitle"] = charTmp
displayList.add(dic.copy())
}
}
table.reloadData()
for i in 0...Int(list.size())-1 {
let data = list.item(with: jint(i)) as! ACContact
contactsArray.append(data)
}
}
func createList()
{
table.frame = view.frame
table.delegate = self
table.dataSource = self
table.tableFooterView = UIView()
view.addSubview(table)
table.register(ContactsGroupCell.self, forCellReuseIdentifier: "cell")
table.register(UITableViewCell.self, forCellReuseIdentifier: "tableCell")
//索引
table.sectionIndexColor = .gray
table.sectionIndexTrackingBackgroundColor = .gray
table.sectionIndexBackgroundColor = .clear
table.autoresizingMask = [.flexibleHeight,.flexibleWidth]
}
func createSearchDisplay()
{
let style = ActorSDK.sharedActor().style
let searchBar = UISearchBar()
searchBar.searchBarStyle = .default
searchBar.isTranslucent = false
searchBar.placeholder = ""
searchBar.barTintColor = style.searchBackgroundColor.forTransparentBar()
searchBar.setBackgroundImage(Imaging.imageWithColor(style.searchBackgroundColor, size: CGSize(width: 1, height: 1)), for: .any, barMetrics: .default)
searchBar.backgroundColor = style.searchBackgroundColor
searchBar.tintColor = style.searchCancelColor
searchBar.keyboardAppearance = style.isDarkApp ? UIKeyboardAppearance.dark : UIKeyboardAppearance.light
let fieldBg = Imaging.imageWithColor(style.searchFieldBgColor, size: CGSize(width: 14,height: 28))
.roundCorners(14, h: 28, roundSize: 4)
searchBar.setSearchFieldBackgroundImage(fieldBg.stretchableImage(withLeftCapWidth: 7, topCapHeight: 0), for: UIControlState())
for subView in searchBar.subviews {
for secondLevelSubview in subView.subviews {
if let tf = secondLevelSubview as? UITextField {
tf.textColor = style.searchFieldTextColor
break
}
}
}
searchDisplay = UISearchDisplayController(searchBar: searchBar, contentsController: self)
searchDisplay.searchBar.delegate = self
searchDisplay.searchResultsDataSource = self
searchDisplay.searchResultsDelegate = self
searchDisplay.delegate = self
searchDisplay.searchResultsTableView.register(ContactsGroupCell.self, forCellReuseIdentifier: "cell")
searchDisplay.searchResultsTableView.separatorStyle = UITableViewCellSeparatorStyle.none
searchDisplay.searchResultsTableView.backgroundColor = ActorSDK.sharedActor().style.vcBgColor
let header = AATableViewHeader(frame: CGRect(x: 0, y: 0, width: view.frame.size.width, height: 44))
header.addSubview(searchDisplay.searchBar)
table.tableHeaderView = header
}
//移除所有父类view
func removeAllFatherView() {
view.removeAllSubviews()
}
func pureLetters(_ str: String) -> Bool{
if str.matches("(?i)[^a-z]*[a-z]+[^a-z]*")
{
return true
}
return false
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
//收到displayList通知
NotificationCenter.default.addObserver(self, selector: #selector(tableReload), name: NSNotification.Name(rawValue: "displayList"), object: nil)
if isReload == false && ActorSDK.sharedActor().contactsList != nil {
tableReload()
}
let searchBar = searchDisplay.searchBar
let superView = searchBar.superview
if !(superView is UITableView) {
searchBar.removeFromSuperview()
superView?.addSubview(searchBar)
}
table.tableHeaderView?.setNeedsLayout()
binder.bind(Actor.getAppState().isContactsEmpty, closure: { (value: Any?) -> () in
if let empty = value as? JavaLangBoolean {
if Bool(empty.booleanValue()) == true {
self.table.hideView()
self.showPlaceholder()
} else {
self.table.showView()
self.hidePlaceholder()
}
}
})
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
searchDisplay.setActive(false, animated: false)
NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "displayList"), object: nil)
}
// Searching for contact
func findContact() {
startEditField { (c) -> () in
c.title = "FindTitle"
c.actionTitle = "NavigationFind"
c.hint = "FindHint"
c.fieldHint = "FindFieldHint"
c.fieldAutocapitalizationType = .none
c.fieldAutocorrectionType = .no
c.fieldReturnKey = .search
c.didDoneTap = { (t, c) -> () in
if t.length == 0 {
return
}
self.executeSafeOnlySuccess(Actor.findUsersCommand(withQuery: t), successBlock: { (val) -> Void in
var user: ACUserVM? = nil
if let users = val as? IOSObjectArray {
if Int(users.length()) > 0 {
if let tempUser = users.object(at: 0) as? ACUserVM {
user = tempUser
}
}
}
if user != nil {
c.execute(Actor.addContactCommand(withUid: user!.getId())!, successBlock: { (val) -> Void in
if let customController = ActorSDK.sharedActor().delegate.actorControllerForConversation(ACPeer_userWithInt_(user!.getId())) {
self.navigateDetail(customController)
} else {
self.navigateDetail(ConversationViewController(peer: ACPeer_userWithInt_(user!.getId())))
}
c.dismissController()
}, failureBlock: { (val) -> Void in
if let customController = ActorSDK.sharedActor().delegate.actorControllerForConversation(ACPeer_userWithInt_(user!.getId())) {
self.navigateDetail(customController)
} else {
self.navigateDetail(ConversationViewController(peer: ACPeer_userWithInt_(user!.getId())))
}
c.dismissController()
})
} else {
c.alertUser("FindNotFound")
}
})
}
}
}
}
|
agpl-3.0
|
c7be73e0354dd2a34f5c829f42cd0866
| 38.46049 | 157 | 0.575128 | 5.277697 | false | false | false | false |
iwheelbuy/VK
|
VK/Object/VK+Object+CheckedLink.swift
|
1
|
2179
|
import Foundation
public extension Object {
/// Информацию о том, является ли внешняя ссылка заблокированной на сайте ВКонтакте
public struct CheckedLink: Decodable {
/// Статус ссылки
public enum Status: Decodable {
/// Ссылка не заблокирована
case not_banned
/// Ссылка заблокирована
case banned
/// Ссылка проверяется, необходимо выполнить повторный запрос через несколько секунд
case processing
/// Неизвестное значение
case unexpected(String)
init(rawValue: String) {
switch rawValue {
case "not_banned":
self = .not_banned
case "banned":
self = .banned
case "processing":
self = .processing
default:
self = .unexpected(rawValue)
}
}
public var rawValue: String {
switch self {
case .not_banned:
return "not_banned"
case .banned:
return "banned"
case .processing:
return "processing"
case .unexpected(let value):
return value
}
}
public init(from decoder: Decoder) throws {
var container = try decoder.singleValueContainer()
let rawValue: String = try container.decode()
self = Object.CheckedLink.Status(rawValue: rawValue)
}
}
/// Исходная ссылка (url) либо полная ссылка (если в url была передана сокращенная ссылка)
public let link: String?
/// Статус ссылки
public let status: Object.CheckedLink.Status?
}
}
|
mit
|
3ba2fd903ccf6812ecb9376e1fed4fee
| 34.055556 | 98 | 0.493925 | 4.628362 | false | false | false | false |
larryhou/swift
|
VideoDecode/VideoDecode/AppDelegate.swift
|
1
|
4560
|
//
// AppDelegate.swift
// VideoDecode
//
// Created by larryhou on 08/01/2018.
// Copyright © 2018 larryhou. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "VideoDecode")
container.loadPersistentStores(completionHandler: { (_, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
mit
|
1527c5eb41a1d30f633bbe4c2ff54761
| 49.098901 | 285 | 0.68787 | 5.844872 | false | false | false | false |
samodom/TestableUIKit
|
TestableUIKit/UIResponder/UIView/UITableView/UITableViewReloadDataSpy.swift
|
1
|
1679
|
//
// UITableViewReloadDataSpy.swift
// TestableUIKit
//
// Created by Sam Odom on 2/22/17.
// Copyright © 2017 Swagger Soft. All rights reserved.
//
import FoundationSwagger
import TestSwagger
public extension UITableView {
private static let reloadDataCalledString = UUIDKeyString()
private static let reloadDataCalledKey = ObjectAssociationKey(reloadDataCalledString)
private static let reloadDataCalledReference = SpyEvidenceReference(key: reloadDataCalledKey)
/// Spy controller for ensuring a table view has had `reloadData` called on it.
public enum ReloadDataSpyController: SpyController {
public static let rootSpyableClass: AnyClass = UITableView.self
public static let vector = SpyVector.direct
public static let coselectors = [
SpyCoselectors(
methodType: .instance,
original: #selector(UITableView.reloadData),
spy: #selector(UITableView.spy_reloadData)
)
] as Set
public static let evidence = [reloadDataCalledReference] as Set
public static let forwardsInvocations = true
}
/// Spy method that replaces the true implementation of `reloadData`
public func spy_reloadData() {
reloadDataCalled = true
spy_reloadData()
}
/// Indicates whether the `reloadData` method has been called on this object.
public final var reloadDataCalled: Bool {
get {
return loadEvidence(with: UITableView.reloadDataCalledReference) as? Bool ?? false
}
set {
saveEvidence(true, with: UITableView.reloadDataCalledReference)
}
}
}
|
mit
|
27a70e3bec52f59b92eaf8c29410283e
| 30.660377 | 97 | 0.67938 | 5.48366 | false | false | false | false |
RoRoche/iOSSwiftStarter
|
iOSSwiftStarter/Pods/Kingfisher/Kingfisher/ImageCache.swift
|
5
|
27351
|
//
// ImageCache.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 UIKit
/**
This notification will be sent when the disk cache got cleaned either there are cached files expired or the total size exceeding the max allowed size. The manually invoking of `clearDiskCache` method will not trigger this notification.
The `object` of this notification is the `ImageCache` object which sends the notification.
A list of removed hashes (files) could be retrieved by accessing the array under `KingfisherDiskCacheCleanedHashKey` key in `userInfo` of the notification object you received. By checking the array, you could know the hash codes of files are removed.
The main purpose of this notification is supplying a chance to maintain some necessary information on the cached files. See [this wiki](https://github.com/onevcat/Kingfisher/wiki/How-to-implement-ETag-based-304-(Not-Modified)-handling-in-Kingfisher) for a use case on it.
*/
public let KingfisherDidCleanDiskCacheNotification = "com.onevcat.Kingfisher.KingfisherDidCleanDiskCacheNotification"
/**
Key for array of cleaned hashes in `userInfo` of `KingfisherDidCleanDiskCacheNotification`.
*/
public let KingfisherDiskCacheCleanedHashKey = "com.onevcat.Kingfisher.cleanedHash"
private let defaultCacheName = "default"
private let cacheReverseDNS = "com.onevcat.Kingfisher.ImageCache."
private let ioQueueName = "com.onevcat.Kingfisher.ImageCache.ioQueue."
private let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue."
private let defaultCacheInstance = ImageCache(name: defaultCacheName)
private let defaultMaxCachePeriodInSecond: NSTimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week
/// It represents a task of retrieving image. You can call `cancel` on it to stop the process.
public typealias RetrieveImageDiskTask = dispatch_block_t
/**
Cache type of a cached image.
- None: The image is not cached yet when retrieving it.
- Memory: The image is cached in memory.
- Disk: The image is cached in disk.
*/
public enum CacheType {
case None, Memory, Disk
}
/// `ImageCache` represents both the memory and disk cache system of Kingfisher. While a default image cache object will be used if you prefer the extension methods of Kingfisher, you can create your own cache object and configure it as your need. You should use an `ImageCache` object to manipulate memory and disk cache for Kingfisher.
public class ImageCache {
//Memory
private let memoryCache = NSCache()
/// The largest cache cost of memory cache. The total cost is pixel count of all cached images in memory.
public var maxMemoryCost: UInt = 0 {
didSet {
self.memoryCache.totalCostLimit = Int(maxMemoryCost)
}
}
//Disk
private let ioQueue: dispatch_queue_t
private var fileManager: NSFileManager!
///The disk cache location.
public let diskCachePath: String
/// The longest time duration of the cache being stored in disk. Default is 1 week.
public var maxCachePeriodInSecond = defaultMaxCachePeriodInSecond
/// The largest disk size can be taken for the cache. It is the total allocated size of cached files in bytes. Default is 0, which means no limit.
public var maxDiskCacheSize: UInt = 0
private let processQueue: dispatch_queue_t
/// The default cache.
public class var defaultCache: ImageCache {
return defaultCacheInstance
}
/**
Init method. Passing a name for the cache. It represents a cache folder in the memory and disk.
- parameter name: Name of the cache. It will be used as the memory cache name and the disk cache folder name appending to the cache path. This value should not be an empty string.
- parameter path: Optional - Location of cache path on disk. If `nil` is passed (the default value),
the cache folder in of your app will be used. If you want to cache some user generating images, you could pass the Documentation path here.
- returns: The cache object.
*/
public init(name: String, path: String? = nil) {
if name.isEmpty {
fatalError("[Kingfisher] You should specify a name for the cache. A cache with empty name is not permitted.")
}
let cacheName = cacheReverseDNS + name
memoryCache.name = cacheName
let dstPath = path ?? NSSearchPathForDirectoriesInDomains(.CachesDirectory, NSSearchPathDomainMask.UserDomainMask, true).first!
diskCachePath = (dstPath as NSString).stringByAppendingPathComponent(cacheName)
ioQueue = dispatch_queue_create(ioQueueName + name, DISPATCH_QUEUE_SERIAL)
processQueue = dispatch_queue_create(processQueueName + name, DISPATCH_QUEUE_CONCURRENT)
dispatch_sync(ioQueue, { () -> Void in
self.fileManager = NSFileManager()
})
NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache", name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "cleanExpiredDiskCache", name: UIApplicationWillTerminateNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "backgroundCleanExpiredDiskCache", name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
// MARK: - Store & Remove
public extension ImageCache {
/**
Store an image to cache. It will be saved to both memory and disk.
It is an async operation, if you need to do something about the stored image, use `-storeImage:forKey:toDisk:completionHandler:`
instead.
- parameter image: The image will be stored.
- parameter originalData: The original data of the image.
Kingfisher will use it to check the format of the image and optimize cache size on disk.
If `nil` is supplied, the image data will be saved as a normalized PNG file.
It is strongly suggested to supply it whenever possible, to get a better performance and disk usage.
- parameter key: Key for the image.
*/
public func storeImage(image: UIImage, originalData: NSData? = nil, forKey key: String) {
storeImage(image, originalData: originalData, forKey: key, toDisk: true, completionHandler: nil)
}
/**
Store an image to cache. It is an async operation.
- parameter image: The image will be stored.
- parameter originalData: The original data of the image.
Kingfisher will use it to check the format of the image and optimize cache size on disk.
If `nil` is supplied, the image data will be saved as a normalized PNG file.
It is strongly suggested to supply it whenever possible, to get a better performance and disk usage.
- parameter key: Key for the image.
- parameter toDisk: Whether this image should be cached to disk or not. If false, the image will be only cached in memory.
- parameter completionHandler: Called when stroe operation completes.
*/
public func storeImage(image: UIImage, originalData: NSData? = nil, forKey key: String, toDisk: Bool, completionHandler: (() -> ())?) {
memoryCache.setObject(image, forKey: key, cost: image.kf_imageCost)
func callHandlerInMainQueue() {
if let handler = completionHandler {
dispatch_async(dispatch_get_main_queue()) {
handler()
}
}
}
if toDisk {
dispatch_async(ioQueue, { () -> Void in
let imageFormat: ImageFormat
if let originalData = originalData {
imageFormat = originalData.kf_imageFormat
} else {
imageFormat = .Unknown
}
let data: NSData?
switch imageFormat {
case .PNG: data = originalData ?? UIImagePNGRepresentation(image)
case .JPEG: data = originalData ?? UIImageJPEGRepresentation(image, 1.0)
case .GIF: data = originalData ?? UIImageGIFRepresentation(image)
case .Unknown: data = originalData ?? UIImagePNGRepresentation(image.kf_normalizedImage())
}
if let data = data {
if !self.fileManager.fileExistsAtPath(self.diskCachePath) {
do {
try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
} catch _ {}
}
self.fileManager.createFileAtPath(self.cachePathForKey(key), contents: data, attributes: nil)
}
callHandlerInMainQueue()
})
} else {
callHandlerInMainQueue()
}
}
/**
Remove the image for key for the cache. It will be opted out from both memory and disk.
It is an async operation, if you need to do something about the stored image, use `-removeImageForKey:fromDisk:completionHandler:`
instead.
- parameter key: Key for the image.
*/
public func removeImageForKey(key: String) {
removeImageForKey(key, fromDisk: true, completionHandler: nil)
}
/**
Remove the image for key for the cache. It is an async operation.
- parameter key: Key for the image.
- parameter fromDisk: Whether this image should be removed from disk or not. If false, the image will be only removed from memory.
- parameter completionHandler: Called when removal operation completes.
*/
public func removeImageForKey(key: String, fromDisk: Bool, completionHandler: (() -> ())?) {
memoryCache.removeObjectForKey(key)
func callHandlerInMainQueue() {
if let handler = completionHandler {
dispatch_async(dispatch_get_main_queue()) {
handler()
}
}
}
if fromDisk {
dispatch_async(ioQueue, { () -> Void in
do {
try self.fileManager.removeItemAtPath(self.cachePathForKey(key))
} catch _ {}
callHandlerInMainQueue()
})
} else {
callHandlerInMainQueue()
}
}
}
// MARK: - Get data from cache
extension ImageCache {
/**
Get an image for a key from memory or disk.
- parameter key: Key for the image.
- parameter options: Options of retrieving image.
- parameter completionHandler: Called when getting operation completes with image result and cached type of this image. If there is no such key cached, the image will be `nil`.
- returns: The retrieving task.
*/
public func retrieveImageForKey(key: String, options: KingfisherManager.Options, completionHandler: ((UIImage?, CacheType!) -> ())?) -> RetrieveImageDiskTask? {
// No completion handler. Not start working and early return.
guard let completionHandler = completionHandler else {
return nil
}
var block: RetrieveImageDiskTask?
if let image = self.retrieveImageInMemoryCacheForKey(key) {
//Found image in memory cache.
if options.shouldDecode {
dispatch_async(self.processQueue, { () -> Void in
let result = image.kf_decodedImage(scale: options.scale)
dispatch_async(options.queue, { () -> Void in
completionHandler(result, .Memory)
})
})
} else {
completionHandler(image, .Memory)
}
} else {
var sSelf: ImageCache! = self
block = dispatch_block_create(DISPATCH_BLOCK_INHERIT_QOS_CLASS) {
// Begin to load image from disk
dispatch_async(sSelf.ioQueue, { () -> Void in
if let image = sSelf.retrieveImageInDiskCacheForKey(key, scale: options.scale) {
if options.shouldDecode {
dispatch_async(sSelf.processQueue, { () -> Void in
let result = image.kf_decodedImage(scale: options.scale)
sSelf.storeImage(result!, forKey: key, toDisk: false, completionHandler: nil)
dispatch_async(options.queue, { () -> Void in
completionHandler(result, .Memory)
sSelf = nil
})
})
} else {
sSelf.storeImage(image, forKey: key, toDisk: false, completionHandler: nil)
dispatch_async(options.queue, { () -> Void in
completionHandler(image, .Disk)
sSelf = nil
})
}
} else {
// No image found from either memory or disk
dispatch_async(options.queue, { () -> Void in
completionHandler(nil, nil)
sSelf = nil
})
}
})
}
dispatch_async(dispatch_get_main_queue(), block!)
}
return block
}
/**
Get an image for a key from memory.
- parameter key: Key for the image.
- returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
public func retrieveImageInMemoryCacheForKey(key: String) -> UIImage? {
return memoryCache.objectForKey(key) as? UIImage
}
/**
Get an image for a key from disk.
- parameter key: Key for the image.
- param scale: The scale factor to assume when interpreting the image data.
- returns: The image object if it is cached, or `nil` if there is no such key in the cache.
*/
public func retrieveImageInDiskCacheForKey(key: String, scale: CGFloat = KingfisherManager.DefaultOptions.scale) -> UIImage? {
return diskImageForKey(key, scale: scale)
}
}
// MARK: - Clear & Clean
extension ImageCache {
/**
Clear memory cache.
*/
@objc public func clearMemoryCache() {
memoryCache.removeAllObjects()
}
/**
Clear disk cache. This is could be an async or sync operation.
Specify the way you want it by passing the `sync` parameter.
*/
public func clearDiskCache() {
clearDiskCacheWithCompletionHandler(nil)
}
/**
Clear disk cache. This is an async operation.
- parameter completionHander: Called after the operation completes.
*/
public func clearDiskCacheWithCompletionHandler(completionHander: (()->())?) {
dispatch_async(ioQueue, { () -> Void in
do {
try self.fileManager.removeItemAtPath(self.diskCachePath)
try self.fileManager.createDirectoryAtPath(self.diskCachePath, withIntermediateDirectories: true, attributes: nil)
} catch _ {
}
if let completionHander = completionHander {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHander()
})
}
})
}
/**
Clean expired disk cache. This is an async operation.
*/
@objc public func cleanExpiredDiskCache() {
cleanExpiredDiskCacheWithCompletionHander(nil)
}
/**
Clean expired disk cache. This is an async operation.
- parameter completionHandler: Called after the operation completes.
*/
public func cleanExpiredDiskCacheWithCompletionHander(completionHandler: (()->())?) {
// Do things in cocurrent io queue
dispatch_async(ioQueue, { () -> Void in
let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath)
let resourceKeys = [NSURLIsDirectoryKey, NSURLContentModificationDateKey, NSURLTotalFileAllocatedSizeKey]
let expiredDate = NSDate(timeIntervalSinceNow: -self.maxCachePeriodInSecond)
var cachedFiles = [NSURL: [NSObject: AnyObject]]()
var URLsToDelete = [NSURL]()
var diskCacheSize: UInt = 0
if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil),
urls = fileEnumerator.allObjects as? [NSURL] {
for fileURL in urls {
do {
let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys)
// If it is a Directory. Continue to next file URL.
if let isDirectory = resourceValues[NSURLIsDirectoryKey] as? NSNumber {
if isDirectory.boolValue {
continue
}
}
// If this file is expired, add it to URLsToDelete
if let modificationDate = resourceValues[NSURLContentModificationDateKey] as? NSDate {
if modificationDate.laterDate(expiredDate) == expiredDate {
URLsToDelete.append(fileURL)
continue
}
}
if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
diskCacheSize += fileSize.unsignedLongValue
cachedFiles[fileURL] = resourceValues
}
} catch _ {
}
}
}
for fileURL in URLsToDelete {
do {
try self.fileManager.removeItemAtURL(fileURL)
} catch _ {
}
}
if self.maxDiskCacheSize > 0 && diskCacheSize > self.maxDiskCacheSize {
let targetSize = self.maxDiskCacheSize / 2
// Sort files by last modify date. We want to clean from the oldest files.
let sortedFiles = cachedFiles.keysSortedByValue {
resourceValue1, resourceValue2 -> Bool in
if let date1 = resourceValue1[NSURLContentModificationDateKey] as? NSDate,
date2 = resourceValue2[NSURLContentModificationDateKey] as? NSDate {
return date1.compare(date2) == .OrderedAscending
}
// Not valid date information. This should not happen. Just in case.
return true
}
for fileURL in sortedFiles {
do {
try self.fileManager.removeItemAtURL(fileURL)
} catch {
}
URLsToDelete.append(fileURL)
if let fileSize = cachedFiles[fileURL]?[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
diskCacheSize -= fileSize.unsignedLongValue
}
if diskCacheSize < targetSize {
break
}
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if URLsToDelete.count != 0 {
let cleanedHashes = URLsToDelete.map( {$0.lastPathComponent!} )
NSNotificationCenter.defaultCenter().postNotificationName(KingfisherDidCleanDiskCacheNotification, object: self, userInfo: [KingfisherDiskCacheCleanedHashKey: cleanedHashes])
}
completionHandler?()
})
})
}
/**
Clean expired disk cache when app in background. This is an async operation.
In most cases, you should not call this method explicitly.
It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
*/
@objc public func backgroundCleanExpiredDiskCache() {
func endBackgroundTask(inout task: UIBackgroundTaskIdentifier) {
UIApplication.sharedApplication().endBackgroundTask(task)
task = UIBackgroundTaskInvalid
}
var backgroundTask: UIBackgroundTaskIdentifier!
backgroundTask = UIApplication.sharedApplication().beginBackgroundTaskWithExpirationHandler { () -> Void in
endBackgroundTask(&backgroundTask!)
}
cleanExpiredDiskCacheWithCompletionHander { () -> () in
endBackgroundTask(&backgroundTask!)
}
}
}
// MARK: - Check cache status
public extension ImageCache {
/**
* Cache result for checking whether an image is cached for a key.
*/
public struct CacheCheckResult {
public let cached: Bool
public let cacheType: CacheType?
}
/**
Check whether an image is cached for a key.
- parameter key: Key for the image.
- returns: The check result.
*/
public func isImageCachedForKey(key: String) -> CacheCheckResult {
if memoryCache.objectForKey(key) != nil {
return CacheCheckResult(cached: true, cacheType: .Memory)
}
let filePath = cachePathForKey(key)
var diskCached = false
dispatch_sync(ioQueue) { () -> Void in
diskCached = self.fileManager.fileExistsAtPath(filePath)
}
if diskCached {
return CacheCheckResult(cached: true, cacheType: .Disk)
}
return CacheCheckResult(cached: false, cacheType: nil)
}
/**
Get the hash for the key. This could be used for matching files.
- parameter key: The key which is used for caching.
- returns: Corresponding hash.
*/
public func hashForKey(key: String) -> String {
return cacheFileNameForKey(key)
}
/**
Calculate the disk size taken by cache.
It is the total allocated size of the cached files in bytes.
- parameter completionHandler: Called with the calculated size when finishes.
*/
public func calculateDiskCacheSizeWithCompletionHandler(completionHandler: ((size: UInt) -> ())) {
dispatch_async(ioQueue, { () -> Void in
let diskCacheURL = NSURL(fileURLWithPath: self.diskCachePath)
let resourceKeys = [NSURLIsDirectoryKey, NSURLTotalFileAllocatedSizeKey]
var diskCacheSize: UInt = 0
if let fileEnumerator = self.fileManager.enumeratorAtURL(diskCacheURL, includingPropertiesForKeys: resourceKeys, options: NSDirectoryEnumerationOptions.SkipsHiddenFiles, errorHandler: nil),
urls = fileEnumerator.allObjects as? [NSURL] {
for fileURL in urls {
do {
let resourceValues = try fileURL.resourceValuesForKeys(resourceKeys)
// If it is a Directory. Continue to next file URL.
if let isDirectory = resourceValues[NSURLIsDirectoryKey]?.boolValue {
if isDirectory {
continue
}
}
if let fileSize = resourceValues[NSURLTotalFileAllocatedSizeKey] as? NSNumber {
diskCacheSize += fileSize.unsignedLongValue
}
} catch _ {
}
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
completionHandler(size: diskCacheSize)
})
})
}
}
// MARK: - Internal Helper
extension ImageCache {
func diskImageForKey(key: String, scale: CGFloat) -> UIImage? {
if let data = diskImageDataForKey(key) {
return UIImage.kf_imageWithData(data, scale: scale)
} else {
return nil
}
}
func diskImageDataForKey(key: String) -> NSData? {
let filePath = cachePathForKey(key)
return NSData(contentsOfFile: filePath)
}
func cachePathForKey(key: String) -> String {
let fileName = cacheFileNameForKey(key)
return (diskCachePath as NSString).stringByAppendingPathComponent(fileName)
}
func cacheFileNameForKey(key: String) -> String {
return key.kf_MD5()
}
}
extension UIImage {
var kf_imageCost: Int {
return images == nil ?
Int(size.height * size.width * scale * scale) :
Int(size.height * size.width * scale * scale) * images!.count
}
}
extension Dictionary {
func keysSortedByValue(isOrderedBefore: (Value, Value) -> Bool) -> [Key] {
return Array(self).sort{ isOrderedBefore($0.1, $1.1) }.map{ $0.0 }
}
}
|
apache-2.0
|
1e0a24cd6c6cadf79606c275baaf6314
| 41.078462 | 337 | 0.589302 | 5.658047 | false | false | false | false |
imitationgame/pokemonpassport
|
pokepass/Model/Main/Nav/MMainNavItem.swift
|
1
|
858
|
import UIKit
class MMainNavItem
{
let image:String
let index:Int
private(set) var state:MMainNavItemState
weak var cell:VMainBarCell?
init(image:String, index:Int)
{
self.image = image
self.index = index
state = MMainNavItemStateNone()
}
//MARK: public
func restate(state:MMainNavItemState)
{
self.state = state
cell?.image.tintColor = state.color
}
func config(cell:VMainBarCell)
{
self.cell = cell
cell.image.image = UIImage(named:image)?.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
cell.image.tintColor = state.color
}
func selected()
{
}
func controller() -> UIViewController
{
let controller:UIViewController = CProjects()
return controller
}
}
|
mit
|
a74483d75c14947e465e300482d25185
| 19.428571 | 103 | 0.602564 | 4.377551 | false | false | false | false |
practicalswift/swift
|
validation-test/compiler_crashers_fixed/00064-bool.swift
|
65
|
678
|
// This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
func q(v: h) -> <r>(() -> r) -> h {
n { u o "\(v): \(u())" }
}
struct e<r> {
j p: , () -> ())] = []
}
protocol p {
}
protocol m : p {
}
protocol v : p {
}
protocol m {
v = m
}
func s<s : m, v : m u v.v == s> (m: v) {
}
func s<v : m u v.v == v> (m: v) {
}
s( {
({})
}
t
|
apache-2.0
|
c08839520dbe2ed6f667a79747f93a09
| 20.870968 | 79 | 0.584071 | 2.83682 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureSettings/Sources/FeatureSettingsUI/Routers/SettingsRouter.swift
|
1
|
24278
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import BlockchainNamespace
import Combine
import DIKit
import FeatureAuthenticationDomain
import FeatureCardPaymentDomain
import FeatureNotificationPreferencesUI
import FeatureReferralDomain
import FeatureReferralUI
import FeatureSettingsDomain
import FeatureUserDeletionData
import FeatureUserDeletionUI
import Localization
import MoneyKit
import PlatformKit
import PlatformUIKit
import RxCocoa
import RxRelay
import RxSwift
import SafariServices
import SwiftUI
import ToolKit
import UIKit
import WebKit
public enum CardOrderingResult {
case created
case cancelled
}
public protocol CardIssuingViewControllerAPI: AnyObject {
func makeIntroViewController(onComplete: @escaping (CardOrderingResult) -> Void) -> UIViewController
func makeManagementViewController(onComplete: @escaping () -> Void) -> UIViewController
}
public protocol AuthenticationCoordinating: AnyObject {
func enableBiometrics()
func changePin()
}
public protocol PaymentMethodsLinkerAPI {
func routeToBankLinkingFlow(
for currency: FiatCurrency,
from viewController: UIViewController,
completion: @escaping () -> Void
)
func routeToCardLinkingFlow(from viewController: UIViewController, completion: @escaping () -> Void)
}
public protocol KYCRouterAPI {
func presentLimitsOverview(from presenter: UIViewController)
}
// swiftlint:disable type_body_length
final class SettingsRouter: SettingsRouterAPI {
private let app: AppProtocol = resolve()
typealias AnalyticsEvent = AnalyticsEvents.Settings
let actionRelay = PublishRelay<SettingsScreenAction>()
let previousRelay = PublishRelay<Void>()
let navigationRouter: NavigationRouterAPI
// MARK: - Routers
private lazy var updateMobileRouter = UpdateMobileRouter(navigationRouter: navigationRouter)
private lazy var backupRouterAPI = BackupFundsRouter(entry: .settings, navigationRouter: navigationRouter)
// MARK: - Private
private let guidRepositoryAPI: FeatureAuthenticationDomain.GuidRepositoryAPI
private let analyticsRecording: AnalyticsEventRecorderAPI
private let alertPresenter: AlertViewPresenter
private let paymentMethodTypesService: PaymentMethodTypesServiceAPI
private unowned let tabSwapping: TabSwapping
private unowned let authenticationCoordinator: AuthenticationCoordinating
private unowned let appStoreOpener: AppStoreOpening
private let passwordRepository: PasswordRepositoryAPI
private let wallet: WalletRecoveryVerifing
private let repository: DataRepositoryAPI
private let pitConnectionAPI: PITConnectionStatusProviding
private let builder: SettingsBuilding
private let analyticsRecorder: AnalyticsEventRecorderAPI
private let externalActionsProvider: ExternalActionsProviderAPI
private let kycRouter: KYCRouterAPI
private let paymentMethodLinker: PaymentMethodsLinkerAPI
private let cardIssuingAdapter: CardIssuingAdapterAPI
private let addCardCompletionRelay = PublishRelay<Void>()
private let disposeBag = DisposeBag()
private var cancellables = Set<AnyCancellable>()
private let exchangeUrlProvider: () -> String
private let urlOpener: URLOpener
private var topViewController: UIViewController {
let topViewController = navigationRouter.topMostViewControllerProvider.topMostViewController
guard let viewController = topViewController else {
fatalError("Failed to present open banking flow, no view controller available for presentation")
}
return viewController
}
init(
builder: SettingsBuilding = SettingsBuilder(),
wallet: WalletRecoveryVerifing = resolve(),
guidRepositoryAPI: FeatureAuthenticationDomain.GuidRepositoryAPI = resolve(),
authenticationCoordinator: AuthenticationCoordinating = resolve(),
appStoreOpener: AppStoreOpening = resolve(),
navigationRouter: NavigationRouterAPI = resolve(),
analyticsRecording: AnalyticsEventRecorderAPI = resolve(),
alertPresenter: AlertViewPresenter = resolve(),
kycRouter: KYCRouterAPI = resolve(),
cardListService: CardListServiceAPI = resolve(),
paymentMethodTypesService: PaymentMethodTypesServiceAPI = resolve(),
pitConnectionAPI: PITConnectionStatusProviding = resolve(),
tabSwapping: TabSwapping = resolve(),
passwordRepository: PasswordRepositoryAPI = resolve(),
repository: DataRepositoryAPI = resolve(),
paymentMethodLinker: PaymentMethodsLinkerAPI = resolve(),
analyticsRecorder: AnalyticsEventRecorderAPI = resolve(),
externalActionsProvider: ExternalActionsProviderAPI = resolve(),
cardIssuingAdapter: CardIssuingAdapterAPI = resolve(),
urlOpener: URLOpener = resolve(),
exchangeUrlProvider: @escaping () -> String
) {
self.wallet = wallet
self.builder = builder
self.authenticationCoordinator = authenticationCoordinator
self.appStoreOpener = appStoreOpener
self.navigationRouter = navigationRouter
self.alertPresenter = alertPresenter
self.analyticsRecording = analyticsRecording
self.kycRouter = kycRouter
self.tabSwapping = tabSwapping
self.guidRepositoryAPI = guidRepositoryAPI
self.paymentMethodTypesService = paymentMethodTypesService
self.pitConnectionAPI = pitConnectionAPI
self.passwordRepository = passwordRepository
self.repository = repository
self.paymentMethodLinker = paymentMethodLinker
self.analyticsRecorder = analyticsRecorder
self.externalActionsProvider = externalActionsProvider
self.cardIssuingAdapter = cardIssuingAdapter
self.exchangeUrlProvider = exchangeUrlProvider
self.urlOpener = urlOpener
previousRelay
.bindAndCatch(weak: self) { (self) in
self.dismiss()
}
.disposed(by: disposeBag)
actionRelay
.bindAndCatch(weak: self) { (self, action) in
self.handle(action: action)
}
.disposed(by: disposeBag)
addCardCompletionRelay
.bindAndCatch(weak: self) { (self) in
cardListService
.fetchCards()
.asSingle()
.subscribe()
.disposed(by: self.disposeBag)
}
.disposed(by: disposeBag)
}
func makeViewController() -> SettingsViewController {
let interactor = SettingsScreenInteractor(
wallet: wallet,
paymentMethodTypesService: paymentMethodTypesService,
authenticationCoordinator: authenticationCoordinator
)
let presenter = SettingsScreenPresenter(interactor: interactor, router: self)
return SettingsViewController(presenter: presenter)
}
func presentSettings() {
navigationRouter.present(viewController: makeViewController(), using: .modalOverTopMost)
}
func dismiss() {
guard let navController = navigationRouter.navigationControllerAPI else { return }
if navController.viewControllersCount > 1 {
navController.popViewController(animated: true)
} else {
navController.dismiss(animated: true, completion: nil)
navigationRouter.navigationControllerAPI = nil
}
}
// swiftlint:disable:next cyclomatic_complexity function_body_length
private func handle(action: SettingsScreenAction) {
switch action {
case .showURL(let url):
navigationRouter
.navigationControllerAPI?
.present(SFSafariViewController(url: url), animated: true, completion: nil)
case .launchChangePassword:
let interactor = ChangePasswordScreenInteractor(passwordAPI: passwordRepository)
let presenter = ChangePasswordScreenPresenter(previousAPI: self, interactor: interactor)
let controller = ChangePasswordViewController(presenter: presenter)
navigationRouter.present(viewController: controller)
case .showRemoveCardScreen(let data):
let viewController = builder.removeCardPaymentMethodViewController(cardData: data)
viewController.transitioningDelegate = sheetPresenter
viewController.modalPresentationStyle = .custom
topViewController.present(viewController, animated: true, completion: nil)
case .showRemoveBankScreen(let data):
let viewController = builder.removeBankPaymentMethodViewController(beneficiary: data)
viewController.transitioningDelegate = sheetPresenter
viewController.modalPresentationStyle = .custom
topViewController.present(viewController, animated: true, completion: nil)
case .showAddCardScreen:
showCardLinkingFlow()
case .showAddBankScreen(let fiatCurrency):
showBankLinkingFlow(currency: fiatCurrency)
case .showAppStore:
appStoreOpener.openAppStore()
case .showBackupScreen:
backupRouterAPI.start()
case .showChangePinScreen:
authenticationCoordinator.changePin()
case .showCurrencySelectionScreen:
let settingsService: FiatCurrencySettingsServiceAPI = resolve()
settingsService
.displayCurrency
.asSingle()
.observe(on: MainScheduler.instance)
.subscribe(onSuccess: { [weak self] currency in
self?.showFiatCurrencySelectionScreen(selectedCurrency: currency)
})
.disposed(by: disposeBag)
case .showTradingCurrencySelectionScreen:
let settingsService: FiatCurrencySettingsServiceAPI = resolve()
settingsService
.tradingCurrency
.asSingle()
.observe(on: MainScheduler.instance)
.subscribe(onSuccess: { [weak self] currency in
self?.showFiatTradingCurrencySelectionScreen(selectedCurrency: currency)
})
.disposed(by: disposeBag)
case .launchWebLogin:
let presenter = WebLoginScreenPresenter(service: WebLoginQRCodeService())
let viewController = WebLoginScreenViewController(presenter: presenter)
viewController.modalPresentationStyle = .overFullScreen
navigationRouter.present(viewController: viewController)
case .promptGuidCopy:
guidRepositoryAPI.guid.asSingle()
.map(weak: self) { _, value -> String in
value ?? ""
}
.observe(on: MainScheduler.instance)
.subscribe(onSuccess: { [weak self] guid in
guard let self = self else { return }
let alert = UIAlertController(
title: LocalizationConstants.AddressAndKeyImport.copyWalletId,
message: LocalizationConstants.AddressAndKeyImport.copyWarning,
preferredStyle: .actionSheet
)
let copyAction = UIAlertAction(
title: LocalizationConstants.AddressAndKeyImport.copyCTA,
style: .destructive,
handler: { [weak self] _ in
guard let self = self else { return }
self.analyticsRecording.record(event: AnalyticsEvent.settingsWalletIdCopied)
UIPasteboard.general.string = guid
}
)
let cancelAction = UIAlertAction(title: LocalizationConstants.cancel, style: .cancel, handler: nil)
alert.addAction(cancelAction)
alert.addAction(copyAction)
guard let navController = self.navigationRouter
.navigationControllerAPI as? UINavigationController
else {
return
}
navController.present(alert, animated: true)
})
.disposed(by: disposeBag)
case .presentTradeLimits:
kycRouter.presentLimitsOverview(from: topViewController)
case .launchPIT:
guard let exchangeUrl = URL(string: exchangeUrlProvider()) else { return }
let launchPIT = AlertAction(
style: .confirm(LocalizationConstants.Exchange.Launch.launchExchange),
metadata: .url(exchangeUrl)
)
let model = AlertModel(
headline: LocalizationConstants.Exchange.title,
body: nil,
actions: [launchPIT],
image: #imageLiteral(resourceName: "exchange-icon-small"),
dismissable: true,
style: .sheet
)
let alert = AlertView.make(with: model) { [weak self] action in
guard let self = self else { return }
guard let metadata = action.metadata else { return }
switch metadata {
case .block(let block):
block()
case .url(let exchangeUrl):
self.urlOpener.open(exchangeUrl)
case .dismiss,
.pop,
.payload:
break
}
}
alert.show()
case .showUpdateEmailScreen:
let interactor = UpdateEmailScreenInteractor()
let presenter = UpdateEmailScreenPresenter(emailScreenInteractor: interactor)
let controller = UpdateEmailScreenViewController(presenter: presenter)
navigationRouter.present(viewController: controller)
case .showUpdateMobileScreen:
updateMobileRouter.start()
case .logout:
externalActionsProvider.logout()
case .showAccountsAndAddresses:
externalActionsProvider.handleAccountsAndAddresses()
case .showContactSupport:
externalActionsProvider.handleSupport()
case .showWebLogin:
externalActionsProvider.handleSecureChannel()
case .showCardIssuing:
showCardIssuingFlow()
case .showNotificationsSettings:
showNotificationsSettingsScreen()
case .showReferralScreen(let referral):
showReferralScreen(with: referral)
case .showUserDeletionScreen:
showUserDeletionScreen()
case .none:
break
}
}
private func showCardIssuingFlow() {
cardIssuingAdapter
.hasCard()
.receive(on: DispatchQueue.main)
.sink { [weak self] hasCard in
if hasCard {
self?.showCardManagementFlow()
} else {
self?.showCardOrderingFlow()
}
}
.store(in: &cancellables)
}
private func showCardManagementFlow() {
let cardIssuing: CardIssuingViewControllerAPI = resolve()
let nav = navigationRouter.navigationControllerAPI
nav?.pushViewController(
cardIssuing.makeManagementViewController(onComplete: {
nav?.popToRootViewControllerAnimated(animated: true)
}),
animated: true
)
}
private func showCardOrderingFlow() {
let cardIssuing: CardIssuingViewControllerAPI = resolve()
let nav = navigationRouter.navigationControllerAPI
nav?.pushViewController(
cardIssuing.makeIntroViewController(onComplete: { [weak self] result in
nav?.popToRootViewControllerAnimated(animated: true)
switch result {
case .created:
self?.showCardManagementFlow()
case .cancelled:
break
}
}),
animated: true
)
}
private func showCardLinkingFlow() {
let presenter = topViewController
app.state.set(blockchain.ux.error.context.action, to: "SETTINGS_CARD_LINKING")
paymentMethodLinker.routeToCardLinkingFlow(from: presenter) { [app, addCardCompletionRelay] in
presenter.dismiss(animated: true) {
addCardCompletionRelay.accept(())
}
app.state.clear(blockchain.ux.error.context.action)
}
}
private func showNotificationsSettingsScreen() {
analyticsRecording.record(event: AnalyticsEvents.New.Settings.notificationClicked)
let presenter = topViewController
let notificationCenterView = FeatureNotificationPreferencesView(store: .init(
initialState: .init(viewState: .loading),
reducer: featureNotificationPreferencesMainReducer,
environment: NotificationPreferencesEnvironment(
mainQueue: .main,
notificationPreferencesRepository: DIKit.resolve(),
analyticsRecorder: DIKit.resolve()
)
))
presenter.present(notificationCenterView)
}
private func showReferralScreen(with referral: Referral) {
let origin = AnalyticsEvents.New.Settings.ReferralOrigin.profile.rawValue
analyticsRecording.record(event: AnalyticsEvents
.New
.Settings
.walletReferralProgramClicked(origin: origin))
let presenter = topViewController
let referralView = ReferFriendView(store: .init(
initialState: .init(referralInfo: referral),
reducer: ReferFriendModule.reducer,
environment: .init(
mainQueue: .main,
analyticsRecorder: DIKit.resolve()
)
))
presenter.present(referralView)
}
private func showUserDeletionScreen() {
analyticsRecording.record(
event: AnalyticsEvents.New.Settings.deleteAccountClicked(
origin: AnalyticsEvents.New.Settings.Origin.settings.rawValue
)
)
let presenter = topViewController
let logoutAndForgetWallet = { [weak self] in
presenter.dismiss(animated: true) {
self?.externalActionsProvider
.logoutAndForgetWallet()
}
}
let dismissFlow = {
presenter.dismiss(animated: true)
}
let view = UserDeletionView(store: .init(
initialState: UserDeletionState(),
reducer: UserDeletionModule.reducer,
environment: .init(
mainQueue: .main,
userDeletionRepository: resolve(),
analyticsRecorder: resolve(),
dismissFlow: dismissFlow,
logoutAndForgetWallet: logoutAndForgetWallet
)
))
presenter.present(view)
}
private func showBankLinkingFlow(currency: FiatCurrency) {
analyticsRecorder.record(event: AnalyticsEvents.New.Withdrawal.linkBankClicked(origin: .settings))
let viewController = topViewController
paymentMethodLinker.routeToBankLinkingFlow(for: currency, from: viewController) {
viewController.dismiss(animated: true, completion: nil)
}
}
private func showFiatCurrencySelectionScreen(selectedCurrency: FiatCurrency) {
let selectionService = FiatCurrencySelectionService(defaultSelectedData: selectedCurrency)
let interactor = SelectionScreenInteractor(service: selectionService)
let presenter = SelectionScreenPresenter(
title: LocalizationConstants.Settings.SelectCurrency.title,
description: LocalizationConstants.Settings.SelectCurrency.description,
searchBarPlaceholder: LocalizationConstants.Settings.SelectCurrency.searchBarPlaceholder,
interactor: interactor
)
let viewController = SelectionScreenViewController(presenter: presenter)
viewController.isModalInPresentation = true
navigationRouter.present(viewController: viewController)
interactor.selectedIdOnDismissal
.map { FiatCurrency(code: $0)! }
.flatMap { currency -> Single<FiatCurrency> in
let settings: FiatCurrencySettingsServiceAPI = resolve()
return settings
.update(
displayCurrency: currency,
context: .settings
)
.asSingle()
.asCompletable()
.andThen(Single.just(currency))
}
.observe(on: MainScheduler.instance)
.subscribe(
onSuccess: { [weak self] currency in
guard let self = self else { return }
// TODO: Remove this and `fiatCurrencySelected` once `ReceiveBTC` and
// `SendBTC` are replaced with Swift implementations.
NotificationCenter.default.post(name: .fiatCurrencySelected, object: nil)
self.analyticsRecording.record(events: [
AnalyticsEvents.Settings.settingsCurrencySelected(currency: currency.code),
AnalyticsEvents.New.Settings.settingsCurrencyClicked(currency: currency.code)
])
},
onFailure: { [weak self] _ in
guard let self = self else { return }
self.alertPresenter.standardError(
message: LocalizationConstants.GeneralError.loadingData
)
}
)
.disposed(by: disposeBag)
}
private func showFiatTradingCurrencySelectionScreen(selectedCurrency: FiatCurrency) {
let selectionService = FiatCurrencySelectionService(
defaultSelectedData: selectedCurrency,
provider: FiatTradingCurrencySelectionProvider()
)
let interactor = SelectionScreenInteractor(service: selectionService)
let presenter = SelectionScreenPresenter(
title: LocalizationConstants.Settings.SelectCurrency.trading,
description: LocalizationConstants.Settings.SelectCurrency.tradingDescription,
searchBarPlaceholder: LocalizationConstants.Settings.SelectCurrency.searchBarPlaceholder,
interactor: interactor
)
let viewController = SelectionScreenViewController(presenter: presenter)
viewController.isModalInPresentation = true
navigationRouter.present(viewController: viewController)
interactor.selectedIdOnDismissal
.map { FiatCurrency(code: $0)! }
.flatMap { currency -> Single<FiatCurrency> in
let settings: FiatCurrencySettingsServiceAPI = resolve()
return settings
.update(
tradingCurrency: currency,
context: .settings
)
.asSingle()
.asCompletable()
.andThen(Single.just(currency))
}
.observe(on: MainScheduler.instance)
.subscribe(
onSuccess: { [weak self] currency in
guard let self = self else { return }
self.analyticsRecording.record(events: [
AnalyticsEvents.Settings.settingsTradingCurrencySelected(currency: currency.code),
AnalyticsEvents.New.Settings.settingsTradingCurrencyClicked(currency: currency.code)
])
},
onFailure: { [weak self] _ in
guard let self = self else { return }
self.alertPresenter.standardError(
message: LocalizationConstants.GeneralError.loadingData
)
}
)
.disposed(by: disposeBag)
}
private lazy var sheetPresenter = BottomSheetPresenting()
}
|
lgpl-3.0
|
c7bd3b188f178f17a8a5df091b102272
| 41.892226 | 119 | 0.636364 | 6.010646 | false | false | false | false |
pdcgomes/RendezVous
|
RendezVous/CommandLineParser.swift
|
1
|
2435
|
//
// cli.swift
// RendezVous
//
// Created by Pedro Gomes on 03/08/2015.
// Copyright © 2015 Pedro Gomes. All rights reserved.
//
import Foundation
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public class CommandLineParser {
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public func runWithArguments(arguments: [String]) -> Bool {
guard validateArguments(arguments) else { return false }
return true
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
public func printUsage() {
let doc : String =
"RendezVous, a simple .strings merger by Pedro Gomes (c) 2015\n" +
"\n" +
"Usage:\n" +
" rendezvous [OPTIONS] <generated_dir> <translations_dir>\n" +
"\n" +
"Examples:\n" +
" rendezvous --reporter json ~/Projects/MyProject/GeneratedStrings ~/Projects/MyProject/Translations\n" +
"\n" +
"Options:\n" +
" -r, --reporter TYPE\n\n" +
"Reporters:\n" +
" json (default)\n" +
" pretty\n"
print(doc)
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
private func validateArguments(arguments: [String]) -> Bool {
guard arguments.count == 2 else { return false }
let tracker = ChangeTracker()
let merger = LocalizedFileMerger(tracker: tracker)
guard merger.checkDirectoryExists(arguments[0]) else { return false }
guard merger.checkDirectoryExists(arguments[1]) else { return false }
let result = merger.findAndMerge(arguments[0], pathForTranslatedStrings: arguments[1])
if result {
// let reporter = ChangeReportStandardOutputRenderer()
let reporter = ChangeReportJSONRender()
reporter.render(tracker.changes, errors: tracker.errors)
}
return true
}
}
|
mit
|
120ddff3ee852f0a1ad3dfa5e58f5d47
| 36.461538 | 119 | 0.40797 | 5.822967 | false | false | false | false |
shaps80/Stack
|
Pod/Classes/Readable.swift
|
1
|
5356
|
/*
Copyright © 2015 Shaps Mohsenin. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY SHAPS MOHSENIN `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 APP BUSINESS 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 CoreData
extension Readable {
/**
Copies the specified object into the current thread's context and returns it to the caller
- parameter object: The object to copy
- returns: The newly copied object
*/
public func copy<T: NSManagedObject>(object: T) -> T {
let objects = copy([object]) as [T]
return objects.first!
}
/**
Copies the specified objects into the current thread's context and returns them to the caller
- parameter objs: The objects to copy
- returns: The newly copied objects
*/
public func copy<T: NSManagedObject>(objects objs: T...) -> [T] {
return copy(objs)
}
/**
Copies the specified objects into the current thread's context and returns them to the caller
- parameter objects: The objects to copy
- returns: The newly copied objects
*/
public func copy<T: NSManagedObject>(objects: [T]) -> [T] {
var results = [T]()
for object in objects {
if object.managedObjectContext == _stack().currentThreadContext() {
results.append(object)
} else {
if let obj = _stack().currentThreadContext().objectWithID(object.objectID) as? T {
results.append(obj)
}
}
}
return results
}
/**
Returns the number of results that would be returned if a fe
tch was performed using the specified query
- parameter query: The query to perform
- throws: An error will be thrown if the query cannot be performed
- returns: The number of results
*/
public func count<T: NSManagedObject>(query: Query<T>) throws -> Int {
let request = try fetchRequest(query)
var error: NSError?
let count = _stack().currentThreadContext().countForFetchRequest(request, error: &error)
if let error = error {
throw StackError.FetchError(error)
}
return count
}
/**
Performs a fetch using the specified query and returns the results to the caller
- parameter query: The query to perform
- throws: An eror will be thrown if the query cannot be performed
- returns: The resulting objects
*/
public func fetch<T: NSManagedObject>(query: Query<T>) throws -> [T] {
let request = try fetchRequest(query)
let stack = _stack()
let context = stack.currentThreadContext()
guard let results = try context.executeFetchRequest(request) as? [T] else {
throw StackError.InvalidResultType(T.Type)
}
return results
}
/**
Performs a fetch using the specified query and returns the first result
- parameter query: The query to perform
- throws: An error will be thrown is the query cannot be performed
- returns: The resulting object or nil
*/
public func fetch<T: NSManagedObject>(first query: Query<T>) throws -> T? {
return try fetch(query).first
}
/**
Performs a fetch using the specified query and returns the last result
- parameter query: The query to perform
- throws: An error will be thrown is the query cannot be performed
- returns: The resulting object or nil
*/
public func fetch<T: NSManagedObject>(last query: Query<T>) throws -> T? {
return try fetch(query).first
}
/**
A convenience method that converts this query into an NSFetchRequest
- parameter query: The query to convert
- throws: An error will be thrown is the entity name cannot be found or an entity couldn't be associated with the specified class (using generics)
- returns: The resulting NSFetchRequest -- Note: this will not be configured
*/
internal func fetchRequest<T: NSManagedObject>(query: Query<T>) throws -> NSFetchRequest {
guard let entityName = _stack().entityNameForManagedObjectClass(T) else {
throw StackError.EntityNameNotFoundForClass(T)
}
guard let request = query.fetchRequestForEntityNamed(entityName) else {
throw StackError.EntityNotFoundInStack(_stack(), entityName)
}
return request
}
}
|
mit
|
edc53928b52a83aeef2ff16922c08ab5
| 30.875 | 149 | 0.695612 | 4.76 | false | false | false | false |
jackcook/mist
|
Mist/Mozart.swift
|
1
|
3889
|
// Mozart.swift (v. 0.1)
//
// Copyright (c) 2015 Jack Cook
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
class Mozart {
class func load(url: String) -> LoadingClass {
let loadingClass = LoadingClass(url: url)
return loadingClass
}
}
class LoadingClass {
var url: String!
var completionBlock: (UIImage -> Void)!
var imageView: UIImageView!
var button: UIButton!
var controlState: UIControlState!
var controlStates: [UIControlState]!
var holderType = ImageHolder.Unknown
init(url: String) {
self.url = url
getImage() { (img) -> Void in
switch self.holderType {
case .ImageView:
self.imageView.image = img
case .ButtonWithoutControlState:
self.button.setImage(img, forState: .Normal)
case .ButtonWithControlState:
self.button.setImage(img, forState: self.controlState)
case .ButtonWithControlStates:
for state in self.controlStates {
self.button.setImage(img, forState: state)
}
case .Unknown:
break
}
}
}
func into(imageView: UIImageView) -> LoadingClass {
self.imageView = imageView
holderType = .ImageView
return self
}
func into(button: UIButton) -> LoadingClass {
self.button = button
holderType = .ButtonWithoutControlState
return self
}
func into(button: UIButton, forState state: UIControlState) -> LoadingClass {
self.button = button
controlState = state
holderType = .ButtonWithControlState
return self
}
func into(button: UIButton, forStates states: [UIControlState]) -> LoadingClass {
self.button = button
controlStates = states
holderType = .ButtonWithControlStates
return self
}
func completion(block: UIImage -> Void) {
completionBlock = block
}
internal func getImage(block: UIImage -> Void) {
let actualUrl = NSURL(string: url)!
let request = NSURLRequest(URL: actualUrl)
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { (response, data, error) -> Void in
if error == nil {
let image = UIImage(data: data)!
block(image)
if (self.completionBlock != nil) {
self.completionBlock(image)
}
} else {
println("Error: \(error.localizedDescription)")
}
}
}
}
enum ImageHolder {
case ImageView, ButtonWithoutControlState, ButtonWithControlState, ButtonWithControlStates, Unknown
}
|
mit
|
fdb91a25951688633a90fa53b85a8bf6
| 31.966102 | 130 | 0.625868 | 4.873434 | false | false | false | false |
googlearchive/science-journal-ios
|
ScienceJournal/UI/SensorStatsView.swift
|
1
|
4924
|
/*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import UIKit
/// A view that displays the minimum, average and maximum values of a given sensor recording, in a
/// horizontally aligned stackView. This view is used in Trial cards (via TrialCardSensorView) but
/// can also be used in sensor cards when recording. Looks like:
///
/// Header | Header | Header
/// Value | Value | Value
///
class SensorStatsView: UIView {
// MARK: - Properties
/// The height of the sensor stats view.
static let height = StatView.height
/// The color of the min and max value labels.
var textColor: UIColor? = SensorStatType.min.textColor {
didSet {
minView.valueTextColor = textColor
maxView.valueTextColor = textColor
}
}
private let minView = StatView(headerText: SensorStatType.min.title,
valueTextColor: SensorStatType.min.textColor)
private let averageView = StatView(headerText: SensorStatType.average.title,
valueTextColor: SensorStatType.average.textColor)
private let maxView = StatView(headerText: SensorStatType.max.title,
valueTextColor: SensorStatType.max.textColor)
private let firstPipeView = SeparatorView(direction: .vertical, style: .dark)
private let secondPipeView = SeparatorView(direction: .vertical, style: .dark)
private enum Metrics {
static let statsSpacing: CGFloat = 26.0
}
private var size: CGSize {
let width = minView.frame.width + averageView.frame.width + maxView.frame.width +
Metrics.statsSpacing * 4 + firstPipeView.frame.width + secondPipeView.frame.width
return CGSize(width: width, height: SensorStatsView.height)
}
// MARK: - Public
/// Designated initializer.
///
/// - Parameters:
/// - min: The minimum value.
/// - average: The average value.
/// - max: The maximum value.
init(min: String, average: String, max: String) {
super.init(frame: .zero)
configureView()
setMin(min, average: average, max: max)
}
override init(frame: CGRect) {
fatalError("init(frame:) is not supported")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) is not supported")
}
override var intrinsicContentSize: CGSize {
return size
}
override func sizeThatFits(_ size: CGSize) -> CGSize {
return self.size
}
/// Sets the stat values.
///
/// - Parameters:
/// - min: The minimum value.
/// - average: The average value.
/// - max: The maximum value.
func setMin(_ min: String, average: String, max: String) {
minView.valueText = min
minView.sizeToFit()
averageView.valueText = average
averageView.sizeToFit()
maxView.valueText = max
maxView.sizeToFit()
setNeedsLayout()
}
override func layoutSubviews() {
super.layoutSubviews()
minView.frame = CGRect(x: 0,
y: 0,
width: minView.frame.width,
height: minView.frame.height)
firstPipeView.frame = CGRect(x: minView.frame.maxX + Metrics.statsSpacing,
y: 0,
width: firstPipeView.frame.width,
height: bounds.height)
averageView.frame = CGRect(x: firstPipeView.frame.maxX + Metrics.statsSpacing,
y: 0,
width: averageView.frame.width,
height: averageView.frame.height)
secondPipeView.frame = CGRect(x: averageView.frame.maxX + Metrics.statsSpacing,
y: 0,
width: secondPipeView.frame.width,
height: bounds.height)
maxView.frame = CGRect(x: secondPipeView.frame.maxX + Metrics.statsSpacing,
y: 0,
width: maxView.frame.width,
height: maxView.frame.height)
[minView, firstPipeView, averageView, secondPipeView, maxView].forEach {
$0.adjustFrameForLayoutDirection()
}
}
// MARK: - Private
private func configureView() {
addSubview(minView)
addSubview(firstPipeView)
addSubview(averageView)
addSubview(secondPipeView)
addSubview(maxView)
}
}
|
apache-2.0
|
2dbdcb3535343ec4b284d1959856652b
| 32.958621 | 98 | 0.626117 | 4.319298 | false | false | false | false |
yscode001/YSExtension
|
YSExtension/YSExtension/YSExtension/Foundation/CGFloat+ysExtension.swift
|
1
|
1614
|
import UIKit
extension CGFloat{
/// 根据参考值获取结果(如:目标1-1000,参考100-100000,开始与结束值对应,那么参考值为555时,返回5.55)
///
/// - Parameters:
/// - resultFrom: 结果From
/// - resultTo: 结果To
/// - consuleFrom: 参考From
/// - consuleTo: 参考To
/// - consuleValue: 参考值
/// - Returns: 结果值
public static func ys_getResultValue(resultFrom:CGFloat, resultTo:CGFloat, consuleFrom:CGFloat, consuleTo:CGFloat, consuleValue:CGFloat) -> CGFloat{
if resultFrom <= 0 || resultTo <= 0 || consuleFrom <= 0 || consuleTo <= 0 || consuleValue <= 0{
return 0
}
if resultFrom >= resultTo || consuleFrom >= consuleTo{
return 0
}
let a = (resultFrom - resultTo) / (consuleFrom - consuleTo);
let b = resultFrom - (a * consuleFrom);
return a * consuleValue + b;
}
public func ys_string(locale:Locale? = nil) -> String{
let loc = locale == nil ? Locale.current : locale
return String(format: "%f", locale: loc, self)
}
/// 非0即真
///
/// - Returns: bool值
public func ys_boolValue() -> Bool{
return self != 0
}
}
extension Float{
public func ys_string(locale:Locale? = nil) -> String{
let loc = locale == nil ? Locale.current : locale
return String(format: "%f", locale: loc, self)
}
/// 非0即真
///
/// - Returns: bool值
public func ys_boolValue() -> Bool{
return self != 0
}
}
|
mit
|
dccc7fbb8075c7fe2d08bcdf0ff571aa
| 26.381818 | 152 | 0.545817 | 3.56872 | false | false | false | false |
san2ride/iOS10-FHG1.0
|
FHG1.1/FHG1.1/TrainingTableViewController.swift
|
1
|
2014
|
//
// TrainingTableViewController.swift
// FHG1.1
//
// Created by don't touch me on 2/6/17.
// Copyright © 2017 trvl, LLC. All rights reserved.
//
import UIKit
class TrainingTableViewController: UITableViewController {
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 128, height: 42))
imageView.contentMode = .scaleAspectFit
let image = UIImage(named: "fhgnew4")
imageView.image = image
navigationItem.titleView = imageView
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let url : URL?
switch indexPath.section {
case 0:
switch indexPath.row {
case 0:
url = URL(string: "http://www.thefhguide.com/train.html")
case 1:
url = URL(string: "http://www.thefhguide.com/train-present.html")
case 2:
url = URL(string: "http://www.thefhguide.com/train-catalog.html")
case 3:
url = URL(string: "http://www.thefhguide.com/train-individuals.html")
case 4:
url = URL(string: "http://www.thefhguide.com/train-families.html")
case 5:
url = URL(string: "http://www.thefhguide.com/train-groups.html")
case 6:
url = URL(string: "http://www.thefhguide.com/train-consultants.html")
case 7:
url = URL(string: "http://www.thefhguide.com/tracker.html")
case 8:
url = URL(string: "http://www.thefhguide.com/train-tools.html")
default:
return;
}
default:
return;
}
if url != nil {
UIApplication.shared.open(url!, options: [:], completionHandler: nil)
}
}
}
|
mit
|
2a8322c66115b5578771e9399e5ebc57
| 29.5 | 92 | 0.536513 | 4.220126 | false | false | false | false |
jie-json/swift-corelibs-foundation-master
|
Foundation/NSURLProtectionSpace.swift
|
1
|
8481
|
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
/*!
@const NSURLProtectionSpaceHTTP
@abstract The protocol for HTTP
*/
public let NSURLProtectionSpaceHTTP: String = "" // NSUnimplemented
/*!
@const NSURLProtectionSpaceHTTPS
@abstract The protocol for HTTPS
*/
public let NSURLProtectionSpaceHTTPS: String = "" // NSUnimplemented
/*!
@const NSURLProtectionSpaceFTP
@abstract The protocol for FTP
*/
public let NSURLProtectionSpaceFTP: String = "" // NSUnimplemented
/*!
@const NSURLProtectionSpaceHTTPProxy
@abstract The proxy type for http proxies
*/
public let NSURLProtectionSpaceHTTPProxy: String = "" // NSUnimplemented
/*!
@const NSURLProtectionSpaceHTTPSProxy
@abstract The proxy type for https proxies
*/
public let NSURLProtectionSpaceHTTPSProxy: String = "" // NSUnimplemented
/*!
@const NSURLProtectionSpaceFTPProxy
@abstract The proxy type for ftp proxies
*/
public let NSURLProtectionSpaceFTPProxy: String = "" // NSUnimplemented
/*!
@const NSURLProtectionSpaceSOCKSProxy
@abstract The proxy type for SOCKS proxies
*/
public let NSURLProtectionSpaceSOCKSProxy: String = "" // NSUnimplemented
/*!
@const NSURLAuthenticationMethodDefault
@abstract The default authentication method for a protocol
*/
public let NSURLAuthenticationMethodDefault: String = "" // NSUnimplemented
/*!
@const NSURLAuthenticationMethodHTTPBasic
@abstract HTTP basic authentication. Equivalent to
NSURLAuthenticationMethodDefault for http.
*/
public let NSURLAuthenticationMethodHTTPBasic: String = "" // NSUnimplemented
/*!
@const NSURLAuthenticationMethodHTTPDigest
@abstract HTTP digest authentication.
*/
public let NSURLAuthenticationMethodHTTPDigest: String = "" // NSUnimplemented
/*!
@const NSURLAuthenticationMethodHTMLForm
@abstract HTML form authentication. Applies to any protocol.
*/
public let NSURLAuthenticationMethodHTMLForm: String = "" // NSUnimplemented
/*!
@const NSURLAuthenticationMethodNTLM
@abstract NTLM authentication.
*/
public let NSURLAuthenticationMethodNTLM: String = "" // NSUnimplemented
/*!
@const NSURLAuthenticationMethodNegotiate
@abstract Negotiate authentication.
*/
public let NSURLAuthenticationMethodNegotiate: String = "" // NSUnimplemented
/*!
@const NSURLAuthenticationMethodClientCertificate
@abstract SSL Client certificate. Applies to any protocol.
*/
public let NSURLAuthenticationMethodClientCertificate: String = "" // NSUnimplemented
/*!
@const NSURLAuthenticationMethodServerTrust
@abstract SecTrustRef validation required. Applies to any protocol.
*/
public let NSURLAuthenticationMethodServerTrust: String = "" // NSUnimplemented
/*!
@class NSURLProtectionSpace
@discussion This class represents a protection space requiring authentication.
*/
public class NSURLProtectionSpace : NSObject, NSSecureCoding, NSCopying {
public func copyWithZone(zone: NSZone) -> AnyObject { NSUnimplemented() }
public static func supportsSecureCoding() -> Bool { return true }
public func encodeWithCoder(aCoder: NSCoder) {
NSUnimplemented()
}
public required init?(coder aDecoder: NSCoder) {
NSUnimplemented()
}
/*!
@method initWithHost:port:protocol:realm:authenticationMethod:
@abstract Initialize a protection space representing an origin server, or a realm on one
@param host The hostname of the server
@param port The port for the server
@param protocol The sprotocol for this server - e.g. "http", "ftp", "https"
@param realm A string indicating a protocol-specific subdivision
of a single host. For http and https, this maps to the realm
string in http authentication challenges. For many other protocols
it is unused.
@param authenticationMethod The authentication method to use to access this protection space -
valid values include nil (default method), @"digest" and @"form".
@result The initialized object.
*/
public init(host: String, port: Int, `protocol`: String?, realm: String?, authenticationMethod: String?) { NSUnimplemented() }
/*!
@method initWithProxyHost:port:type:realm:authenticationMethod:
@abstract Initialize a protection space representing a proxy server, or a realm on one
@param host The hostname of the proxy server
@param port The port for the proxy server
@param type The type of proxy - e.g. "http", "ftp", "SOCKS"
@param realm A string indicating a protocol-specific subdivision
of a single host. For http and https, this maps to the realm
string in http authentication challenges. For many other protocols
it is unused.
@param authenticationMethod The authentication method to use to access this protection space -
valid values include nil (default method) and @"digest"
@result The initialized object.
*/
public init(proxyHost host: String, port: Int, type: String?, realm: String?, authenticationMethod: String?) { NSUnimplemented() }
/*!
@method realm
@abstract Get the authentication realm for which the protection space that
needs authentication
@discussion This is generally only available for http
authentication, and may be nil otherwise.
@result The realm string
*/
public var realm: String? { NSUnimplemented() }
/*!
@method receivesCredentialSecurely
@abstract Determine if the password for this protection space can be sent securely
@result YES if a secure authentication method or protocol will be used, NO otherwise
*/
public var receivesCredentialSecurely: Bool { NSUnimplemented() }
/*!
@method isProxy
@abstract Determine if this authenticating protection space is a proxy server
@result YES if a proxy, NO otherwise
*/
/*!
@method host
@abstract Get the proxy host if this is a proxy authentication, or the host from the URL.
@result The host for this protection space.
*/
public var host: String { NSUnimplemented() }
/*!
@method port
@abstract Get the proxy port if this is a proxy authentication, or the port from the URL.
@result The port for this protection space, or 0 if not set.
*/
public var port: Int { NSUnimplemented() }
/*!
@method proxyType
@abstract Get the type of this protection space, if a proxy
@result The type string, or nil if not a proxy.
*/
public var proxyType: String? { NSUnimplemented() }
/*!
@method protocol
@abstract Get the protocol of this protection space, if not a proxy
@result The type string, or nil if a proxy.
*/
public var `protocol`: String? { NSUnimplemented() }
/*!
@method authenticationMethod
@abstract Get the authentication method to be used for this protection space
@result The authentication method
*/
public var authenticationMethod: String { NSUnimplemented() }
public override func isProxy() -> Bool { NSUnimplemented() }
}
extension NSURLProtectionSpace {
/*!
@method distinguishedNames
@abstract Returns an array of acceptable certificate issuing authorities for client certification authentication. Issuers are identified by their distinguished name and returned as a DER encoded data.
@result An array of NSData objects. (Nil if the authenticationMethod is not NSURLAuthenticationMethodClientCertificate)
*/
public var distinguishedNames: [NSData]? { NSUnimplemented() }
}
// TODO: Currently no implementation of Security.framework
/*
extension NSURLProtectionSpace {
/*!
@method serverTrust
@abstract Returns a SecTrustRef which represents the state of the servers SSL transaction state
@result A SecTrustRef from Security.framework. (Nil if the authenticationMethod is not NSURLAuthenticationMethodServerTrust)
*/
public var serverTrust: SecTrust? { NSUnimplemented() }
}
*/
|
apache-2.0
|
a0bc38e17c023218d4414b5ebbc22c4d
| 35.556034 | 208 | 0.710765 | 5.401911 | false | false | false | false |
ohadh123/MuscleUp-
|
Pods/LionheartExtensions/Pod/Classes/Core/NSDecimalNumber+LionheartExtensions.swift
|
1
|
1891
|
//
// NSDecimalNumber.swift
// Pods
//
// Created by Daniel Loewenherz on 3/16/16.
//
//
import Foundation
/**
- source: https://gist.github.com/mattt/1ed12090d7c89f36fd28
*/
extension NSDecimalNumber: Comparable {}
public extension NSDecimalNumber {
static func ==(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool {
return lhs.compare(rhs) == .orderedSame
}
static func <(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool {
return lhs.compare(rhs) == .orderedAscending
}
static func >(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> Bool {
return lhs.compare(rhs) == .orderedDescending
}
static prefix func -(value: NSDecimalNumber) -> NSDecimalNumber {
return value.multiplying(by: NSDecimalNumber(mantissa: 1, exponent: 0, isNegative: true))
}
static func +(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.adding(rhs)
}
static func -(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.subtracting(rhs)
}
static func *(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.multiplying(by: rhs)
}
static func /(lhs: NSDecimalNumber, rhs: NSDecimalNumber) -> NSDecimalNumber {
return lhs.dividing(by: rhs)
}
static func ^(lhs: NSDecimalNumber, rhs: Int) -> NSDecimalNumber {
return lhs.raising(toPower: rhs)
}
// MARK: - Assignment
static func +=(lhs: inout NSDecimalNumber, rhs: NSDecimalNumber) {
lhs = lhs + rhs
}
static func -=(lhs: inout NSDecimalNumber, rhs: NSDecimalNumber) {
lhs = lhs - rhs
}
static func *=(lhs: inout NSDecimalNumber, rhs: NSDecimalNumber) {
lhs = lhs * rhs
}
static func /=(lhs: inout NSDecimalNumber, rhs: NSDecimalNumber) {
lhs = lhs / rhs
}
}
|
apache-2.0
|
cf133c9f6c0497961516c1dac0b1038a
| 25.633803 | 97 | 0.644632 | 4.367206 | false | false | false | false |
Bartlebys/Bartleby
|
Bartleby.xOS/core/extensions/BartlebyDocument+Operations.swift
|
1
|
15178
|
//
// Document+Operations.swift
// BartlebyKit
//
// Created by Benoit Pereira da silva on 05/05/2016.
//
//
import Foundation
// MARK: - Operation support
extension BartlebyDocument {
// MARK: - Supervised Automatic Push
func startPushLoopIfNecessary() {
if self._timer == nil && !self.metadata.isolatedUserMode{
self._timer = Timer.scheduledTimer(timeInterval: Bartleby.configuration.LOOP_TIME_INTERVAL_IN_SECONDS,
target: self,
selector: #selector(BartlebyDocument._pushLoop),
userInfo: nil,
repeats: true)
}
}
func destroyThePushLoop(){
self._timer?.invalidate()
self._timer=nil
}
// The push loop
@objc internal func _pushLoop () -> () {
if self.metadata.pushOnChanges{
self.synchronizePendingOperations()
}
}
// MARK: - Operations
/**
Synchronizes the pending operations
1. Proceeds to login if necessart
2. Then commits the pending changes and pushes operations
- parameter handlers: the handlers to monitor the progress and completion
*/
public func synchronizePendingOperations() {
if let currentUser=self.metadata.currentUser {
if currentUser.loginHasSucceed{
do {
try self._commitAndPushPendingOperations()
} catch {
self.synchronizationHandlers.on(Completion.failureState("Push operations has failed. Error: \(error)", statusCode: StatusOfCompletion.expectation_Failed))
}
}else{
currentUser.login( sucessHandler: {
do {
try self._commitAndPushPendingOperations()
} catch {
self.synchronizationHandlers.on(Completion.failureState("Push operations has failed. Error: \(error)", statusCode: StatusOfCompletion.expectation_Failed))
}
}, failureHandler: { (context) in
if context.httpStatusCode==403{
self.close()
}else{
self.log("synchronizePendingOperations Login has failed \(context)", file: #file, function: #function, line: #line, category: Default.LOG_DEFAULT, decorative: false)
self.transition(DocumentMetadata.Transition.onToOff)
}
})
}
}
}
/**
Commits and Pushes the pending operations.
The Command will optimize and inject commands if some changes has occured.
- parameter handlers: the handlers to monitor the progress and completion
- throws: throws
*/
fileprivate func _commitAndPushPendingOperations()throws {
// Commit the pending changes (if there are changes)
// Each changed object creates a new Operation
try self.commitPendingChanges()
self._pushNextBunch()
}
/**
Commits the pending changes.
- throws: may throw on collection iteration
*/
public func commitPendingChanges() throws {
self.iterateOnCollections { (collection) in
collection.commitChanges()
}
}
fileprivate func _pushNextBunch(){
// Push next bunch if there is no bunch in progress
if !self.metadata.bunchInProgress {
// We donnot want to schedule anything if there is nothing to do.
if self.pushOperations.count > 0 {
let nextBunchOfOperations=self._getNextBunchOfPendingOperations()
if nextBunchOfOperations.count>0{
self.log("Pushing Next Bunch of operations",file:#file,function:#function,line:#line,category:Default.LOG_DEFAULT,decorative:false)
let bunchHandlers=Handlers(completionHandler: { (completionState) in
self._pushNextBunch()
}, progressionHandler: { (progressionState) in
self.synchronizationHandlers.notify(progressionState)
})
self.pushSortedOperations(nextBunchOfOperations, handlers:bunchHandlers)
}
}
}
}
fileprivate func _getNextBunchOfPendingOperations()->[PushOperation]{
var nextBunch=[PushOperation]()
let filtered=self.pushOperations.filter { $0.canBePushed() }
let filteredCount=filtered.count
let maxBunchSize=Bartleby.configuration.MAX_OPERATIONS_BUNCH_SIZE
if filteredCount > 0 {
let lastOperationIdx = filteredCount-1
let maxIndex:Int = min(maxBunchSize,lastOperationIdx)
for i in 0 ... maxIndex {
nextBunch.append(filtered[i])
}
}
return nextBunch
}
/**
Pushes an array of operations
- On successful completion the operation is deleted.
- On total completion the tasks are deleted on global success.
If an error as occured the task group is preserved for re-run or analysis.
- parameter operations: the sorted operations to be excecuted
- parameter handlers: the handlers to hook the completion / Progression
*/
public func pushSortedOperations(_ bunchOfOperations: [PushOperation], handlers: Handlers?)->() {
let totalNumberOfOperations=self.pushOperations.count
if self.metadata.pendingOperationsProgressionState==nil{
// It is the first Bunch
self.metadata.totalNumberOfOperations=self.pushOperations.count
self.metadata.pendingOperationsProgressionState=Progression(currentTaskIndex: 0, totalTaskCount:totalNumberOfOperations, currentPercentProgress:0, message: self._messageForOperation(nil), data:nil).identifiedBy("Operations", identity:"Operations."+self.UID)
}
let nbOfOperationsInCurrentBunch=bunchOfOperations.count
if nbOfOperationsInCurrentBunch>0 {
// Flag there is an active Bunch of Operations in Progress
self.metadata.bunchInProgress=true
for operation in bunchOfOperations{
if let serialized=operation.serialized {
do{
let o = try self.dynamics.deserialize(typeName: operation.operationName, data: serialized, document: nil)
// #TODO why is it necessary to cast to ManagedModel?
// If we set to BartlebyOperation it fails
if let op=o as? ManagedModel & BartlebyOperation {
op.referentDocument = self
syncOnMain{
// Push the command.
op.push(sucessHandler: { (context) in
//////////////////////////////////////////////////
// Delete the operation from self.pushOperations
//////////////////////////////////////////////////
self.delete(operation)
// Update the completion / Progression
self._onCompletion(operation, within: bunchOfOperations, handlers: handlers,identity:self.metadata.pendingOperationsProgressionState!.externalIdentifier)
}, failureHandler: { (context) in
let statusCode=context.httpStatusCode
// Operations Quarantine
// According to https://github.com/Bartlebys/Bartleby/issues/23
if [403,406,412,417].contains(statusCode) {
//////////////////////////////////////////////////
// Put the operation in Quarantine
// Delete the operation from self.pushOperations
//////////////////////////////////////////////////
self.metadata.operationsQuarantine.append(operation)
self.delete(operation)
}else if statusCode == 404 {
//////////////////////////////////////////////////
// UPDATE operation with 404 is normal on deleted entity
// According to https://github.com/Bartlebys/Bartleby/issues/24
//////////////////////////////////////////////////
let opTypeName=op.runTimeTypeName()
if opTypeName.contains("Update"){
// We delete the operation
// And The local entity will be deleted by a trigger later.
self.delete(operation)
}
}
// Update the completion / Progression
self._onCompletion(operation, within: bunchOfOperations, handlers: handlers,identity:self.metadata.pendingOperationsProgressionState!.externalIdentifier)
})
}
} else {
let completion=Completion.failureState(NSLocalizedString("Error of operation casting", tableName:"operations", comment: "Error of operation casting"), statusCode: StatusOfCompletion.expectation_Failed)
self.log(completion, file: #file, function: #function, line: #line, category: "Operations")
handlers?.on(completion)
}
} catch {
let completion=Completion.failureState(NSLocalizedString( "Error on operation deserialization", tableName:"operations", comment: "Error on operation deserialization"), statusCode: StatusOfCompletion.expectation_Failed)
self.log(completion, file: #file, function: #function, line: #line, category: "Operations")
handlers?.on(completion)
}
} else {
let completion=Completion.failureState(NSLocalizedString( "Error when converting the operation to dictionnary", tableName:"operations", comment: "Error when converting the operation to dictionnary"), statusCode: StatusOfCompletion.precondition_Failed)
self.log(completion, file: #file, function: #function, line: #line, category: "Operations")
handlers?.on(completion)
}
}
} else {
let completion=Completion.successState()
completion.message=NSLocalizedString("Void bunch of operations", tableName:"operations", comment: "Void bunch of operations")
handlers?.on(completion)
}
}
/**
Called on the completion of any operation in the bunch
- parameter completedOperation: the completed operation
- parameter bunchOfOperations: the bunch
- parameter handlers: the global handlers
- parameter identity: the bunch identity
*/
fileprivate func _onCompletion(_ completedOperation:PushOperation,within bunchOfOperations:[PushOperation], handlers:Handlers?,identity:String){
let nbOfunCompletedOperationsInBunch=Double(bunchOfOperations.filter { $0.completionState==nil }.count)
let currentOperationsCounter=self.pushOperations.count
if nbOfunCompletedOperationsInBunch == 0{
let _=self._updateProgressionState(completedOperation,currentOperationsCounter)
// All the operation of that bunch have been completed.
let bunchCompletionState=Completion().identifiedBy("Operations", identity:identity)
bunchCompletionState.success=bunchOfOperations.reduce(true, { (success, operation) -> Bool in
if operation.completionState?.success==true{
return true
}
return false
})
if bunchCompletionState.success{
bunchCompletionState.statusCode = StatusOfCompletion.ok.rawValue
}else{
bunchCompletionState.statusCode = StatusOfCompletion.expectation_Failed.rawValue
}
self.metadata.bunchInProgress=false
handlers?.on(bunchCompletionState)
// Let's remove the progression state if there is no more operations
if currentOperationsCounter==0 {
self.metadata.pendingOperationsProgressionState=nil
self.metadata.totalNumberOfOperations=0//Reset the number of operation
let finalCompletionState=Completion.successState().identifiedBy("Operations", identity:identity)
self.synchronizationHandlers.on(finalCompletionState)
}
}else{
if let progressionState=self._updateProgressionState(completedOperation,currentOperationsCounter){
handlers?.notify(progressionState)
}
}
}
fileprivate func _updateProgressionState(_ completedOperation:PushOperation,_ currentOperationsCounter:Int)->Progression?{
if let progressionState=self.metadata.pendingOperationsProgressionState{
let total=Double(self.metadata.totalNumberOfOperations)
let completed=Double(self.metadata.totalNumberOfOperations-currentOperationsCounter)
let currentPercentProgress=completed*Double(100)/total
progressionState.currentTaskIndex=Int(completed)
progressionState.totalTaskCount=Int(total)
progressionState.currentPercentProgress=currentPercentProgress
progressionState.message=self._messageForOperation(completedOperation)
return progressionState
}else{
self.log("Internal inconsistency unable to find identified operation bunch", file: #file, function: #function, line: #line, category: "Operations")
return nil
}
}
fileprivate func _messageForOperation(_ operation:PushOperation?)->String{
return NSLocalizedString("Upstream Data transmission", tableName:"operations", comment: "Upstream Data transmission")
}
/**
A collection iterator
- parameter on: the iteration closure
*/
public func iterateOnCollections(_ on:(_ collection: BartlebyCollection)->()){
for (_, collection) in self._collections {
on(collection)
}
}
}
|
apache-2.0
|
ab862fe9cf4a2070f5eacf3af6fdb128
| 46.283489 | 271 | 0.56516 | 5.885227 | false | false | false | false |
cdtschange/SwiftMKit
|
SwiftMKit/UI/Schema/BaseKitViewModel.swift
|
1
|
1844
|
//
// BaseKitViewModel.swift
// SwiftMKitDemo
//
// Created by Mao on 4/3/16.
// Copyright © 2016 cdts. All rights reserved.
//
import UIKit
import CocoaLumberjack
import Alamofire
open class BaseKitViewModel: NSObject {
open weak var viewController: BaseKitViewController!
open var hud: HudProtocol {
get { return self.viewController.hud }
}
open var taskIndicator: Indicator {
get { return self.viewController.taskIndicator }
}
open var view: UIView {
get { return self.viewController.view }
}
open func fetchData() {
}
open func dataBinded() {
}
deinit {
DDLogError("Deinit: \(NSStringFromClass(type(of: self)))")
}
}
//HUD
extension BaseKitViewModel {
public func showTip(_ tip: String, completion : @escaping () -> Void = {}) {
viewController.showTip(inView: viewController.view, text: tip, completion: completion)
}
public func showTip(_ tip: String, image: UIImage?, completion : @escaping () -> Void = {}) {
viewController.showTip(inView: viewController.view, text: tip, image: image, completion: completion)
}
public func showTip(_ tip: String, view: UIView, offset: CGPoint = CGPoint.zero, completion : @escaping () -> Void = {}) {
viewController.showTip(inView: view, text: tip, offset: offset, completion: completion)
}
public func showLoading(text: String? = nil, detailText: String? = nil) {
viewController.showLoading(text: text, detailText: detailText)
}
public func showLoading(_ text: String, view: UIView) {
viewController.showIndicator(inView: view, text: text)
}
public func hideLoading() {
viewController?.hideLoading()
}
public func hideLoading(_ view: UIView) {
viewController?.hideLoading(view)
}
}
|
mit
|
f3277aa26ce7820ae14d71f264d5534e
| 29.716667 | 126 | 0.653283 | 4.286047 | false | false | false | false |
cnoon/swift-compiler-crashes
|
crashes-duplicates/24623-llvm-dagtypelegalizer-expandres-bitcast.swift
|
9
|
2313
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
class B
struct S<T where g:B
map
enum S<T where g:a{}typealias F = B{
import Foundation
struct A:a{
var d : N
var : T NSObject {
enum S<T NSObject {
func d:a{
class a{
}typealias F = B{}
class B<T :a{
let end = D
let h=(false)
class A{
typealias e
struct B<U:a{}}
import Foundation
}
let a d{
b}
enum S<T where B : d
}
}
enum S<T {
}
{
struct Q<T :a{
struct B
class B<T where g:A,T where g: P {
let end = D
}
class A{
protocol A<T where B : P {
}}
enum S<T where g: d
class A{
struct B{
}{
d {
if c{
enum S<d : T {
struct D : a {
A
{
{
if true {
class d
} :SequenceType
class c<T where g: () {
d : T where g:a{
}
{
struct A{{}func i(}}
class A{
enum S<T NSObject {
let end = D> ) {
}}
class a
let end = D
}
struct B<T NSObject {
}
d {func g {
func a{
struct B
let end = D> ) {
{
} :a{{ {}}}
let end = D> ) {
typealias F = D> ) {
let end = B
var d {var b}
typealias e:a{var b{}protocol a{
func d:a{
typealias e:a{
struct B
}}}}func g {
" B<T {
b}}
func a{
struct Q<d {func d:d
func g {
var _=a{
typealias d
func a{
}
func i() {
func a{
class a{func a{
" B<T where g: a {
assert(}func a{
}}
b{
{var b}protocol A{}
map
class B
}
d {
{
class d
class B
{{ {
let h=(}}
{
let end = B{
protocol A{
if true {
}
}func i(x{
A,T {
let end = B{
{}
struct B<T where g: d
}}protocol a{
{
class d {var _=a{
class B<d : d
map
enum S<A<A:A:a{
{func d<T where g:A<A.e:d
typealias e
struct S<T where g:B:d
func i(false)
class B<A{
}
class a{}}
func a{{ {
struct S<T {
}protocol A:a{}
struct B
}
struct B
class c<d where g:A{
}
if true {
struct B<T NSObject {
if true {
struct B<T NSObject {
enum S<T {
struct B<T :SequenceType
class A<T where g:a{
}typealias d:A
func a{
import Foundation
struct B
var _=a{
class a{var b[]
struct S{
struct A<T :a{var b[B<T where B : d{
func d{
class A
if c<T where g: P {}
let a {
struct A,T where g: T NSObject {}
var _=() {
typealias F = D
}
}}}
}}func g {
func i() {{ {{
{
func a
enum S<T where g: a d
class B<T where g:SequenceType
typealias d:d<A{
import Foundation
struct A:a{
struct A{
struct S<d : d:a{{
struct B<T where B:a
struct S<T :A{
}}
class d {
}
" B
struct B<T :SequenceType
enum S<T where g:a{
}func a{
protocol
|
mit
|
6e6d703729d791df11dd3b10b25a2376
| 11.502703 | 87 | 0.619974 | 2.343465 | false | false | false | false |
jemmons/SessionArtist
|
Tests/SessionArtistTests/HostTests.swift
|
1
|
852
|
import Foundation
import XCTest
import SessionArtist
class HostTests: XCTestCase {
func testURLTransparency() {
let aURL = URL(string: "http://example.com")!
let subject = Host(baseURL: aURL)
XCTAssertEqual(aURL, subject.url)
}
func testHeaderTransparency() {
let nilHost = Host(baseURL: URL(string: "http://example.com")!)
XCTAssert(nilHost.headers.isEmpty)
let acceptHost = Host(baseURL: URL(string: "http://example.com")!, defaultHeaders: [.accept: "foo"])
XCTAssertEqual("foo", acceptHost.headers[.accept])
}
func testTimeoutTransparency() {
let defaultHost = Host(baseURL: URL(string: "http://example.com")!)
XCTAssertEqual(15, defaultHost.timeout)
let tenHost = Host(baseURL: URL(string: "http://example.com")!, timeout: 10)
XCTAssertEqual(10, tenHost.timeout)
}
}
|
mit
|
c8e91a3891d1d57c5c8eac15b87249bc
| 26.483871 | 104 | 0.679577 | 4.037915 | false | true | false | false |
MediaArea/MediaInfo
|
Source/GUI/iOS/MediaInfo/ViewsController.swift
|
1
|
3498
|
/* Copyright (c) MediaArea.net SARL. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license that can
* be found in the License.html file in the root of the source tree.
*/
import UIKit
class ViewsController: UITableViewController {
var core: Core = Core()
var currentView: String = "HTML"
override func viewDidLoad() {
super.viewDidLoad()
if SubscriptionManager.shared.subscriptionActive {
subscriptionActive()
}
NotificationCenter.default.addObserver(self, selector: #selector(subscriptionStateChanged(_:)), name: .subscriptionStateChanged, object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return core.views.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: UITableViewCell = tableView.dequeueReusableCell(withIdentifier: "ViewCell", for: indexPath)
if(core.views[indexPath.row].name == currentView) {
cell.accessoryType = UITableViewCell.AccessoryType.checkmark
}
if(core.views[indexPath.row].desc == "Text") {
cell.textLabel?.text = NSLocalizedString("Text", tableName: "Core", comment: "")
}
else {
cell.textLabel?.text = core.views[indexPath.row].desc
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
currentView = core.views[indexPath.row].name
performSegue(withIdentifier: "unwindFromViews", sender: self)
}
@objc func subscriptionStateChanged(_ notification: Notification) {
if SubscriptionManager.shared.subscriptionActive {
subscriptionActive()
}
}
open func subscriptionActive() {
if Core.shared.darkMode {
enableDarkMode()
}
NotificationCenter.default.addObserver(self, selector: #selector(darkModeEnabled(_:)), name: .darkModeEnabled, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(darkModeDisabled(_:)), name: .darkModeDisabled, object: nil)
}
// MARK: - Theme
@objc func darkModeEnabled(_ notification: Notification) {
enableDarkMode()
self.tableView.reloadData()
}
@objc func darkModeDisabled(_ notification: Notification) {
disableDarkMode()
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
if SubscriptionManager.shared.subscriptionActive && core.darkMode {
cell.backgroundColor = UIColor.darkGray
cell.textLabel?.textColor = UIColor.white
} else {
cell.backgroundColor = UIColor.white
cell.textLabel?.textColor = UIColor.black
}
}
open func enableDarkMode() {
view.backgroundColor = UIColor.darkGray
navigationController?.navigationBar.barStyle = .black
}
open func disableDarkMode() {
view.backgroundColor = UIColor.white
navigationController?.navigationBar.barStyle = .default
}
}
|
bsd-2-clause
|
8e0a0f9eaa25fc5255bda53fb68cb689
| 32.634615 | 149 | 0.667524 | 5.182222 | false | false | false | false |
hejunbinlan/Carlos
|
Tests/KeyTransformationTests.swift
|
2
|
12103
|
import Foundation
import Quick
import Nimble
import Carlos
private struct KeyTransformationsSharedExamplesContext {
static let CacheToTest = "cache"
static let InternalCache = "internalCache"
static let Transformer = "transformer"
}
class KeyTransformationSharedExamplesConfiguration: QuickConfiguration {
override class func configure(configuration: Configuration) {
sharedExamples("a fetch closure with transformed keys") { (sharedExampleContext: SharedExampleContext) in
var cache: BasicCache<Int, Int>!
var internalCache: CacheLevelFake<String, Int>!
var transformer: OneWayTransformationBox<Int, String>!
beforeEach {
cache = sharedExampleContext()[KeyTransformationsSharedExamplesContext.CacheToTest] as? BasicCache<Int, Int>
internalCache = sharedExampleContext()[KeyTransformationsSharedExamplesContext.InternalCache] as? CacheLevelFake<String, Int>
transformer = sharedExampleContext()[KeyTransformationsSharedExamplesContext.Transformer] as? OneWayTransformationBox<Int, String>
}
context("when calling get") {
context("when the transformation closure returns a value") {
let key = 12
var successValue: Int?
var failureValue: NSError?
var fakeRequest: CacheRequest<Int>!
beforeEach {
fakeRequest = CacheRequest<Int>()
internalCache.cacheRequestToReturn = fakeRequest
cache.get(key).onSuccess({ successValue = $0 }).onFailure({ failureValue = $0 })
}
it("should forward the call to the internal cache") {
expect(internalCache.numberOfTimesCalledGet).to(equal(1))
}
it("should transform the key first") {
expect(internalCache.didGetKey).to(equal(transformer.transform(key)))
}
context("when the request succeeds") {
let value = 101
beforeEach {
fakeRequest.succeed(value)
}
it("should call the original success closure") {
expect(successValue).to(equal(value))
}
}
context("when the request fails") {
let errorCode = -110
beforeEach {
fakeRequest.fail(NSError(domain: "test", code: errorCode, userInfo: nil))
}
it("should call the original failure closure") {
expect(failureValue?.code).to(equal(errorCode))
}
}
}
context("when the transformation closure returns nil") {
let key = -12
var successValue: Int?
var failureValue: NSError?
var fakeRequest: CacheRequest<Int>!
beforeEach {
fakeRequest = CacheRequest<Int>()
internalCache.cacheRequestToReturn = fakeRequest
cache.get(key).onSuccess({ successValue = $0 }).onFailure({ failureValue = $0 })
}
it("should not forward the call to the internal cache") {
expect(internalCache.numberOfTimesCalledGet).to(equal(0))
}
it("should not call the original success closure") {
expect(successValue).to(beNil())
}
it("should call the original failure closure") {
expect(failureValue).notTo(beNil())
}
it("should pass the right error code") {
expect(failureValue?.code).to(equal(FetchError.KeyTransformationFailed.rawValue))
}
}
}
}
sharedExamples("a cache with transformed keys") { (sharedExampleContext: SharedExampleContext) in
var cache: BasicCache<Int, Int>!
var internalCache: CacheLevelFake<String, Int>!
var transformer: OneWayTransformationBox<Int, String>!
beforeEach {
cache = sharedExampleContext()[KeyTransformationsSharedExamplesContext.CacheToTest] as? BasicCache<Int, Int>
internalCache = sharedExampleContext()[KeyTransformationsSharedExamplesContext.InternalCache] as? CacheLevelFake<String, Int>
transformer = sharedExampleContext()[KeyTransformationsSharedExamplesContext.Transformer] as? OneWayTransformationBox<Int, String>
}
itBehavesLike("a fetch closure with transformed keys") {
[
KeyTransformationsSharedExamplesContext.CacheToTest: cache,
KeyTransformationsSharedExamplesContext.InternalCache: internalCache,
KeyTransformationsSharedExamplesContext.Transformer: transformer
]
}
context("when calling set") {
context("when the transformation closure returns a value") {
let key = 10
let value = 222
beforeEach {
cache.set(value, forKey: key)
}
it("should forward the call to the internal cache") {
expect(internalCache.numberOfTimesCalledSet).to(equal(1))
}
it("should transform the key first") {
expect(internalCache.didSetKey).to(equal(transformer.transform(key)))
}
it("should pass the right value") {
expect(internalCache.didSetValue).to(equal(value))
}
}
context("when the transformation closure fails") {
let key = -10
let value = 222
beforeEach {
cache.set(value, forKey: key)
}
it("should not forward the call to the internal cache") {
expect(internalCache.numberOfTimesCalledSet).to(equal(0))
}
}
}
context("when calling clear") {
beforeEach {
cache.clear()
}
it("should forward the call to the internal cache") {
expect(internalCache.numberOfTimesCalledClear).to(equal(1))
}
}
context("when calling onMemoryWarning") {
beforeEach {
cache.onMemoryWarning()
}
it("should forward the call to the internal cache") {
expect(internalCache.numberOfTimesCalledOnMemoryWarning).to(equal(1))
}
}
}
}
}
class KeyTransformationTests: QuickSpec {
override func spec() {
var cache: BasicCache<Int, Int>!
var internalCache: CacheLevelFake<String, Int>!
var transformer: OneWayTransformationBox<Int, String>!
let transformationClosure: Int -> String? = {
if $0 > 0 {
return "\($0 + 1)"
} else {
return nil
}
}
describe("Key transformation using a transformer and a cache, with the global function") {
beforeEach {
internalCache = CacheLevelFake<String, Int>()
transformer = OneWayTransformationBox(transform: transformationClosure)
cache = transformKeys(transformer, internalCache)
}
itBehavesLike("a cache with transformed keys") {
[
KeyTransformationsSharedExamplesContext.CacheToTest: cache,
KeyTransformationsSharedExamplesContext.InternalCache: internalCache,
KeyTransformationsSharedExamplesContext.Transformer: transformer
]
}
}
describe("Key transformation using a transformer and a cache, with the operator") {
beforeEach {
internalCache = CacheLevelFake<String, Int>()
transformer = OneWayTransformationBox(transform: transformationClosure)
cache = transformer =>> internalCache
}
itBehavesLike("a cache with transformed keys") {
[
KeyTransformationsSharedExamplesContext.CacheToTest: cache,
KeyTransformationsSharedExamplesContext.InternalCache: internalCache,
KeyTransformationsSharedExamplesContext.Transformer: transformer
]
}
}
describe("Key transformation using a transformation closure and a cache, with the global function") {
beforeEach {
internalCache = CacheLevelFake<String, Int>()
transformer = OneWayTransformationBox(transform: transformationClosure)
cache = transformKeys(transformationClosure, internalCache)
}
itBehavesLike("a cache with transformed keys") {
[
KeyTransformationsSharedExamplesContext.CacheToTest: cache,
KeyTransformationsSharedExamplesContext.InternalCache: internalCache,
KeyTransformationsSharedExamplesContext.Transformer: transformer
]
}
}
describe("Key transformation using a transformation closure and a cache, with the operator") {
beforeEach {
internalCache = CacheLevelFake<String, Int>()
transformer = OneWayTransformationBox(transform: transformationClosure)
cache = transformationClosure =>> internalCache
}
itBehavesLike("a cache with transformed keys") {
[
KeyTransformationsSharedExamplesContext.CacheToTest: cache,
KeyTransformationsSharedExamplesContext.InternalCache: internalCache,
KeyTransformationsSharedExamplesContext.Transformer: transformer
]
}
}
describe("Key transformation using a transformation closure and a fetch closure, with the global function") {
beforeEach {
internalCache = CacheLevelFake<String, Int>()
let fetchClosure = internalCache.get
transformer = OneWayTransformationBox(transform: transformationClosure)
cache = transformKeys(transformationClosure, fetchClosure)
}
itBehavesLike("a fetch closure with transformed keys") {
[
KeyTransformationsSharedExamplesContext.CacheToTest: cache,
KeyTransformationsSharedExamplesContext.InternalCache: internalCache,
KeyTransformationsSharedExamplesContext.Transformer: transformer
]
}
}
describe("Key transformation using a transformation closure and a fetch closure, with the operator") {
beforeEach {
internalCache = CacheLevelFake<String, Int>()
let fetchClosure = internalCache.get
transformer = OneWayTransformationBox(transform: transformationClosure)
cache = transformationClosure =>> fetchClosure
}
itBehavesLike("a fetch closure with transformed keys") {
[
KeyTransformationsSharedExamplesContext.CacheToTest: cache,
KeyTransformationsSharedExamplesContext.InternalCache: internalCache,
KeyTransformationsSharedExamplesContext.Transformer: transformer
]
}
}
describe("Key transformation using a transformer and a fetch closure, with the global function") {
beforeEach {
internalCache = CacheLevelFake<String, Int>()
let fetchClosure = internalCache.get
transformer = OneWayTransformationBox(transform: transformationClosure)
cache = transformKeys(transformer, fetchClosure)
}
itBehavesLike("a fetch closure with transformed keys") {
[
KeyTransformationsSharedExamplesContext.CacheToTest: cache,
KeyTransformationsSharedExamplesContext.InternalCache: internalCache,
KeyTransformationsSharedExamplesContext.Transformer: transformer
]
}
}
describe("Key transformation using a transformer and a fetch closure, with the operator") {
beforeEach {
internalCache = CacheLevelFake<String, Int>()
let fetchClosure = internalCache.get
transformer = OneWayTransformationBox(transform: transformationClosure)
cache = transformer =>> fetchClosure
}
itBehavesLike("a fetch closure with transformed keys") {
[
KeyTransformationsSharedExamplesContext.CacheToTest: cache,
KeyTransformationsSharedExamplesContext.InternalCache: internalCache,
KeyTransformationsSharedExamplesContext.Transformer: transformer
]
}
}
}
}
|
mit
|
e834150545aca5b97eb219be7ad4e39f
| 35.902439 | 138 | 0.638189 | 5.938665 | false | false | false | false |
edx/edx-app-ios
|
Source/ProgressController.swift
|
1
|
4189
|
//
// ProgressController.swift
// edX
//
// Created by Ehmad Zubair Chughtai on 15/07/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
/// Responsible for the size of the CircularProgressView as well as the button
private let ProgressViewFrame = CGRect(x: 0, y: 0, width: 30, height: 30)
/// To be used whenever we want to show the download progress of the Videos.
public class ProgressController: NSObject {
private let circularProgressView : DACircularProgressView
private let downloadButton : UIButton
private var dataInterface : OEXInterface?
private weak var router : OEXRouter?
private weak var owner : UIViewController?
lazy var percentFormatter: NumberFormatter = {
let pf = NumberFormatter()
pf.numberStyle = NumberFormatter.Style.percent
return pf
}()
private var downloadProgress : CGFloat {
return CGFloat(self.dataInterface?.totalProgress ?? 0)
}
init(owner : UIViewController, router : OEXRouter?, dataInterface : OEXInterface?) {
circularProgressView = DACircularProgressView(frame: ProgressViewFrame)
circularProgressView.progressTintColor = OEXStyles.shared().progressBarTintColor
circularProgressView.trackTintColor = OEXStyles.shared().progressBarTrackTintColor
circularProgressView.accessibilityIdentifier = "ProgressController:circular-progress-view"
downloadButton = UIButton(type: .system)
downloadButton.accessibilityIdentifier = "ProgressController:download-button"
downloadButton.setImage(Icon.ContentCanDownload.imageWithFontSize(size: 14), for: .normal)
downloadButton.tintColor = OEXStyles.shared().navigationItemTintColor()
downloadButton.accessibilityLabel = Strings.accessibilityDownloadProgressButton(percentComplete: 0, formatted: nil)
downloadButton.accessibilityHint = Strings.Accessibility.showCurrentDownloadsButtonHint
downloadButton.accessibilityTraits = UIAccessibilityTraits(rawValue: UIAccessibilityTraits.button.rawValue | UIAccessibilityTraits.updatesFrequently.rawValue)
downloadButton.frame = ProgressViewFrame
circularProgressView.addSubview(downloadButton)
super.init()
self.dataInterface = dataInterface
self.router = router
self.owner = owner
self.dataInterface?.progressViews.add(circularProgressView)
self.dataInterface?.progressViews.add(downloadButton)
downloadButton.oex_addAction({ [weak self](_) -> Void in
if let owner = self?.owner {
self?.router?.showDownloads(from: owner)
}
}, for: .touchUpInside)
NotificationCenter.default.oex_addObserver(observer: self, name: NSNotification.Name.OEXDownloadProgressChanged.rawValue) { (_, observer, _) -> Void in
observer.updateProgressDisplay()
}
}
private func updateProgressDisplay() {
//Assuming there wouldn't be a situation where we'd want to force-hide the views. Also, this will automatically show the View when reachability is back on or any other situation where we hid it unwillingly.
showProgessView()
circularProgressView.setProgress(downloadProgress, animated: true)
let percentStr = percentFormatter.string(from: NSNumber(value: Float(downloadProgress)))!
let numeric = Int(downloadProgress * 100)
downloadButton.accessibilityLabel = Strings.accessibilityDownloadProgressButton(percentComplete: numeric, formatted: percentStr)
}
func navigationItem() -> UIBarButtonItem {
let item = UIBarButtonItem(customView: circularProgressView)
item.accessibilityIdentifier = "ProgressController:navigation-item"
return item
}
func progressView() -> UIView {
return circularProgressView
}
func hideProgessView() {
circularProgressView.isHidden = true
downloadButton.isHidden = true
}
func showProgessView() {
circularProgressView.isHidden = false
downloadButton.isHidden = false
}
}
|
apache-2.0
|
c0bb6ef34615ec6d0d2b04a9a0d64520
| 41.313131 | 214 | 0.706613 | 5.49017 | false | false | false | false |
lorentey/swift
|
test/PrintAsObjC/imports.swift
|
6
|
2313
|
// Please keep this file in alphabetical order!
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules/ -F %S/Inputs/ -emit-module -o %t %s -disable-objc-attr-requires-foundation-module
// RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %S/Inputs/custom-modules/ -F %S/Inputs/ -parse-as-library %t/imports.swiftmodule -typecheck -emit-objc-header-path %t/imports.h -import-objc-header %S/../Inputs/empty.h -disable-objc-attr-requires-foundation-module
// RUN: %FileCheck %s < %t/imports.h
// RUN: %FileCheck -check-prefix=NEGATIVE %s < %t/imports.h
// RUN: %check-in-clang %t/imports.h -I %S/Inputs/custom-modules/ -F %S/Inputs/ -Watimport-in-framework-header
// REQUIRES: objc_interop
// CHECK: @import Base;
// CHECK-NEXT: @import Base.ExplicitSub;
// CHECK-NEXT: @import Base.ExplicitSub.ExSub;
// CHECK-NEXT: @import Base.ImplicitSub.ExSub;
// CHECK-NEXT: @import Foundation;
// CHECK-NEXT: @import MostlyPrivate1;
// CHECK-NEXT: @import MostlyPrivate1_Private;
// CHECK-NEXT: @import MostlyPrivate2_Private;
// CHECK-NEXT: @import ObjectiveC;
// CHECK-NEXT: @import ctypes.bits;
// NEGATIVE-NOT: ctypes;
// NEGATIVE-NOT: ImSub;
// NEGATIVE-NOT: ImplicitSub;
// NEGATIVE-NOT: MostlyPrivate2;
// NEGATIVE-NOT: MiserablePileOfSecrets;
// NEGATIVE-NOT: secretMethod
import ctypes.bits
import Foundation
import Base
import Base.ImplicitSub
import Base.ImplicitSub.ImSub
import Base.ImplicitSub.ExSub
import Base.ExplicitSub
import Base.ExplicitSub.ImSub
import Base.ExplicitSub.ExSub
import MostlyPrivate1
import MostlyPrivate1_Private
// Deliberately not importing MostlyPrivate2
import MostlyPrivate2_Private
@_implementationOnly import MiserablePileOfSecrets
@objc class Test {
@objc let word: DWORD = 0
@objc let number: TimeInterval = 0.0
@objc let baseI: BaseI = 0
@objc let baseII: BaseII = 0
@objc let baseIE: BaseIE = 0
@objc let baseE: BaseE = 0
@objc let baseEI: BaseEI = 0
@objc let baseEE: BaseEE = 0
// Deliberately use the private type before the public type.
@objc let mp1priv: MP1PrivateType = 0
@objc let mp1pub: MP1PublicType = 0
@objc let mp2priv: MP2PrivateType = 0
}
@objc public class TestSubclass: NSObject {
@_implementationOnly public override func secretMethod() {}
}
|
apache-2.0
|
ccc0d1c98f8173907e8ae0c712648d47
| 32.521739 | 279 | 0.741461 | 3.177198 | false | false | false | false |
cacawai/Tap2Read
|
tap2read/tap2read/CardModelMgr.swift
|
1
|
16878
|
//
// CardModelMgr.swift
// tap2read
//
// Created by 徐新元 on 16/8/28.
// Copyright © 2016年 Last4 Team. All rights reserved.
//
import UIKit
import HandyJSON
import SDWebImage
enum ContentType {
case Category
case Card
}
let CategoryIdNumber = 3
let CategoryIdLetter = 4
let CategoryIdColor = 5
class CardModelMgr: NSObject {
var minNumber = 1
var maxNumber = 20
var categoryModels: [CategoryModel] = [CategoryModel]()
var cardModels:[CardModel] = [CardModel]()
var currentCategoryIndex: NSInteger = 0
class var sharedInstance : CardModelMgr {
struct Static {
static let instance : CardModelMgr = CardModelMgr()
}
return Static.instance
}
func reloadCardModels() {
//Clean all data
categoryModels.removeAll()
cardModels.removeAll()
//Load custom categories
let userDataFolderUrl = getDocumentsDirectory().appendingPathComponent("user_data")
self.loadCategoriesFromFolder(folderPath: userDataFolderUrl.path)
//Load preload categories
let path = Bundle.main.resourcePath!
let preloadPath = path.appendingFormat("/preload")
self.loadCategoriesFromFolder(folderPath: preloadPath)
//Load cards in the category
let currentCategory = self.categoryModels[self.currentCategoryIndex];
if currentCategory.categoryId == CategoryIdNumber {
self.loadNumberCards(from: minNumber, to: maxNumber)
}else if currentCategory.categoryId == CategoryIdLetter {
self.loadLetterCards()
}else{
self.loadCardsFromFolder(folderPath: self.categoryModels[self.currentCategoryIndex].categoryFolder)
}
}
func switchToNextCategory() {
currentCategoryIndex += 1
if currentCategoryIndex >= self.getCategoryCount() {
currentCategoryIndex = 0
}
// cardModelType = CardModelType.init(rawValue: (cardModelType.rawValue + 1)%CardModelTypeCount)!
reloadCardModels()
}
func setCurrentCategoryIndex(index:NSInteger!) {
currentCategoryIndex = index
if currentCategoryIndex >= self.getCategoryCount() {
currentCategoryIndex = 0
}
reloadCardModels()
}
func getCurrentCategoryModel()->CategoryModel {
return categoryModels[currentCategoryIndex]
}
//MARK: === Number cards ===
func loadNumberCards(from:Int, to:Int) {
minNumber = from
maxNumber = to
cardModels.removeAll()
var index = 0
for i in from...to {
let cardModel:CardModel = CardModel()
cardModel.categoryId = CategoryIdNumber
cardModel.cardId = index
cardModel.titleJson = ["en":"\(i)"]
cardModels.append(cardModel)
index += 1
}
}
//MARK: === Letter cards ===
func loadLetterCards() {
cardModels.removeAll()
let aScalars = "a".unicodeScalars
let aCode = aScalars[aScalars.startIndex].value
var index = 0
for i in 0..<26 {
let cardModel:CardModel = CardModel()
cardModel.categoryId = CategoryIdLetter
cardModel.cardId = index
let letter = UnicodeScalar(aCode + UInt32(i))!
cardModel.titleJson = ["en":"\(letter)"]
cardModels.append(cardModel)
index += 1
}
}
//MARK: === Image cards ===
func loadImageData() {
cardModels.removeAll()
let userDataFolderUrl = getDocumentsDirectory().appendingPathComponent("user_data")
self.loadCardsFromFolder(folderPath: userDataFolderUrl.path)
let path = Bundle.main.resourcePath!
let preloadPath = path.appendingFormat("/preload")
self.loadCardsFromFolder(folderPath: preloadPath)
}
func loadCategoriesFromFolder(folderPath:String!) {
// categoryModels.removeAll()
let fm = FileManager.default
do {
let items = try fm.subpathsOfDirectory(atPath: folderPath)
for item in items.reversed() {
let path:String = folderPath + "/" + "\(item)"
var isDir : ObjCBool = false
let exist = fm.fileExists(atPath: path, isDirectory: &isDir)
if exist {
if isDir.boolValue {
//isFolder
}else{
//isFile
// print("\(path)")
if path.hasSuffix("category.json") {
let categoryJson = try! String.init(contentsOfFile: path)
//Json file
let categoryModel:CategoryModel? = JSONDeserializer<CategoryModel>.deserializeFrom(json: categoryJson)
if categoryModel != nil {
let folderPath = path.replacingOccurrences(of: "/category.json", with: "")
categoryModel!.categoryFolder = folderPath
var alreadyAdded = false
for category in categoryModels {
alreadyAdded = (category.categoryId == categoryModel?.categoryId)
if alreadyAdded {
break
}
}
if !alreadyAdded {
categoryModels.append(categoryModel!)
}
print("CategoryModel: \(String(describing: categoryModel!.titleJson!))")
}
}
}
}
}
} catch {
// failed to read directory
print("failed to read directory")
}
}
func loadCardsFromFolder(folderPath:String!) {
cardModels.removeAll()
let fm = FileManager.default
do {
let items = try fm.subpathsOfDirectory(atPath: folderPath)
for item in items {
let path:String = folderPath + "/" + "\(item)"
var isDir : ObjCBool = false
let exist = fm.fileExists(atPath: path, isDirectory: &isDir)
if exist {
if isDir.boolValue {
//isFolder
}else{
//isFile
// print("\(path)")
if path.hasSuffix("item.json") {
let itemJson = try! String.init(contentsOfFile: path)
//Json file
let cardModel:CardModel? = JSONDeserializer<CardModel>.deserializeFrom(json: itemJson)
if cardModel != nil {
let folderPath = path.replacingOccurrences(of: "/item.json", with: "")
cardModels.append(cardModel!)
cardModel!.cardFolder = folderPath
print("【CardModule】 cardId:\(cardModel!.cardId!) categoryId:\(String(describing: cardModel!.categoryId)) titleJson:\(cardModel!.titleJson!) ")
}
}
}
}
}
} catch {
// failed to read directory
print("failed to read directory")
}
cardModels.shuffle()
}
// func loadDataFromResourceFolder(folderPath:String!) {
// let fm = FileManager.default
//
// do {
// let items = try fm.subpathsOfDirectory(atPath: folderPath)
//
// for item in items.reversed() {
// let path:String = folderPath + "/" + "\(item)"
//
// var isDir : ObjCBool = false
// let exist = fm.fileExists(atPath: path, isDirectory: &isDir)
// if exist {
// if isDir.boolValue {
// //isFolder
// }else{
// //isFile
//// print("\(path)")
// if path.hasSuffix("item.json") {
// let itemJson = try! String.init(contentsOfFile: path)
// //Json file
// let cardModel:CardModel? = JSONDeserializer<CardModel>.deserializeFrom(json: itemJson)
// if cardModel != nil {
// let folderPath = path.replacingOccurrences(of: "item.json", with: "")
// if cardModel!.coverImage != nil {
// cardModel!.coverImage! = "\(folderPath)" + "\(cardModel!.coverImage!)"
// }
// if cardModel!.coverImage != nil {
// cardModels.append(cardModel!)
// }
// print("【CardModule】 cardId:\(cardModel!.cardId) categoryId:\(cardModel!.categoryId) titleJson:\(cardModel!.titleJson) ")
// }
// }else if path.hasSuffix("category.json") {
// let categoryJson = try! String.init(contentsOfFile: path)
// //Json file
// let categoryModel:CategoryModel? = JSONDeserializer<CategoryModel>.deserializeFrom(json: categoryJson)
// if categoryModel != nil {
// let folderPath = path.replacingOccurrences(of: "category.json", with: "")
// if categoryModel!.coverImage != nil {
// categoryModel!.coverImage! = "\(folderPath)" + "\(categoryModel!.coverImage!)"
// }
// if categoryModel!.coverImage != nil {
// categoryModels.append(categoryModel!)
// }
// print("CategoryModel: \(categoryModel!.titleJson)")
// }
// }
// }
// }
//// let itemJson = ""
//// let cardModel = JSONDeserializer<CardModel>.deserializeFrom(itemJson: json)
//// cardModels =
// }
// } catch {
// // failed to read directory
// print("failed to read directory")
// }
// }
func getCategoryCount() -> NSInteger {
return categoryModels.count
}
//MARK: Create Category
func createNewCategory(image:UIImage?, title:String?) {
if image == nil {
return
}
if title == nil {
return
}
let timeStamp = self.createTimeStamp()
let data = UIImageJPEGRepresentation(image!, 0.7)
let folderName = "custom_category_" + "\(timeStamp)"
let folderUrl = getDocumentsDirectory().appendingPathComponent("user_data/"+"\(folderName)")
do {
try FileManager.default.createDirectory(at: folderUrl, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
let imageFileUrl = getDocumentsDirectory().appendingPathComponent("user_data/"+"\(folderName)"+"/image.jpg")
try? data?.write(to: imageFileUrl)
let category = CategoryModel()
category.categoryId = timeStamp
category.titleJson = [String:String]()
category.titleJson!["zh-CN"] = title
let jsonString = JSONSerializer.serialize(model: category).toJSON()!
let categoryJsonFileUrl = getDocumentsDirectory().appendingPathComponent("user_data/"+"\(folderName)"+"/category.json")
try? jsonString.write(to: categoryJsonFileUrl, atomically: true, encoding: String.Encoding.utf8)
self.reloadCardModels()
}
func editCategory(category:CategoryModel!, image:UIImage?, title:String?, language:String?) {
if title == nil {
return
}
var lan:String? = language
if lan == nil {
lan = "zh-CN"
}
if image != nil {
let data = UIImageJPEGRepresentation(image!, 0.7)
let imageFileUrl = category.getImageFileUrl()
try? data?.write(to: imageFileUrl!)
SDImageCache.shared().removeImage(forKey: imageFileUrl!.absoluteString, fromDisk: true, withCompletion: nil)
}
category.titleJson![lan!] = title
let jsonString = JSONSerializer.serialize(model: category).toJSON()!
let itemJsonFileUrl = category.getCategoryJsonFileUrl()
try? jsonString.write(to: itemJsonFileUrl!, atomically: true, encoding: String.Encoding.utf8)
self.reloadCardModels()
}
func deleteCategory(categoryModel:CategoryModel!) {
if categoryModel.categoryFolder != nil {
try? FileManager.default.removeItem(atPath: categoryModel.categoryFolder!)
self.reloadCardModels()
}
}
//MARK: Create Edit Delte Card
func createNewCard(image:UIImage?, title:String?, language:String?) {
if image == nil {
return
}
if title == nil {
return
}
var lan:String? = language
if lan == nil {
lan = "zh-CN"
}
let currentCategory = self.getCurrentCategoryModel()
let timeStamp = self.createTimeStamp()
let data = UIImageJPEGRepresentation(image!, 0.7)
let folderName = "item_" + "\(timeStamp)"
let folderUrl = URL.init(fileURLWithPath: currentCategory.categoryFolder!).appendingPathComponent("\(folderName)")
do {
try FileManager.default.createDirectory(at: folderUrl, withIntermediateDirectories: true, attributes: nil)
} catch let error as NSError {
print(error.localizedDescription);
}
let imageFileUrl = folderUrl.appendingPathComponent("/image.jpg")
try? data?.write(to: imageFileUrl)
let cardModel = CardModel()
cardModel.cardId = timeStamp
cardModel.categoryId = currentCategory.categoryId
cardModel.titleJson = [String:String]()
cardModel.titleJson![lan!] = title
let jsonString = JSONSerializer.serialize(model: cardModel).toJSON()!
let itemJsonFileUrl = folderUrl.appendingPathComponent("/item.json")
try? jsonString.write(to: itemJsonFileUrl, atomically: true, encoding: String.Encoding.utf8)
self.reloadCardModels()
}
func editCard(cardModel:CardModel!, image:UIImage?, title:String?, language:String?) {
if title == nil {
return
}
var lan:String? = language
if lan == nil {
lan = "zh-CN"
}
if image != nil {
let data = UIImageJPEGRepresentation(image!, 0.7)
let imageFileUrl = cardModel.getImageFileUrl()
if imageFileUrl != nil {
try? data?.write(to: imageFileUrl!)
SDImageCache.shared().removeImage(forKey: imageFileUrl!.absoluteString, fromDisk: true, withCompletion: nil)
}
}
cardModel.titleJson![lan!] = title
let jsonString = JSONSerializer.serialize(model: cardModel).toJSON()!
let itemJsonFileUrl = cardModel.getItemJsonFileUrl()
try? jsonString.write(to: itemJsonFileUrl!, atomically: true, encoding: String.Encoding.utf8)
self.reloadCardModels()
}
func deleteCard(cardModel:CardModel!) {
if cardModel.cardFolder != nil {
try? FileManager.default.removeItem(atPath: cardModel.cardFolder!)
self.reloadCardModels()
}
}
//MARK: Utils
func getDocumentsDirectory() -> URL {
let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
let documentsDirectory = paths[0]
return documentsDirectory
}
func createTimeStamp() ->Int {
//获取当前时间
let now = Date()
// 创建一个日期格式器
let dformatter = DateFormatter()
dformatter.dateFormat = "yyyy年MM月dd日 HH:mm:ss"
print("当前日期时间:\(dformatter.string(from: now))")
//当前时间的时间戳
let timeInterval:TimeInterval = now.timeIntervalSince1970
let timeStamp = Int(timeInterval)
print("当前时间的时间戳:\(timeStamp)")
return timeStamp
}
}
|
mit
|
ef93e5c825b33afe13f826d712f4d3d1
| 37.043084 | 174 | 0.538773 | 5.189298 | false | false | false | false |
ZekeSnider/Jared
|
Pods/Telegraph/Sources/Protocols/HTTP/Routing/Server+Routing.swift
|
1
|
3011
|
//
// Server+Routing.swift
// Telegraph
//
// Created by Yvo van Beek on 2/19/17.
// Copyright © 2017 Building42. All rights reserved.
//
import Foundation
public extension Server {
/// Adds a route handler consisting of a HTTP method, uri and handler closure.
func route(_ method: HTTPMethod, _ uri: String, _ handler: @escaping HTTPRequest.Handler) {
guard let httpRoute = try? HTTPRoute(methods: [method], uri: uri, handler: handler) else {
fatalError("Could not add route - invalid uri: \(uri)")
}
route(httpRoute)
}
/// Adds a route handler consisting of a HTTP method, uri regex and handler closure.
func route(_ method: HTTPMethod, regex: String, _ handler: @escaping HTTPRequest.Handler) {
guard let httpRoute = try? HTTPRoute(methods: [method], regex: regex, handler: handler) else {
fatalError("Could not add route - invalid regex: \(regex)")
}
route(httpRoute)
}
/// Adds a route.
func route(_ httpRoute: HTTPRoute) {
guard let routeHandler = httpConfig.requestHandlers.first(ofType: HTTPRouteHandler.self) else {
fatalError("Could not add route - the server doesn't have a route handler")
}
routeHandler.routes.append(httpRoute)
}
}
// MARK: Serve static content methods
public extension Server {
/// Adds a route that serves files from a bundle.
func serveBundle(_ bundle: Bundle, _ uri: String = "/", index: String? = "index.html") {
serveDirectory(bundle.resourceURL!, uri, index: index)
}
/// Adds a route that serves files from a directory.
func serveDirectory(_ url: URL, _ uri: String = "/", index: String? = "index.html") {
let baseURI = URI(path: uri)
// Construct the uri, do not match exactly to support subdirectories
var routeURI = baseURI.path
if !routeURI.hasSuffix("*") {
if !routeURI.hasSuffix("/") { routeURI += "/" }
routeURI += "*"
}
// Wrap the file handler into a route
let handler = HTTPFileHandler(directoryURL: url, baseURI: baseURI, index: index)
route(.GET, routeURI) { request in
try handler.respond(to: request) { _ in HTTPResponse(.notFound) }
}
}
}
// MARK: Response helper methods
public extension Server {
/// Adds a route that responds to *method* on *uri* that responds with a *response*.
func route(_ method: HTTPMethod, _ uri: String, response: @escaping () -> HTTPResponse) {
route(method, uri) { _ in response() }
}
/// Adds a route that responds to *method* on *uri* that responds with a *statusCode*.
func route(_ method: HTTPMethod, _ uri: String, status: @escaping () -> HTTPStatus) {
route(method, uri) { _ in HTTPResponse(status()) }
}
/// Adds a route that responds to *method* on *uri* that responds with *statusCode* and text content.
func route(_ method: HTTPMethod, _ uri: String, content: @escaping () -> (HTTPStatus, String)) {
route(method, uri) { _ in
let (status, string) = content()
return HTTPResponse(status, content: string)
}
}
}
|
apache-2.0
|
30a010bb6c5931801ed20fe9f5aa5d5b
| 33.597701 | 103 | 0.664452 | 3.914174 | false | false | false | false |
josh64x2/vienna-rss
|
Vienna/Sources/Main window/OverlayStatusBar.swift
|
2
|
13604
|
//
// OverlayStatusBar.swift
// Vienna
//
// Copyright 2017-2018
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Cocoa
/// An overlay status bar can show context-specific information above a view.
/// It is supposed to be a subview of another view. Once added, it will set its
/// own frame and constraints. Removing the status bar from its superview will
/// unwind the constraints.
///
/// Setting or unsetting the `label` property will show or hide the status bar
/// accordingly. It will not hide by itself.
final class OverlayStatusBar: NSView {
// MARK: Subviews
private var backgroundView: NSVisualEffectView = {
let backgroundView = NSVisualEffectView(frame: .zero)
backgroundView.wantsLayer = true
backgroundView.blendingMode = .withinWindow
backgroundView.material = .menu
backgroundView.alphaValue = 0
backgroundView.layer?.cornerRadius = 3
return backgroundView
}()
private var addressField: NSTextField = {
let addressField = NSTextField(labelWithString: "")
addressField.font = .systemFont(ofSize: 12, weight: .medium)
addressField.textColor = .overlayStatusBarPrimaryLabelColor
addressField.lineBreakMode = .byTruncatingMiddle
addressField.allowsDefaultTighteningForTruncation = true
return addressField
}()
// MARK: Initialization
init() {
super.init(frame: NSRect(x: 0, y: 0, width: 4_800, height: 26))
// Make sure that no other constraints are created.
translatesAutoresizingMaskIntoConstraints = false
backgroundView.translatesAutoresizingMaskIntoConstraints = false
addressField.translatesAutoresizingMaskIntoConstraints = false
// The text field should always be among the first views to shrink.
addressField.setContentHuggingPriority(.defaultHigh, for: .horizontal)
addressField.setContentCompressionResistancePriority(.fittingSizeCompression, for: .horizontal)
addSubview(backgroundView)
backgroundView.addSubview(addressField)
// Set the constraints.
var backgroundViewConstraints: [NSLayoutConstraint] = []
backgroundViewConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-3-[view]-3-|",
metrics: nil, views: ["view": backgroundView])
backgroundViewConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-3-[view]-3-|",
metrics: nil, views: ["view": backgroundView])
var addressFieldConstraints: [NSLayoutConstraint] = []
addressFieldConstraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|-1@250-[label]-3@250-|",
options: .alignAllCenterY, metrics: nil,
views: ["label": addressField])
addressFieldConstraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|-6-[label]-6-|",
metrics: nil, views: ["label": addressField])
NSLayoutConstraint.activate(backgroundViewConstraints)
NSLayoutConstraint.activate(addressFieldConstraints)
}
// Make this initialiser unavailable.
override private convenience init(frame frameRect: NSRect) {
self.init()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("\(#function) has not been implemented")
}
// MARK: Setting the view hierarchy
// When the status bar is added to the view hierarchy of another view,
// perform additional setup, such as setting the constraints and creating
// a tracking area for mouse movements.
override func viewDidMoveToSuperview() {
super.viewDidMoveToSuperview()
guard let superview = superview else {
return
}
// Layer-backing will make sure that the visual-effect view redraws.
superview.wantsLayer = true
var baseContraints: [NSLayoutConstraint] = []
baseContraints += NSLayoutConstraint.constraints(withVisualFormat: "V:|->=0-[view]-0-|",
options: [], metrics: nil, views: ["view": self])
baseContraints += NSLayoutConstraint.constraints(withVisualFormat: "H:|->=0-[view]->=0-|",
options: [], metrics: nil, views: ["view": self])
NSLayoutConstraint.activate(baseContraints)
// Pin the view to the left side.
pin(to: .leadingEdge, of: superview)
startTrackingMouse(on: superview)
}
// If the status bar is removed from the view hierarchy, then the tracking
// area must be removed too.
override func viewWillMove(toSuperview newSuperview: NSView?) {
if let superview = superview {
stopTrackingMouse(on: superview)
isShown = false
position = nil
}
}
// MARK: Pinning the status bar
private enum Position {
case leadingEdge, trailingEdge
}
private var position: Position?
private lazy var leadingConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[view]", options: [], metrics: nil, views: ["view": self])
private lazy var trailingConstraints = NSLayoutConstraint.constraints(withVisualFormat: "H:[view]-0-|", options: [], metrics: nil, views: ["view": self])
// The status bar is pinned simply by setting and unsetting constraints.
private func pin(to position: Position, of positioningView: NSView) {
guard position != self.position else {
return
}
let oldConstraints: [NSLayoutConstraint]
let newConstraints: [NSLayoutConstraint]
switch position {
case .leadingEdge:
oldConstraints = trailingConstraints
newConstraints = leadingConstraints
case .trailingEdge:
oldConstraints = leadingConstraints
newConstraints = trailingConstraints
}
// Remove existing constraints.
NSLayoutConstraint.deactivate(oldConstraints)
// Add new constraints.
NSLayoutConstraint.activate(newConstraints)
self.position = position
}
// MARK: Handling status updates
private lazy var formatter: URLFormatter = {
let urlFormatter = URLFormatter()
// Set the default attributes. This should match addressField.
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byTruncatingMiddle
paragraphStyle.allowsDefaultTighteningForTruncation = true
urlFormatter.defaultAttributes = [
.font: NSFont.systemFont(ofSize: 12, weight: .medium),
.paragraphStyle: paragraphStyle,
.foregroundColor: NSColor.overlayStatusBarPrimaryLabelColor
]
urlFormatter.primaryAttributes = [
.font: NSFont.systemFont(ofSize: 12, weight: .medium),
.foregroundColor: NSColor.overlayStatusBarPrimaryLabelColor
]
urlFormatter.secondaryAttributes = [
.font: NSFont.systemFont(ofSize: 12, weight: .regular),
.foregroundColor: NSColor.overlayStatusBarSecondaryLabelColor
]
return urlFormatter
}()
/// The label to show. Setting this property will show or hide the status
/// bar. It will remain visible until the label is set to `nil`.
@objc var label: String? {
didSet {
// This closure is meant to be called very often. It should not
// cause any expensive computations.
if let label = label, !label.isEmpty {
// URLs can have special formatting with an attributed string.
if let url = URL(string: label) {
let attrString = formatter.attributedString(from: url)
if attrString != addressField.attributedStringValue {
addressField.attributedStringValue = attrString
}
} else if label != addressField.stringValue {
addressField.stringValue = label
}
isShown = true
} else {
isShown = false
}
}
}
private var isShown = false {
didSet {
guard isShown != oldValue else {
return
}
NSAnimationContext.runAnimationGroup({ context in
context.duration = 0.4
backgroundView.animator().alphaValue = isShown ? 1 : 0
}, completionHandler: nil)
}
}
// MARK: Setting up mouse tracking
private var trackingArea: NSTrackingArea?
private func startTrackingMouse(on trackingView: NSView) {
if let trackingArea = self.trackingArea, trackingView.trackingAreas.contains(trackingArea) {
return
}
let rect = trackingView.bounds
let size = CGSize(width: rect.maxX, height: frame.height + 15)
let origin = CGPoint(x: rect.minX, y: rect.minY)
let trackingArea = NSTrackingArea(rect: NSRect(origin: origin, size: size),
options: [.mouseEnteredAndExited, .mouseMoved,
.activeInKeyWindow],
owner: self, userInfo: nil)
self.trackingArea = trackingArea
trackingView.addTrackingArea(trackingArea)
}
// Remove the tracking area and unset the reference.
private func stopTrackingMouse(on trackingView: NSView) {
if let trackingArea = trackingArea {
trackingView.removeTrackingArea(trackingArea)
self.trackingArea = nil
}
}
// This method is called often, thus only change the tracking area when
// the superview's bounds width and the tracking area's width do not match.
override func updateTrackingAreas() {
super.updateTrackingAreas()
guard let superview = superview, let trackingArea = trackingArea else {
return
}
if superview.trackingAreas.contains(trackingArea), trackingArea.rect.width != superview.bounds.width {
stopTrackingMouse(on: superview)
startTrackingMouse(on: superview)
}
}
// MARK: Responding to mouse movement
private var widthConstraint: NSLayoutConstraint?
// Once the mouse enters the tracking area, the width of the status bar
// should shrink. This is done by adding a width constraint.
override func mouseEntered(with event: NSEvent) {
super.mouseEntered(with: event)
guard let superview = superview, event.trackingArea == trackingArea else {
return
}
// Add the width constraint, if not already added.
if widthConstraint == nil {
let widthConstraint = NSLayoutConstraint(item: self, attribute: .width, relatedBy: .lessThanOrEqual,
toItem: nil, attribute: .notAnAttribute, multiplier: 1,
constant: superview.bounds.midX - 8)
self.widthConstraint = widthConstraint
widthConstraint.isActive = true
}
}
// Pin the status bar to the side, opposite of the mouse's position.
override func mouseMoved(with event: NSEvent) {
super.mouseMoved(with: event)
guard let superview = superview else {
return
}
// Map the mouse location to the superview's bounds.
let point = superview.convert(event.locationInWindow, from: nil)
if point.x <= superview.bounds.midX {
pin(to: .trailingEdge, of: superview)
} else {
pin(to: .leadingEdge, of: superview)
}
}
// Once the mouse exits the tracking area, the status bar's intrinsic width
// should be restored, by removing the width constraint and pinning the view
// back to the left side.
override func mouseExited(with event: NSEvent) {
super.mouseExited(with: event)
guard let superview = superview, event.trackingArea == trackingArea else {
return
}
pin(to: .leadingEdge, of: superview)
if let constraint = widthConstraint {
removeConstraint(constraint)
// Delete the constraint to make sure that a new one is created,
// appropriate for the superview size (which may change).
widthConstraint = nil
}
}
}
private extension NSColor {
class var overlayStatusBarPrimaryLabelColor: NSColor {
return NSColor(named: "OverlayStatusBarPrimaryTextColor")!
}
class var overlayStatusBarSecondaryLabelColor: NSColor {
return NSColor(named: "OverlayStatusBarSecondaryTextColor")!
}
}
|
apache-2.0
|
f2fc6f2443a0bcdb41261af506c5961f
| 37 | 157 | 0.625919 | 5.626137 | false | false | false | false |
tappytaps/TTLiveAgentWidget
|
Example/TTLiveAgentWidgetExample/ViewController.swift
|
1
|
1408
|
//
// ViewController.swift
// TTLiveAgentWidgetExample
//
// Created by Lukas Boura on 10/02/15.
// Copyright (c) 2015 TappyTaps s.r.o. All rights reserved.
//
import UIKit
import TTLiveAgentWidget
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func goToWidget(sender: AnyObject) {
// Get Support widget instance
var supportWidget = TTLiveAgentWidget.getInstance()
// Config widget
supportWidget.topics = [
TTLiveAgentWidgetSupportTopic(key: "ios-general", title: "General issue"),
TTLiveAgentWidgetSupportTopic(key: "ios-problem", title: "Something is not working")
]
// Config email
supportWidget.supportEmail = "[email protected]"
supportWidget.supportEmailSubject = "My iOS App - feedback"
supportWidget.supportEmailFooter = [
"ID": "123-SDF-+23",
"OS": "iOS 8.1.3",
"Version": "3.5.6"
]
// Open widget
supportWidget.open(fromController: self, style: TTLiveAgentWidgetStyle.Push)
}
}
|
mit
|
e3882f171215e5f4cb761aa1317099f1
| 27.734694 | 96 | 0.62571 | 4.70903 | false | false | false | false |
tomasharkema/swift-bootcamp
|
Auto.playground/Contents.swift
|
1
|
730
|
//: Playground - noun: a place where people can play
import UIKit
class Auto {
let brand: String
let type: String
let power = 0.4
var speed: Double = 0
init(brand: String, type: String) {
self.brand = brand
self.type = type
}
func breaks() {
print("breaking...")
}
func throttle() {
speed = speed + power
print(speed)
}
}
let someAuto = Auto(brand: "Peugeot", type: "107")
someAuto.breaks()
someAuto.throttle()
someAuto.throttle()
someAuto.throttle()
let fooAuto = Auto(brand: "BMW", type: "M8")
fooAuto.speed
/// TODO: Implementeer throttle en speed.
/// TODO: Geef auto snelheid. Standaard is dat 0.
/// TODO: Verhoog elke keer dat throttle wordt aangeroepen speed met power.
|
cc0-1.0
|
3cf667bb7dd8f32c5ec7c5e21006069a
| 16.804878 | 75 | 0.660274 | 3.173913 | false | false | false | false |
slavapestov/swift
|
test/SILGen/witnesses.swift
|
1
|
29248
|
// RUN: %target-swift-frontend -emit-silgen %s -disable-objc-attr-requires-foundation-module | FileCheck %s
infix operator <~> {}
func archetype_method<T: X>(x x: T, y: T) -> T {
var x = x
var y = y
return x.selfTypes(x: y)
}
// CHECK-LABEL: sil hidden @_TF9witnesses16archetype_method{{.*}} : $@convention(thin) <T where T : X> (@out T, @in T, @in T) -> () {
// CHECK: [[METHOD:%.*]] = witness_method $T, #X.selfTypes!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@out τ_0_0, @in τ_0_0, @inout τ_0_0) -> ()
// CHECK: apply [[METHOD]]<T>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X> (@out τ_0_0, @in τ_0_0, @inout τ_0_0) -> ()
// CHECK: }
func archetype_generic_method<T: X>(x x: T, y: Loadable) -> Loadable {
var x = x
return x.generic(x: y)
}
// CHECK-LABEL: sil hidden @_TF9witnesses24archetype_generic_method{{.*}} : $@convention(thin) <T where T : X> (@in T, Loadable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $T, #X.generic!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@out τ_1_0, @in τ_1_0, @inout τ_0_0) -> ()
// CHECK: apply [[METHOD]]<T, Loadable>({{%.*}}, {{%.*}}, {{%.*}}) : $@convention(witness_method) <τ_0_0 where τ_0_0 : X><τ_1_0> (@out τ_1_0, @in τ_1_0, @inout τ_0_0) -> ()
// CHECK: }
// CHECK-LABEL: sil hidden @_TF9witnesses32archetype_associated_type_method{{.*}} : $@convention(thin) <T where T : WithAssocType> (@out T, @in T, @in T.AssocType) -> ()
// CHECK: apply %{{[0-9]+}}<T, T.AssocType>
func archetype_associated_type_method<T: WithAssocType>(x x: T, y: T.AssocType) -> T {
return x.useAssocType(x: y)
}
protocol StaticMethod { static func staticMethod() }
// CHECK-LABEL: sil hidden @_TF9witnesses23archetype_static_method{{.*}} : $@convention(thin) <T where T : StaticMethod> (@in T) -> ()
func archetype_static_method<T: StaticMethod>(x x: T) {
// CHECK: [[METHOD:%.*]] = witness_method $T, #StaticMethod.staticMethod!1 : $@convention(witness_method) <τ_0_0 where τ_0_0 : StaticMethod> (@thick τ_0_0.Type) -> ()
// CHECK: apply [[METHOD]]<T>
T.staticMethod()
}
protocol Existentiable {
func foo() -> Loadable
func generic<T>() -> T
}
func protocol_method(x x: Existentiable) -> Loadable {
return x.foo()
}
// CHECK-LABEL: sil hidden @_TF9witnesses15protocol_methodFT1xPS_13Existentiable__VS_8Loadable : $@convention(thin) (@in Existentiable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.foo!1
// CHECK: apply [[METHOD]]<[[OPENED]]>({{%.*}})
// CHECK: }
func protocol_generic_method(x x: Existentiable) -> Loadable {
return x.generic()
}
// CHECK-LABEL: sil hidden @_TF9witnesses23protocol_generic_methodFT1xPS_13Existentiable__VS_8Loadable : $@convention(thin) (@in Existentiable) -> Loadable {
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED:@opened(.*) Existentiable]], #Existentiable.generic!1
// CHECK: apply [[METHOD]]<[[OPENED]], Loadable>({{%.*}}, {{%.*}})
// CHECK: }
@objc protocol ObjCAble {
func foo()
}
// CHECK-LABEL: sil hidden @_TF9witnesses20protocol_objc_methodFT1xPS_8ObjCAble__T_ : $@convention(thin) (@owned ObjCAble) -> ()
// CHECK: witness_method [volatile] $@opened({{.*}}) ObjCAble, #ObjCAble.foo!1.foreign
func protocol_objc_method(x x: ObjCAble) {
x.foo()
}
struct Loadable {}
protocol AddrOnly {}
protocol Classes : class {}
protocol X {
mutating
func selfTypes(x x: Self) -> Self
mutating
func loadable(x x: Loadable) -> Loadable
mutating
func addrOnly(x x: AddrOnly) -> AddrOnly
mutating
func generic<A>(x x: A) -> A
mutating
func classes<A2: Classes>(x x: A2) -> A2
func <~>(x: Self, y: Self) -> Self
}
protocol Y {}
protocol WithAssocType {
typealias AssocType
func useAssocType(x x: AssocType) -> Self
}
protocol ClassBounded : class {
func selfTypes(x x: Self) -> Self
}
struct ConformingStruct : X {
mutating
func selfTypes(x x: ConformingStruct) -> ConformingStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@out ConformingStruct, @in ConformingStruct, @inout ConformingStruct) -> () {
// CHECK: bb0(%0 : $*ConformingStruct, %1 : $*ConformingStruct, %2 : $*ConformingStruct):
// CHECK-NEXT: %3 = load %1 : $*ConformingStruct
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %4 = function_ref @_TFV9witnesses16ConformingStruct9selfTypes{{.*}} : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct
// CHECK-NEXT: %5 = apply %4(%3, %2) : $@convention(method) (ConformingStruct, @inout ConformingStruct) -> ConformingStruct
// CHECK-NEXT: store %5 to %0 : $*ConformingStruct
// CHECK-NEXT: %7 = tuple ()
// CHECK-NEXT: return %7 : $()
// CHECK-NEXT: }
mutating
func loadable(x x: Loadable) -> Loadable { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_8loadable{{.*}} : $@convention(witness_method) (Loadable, @inout ConformingStruct) -> Loadable {
// CHECK: bb0(%0 : $Loadable, %1 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %2 = function_ref @_TFV9witnesses16ConformingStruct8loadable{{.*}} : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable
// CHECK-NEXT: %3 = apply %2(%0, %1) : $@convention(method) (Loadable, @inout ConformingStruct) -> Loadable
// CHECK-NEXT: return %3 : $Loadable
// CHECK-NEXT: }
mutating
func addrOnly(x x: AddrOnly) -> AddrOnly { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_8addrOnly{{.*}} : $@convention(witness_method) (@out AddrOnly, @in AddrOnly, @inout ConformingStruct) -> () {
// CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses16ConformingStruct8addrOnly{{.*}} : $@convention(method) (@out AddrOnly, @in AddrOnly, @inout ConformingStruct) -> ()
// CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@out AddrOnly, @in AddrOnly, @inout ConformingStruct) -> ()
// CHECK-NEXT: return %4 : $()
// CHECK-NEXT: }
mutating
func generic<C>(x x: C) -> C { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_7generic{{.*}} : $@convention(witness_method) <A> (@out A, @in A, @inout ConformingStruct) -> () {
// CHECK: bb0(%0 : $*A, %1 : $*A, %2 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses16ConformingStruct7generic{{.*}} : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformingStruct) -> ()
// CHECK-NEXT: %4 = apply %3<A>(%0, %1, %2) : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformingStruct) -> ()
// CHECK-NEXT: return %4 : $()
// CHECK-NEXT: }
mutating
func classes<C2: Classes>(x x: C2) -> C2 { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_FS1_7classes{{.*}} : $@convention(witness_method) <A2 where A2 : Classes> (@owned A2, @inout ConformingStruct) -> @owned A2 {
// CHECK: bb0(%0 : $A2, %1 : $*ConformingStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %2 = function_ref @_TFV9witnesses16ConformingStruct7classes{{.*}} : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0
// CHECK-NEXT: %3 = apply %2<A2>(%0, %1) : $@convention(method) <τ_0_0 where τ_0_0 : Classes> (@owned τ_0_0, @inout ConformingStruct) -> @owned τ_0_0
// CHECK-NEXT: return %3 : $A2
// CHECK-NEXT: }
}
func <~>(x: ConformingStruct, y: ConformingStruct) -> ConformingStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16ConformingStructS_1XS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@out ConformingStruct, @in ConformingStruct, @in ConformingStruct, @thick ConformingStruct.Type) -> () {
// CHECK: bb0(%0 : $*ConformingStruct, %1 : $*ConformingStruct, %2 : $*ConformingStruct, %3 : $@thick ConformingStruct.Type):
// CHECK-NEXT: %4 = load %1 : $*ConformingStruct
// CHECK-NEXT: %5 = load %2 : $*ConformingStruct
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %6 = function_ref @_TZF9witnessesoi3ltgFTVS_16ConformingStructS0__S0_ : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
// CHECK-NEXT: %7 = apply %6(%4, %5) : $@convention(thin) (ConformingStruct, ConformingStruct) -> ConformingStruct
// CHECK-NEXT: store %7 to %0 : $*ConformingStruct
// CHECK-NEXT: %9 = tuple ()
// CHECK-NEXT: return %9 : $()
// CHECK-NEXT: }
final class ConformingClass : X {
func selfTypes(x x: ConformingClass) -> ConformingClass { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses15ConformingClassS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@out ConformingClass, @in ConformingClass, @inout ConformingClass) -> () {
// CHECK: bb0(%0 : $*ConformingClass, %1 : $*ConformingClass, %2 : $*ConformingClass):
// -- load and retain 'self' from inout witness 'self' parameter
// CHECK-NEXT: %3 = load %2 : $*ConformingClass
// CHECK-NEXT: strong_retain %3 : $ConformingClass
// CHECK-NEXT: %5 = load %1 : $*ConformingClass
// CHECK: %6 = function_ref @_TFC9witnesses15ConformingClass9selfTypes
// CHECK-NEXT: %7 = apply %6(%5, %3) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass
// CHECK-NEXT: store %7 to %0 : $*ConformingClass
// CHECK-NEXT: %9 = tuple ()
// CHECK-NEXT: strong_release %3
// CHECK-NEXT: return %9 : $()
// CHECK-NEXT: }
func loadable(x x: Loadable) -> Loadable { return x }
func addrOnly(x x: AddrOnly) -> AddrOnly { return x }
func generic<D>(x x: D) -> D { return x }
func classes<D2: Classes>(x x: D2) -> D2 { return x }
}
func <~>(x: ConformingClass, y: ConformingClass) -> ConformingClass { return x }
extension ConformingClass : ClassBounded { }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses15ConformingClassS_12ClassBoundedS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass {
// CHECK: bb0([[C0:%.*]] : $ConformingClass, [[C1:%.*]] : $ConformingClass):
// CHECK-NEXT: strong_retain [[C1]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[FUN:%.*]] = function_ref @_TFC9witnesses15ConformingClass9selfTypes
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FUN]]([[C0]], [[C1]]) : $@convention(method) (@owned ConformingClass, @guaranteed ConformingClass) -> @owned ConformingClass
// CHECK-NEXT: strong_release [[C1]]
// CHECK-NEXT: return [[RESULT]] : $ConformingClass
// CHECK-NEXT: }
struct ConformingAOStruct : X {
var makeMeAO : AddrOnly
mutating
func selfTypes(x x: ConformingAOStruct) -> ConformingAOStruct { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses18ConformingAOStructS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@out ConformingAOStruct, @in ConformingAOStruct, @inout ConformingAOStruct) -> () {
// CHECK: bb0(%0 : $*ConformingAOStruct, %1 : $*ConformingAOStruct, %2 : $*ConformingAOStruct):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses18ConformingAOStruct9selfTypes{{.*}} : $@convention(method) (@out ConformingAOStruct, @in ConformingAOStruct, @inout ConformingAOStruct) -> ()
// CHECK-NEXT: %4 = apply %3(%0, %1, %2) : $@convention(method) (@out ConformingAOStruct, @in ConformingAOStruct, @inout ConformingAOStruct) -> ()
// CHECK-NEXT: return %4 : $()
// CHECK-NEXT: }
func loadable(x x: Loadable) -> Loadable { return x }
func addrOnly(x x: AddrOnly) -> AddrOnly { return x }
func generic<D>(x x: D) -> D { return x }
func classes<D2: Classes>(x x: D2) -> D2 { return x }
}
func <~>(x: ConformingAOStruct, y: ConformingAOStruct) -> ConformingAOStruct { return x }
struct ConformsWithMoreGeneric : X, Y {
mutating
func selfTypes<E>(x x: E) -> E { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_9selfTypes{{.*}} : $@convention(witness_method) (@out ConformsWithMoreGeneric, @in ConformsWithMoreGeneric, @inout ConformsWithMoreGeneric) -> () {
// CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_TFV9witnesses23ConformsWithMoreGeneric9selfTypes{{.*}} : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
func loadable<F>(x x: F) -> F { return x }
mutating
func addrOnly<G>(x x: G) -> G { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_8addrOnly{{.*}} : $@convention(witness_method) (@out AddrOnly, @in AddrOnly, @inout ConformsWithMoreGeneric) -> () {
// CHECK: bb0(%0 : $*AddrOnly, %1 : $*AddrOnly, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses23ConformsWithMoreGeneric8addrOnly{{.*}} : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: %4 = apply %3<AddrOnly>(%0, %1, %2) : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: return %4 : $()
// CHECK-NEXT: }
mutating
func generic<H>(x x: H) -> H { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_7generic{{.*}} : $@convention(witness_method) <A> (@out A, @in A, @inout ConformsWithMoreGeneric) -> () {
// CHECK: bb0(%0 : $*A, %1 : $*A, %2 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: %3 = function_ref @_TFV9witnesses23ConformsWithMoreGeneric7generic{{.*}} : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: %4 = apply %3<A>(%0, %1, %2) : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: return %4 : $()
// CHECK-NEXT: }
mutating
func classes<I>(x x: I) -> I { return x }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_FS1_7classes{{.*}} : $@convention(witness_method) <A2 where A2 : Classes> (@owned A2, @inout ConformsWithMoreGeneric) -> @owned A2 {
// CHECK: bb0(%0 : $A2, %1 : $*ConformsWithMoreGeneric):
// CHECK-NEXT: [[RESULT_BOX:%.*]] = alloc_stack $A2
// CHECK-NEXT: [[SELF_BOX:%.*]] = alloc_stack $A2
// CHECK-NEXT: store %0 to [[SELF_BOX]] : $*A2
// CHECK-NEXT: // function_ref witnesses.ConformsWithMoreGeneric.classes
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_TFV9witnesses23ConformsWithMoreGeneric7classes{{.*}} : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<A2>([[RESULT_BOX]], [[SELF_BOX]], %1) : $@convention(method) <τ_0_0> (@out τ_0_0, @in τ_0_0, @inout ConformsWithMoreGeneric) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = load [[RESULT_BOX]] : $*A2
// CHECK-NEXT: dealloc_stack [[SELF_BOX]] : $*A2
// CHECK-NEXT: dealloc_stack [[RESULT_BOX]] : $*A2
// CHECK-NEXT: return [[RESULT]] : $A2
// CHECK-NEXT: }
}
func <~> <J: Y, K: Y>(x: J, y: K) -> K { return y }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses23ConformsWithMoreGenericS_1XS_ZFS1_oi3ltg{{.*}} : $@convention(witness_method) (@out ConformsWithMoreGeneric, @in ConformsWithMoreGeneric, @in ConformsWithMoreGeneric, @thick ConformsWithMoreGeneric.Type) -> () {
// CHECK: bb0(%0 : $*ConformsWithMoreGeneric, %1 : $*ConformsWithMoreGeneric, %2 : $*ConformsWithMoreGeneric, %3 : $@thick ConformsWithMoreGeneric.Type):
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[WITNESS_FN:%.*]] = function_ref @_TZF9witnessesoi3ltg{{.*}} : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@out τ_0_1, @in τ_0_0, @in τ_0_1) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS_FN]]<ConformsWithMoreGeneric, ConformsWithMoreGeneric>(%0, %1, %2) : $@convention(thin) <τ_0_0, τ_0_1 where τ_0_0 : Y, τ_0_1 : Y> (@out τ_0_1, @in τ_0_0, @in τ_0_1) -> ()
// CHECK-NEXT: return [[RESULT]] : $()
// CHECK-NEXT: }
protocol LabeledRequirement {
func method(x x: Loadable)
}
struct UnlabeledWitness : LabeledRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16UnlabeledWitnessS_18LabeledRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (Loadable, @in_guaranteed UnlabeledWitness) -> ()
func method(x _: Loadable) {}
}
protocol LabeledSelfRequirement {
func method(x x: Self)
}
struct UnlabeledSelfWitness : LabeledSelfRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses20UnlabeledSelfWitnessS_22LabeledSelfRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (@in UnlabeledSelfWitness, @in_guaranteed UnlabeledSelfWitness) -> ()
func method(x _: UnlabeledSelfWitness) {}
}
protocol UnlabeledRequirement {
func method(x _: Loadable)
}
struct LabeledWitness : UnlabeledRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14LabeledWitnessS_20UnlabeledRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (Loadable, @in_guaranteed LabeledWitness) -> ()
func method(x x: Loadable) {}
}
protocol UnlabeledSelfRequirement {
func method(_: Self)
}
struct LabeledSelfWitness : UnlabeledSelfRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses18LabeledSelfWitnessS_24UnlabeledSelfRequirementS_FS1_6method{{.*}} : $@convention(witness_method) (@in LabeledSelfWitness, @in_guaranteed LabeledSelfWitness) -> ()
func method(x: LabeledSelfWitness) {}
}
protocol ReadOnlyRequirement {
var prop: String { get }
static var prop: String { get }
}
struct ImmutableModel: ReadOnlyRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14ImmutableModelS_19ReadOnlyRequirementS_FS1_g4propSS : $@convention(witness_method) (@in_guaranteed ImmutableModel) -> @owned String
let prop: String = "a"
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses14ImmutableModelS_19ReadOnlyRequirementS_ZFS1_g4propSS : $@convention(witness_method) (@thick ImmutableModel.Type) -> @owned String
static let prop: String = "b"
}
protocol FailableRequirement {
init?(foo: Int)
}
protocol NonFailableRefinement: FailableRequirement {
init(foo: Int)
}
protocol IUOFailableRequirement {
init!(foo: Int)
}
struct NonFailableModel: FailableRequirement, NonFailableRefinement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_19FailableRequirementS_FS1_C{{.*}} : $@convention(witness_method) (@out Optional<NonFailableModel>, Int, @thick NonFailableModel.Type) -> ()
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_21NonFailableRefinementS_FS1_C{{.*}} : $@convention(witness_method) (@out NonFailableModel, Int, @thick NonFailableModel.Type) -> ()
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16NonFailableModelS_22IUOFailableRequirementS_FS1_C{{.*}} : $@convention(witness_method) (@out ImplicitlyUnwrappedOptional<NonFailableModel>, Int, @thick NonFailableModel.Type) -> ()
init(foo: Int) {}
}
struct FailableModel: FailableRequirement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses13FailableModelS_19FailableRequirementS_FS1_C{{.*}}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses13FailableModelS_22IUOFailableRequirementS_FS1_C{{.*}}
// CHECK: bb0([[SELF:%[0-9]+]] : $*ImplicitlyUnwrappedOptional<FailableModel>, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick FailableModel.Type):
// CHECK: [[FN:%.*]] = function_ref @_TFV9witnesses13FailableModelC{{.*}}
// CHECK: [[INNER:%.*]] = apply [[FN]](
// CHECK: [[OUTER:%.*]] = unchecked_trivial_bit_cast [[INNER]] : $Optional<FailableModel> to $ImplicitlyUnwrappedOptional<FailableModel>
// CHECK: store [[OUTER]] to %0
// CHECK: return
init?(foo: Int) {}
}
struct IUOFailableModel : NonFailableRefinement, IUOFailableRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV9witnesses16IUOFailableModelS_21NonFailableRefinementS_FS1_C{{.*}}
// CHECK: bb0([[SELF:%[0-9]+]] : $*IUOFailableModel, [[FOO:%[0-9]+]] : $Int, [[META:%[0-9]+]] : $@thick IUOFailableModel.Type):
// CHECK: [[META:%[0-9]+]] = metatype $@thin IUOFailableModel.Type
// CHECK: [[INIT:%[0-9]+]] = function_ref @_TFV9witnesses16IUOFailableModelC{{.*}} : $@convention(thin) (Int, @thin IUOFailableModel.Type) -> ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: [[IUO_RESULT:%[0-9]+]] = apply [[INIT]]([[FOO]], [[META]]) : $@convention(thin) (Int, @thin IUOFailableModel.Type) -> ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: [[IUO_RESULT_TEMP:%[0-9]+]] = alloc_stack $ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: store [[IUO_RESULT]] to [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: [[FORCE_FN:%[0-9]+]] = function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue{{.*}} : $@convention(thin) <τ_0_0> (@out τ_0_0, @in ImplicitlyUnwrappedOptional<τ_0_0>) -> ()
// CHECK: [[RESULT_TEMP:%[0-9]+]] = alloc_stack $IUOFailableModel
// CHECK: apply [[FORCE_FN]]<IUOFailableModel>([[RESULT_TEMP]], [[IUO_RESULT_TEMP]]) : $@convention(thin) <τ_0_0> (@out τ_0_0, @in ImplicitlyUnwrappedOptional<τ_0_0>) -> ()
// CHECK: [[RESULT:%[0-9]+]] = load [[RESULT_TEMP]] : $*IUOFailableModel
// CHECK: store [[RESULT]] to [[SELF]] : $*IUOFailableModel
// CHECK: dealloc_stack [[RESULT_TEMP]] : $*IUOFailableModel
// CHECK: dealloc_stack [[IUO_RESULT_TEMP]] : $*ImplicitlyUnwrappedOptional<IUOFailableModel>
// CHECK: return
init!(foo: Int) { return nil }
}
protocol FailableClassRequirement: class {
init?(foo: Int)
}
protocol NonFailableClassRefinement: FailableClassRequirement {
init(foo: Int)
}
protocol IUOFailableClassRequirement: class {
init!(foo: Int)
}
final class NonFailableClassModel: FailableClassRequirement, NonFailableClassRefinement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned Optional<NonFailableClassModel>
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_26NonFailableClassRefinementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned NonFailableClassModel
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21NonFailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}} : $@convention(witness_method) (Int, @thick NonFailableClassModel.Type) -> @owned ImplicitlyUnwrappedOptional<NonFailableClassModel>
init(foo: Int) {}
}
final class FailableClassModel: FailableClassRequirement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses18FailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses18FailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}}
// CHECK: [[FUNC:%.*]] = function_ref @_TFC9witnesses18FailableClassModelC{{.*}}
// CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1)
// CHECK: [[OUTER:%.*]] = unchecked_ref_cast [[INNER]] : $Optional<FailableClassModel> to $ImplicitlyUnwrappedOptional<FailableClassModel>
// CHECK: return [[OUTER]] : $ImplicitlyUnwrappedOptional<FailableClassModel>
init?(foo: Int) {}
}
final class IUOFailableClassModel: NonFailableClassRefinement, IUOFailableClassRequirement {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_26NonFailableClassRefinementS_FS1_C{{.*}}
// CHECK: function_ref @_TFs36_getImplicitlyUnwrappedOptionalValue{{.*}}
// CHECK: return [[RESULT:%[0-9]+]] : $IUOFailableClassModel
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_27IUOFailableClassRequirementS_FS1_C{{.*}}
init!(foo: Int) {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses21IUOFailableClassModelS_24FailableClassRequirementS_FS1_C{{.*}}
// CHECK: [[FUNC:%.*]] = function_ref @_TFC9witnesses21IUOFailableClassModelC{{.*}}
// CHECK: [[INNER:%.*]] = apply [[FUNC]](%0, %1)
// CHECK: [[OUTER:%.*]] = unchecked_ref_cast [[INNER]] : $ImplicitlyUnwrappedOptional<IUOFailableClassModel> to $Optional<IUOFailableClassModel>
// CHECK: return [[OUTER]] : $Optional<IUOFailableClassModel>
}
protocol HasAssoc {
typealias Assoc
}
protocol GenericParameterNameCollisionType {
func foo<T>(x: T)
typealias Assoc2
func bar<T>(x: T -> Assoc2)
}
struct GenericParameterNameCollision<T: HasAssoc> :
GenericParameterNameCollisionType {
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTW{{.*}}GenericParameterNameCollision{{.*}}GenericParameterNameCollisionType{{.*}}foo{{.*}} : $@convention(witness_method) <T1 where T1 : HasAssoc><T> (@in T, @in_guaranteed GenericParameterNameCollision<T1>) -> () {
// CHECK: bb0(%0 : $*T, %1 : $*GenericParameterNameCollision<T1>):
// CHECK: apply {{%.*}}<T1, T1.Assoc, T>
func foo<U>(x: U) {}
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTW{{.*}}GenericParameterNameCollision{{.*}}GenericParameterNameCollisionType{{.*}}bar{{.*}} : $@convention(witness_method) <T1 where T1 : HasAssoc><T> (@owned @callee_owned (@out T1.Assoc, @in T) -> (), @in_guaranteed GenericParameterNameCollision<T1>) -> () {
// CHECK: bb0(%0 : $@callee_owned (@out T1.Assoc, @in T) -> (), %1 : $*GenericParameterNameCollision<T1>):
// CHECK: apply {{%.*}}<T1, T1.Assoc, T>
func bar<V>(x: V -> T.Assoc) {}
}
protocol PropertyRequirement {
var width: Int { get set }
static var height: Int { get set }
var depth: Int { get set }
}
class PropertyRequirementBase {
var width: Int = 12
static var height: Int = 13
}
class PropertyRequirementWitnessFromBase : PropertyRequirementBase, PropertyRequirement {
var depth: Int = 14
// Make sure the contravariant return type in materializeForSet works correctly
// If the witness is in a base class of the conforming class, make sure we have a bit_cast in there:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_FS1_m5widthSi : {{.*}} {
// CHECK: upcast
// CHECK-NEXT: [[METH:%.*]] = class_method {{%.*}} : $PropertyRequirementBase, #PropertyRequirementBase.width!materializeForSet.1
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0
// CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1
// CHECK-NEXT: [[CAST:%.*]] = unchecked_trivial_bit_cast [[CADR]]
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CAST]] : {{.*}})
// CHECK-NEXT: strong_release
// CHECK-NEXT: return [[TUPLE]]
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_ZFS1_m6heightSi : {{.*}} {
// CHECK: [[OBJ:%.*]] = upcast %2 : $@thick PropertyRequirementWitnessFromBase.Type to $@thick PropertyRequirementBase.Type
// CHECK: [[METH:%.*]] = function_ref @_TZFC9witnesses23PropertyRequirementBasem6heightSi
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: [[CAR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 0
// CHECK-NEXT: [[CADR:%.*]] = tuple_extract [[RES]] : $({{.*}}), 1
// CHECK-NEXT: [[CAST:%.*]] = unchecked_trivial_bit_cast [[CADR]]
// CHECK-NEXT: [[TUPLE:%.*]] = tuple ([[CAR]] : {{.*}}, [[CAST]] : {{.*}})
// CHECK-NEXT: return [[TUPLE]]
// Otherwise, we shouldn't need the bit_cast:
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC9witnesses34PropertyRequirementWitnessFromBaseS_19PropertyRequirementS_FS1_m5depthSi
// CHECK: [[METH:%.*]] = class_method {{%.*}} : $PropertyRequirementWitnessFromBase, #PropertyRequirementWitnessFromBase.depth!materializeForSet.1
// CHECK-NEXT: [[RES:%.*]] = apply [[METH]]
// CHECK-NEXT: strong_release
// CHECK-NEXT: return [[RES]]
}
|
apache-2.0
|
7dccedd2d1622518fa6c9ad23f379d59
| 58.887064 | 314 | 0.667067 | 3.349604 | false | false | false | false |
drewag/Swiftlier
|
Tests/SwiftlierTests/JSONTests.swift
|
1
|
6744
|
//
// JSONTests.swift
// SwiftlierTests
//
// Created by Andrew J Wagner on 10/2/17.
// Copyright © 2017 Drewag. All rights reserved.
//
import XCTest
import Swiftlier
final class JSONTests: XCTestCase {
func testInitFromData() throws {
let jsonString = """
{
"array": ["value1","value2","value3"],
"dict": {"key":"value"},
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": null
}
"""
let data = jsonString.data(using: .utf8)!
let json = try JSON(data: data)
XCTAssertEqual(json["array"]?.array?.count, 3)
XCTAssertEqual(json["array"]?[0]?.string, "value1")
XCTAssertEqual(json["array"]?[1]?.string, "value2")
XCTAssertEqual(json["array"]?[2]?.string, "value3")
XCTAssertEqual(json["dict"]?.dictionary?.count, 1)
XCTAssertEqual(json["dict"]?["key"]?.string, "value")
XCTAssertEqual(json["integer"]?.int, 20)
XCTAssertEqual(json["decimal"]?.double, 0.3)
XCTAssertEqual(json["boolean"]?.bool, true)
XCTAssertTrue(json["null"]?.object is NSNull)
}
func testInitFromObject() throws {
let json = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
XCTAssertEqual(json["array"]?.array?.count, 3)
XCTAssertEqual(json["array"]?[0]?.string, "value1")
XCTAssertEqual(json["array"]?[1]?.string, "value2")
XCTAssertEqual(json["array"]?[2]?.string, "value3")
XCTAssertEqual(json["dict"]?.dictionary?.count, 1)
XCTAssertEqual(json["dict"]?["key"]?.string, "value")
XCTAssertEqual(json["integer"]?.int, 20)
XCTAssertEqual(json["decimal"]?.double, 0.3)
XCTAssertEqual(json["boolean"]?.bool, true)
XCTAssertTrue(json["null"]?.object is NSNull)
}
func testData() throws {
let original = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let data = try original.data()
let json = try JSON(data: data)
XCTAssertEqual(json["array"]?.array?.count, 3)
XCTAssertEqual(json["array"]?[0]?.string, "value1")
XCTAssertEqual(json["array"]?[1]?.string, "value2")
XCTAssertEqual(json["array"]?[2]?.string, "value3")
XCTAssertEqual(json["dict"]?.dictionary?.count, 1)
XCTAssertEqual(json["dict"]?["key"]?.string, "value")
XCTAssertEqual(json["integer"]?.int, 20)
XCTAssertEqual(json["decimal"]?.double, 0.3)
XCTAssertEqual(json["boolean"]?.bool, true)
XCTAssertTrue(json["null"]?.object is NSNull)
}
func testDecode() throws {
let jsonString = """
{
"string": "some",
"int": 4
}
"""
let data = jsonString.data(using: .utf8)!
let json = try JSON(data: data)
let codable: TestCodable = try json.decode()
XCTAssertEqual(codable.string, "some")
XCTAssertEqual(codable.int, 4)
}
func testEncode() throws {
let codable = TestCodable(string: "some", int: 4)
let json = try JSON(encodable: codable)
XCTAssertEqual(json["string"]?.string, "some")
XCTAssertEqual(json["int"]?.int, 4)
}
func testEquatable() throws {
let one = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let two = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let differentArray = JSON(object: [
"array": ["value1","different","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let differentDictValue = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"different"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let differentDictKey = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["different":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let differentString = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "different",
"integer": 20,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let differentInteger = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 21,
"decimal": 0.3,
"boolean": true,
"null": NSNull(),
])
let differentDecimal = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.31,
"boolean": true,
"null": NSNull(),
])
let differentBool = JSON(object: [
"array": ["value1","value2","value3"],
"dict": ["key":"value"],
"string": "value",
"integer": 20,
"decimal": 0.3,
"boolean": false,
"null": NSNull(),
])
XCTAssertEqual(one, two)
XCTAssertNotEqual(one, differentArray)
XCTAssertNotEqual(one, differentDictValue)
XCTAssertNotEqual(one, differentDictKey)
XCTAssertNotEqual(one, differentString)
XCTAssertNotEqual(one, differentInteger)
XCTAssertNotEqual(one, differentDecimal)
XCTAssertNotEqual(one, differentBool)
}
}
|
mit
|
d56a0b016311c10ea156e9307b7b16c8
| 32.884422 | 61 | 0.489545 | 4.350323 | false | true | false | false |
kstaring/swift
|
test/Generics/generic_types.swift
|
3
|
5671
|
// RUN: %target-parse-verify-swift
protocol MyFormattedPrintable {
func myFormat() -> String
}
func myPrintf(_ format: String, _ args: MyFormattedPrintable...) {}
extension Int : MyFormattedPrintable {
func myFormat() -> String { return "" }
}
struct S<T : MyFormattedPrintable> {
var c : T
static func f(_ a: T) -> T {
return a
}
func f(_ a: T, b: Int) {
return myPrintf("%v %v %v", a, b, c)
}
}
func makeSInt() -> S<Int> {}
typealias SInt = S<Int>
var a : S<Int> = makeSInt()
a.f(1,b: 2)
var b : Int = SInt.f(1)
struct S2<T> {
@discardableResult
static func f() -> T {
S2.f()
}
}
struct X { }
var d : S<X> // expected-error{{type 'X' does not conform to protocol 'MyFormattedPrintable'}}
enum Optional<T> {
case element(T)
case none
init() { self = .none }
init(_ t: T) { self = .element(t) }
}
typealias OptionalInt = Optional<Int>
var uniontest1 : (Int) -> Optional<Int> = OptionalInt.element
var uniontest2 : Optional<Int> = OptionalInt.none
var uniontest3 = OptionalInt(1)
// FIXME: Stuff that should work, but doesn't yet.
// var uniontest4 : OptInt = .none
// var uniontest5 : OptInt = .Some(1)
func formattedTest<T : MyFormattedPrintable>(_ a: T) {
myPrintf("%v", a)
}
struct formattedTestS<T : MyFormattedPrintable> {
func f(_ a: T) {
formattedTest(a)
}
}
struct GenericReq<T : IteratorProtocol, U : IteratorProtocol>
where T.Element == U.Element {
}
func getFirst<R : IteratorProtocol>(_ r: R) -> R.Element {
var r = r
return r.next()!
}
func testGetFirst(ir: CountableRange<Int>) {
_ = getFirst(ir.makeIterator()) as Int
}
struct XT<T> {
init(t : T) {
prop = (t, t)
}
static func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
class YT<T> {
init(_ t : T) {
prop = (t, t)
}
deinit {}
class func f() -> T {}
func g() -> T {}
var prop : (T, T)
}
struct ZT<T> {
var x : T, f : Float
}
struct Dict<K, V> {
subscript(key: K) -> V { get {} set {} }
}
class Dictionary<K, V> { // expected-note{{generic type 'Dictionary' declared here}}
subscript(key: K) -> V { get {} set {} }
}
typealias XI = XT<Int>
typealias YI = YT<Int>
typealias ZI = ZT<Int>
var xi = XI(t: 17)
var yi = YI(17)
var zi = ZI(x: 1, f: 3.0)
var i : Int = XI.f()
i = XI.f()
i = xi.g()
i = yi.f() // expected-error{{static member 'f' cannot be used on instance of type 'YI' (aka 'YT<Int>')}}
i = yi.g()
var xif : (XI) -> () -> Int = XI.g
var gif : (YI) -> () -> Int = YI.g
var ii : (Int, Int) = xi.prop
ii = yi.prop
xi.prop = ii
yi.prop = ii
var d1 : Dict<String, Int>
var d2 : Dictionary<String, Int>
d1["hello"] = d2["world"]
i = d2["blarg"]
struct RangeOfPrintables<R : Sequence>
where R.Iterator.Element : MyFormattedPrintable {
var r : R
func format() -> String {
var s : String
for e in r {
s = s + e.myFormat() + " "
}
return s
}
}
struct Y {}
struct SequenceY : Sequence, IteratorProtocol {
typealias Iterator = SequenceY
typealias Element = Y
func next() -> Element? { return Y() }
func makeIterator() -> Iterator { return self }
}
func useRangeOfPrintables(_ roi : RangeOfPrintables<[Int]>) {
var rop : RangeOfPrintables<X> // expected-error{{type 'X' does not conform to protocol 'Sequence'}}
var rox : RangeOfPrintables<SequenceY> // expected-error{{type 'SequenceY.Element' (aka 'Y') does not conform to protocol 'MyFormattedPrintable'}}
}
var dfail : Dictionary<Int> // expected-error{{generic type 'Dictionary' specialized with too few type parameters (got 1, but expected 2)}}
var notgeneric : Int<Float> // expected-error{{cannot specialize non-generic type 'Int'}}{{21-28=}}
// Make sure that redundant typealiases (that map to the same
// underlying type) don't break protocol conformance or use.
class XArray : ExpressibleByArrayLiteral {
typealias Element = Int
init() { }
required init(arrayLiteral elements: Int...) { }
}
class YArray : XArray {
typealias Element = Int
required init(arrayLiteral elements: Int...) {
super.init()
}
}
var yarray : YArray = [1, 2, 3]
var xarray : XArray = [1, 2, 3]
// Type parameters can be referenced only via unqualified name lookup
struct XParam<T> {
func foo(_ x: T) {
_ = x as T
}
static func bar(_ x: T) {
_ = x as T
}
}
var xp : XParam<Int>.T = Int() // expected-error{{'T' is not a member type of 'XParam<Int>'}}
// Diagnose failure to meet a superclass requirement.
class X1 { }
class X2<T : X1> { } // expected-note{{requirement specified as 'T' : 'X1' [with T = X3]}}
class X3 { }
var x2 : X2<X3> // expected-error{{'X2' requires that 'X3' inherit from 'X1'}}
protocol P {
associatedtype AssocP
}
protocol Q {
associatedtype AssocQ
}
struct X4 : P, Q {
typealias AssocP = Int
typealias AssocQ = String
}
struct X5<T, U> where T: P, T: Q, T.AssocP == T.AssocQ { } // expected-note{{requirement specified as 'T.AssocP' == 'T.AssocQ' [with T = X4]}}
var y: X5<X4, Int> // expected-error{{'X5' requires the types 'X4.AssocP' (aka 'Int') and 'X4.AssocQ' (aka 'String') be equivalent}}
// Recursive generic signature validation.
class Top {}
class Bottom<T : Bottom<Top>> {} // expected-error {{type may not reference itself as a requirement}}
// Invalid inheritance clause
struct UnsolvableInheritance1<T : T.A> {}
// expected-error@-1 {{inheritance from non-protocol, non-class type 'T.A'}}
struct UnsolvableInheritance2<T : U.A, U : T.A> {}
// expected-error@-1 {{inheritance from non-protocol, non-class type 'U.A'}}
// expected-error@-2 {{inheritance from non-protocol, non-class type 'T.A'}}
enum X7<T> where X7.X : G { case X } // expected-error{{enum element 'X' is not a member type of 'X7<T>'}}
|
apache-2.0
|
dac119ed023a4e9028c7273ae59866d0
| 22.629167 | 148 | 0.633927 | 3.035867 | false | false | false | false |
raymondshadow/SwiftDemo
|
SwiftApp/Pods/RxSwift/RxSwift/Observables/Producer.swift
|
3
|
3011
|
//
// Producer.swift
// RxSwift
//
// Created by Krunoslav Zaher on 2/20/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
class Producer<Element> : Observable<Element> {
override init() {
super.init()
}
override func subscribe<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element {
if !CurrentThreadScheduler.isScheduleRequired {
// The returned disposable needs to release all references once it was disposed.
let disposer = SinkDisposer()
let sinkAndSubscription = self.run(observer, cancel: disposer)
disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription)
return disposer
}
else {
return CurrentThreadScheduler.instance.schedule(()) { _ in
let disposer = SinkDisposer()
let sinkAndSubscription = self.run(observer, cancel: disposer)
disposer.setSinkAndSubscription(sink: sinkAndSubscription.sink, subscription: sinkAndSubscription.subscription)
return disposer
}
}
}
func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == Element {
rxAbstractMethod()
}
}
fileprivate final class SinkDisposer: Cancelable {
fileprivate enum DisposeState: Int32 {
case disposed = 1
case sinkAndSubscriptionSet = 2
}
private let _state = AtomicInt(0)
private var _sink: Disposable?
private var _subscription: Disposable?
var isDisposed: Bool {
return isFlagSet(self._state, DisposeState.disposed.rawValue)
}
func setSinkAndSubscription(sink: Disposable, subscription: Disposable) {
self._sink = sink
self._subscription = subscription
let previousState = fetchOr(self._state, DisposeState.sinkAndSubscriptionSet.rawValue)
if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 {
rxFatalError("Sink and subscription were already set")
}
if (previousState & DisposeState.disposed.rawValue) != 0 {
sink.dispose()
subscription.dispose()
self._sink = nil
self._subscription = nil
}
}
func dispose() {
let previousState = fetchOr(self._state, DisposeState.disposed.rawValue)
if (previousState & DisposeState.disposed.rawValue) != 0 {
return
}
if (previousState & DisposeState.sinkAndSubscriptionSet.rawValue) != 0 {
guard let sink = self._sink else {
rxFatalError("Sink not set")
}
guard let subscription = self._subscription else {
rxFatalError("Subscription not set")
}
sink.dispose()
subscription.dispose()
self._sink = nil
self._subscription = nil
}
}
}
|
apache-2.0
|
481d94fb91ac6154a4d47b55f5559eee
| 31.717391 | 136 | 0.619934 | 5.234783 | false | false | false | false |
niunaruto/DeDaoAppSwift
|
testSwift/Pods/YPImagePicker/Source/Pages/Photo/PostiOS10PhotoCapture.swift
|
2
|
4214
|
//
// PostiOS10PhotoCapture.swift
// YPImagePicker
//
// Created by Sacha DSO on 08/03/2018.
// Copyright © 2018 Yummypets. All rights reserved.
//
import UIKit
import AVFoundation
@available(iOS 10.0, *)
class PostiOS10PhotoCapture: NSObject, YPPhotoCapture, AVCapturePhotoCaptureDelegate {
let sessionQueue = DispatchQueue(label: "YPCameraVCSerialQueue", qos: .background)
let session = AVCaptureSession()
var deviceInput: AVCaptureDeviceInput?
var device: AVCaptureDevice? { return deviceInput?.device }
private let photoOutput = AVCapturePhotoOutput()
var output: AVCaptureOutput { return photoOutput }
var isCaptureSessionSetup: Bool = false
var isPreviewSetup: Bool = false
var previewView: UIView!
var videoLayer: AVCaptureVideoPreviewLayer!
var currentFlashMode: YPFlashMode = .off
var hasFlash: Bool {
guard let device = device else { return false }
return device.hasFlash
}
var block: ((Data) -> Void)?
var initVideoZoomFactor: CGFloat = 1.0
// MARK: - Configuration
private func newSettings() -> AVCapturePhotoSettings {
var settings = AVCapturePhotoSettings()
// Catpure Heif when available.
if #available(iOS 11.0, *) {
if photoOutput.availablePhotoCodecTypes.contains(.hevc) {
settings = AVCapturePhotoSettings(format: [AVVideoCodecKey: AVVideoCodecType.hevc])
}
}
// Catpure Highest Quality possible.
settings.isHighResolutionPhotoEnabled = true
// Set flash mode.
if let deviceInput = deviceInput {
if deviceInput.device.isFlashAvailable {
switch currentFlashMode {
case .auto:
if photoOutput.supportedFlashModes.contains(.auto) {
settings.flashMode = .auto
}
case .off:
if photoOutput.supportedFlashModes.contains(.off) {
settings.flashMode = .off
}
case .on:
if photoOutput.supportedFlashModes.contains(.on) {
settings.flashMode = .on
}
}
}
}
return settings
}
func configure() {
photoOutput.isHighResolutionCaptureEnabled = true
// Improve capture time by preparing output with the desired settings.
photoOutput.setPreparedPhotoSettingsArray([newSettings()], completionHandler: nil)
}
// MARK: - Flash
func tryToggleFlash() {
// if device.hasFlash device.isFlashAvailable //TODO test these
switch currentFlashMode {
case .auto:
currentFlashMode = .on
case .on:
currentFlashMode = .off
case .off:
currentFlashMode = .auto
}
}
// MARK: - Shoot
func shoot(completion: @escaping (Data) -> Void) {
block = completion
// Set current device orientation
setCurrentOrienation()
let settings = newSettings()
photoOutput.capturePhoto(with: settings, delegate: self)
}
@available(iOS 11.0, *)
func photoOutput(_ output: AVCapturePhotoOutput, didFinishProcessingPhoto photo: AVCapturePhoto, error: Error?) {
guard let data = photo.fileDataRepresentation() else { return }
block?(data)
}
func photoOutput(_ output: AVCapturePhotoOutput,
didFinishProcessingPhoto photoSampleBuffer: CMSampleBuffer?,
previewPhoto previewPhotoSampleBuffer: CMSampleBuffer?,
resolvedSettings: AVCaptureResolvedPhotoSettings,
bracketSettings: AVCaptureBracketedStillImageSettings?,
error: Error?) {
guard let buffer = photoSampleBuffer else { return }
if let data = AVCapturePhotoOutput
.jpegPhotoDataRepresentation(forJPEGSampleBuffer: buffer,
previewPhotoSampleBuffer: previewPhotoSampleBuffer) {
block?(data)
}
}
}
|
mit
|
726f08c2ceb3a6fa8030e1361d9d1f07
| 33.532787 | 117 | 0.600997 | 5.56539 | false | false | false | false |
huonw/swift
|
stdlib/public/core/Range.swift
|
1
|
32475
|
//===--- Range.swift ------------------------------------------*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that can be used to slice a collection.
///
/// A type that conforms to `RangeExpression` can convert itself to a
/// `Range<Bound>` of indices within a given collection.
public protocol RangeExpression {
/// The type for which the expression describes a range.
associatedtype Bound: Comparable
/// Returns the range of indices described by this range expression within
/// the given collection.
///
/// You can use the `relative(to:)` method to convert a range expression,
/// which could be missing one or both of its endpoints, into a concrete
/// range that is bounded on both sides. The following example uses this
/// method to convert a partial range up to `4` into a half-open range,
/// using an array instance to add the range's lower bound.
///
/// let numbers = [10, 20, 30, 40, 50, 60, 70]
/// let upToFour = ..<4
///
/// let r1 = upToFour.relative(to: numbers)
/// // r1 == 0..<4
///
/// The `r1` range is bounded on the lower end by `0` because that is the
/// starting index of the `numbers` array. When the collection passed to
/// `relative(to:)` starts with a different index, that index is used as the
/// lower bound instead. The next example creates a slice of `numbers`
/// starting at index `2`, and then uses the slice with `relative(to:)` to
/// convert `upToFour` to a concrete range.
///
/// let numbersSuffix = numbers[2...]
/// // numbersSuffix == [30, 40, 50, 60, 70]
///
/// let r2 = upToFour.relative(to: numbersSuffix)
/// // r2 == 2..<4
///
/// Use this method only if you need the concrete range it produces. To
/// access a slice of a collection using a range expression, use the
/// collection's generic subscript that uses a range expression as its
/// parameter.
///
/// let numbersPrefix = numbers[upToFour]
/// // numbersPrefix == [10, 20, 30, 40]
///
/// - Parameter collection: The collection to evaluate this range expression
/// in relation to.
/// - Returns: A range suitable for slicing `collection`. The returned range
/// is *not* guaranteed to be inside the bounds of `collection`. Callers
/// should apply the same preconditions to the return value as they would
/// to a range provided directly by the user.
func relative<C: Collection>(
to collection: C
) -> Range<Bound> where C.Index == Bound
/// Returns a Boolean value indicating whether the given element is contained
/// within the range expression.
///
/// - Parameter element: The element to check for containment.
/// - Returns: `true` if `element` is contained in the range expression;
/// otherwise, `false`.
func contains(_ element: Bound) -> Bool
}
extension RangeExpression {
@inlinable
public static func ~= (pattern: Self, value: Bound) -> Bool {
return pattern.contains(value)
}
}
/// A half-open interval from a lower bound up to, but not including, an upper
/// bound.
///
/// You create a `Range` instance by using the half-open range operator
/// (`..<`).
///
/// let underFive = 0.0..<5.0
///
/// You can use a `Range` instance to quickly check if a value is contained in
/// a particular range of values. For example:
///
/// underFive.contains(3.14)
/// // true
/// underFive.contains(6.28)
/// // false
/// underFive.contains(5.0)
/// // false
///
/// `Range` instances can represent an empty interval, unlike `ClosedRange`.
///
/// let empty = 0.0..<0.0
/// empty.contains(0.0)
/// // false
/// empty.isEmpty
/// // true
///
/// Using a Range as a Collection of Consecutive Values
/// ----------------------------------------------------
///
/// When a range uses integers as its lower and upper bounds, or any other type
/// that conforms to the `Strideable` protocol with an integer stride, you can
/// use that range in a `for`-`in` loop or with any sequence or collection
/// method. The elements of the range are the consecutive values from its
/// lower bound up to, but not including, its upper bound.
///
/// for n in 3..<5 {
/// print(n)
/// }
/// // Prints "3"
/// // Prints "4"
///
/// Because floating-point types such as `Float` and `Double` are their own
/// `Stride` types, they cannot be used as the bounds of a countable range. If
/// you need to iterate over consecutive floating-point values, see the
/// `stride(from:to:by:)` function.
@_fixed_layout
public struct Range<Bound : Comparable> {
/// The range's lower bound.
///
/// In an empty range, `lowerBound` is equal to `upperBound`.
public let lowerBound: Bound
/// The range's upper bound.
///
/// In an empty range, `upperBound` is equal to `lowerBound`. A `Range`
/// instance does not contain its upper bound.
public let upperBound: Bound
/// Creates an instance with the given bounds.
///
/// Because this initializer does not perform any checks, it should be used
/// as an optimization only when you are absolutely certain that `lower` is
/// less than or equal to `upper`. Using the half-open range operator
/// (`..<`) to form `Range` instances is preferred.
///
/// - Parameter bounds: A tuple of the lower and upper bounds of the range.
@inlinable
public init(uncheckedBounds bounds: (lower: Bound, upper: Bound)) {
self.lowerBound = bounds.lower
self.upperBound = bounds.upper
}
/// Returns a Boolean value indicating whether the given element is contained
/// within the range.
///
/// Because `Range` represents a half-open range, a `Range` instance does not
/// contain its upper bound. `element` is contained in the range if it is
/// greater than or equal to the lower bound and less than the upper bound.
///
/// - Parameter element: The element to check for containment.
/// - Returns: `true` if `element` is contained in the range; otherwise,
/// `false`.
@inlinable
public func contains(_ element: Bound) -> Bool {
return lowerBound <= element && element < upperBound
}
/// A Boolean value indicating whether the range contains no elements.
///
/// An empty `Range` instance has equal lower and upper bounds.
///
/// let empty: Range = 10..<10
/// print(empty.isEmpty)
/// // Prints "true"
@inlinable
public var isEmpty: Bool {
return lowerBound == upperBound
}
}
extension Range: Sequence
where Bound: Strideable, Bound.Stride : SignedInteger {
public typealias Element = Bound
public typealias Iterator = IndexingIterator<Range<Bound>>
}
// FIXME: should just be RandomAccessCollection
extension Range: Collection, BidirectionalCollection, RandomAccessCollection
where Bound : Strideable, Bound.Stride : SignedInteger
{
/// A type that represents a position in the range.
public typealias Index = Bound
public typealias Indices = Range<Bound>
public typealias SubSequence = Range<Bound>
@inlinable
public var startIndex: Index { return lowerBound }
@inlinable
public var endIndex: Index { return upperBound }
@inlinable
public func index(after i: Index) -> Index {
_failEarlyRangeCheck(i, bounds: startIndex..<endIndex)
return i.advanced(by: 1)
}
@inlinable
public func index(before i: Index) -> Index {
_precondition(i > lowerBound)
_precondition(i <= upperBound)
return i.advanced(by: -1)
}
@inlinable
public func index(_ i: Index, offsetBy n: Int) -> Index {
let r = i.advanced(by: numericCast(n))
_precondition(r >= lowerBound)
_precondition(r <= upperBound)
return r
}
@inlinable
public func distance(from start: Index, to end: Index) -> Int {
return numericCast(start.distance(to: end))
}
/// Accesses the subsequence bounded by the given range.
///
/// - Parameter bounds: A range of the range's indices. The upper and lower
/// bounds of the `bounds` range must be valid indices of the collection.
@inlinable
public subscript(bounds: Range<Index>) -> Range<Bound> {
return bounds
}
/// The indices that are valid for subscripting the range, in ascending
/// order.
@inlinable
public var indices: Indices {
return self
}
@inlinable
public func _customContainsEquatableElement(_ element: Element) -> Bool? {
return lowerBound <= element && element < upperBound
}
@inlinable
public func _customIndexOfEquatableElement(_ element: Bound) -> Index?? {
return lowerBound <= element && element < upperBound ? element : nil
}
@inlinable
public func _customLastIndexOfEquatableElement(_ element: Bound) -> Index?? {
// The first and last elements are the same because each element is unique.
return _customIndexOfEquatableElement(element)
}
/// Accesses the element at specified position.
///
/// You can subscript a collection with any valid index other than the
/// collection's end index. The end index refers to the position one past
/// the last element of a collection, so it doesn't correspond with an
/// element.
///
/// - Parameter position: The position of the element to access. `position`
/// must be a valid index of the range, and must not equal the range's end
/// index.
@inlinable
public subscript(position: Index) -> Element {
// FIXME: swift-3-indexing-model: tests for the range check.
_debugPrecondition(self.contains(position), "Index out of range")
return position
}
}
extension Range where Bound: Strideable, Bound.Stride : SignedInteger {
/// Now that Range is conditionally a collection when Bound: Strideable,
/// CountableRange is no longer needed. This is a deprecated initializer
/// for any remaining uses of Range(countableRange).
@available(*,deprecated: 4.2,
message: "CountableRange is now Range. No need to convert any more.")
public init(_ other: Range<Bound>) {
self = other
}
/// Creates an instance equivalent to the given `ClosedRange`.
///
/// - Parameter other: A closed range to convert to a `Range` instance.
///
/// An equivalent range must be representable as an instance of Range<Bound>.
/// For example, passing a closed range with an upper bound of `Int.max`
/// triggers a runtime error, because the resulting half-open range would
/// require an upper bound of `Int.max + 1`, which is not representable as
public init(_ other: ClosedRange<Bound>) {
let upperBound = other.upperBound.advanced(by: 1)
self.init(uncheckedBounds: (lower: other.lowerBound, upper: upperBound))
}
}
extension Range: RangeExpression {
/// Returns the range of indices described by this range expression within
/// the given collection.
///
/// - Parameter collection: The collection to evaluate this range expression
/// in relation to.
/// - Returns: A range suitable for slicing `collection`. The returned range
/// is *not* guaranteed to be inside the bounds of `collection`. Callers
/// should apply the same preconditions to the return value as they would
/// to a range provided directly by the user.
@inlinable // FIXME(sil-serialize-all)
public func relative<C: Collection>(to collection: C) -> Range<Bound>
where C.Index == Bound {
return Range(uncheckedBounds: (lower: lowerBound, upper: upperBound))
}
}
extension Range {
/// Returns a copy of this range clamped to the given limiting range.
///
/// The bounds of the result are always limited to the bounds of `limits`.
/// For example:
///
/// let x: Range = 0..<20
/// print(x.clamped(to: 10..<1000))
/// // Prints "10..<20"
///
/// If the two ranges do not overlap, the result is an empty range within the
/// bounds of `limits`.
///
/// let y: Range = 0..<5
/// print(y.clamped(to: 10..<1000))
/// // Prints "10..<10"
///
/// - Parameter limits: The range to clamp the bounds of this range.
/// - Returns: A new range clamped to the bounds of `limits`.
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public func clamped(to limits: Range) -> Range {
let lower =
limits.lowerBound > self.lowerBound ? limits.lowerBound
: limits.upperBound < self.lowerBound ? limits.upperBound
: self.lowerBound
let upper =
limits.upperBound < self.upperBound ? limits.upperBound
: limits.lowerBound > self.upperBound ? limits.lowerBound
: self.upperBound
return Range(uncheckedBounds: (lower: lower, upper: upper))
}
}
extension Range : CustomStringConvertible {
/// A textual representation of the range.
@inlinable // FIXME(sil-serialize-all)
public var description: String {
return "\(lowerBound)..<\(upperBound)"
}
}
extension Range : CustomDebugStringConvertible {
/// A textual representation of the range, suitable for debugging.
@inlinable // FIXME(sil-serialize-all)
public var debugDescription: String {
return "Range(\(String(reflecting: lowerBound))"
+ "..<\(String(reflecting: upperBound)))"
}
}
extension Range : CustomReflectable {
@inlinable // FIXME(sil-serialize-all)
public var customMirror: Mirror {
return Mirror(
self, children: ["lowerBound": lowerBound, "upperBound": upperBound])
}
}
extension Range: Equatable {
/// Returns a Boolean value indicating whether two ranges are equal.
///
/// Two ranges are equal when they have the same lower and upper bounds.
/// That requirement holds even for empty ranges.
///
/// let x: Range = 5..<15
/// print(x == 5..<15)
/// // Prints "true"
///
/// let y: Range = 5..<5
/// print(y == 15..<15)
/// // Prints "false"
///
/// - Parameters:
/// - lhs: A range to compare.
/// - rhs: Another range to compare.
@inlinable
public static func == (lhs: Range<Bound>, rhs: Range<Bound>) -> Bool {
return
lhs.lowerBound == rhs.lowerBound &&
lhs.upperBound == rhs.upperBound
}
}
extension Range: Hashable where Bound: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(lowerBound)
hasher.combine(upperBound)
}
}
/// A partial half-open interval up to, but not including, an upper bound.
///
/// You create `PartialRangeUpTo` instances by using the prefix half-open range
/// operator (prefix `..<`).
///
/// let upToFive = ..<5.0
///
/// You can use a `PartialRangeUpTo` instance to quickly check if a value is
/// contained in a particular range of values. For example:
///
/// upToFive.contains(3.14) // true
/// upToFive.contains(6.28) // false
/// upToFive.contains(5.0) // false
///
/// You can use a `PartialRangeUpTo` instance of a collection's indices to
/// represent the range from the start of the collection up to, but not
/// including, the partial range's upper bound.
///
/// let numbers = [10, 20, 30, 40, 50, 60, 70]
/// print(numbers[..<3])
/// // Prints "[10, 20, 30]"
@_fixed_layout
public struct PartialRangeUpTo<Bound: Comparable> {
public let upperBound: Bound
@inlinable // FIXME(sil-serialize-all)
public init(_ upperBound: Bound) { self.upperBound = upperBound }
}
extension PartialRangeUpTo: RangeExpression {
@inlinable // FIXME(sil-serialize-all)
@_transparent
public func relative<C: Collection>(to collection: C) -> Range<Bound>
where C.Index == Bound {
return collection.startIndex..<self.upperBound
}
@inlinable // FIXME(sil-serialize-all)
@_transparent
public func contains(_ element: Bound) -> Bool {
return element < upperBound
}
}
/// A partial interval up to, and including, an upper bound.
///
/// You create `PartialRangeThrough` instances by using the prefix closed range
/// operator (prefix `...`).
///
/// let throughFive = ...5.0
///
/// You can use a `PartialRangeThrough` instance to quickly check if a value is
/// contained in a particular range of values. For example:
///
/// throughFive.contains(4.0) // true
/// throughFive.contains(5.0) // true
/// throughFive.contains(6.0) // false
///
/// You can use a `PartialRangeThrough` instance of a collection's indices to
/// represent the range from the start of the collection up to, and including,
/// the partial range's upper bound.
///
/// let numbers = [10, 20, 30, 40, 50, 60, 70]
/// print(numbers[...3])
/// // Prints "[10, 20, 30, 40]"
@_fixed_layout
public struct PartialRangeThrough<Bound: Comparable> {
public let upperBound: Bound
@inlinable // FIXME(sil-serialize-all)
public init(_ upperBound: Bound) { self.upperBound = upperBound }
}
extension PartialRangeThrough: RangeExpression {
@inlinable // FIXME(sil-serialize-all)
@_transparent
public func relative<C: Collection>(to collection: C) -> Range<Bound>
where C.Index == Bound {
return collection.startIndex..<collection.index(after: self.upperBound)
}
@inlinable // FIXME(sil-serialize-all)
@_transparent
public func contains(_ element: Bound) -> Bool {
return element <= upperBound
}
}
/// A partial interval extending upward from a lower bound.
///
/// You create `PartialRangeFrom` instances by using the postfix range operator
/// (postfix `...`).
///
/// let atLeastFive = 5...
///
/// You can use a partial range to quickly check if a value is contained in a
/// particular range of values. For example:
///
/// atLeastFive.contains(4)
/// // false
/// atLeastFive.contains(5)
/// // true
/// atLeastFive.contains(6)
/// // true
///
/// You can use a partial range of a collection's indices to represent the
/// range from the partial range's lower bound up to the end of the
/// collection.
///
/// let numbers = [10, 20, 30, 40, 50, 60, 70]
/// print(numbers[3...])
/// // Prints "[40, 50, 60, 70]"
///
/// Using a Partial Range as a Sequence
/// -----------------------------------
///
/// When a partial range uses integers as its lower and upper bounds, or any
/// other type that conforms to the `Strideable` protocol with an integer
/// stride, you can use that range in a `for`-`in` loop or with any sequence
/// method that doesn't require that the sequence is finite. The elements of
/// a partial range are the consecutive values from its lower bound continuing
/// upward indefinitely.
///
/// func isTheMagicNumber(_ x: Int) -> Bool {
/// return x == 3
/// }
///
/// for x in 1... {
/// if isTheMagicNumber(x) {
/// print("\(x) is the magic number!")
/// break
/// } else {
/// print("\(x) wasn't it...")
/// }
/// }
/// // "1 wasn't it..."
/// // "2 wasn't it..."
/// // "3 is the magic number!"
///
/// Because a `PartialRangeFrom` sequence counts upward indefinitely, do not
/// use one with methods that read the entire sequence before returning, such
/// as `map(_:)`, `filter(_:)`, or `suffix(_:)`. It is safe to use operations
/// that put an upper limit on the number of elements they access, such as
/// `prefix(_:)` or `dropFirst(_:)`, and operations that you can guarantee
/// will terminate, such as passing a closure you know will eventually return
/// `true` to `first(where:)`.
///
/// In the following example, the `asciiTable` sequence is made by zipping
/// together the characters in the `alphabet` string with a partial range
/// starting at 65, the ASCII value of the capital letter A. Iterating over
/// two zipped sequences continues only as long as the shorter of the two
/// sequences, so the iteration stops at the end of `alphabet`.
///
/// let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
/// let asciiTable = zip(65..., alphabet)
/// for (code, letter) in asciiTable {
/// print(code, letter)
/// }
/// // "65 A"
/// // "66 B"
/// // "67 C"
/// // ...
/// // "89 Y"
/// // "90 Z"
///
/// The behavior of incrementing indefinitely is determined by the type of
/// `Bound`. For example, iterating over an instance of
/// `PartialRangeFrom<Int>` traps when the sequence's next value would be
/// above `Int.max`.
@_fixed_layout
public struct PartialRangeFrom<Bound: Comparable> {
public let lowerBound: Bound
@inlinable // FIXME(sil-serialize-all)
public init(_ lowerBound: Bound) { self.lowerBound = lowerBound }
}
extension PartialRangeFrom: RangeExpression {
@inlinable // FIXME(sil-serialize-all)
@_transparent
public func relative<C: Collection>(
to collection: C
) -> Range<Bound> where C.Index == Bound {
return self.lowerBound..<collection.endIndex
}
@inlinable // FIXME(sil-serialize-all)
public func contains(_ element: Bound) -> Bool {
return lowerBound <= element
}
}
extension PartialRangeFrom: Sequence
where Bound : Strideable, Bound.Stride : SignedInteger
{
public typealias Element = Bound
/// The iterator for a `PartialRangeFrom` instance.
@_fixed_layout
public struct Iterator: IteratorProtocol {
@usableFromInline
internal var _current: Bound
@inlinable
public init(_current: Bound) { self._current = _current }
/// Advances to the next element and returns it, or `nil` if no next
/// element exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
///
/// - Returns: The next element in the underlying sequence, if a next
/// element exists; otherwise, `nil`.
@inlinable
public mutating func next() -> Bound? {
defer { _current = _current.advanced(by: 1) }
return _current
}
}
/// Returns an iterator for this sequence.
@inlinable
public func makeIterator() -> Iterator {
return Iterator(_current: lowerBound)
}
}
extension Comparable {
/// Returns a half-open range that contains its lower bound but not its upper
/// bound.
///
/// Use the half-open range operator (`..<`) to create a range of any type
/// that conforms to the `Comparable` protocol. This example creates a
/// `Range<Double>` from zero up to, but not including, 5.0.
///
/// let lessThanFive = 0.0..<5.0
/// print(lessThanFive.contains(3.14)) // Prints "true"
/// print(lessThanFive.contains(5.0)) // Prints "false"
///
/// - Parameters:
/// - minimum: The lower bound for the range.
/// - maximum: The upper bound for the range.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public static func ..< (minimum: Self, maximum: Self) -> Range<Self> {
_precondition(minimum <= maximum,
"Can't form Range with upperBound < lowerBound")
return Range(uncheckedBounds: (lower: minimum, upper: maximum))
}
/// Returns a partial range up to, but not including, its upper bound.
///
/// Use the prefix half-open range operator (prefix `..<`) to create a
/// partial range of any type that conforms to the `Comparable` protocol.
/// This example creates a `PartialRangeUpTo<Double>` instance that includes
/// any value less than `5.0`.
///
/// let upToFive = ..<5.0
///
/// upToFive.contains(3.14) // true
/// upToFive.contains(6.28) // false
/// upToFive.contains(5.0) // false
///
/// You can use this type of partial range of a collection's indices to
/// represent the range from the start of the collection up to, but not
/// including, the partial range's upper bound.
///
/// let numbers = [10, 20, 30, 40, 50, 60, 70]
/// print(numbers[..<3])
/// // Prints "[10, 20, 30]"
///
/// - Parameter maximum: The upper bound for the range.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public static prefix func ..< (maximum: Self) -> PartialRangeUpTo<Self> {
return PartialRangeUpTo(maximum)
}
/// Returns a partial range up to, and including, its upper bound.
///
/// Use the prefix closed range operator (prefix `...`) to create a partial
/// range of any type that conforms to the `Comparable` protocol. This
/// example creates a `PartialRangeThrough<Double>` instance that includes
/// any value less than or equal to `5.0`.
///
/// let throughFive = ...5.0
///
/// throughFive.contains(4.0) // true
/// throughFive.contains(5.0) // true
/// throughFive.contains(6.0) // false
///
/// You can use this type of partial range of a collection's indices to
/// represent the range from the start of the collection up to, and
/// including, the partial range's upper bound.
///
/// let numbers = [10, 20, 30, 40, 50, 60, 70]
/// print(numbers[...3])
/// // Prints "[10, 20, 30, 40]"
///
/// - Parameter maximum: The upper bound for the range.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public static prefix func ... (maximum: Self) -> PartialRangeThrough<Self> {
return PartialRangeThrough(maximum)
}
/// Returns a partial range extending upward from a lower bound.
///
/// Use the postfix range operator (postfix `...`) to create a partial range
/// of any type that conforms to the `Comparable` protocol. This example
/// creates a `PartialRangeFrom<Double>` instance that includes any value
/// greater than or equal to `5.0`.
///
/// let atLeastFive = 5.0...
///
/// atLeastFive.contains(4.0) // false
/// atLeastFive.contains(5.0) // true
/// atLeastFive.contains(6.0) // true
///
/// You can use this type of partial range of a collection's indices to
/// represent the range from the partial range's lower bound up to the end
/// of the collection.
///
/// let numbers = [10, 20, 30, 40, 50, 60, 70]
/// print(numbers[3...])
/// // Prints "[40, 50, 60, 70]"
///
/// - Parameter minimum: The lower bound for the range.
@inlinable // FIXME(sil-serialize-all)
@_transparent
public static postfix func ... (minimum: Self) -> PartialRangeFrom<Self> {
return PartialRangeFrom(minimum)
}
}
/// A range expression that represents the entire range of a collection.
///
/// You can use the unbounded range operator (`...`) to create a slice of a
/// collection that contains all of the collection's elements. Slicing with an
/// unbounded range is essentially a conversion of a collection instance into
/// its slice type.
///
/// For example, the following code declares `countLetterChanges(_:_:)`, a
/// function that finds the number of changes required to change one
/// word or phrase into another. The function uses a recursive approach to
/// perform the same comparisons on smaller and smaller pieces of the original
/// strings. In order to use recursion without making copies of the strings at
/// each step, `countLetterChanges(_:_:)` uses `Substring`, a string's slice
/// type, for its parameters.
///
/// func countLetterChanges(_ s1: Substring, _ s2: Substring) -> Int {
/// if s1.isEmpty { return s2.count }
/// if s2.isEmpty { return s1.count }
///
/// let cost = s1.first == s2.first ? 0 : 1
///
/// return min(
/// countLetterChanges(s1.dropFirst(), s2) + 1,
/// countLetterChanges(s1, s2.dropFirst()) + 1,
/// countLetterChanges(s1.dropFirst(), s2.dropFirst()) + cost)
/// }
///
/// To call `countLetterChanges(_:_:)` with two strings, use an unbounded
/// range in each string's subscript.
///
/// let word1 = "grizzly"
/// let word2 = "grisly"
/// let changes = countLetterChanges(word1[...], word2[...])
/// // changes == 2
@_frozen // FIXME(sil-serialize-all)
public enum UnboundedRange_ {
// FIXME: replace this with a computed var named `...` when the language makes
// that possible.
/// Creates an unbounded range expression.
///
/// The unbounded range operator (`...`) is valid only within a collection's
/// subscript.
@inlinable // FIXME(sil-serialize-all)
public static postfix func ... (_: UnboundedRange_) -> () {
fatalError("uncallable")
}
}
/// The type of an unbounded range operator.
public typealias UnboundedRange = (UnboundedRange_)->()
extension Collection {
/// Accesses the contiguous subrange of the collection's elements specified
/// by a range expression.
///
/// The range expression is converted to a concrete subrange relative to this
/// collection. For example, using a `PartialRangeFrom` range expression
/// with an array accesses the subrange from the start of the range
/// expression until the end of the array.
///
/// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"]
/// let streetsSlice = streets[2...]
/// print(streetsSlice)
/// // ["Channing", "Douglas", "Evarts"]
///
/// The accessed slice uses the same indices for the same elements as the
/// original collection uses. This example searches `streetsSlice` for one
/// of the strings in the slice, and then uses that index in the original
/// array.
///
/// let index = streetsSlice.firstIndex(of: "Evarts") // 4
/// print(streets[index!])
/// // "Evarts"
///
/// Always use the slice's `startIndex` property instead of assuming that its
/// indices start at a particular value. Attempting to access an element by
/// using an index outside the bounds of the slice's indices may result in a
/// runtime error, even if that index is valid for the original collection.
///
/// print(streetsSlice.startIndex)
/// // 2
/// print(streetsSlice[2])
/// // "Channing"
///
/// print(streetsSlice[0])
/// // error: Index out of bounds
///
/// - Parameter bounds: A range of the collection's indices. The bounds of
/// the range must be valid indices of the collection.
///
/// - Complexity: O(1)
@inlinable
public subscript<R: RangeExpression>(r: R)
-> SubSequence where R.Bound == Index {
return self[r.relative(to: self)]
}
@inlinable
public subscript(x: UnboundedRange) -> SubSequence {
return self[startIndex...]
}
}
extension MutableCollection {
@inlinable
public subscript<R: RangeExpression>(r: R) -> SubSequence
where R.Bound == Index {
get {
return self[r.relative(to: self)]
}
set {
self[r.relative(to: self)] = newValue
}
}
@inlinable // FIXME(sil-serialize-all)
public subscript(x: UnboundedRange) -> SubSequence {
get {
return self[startIndex...]
}
set {
self[startIndex...] = newValue
}
}
}
// TODO: enhance RangeExpression to make this generic and available on
// any expression.
extension Range {
/// Returns a Boolean value indicating whether this range and the given range
/// contain an element in common.
///
/// This example shows two overlapping ranges:
///
/// let x: Range = 0..<20
/// print(x.overlaps(10...1000))
/// // Prints "true"
///
/// Because a half-open range does not include its upper bound, the ranges
/// in the following example do not overlap:
///
/// let y = 20..<30
/// print(x.overlaps(y))
/// // Prints "false"
///
/// - Parameter other: A range to check for elements in common.
/// - Returns: `true` if this range and `other` have at least one element in
/// common; otherwise, `false`.
@inlinable
public func overlaps(_ other: Range<Bound>) -> Bool {
return (!other.isEmpty && self.contains(other.lowerBound))
|| (!self.isEmpty && other.contains(self.lowerBound))
}
@inlinable
public func overlaps(_ other: ClosedRange<Bound>) -> Bool {
return self.contains(other.lowerBound)
|| (!self.isEmpty && other.contains(self.lowerBound))
}
}
public typealias CountableRange<Bound: Strideable> = Range<Bound>
where Bound.Stride : SignedInteger
public typealias CountablePartialRangeFrom<Bound: Strideable> = PartialRangeFrom<Bound>
where Bound.Stride : SignedInteger
|
apache-2.0
|
b5a0ed283fdf857504ed77382c2d7fcf
| 34.414395 | 87 | 0.648868 | 4.14698 | false | false | false | false |
dongjiali/DatePicker
|
DatePicker/DatePickerViewController.swift
|
1
|
3284
|
//
// DatePickerViewController.swift
// DatePicker
//
// Created by Curry on 15/5/15.
// Copyright (c) 2015年 curry. All rights reserved.
//
import UIKit
protocol DatePickerChoiceDelegate
{
func didChoiceDatePicker(_ datePickerView: DatePickerView)
}
class DatePickerViewController: UIViewController,DatePickerDelegate {
var preaSuperView:UIView = UIView()
var selectDate:String = ""
var choiceDelegate:DatePickerChoiceDelegate?
override func viewDidLoad() {
super.viewDidLoad()
let pickerView = DatePickerView(frame: self.view.frame)
pickerView.delegate = self
pickerView.backgroundColor = UIColor.clear
self.view = pickerView
self.view.frame = CGRect(x: 0, y: self.view.frame.size.height, width: self.view.frame.size.width, height: self.view.frame.height)
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func showDatePickerView()
{
//改变状态栏颜色
UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.lightContent, animated: true)
let keyWindow = UIApplication.shared.keyWindow
keyWindow?.addSubview(self.view)
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.frame = CGRect(x: 0, y: -10, width: self.view.frame.size.width, height: self.view.frame.size.height);
self.preaSuperView.transform = CGAffineTransform(scaleX: 0.90, y: 0.90);
self.preaSuperView.alpha = 0.6;
self.preaSuperView.isUserInteractionEnabled = false;
}, completion: { (Bool) -> Void in
UIView.animate(withDuration: 0.25, animations: { () -> Void in
self.view.frame = CGRect(x: 0, y: 0, width: self.view.frame.size.width, height: self.view.frame.size.height);
})
})
}
func dismissDatePickerView()
{
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.view.frame = CGRect(x: 0, y: self.view.frame.size.height, width: self.view.frame.size.width, height: self.view.frame.size.height);
self.preaSuperView.transform = CGAffineTransform(scaleX: 1.0, y: 1.0);
self.preaSuperView.alpha = 1.0;
}, completion: { (Bool) -> Void in
self.preaSuperView.isUserInteractionEnabled = true;
UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: true)
self.view.removeFromSuperview()
})
}
func didSelectedItemDatePicker(_ datePickerView: DatePickerView) {
selectDate = datePickerView.selectedDateString
choiceDelegate?.didChoiceDatePicker(datePickerView)
self.dismissDatePickerView()
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
c406fd93841f7afcc0fd17374a8f2d6c
| 37.904762 | 147 | 0.657283 | 4.446259 | false | false | false | false |
Igor-Palaguta/MotoSwift
|
Sources/MotoSwiftFramework/CoreData/Parser/Attribute+XMLParser.swift
|
1
|
1282
|
import Foundation
import SWXMLHash
extension Attribute {
init(xml: XMLIndexer) throws {
self.name = try xml.value(ofAttribute: "name")
self.type = try AttributeType(stringValue: try xml.value(ofAttribute: "attributeType"))
self.isScalar = xml.value(ofAttribute: "usesScalarValueType") ?? false
self.isOptional = xml.value(ofAttribute: "optional") ?? false
self.userInfo = try xml.userInfo()
}
}
private extension AttributeType {
private static let typesMapping: [String: AttributeType] = [
"Boolean": .boolean,
"Binary": .binary,
"Date": .date,
"Decimal": .decimal,
"Double": .double,
"Float": .float,
"Integer 16": .integer16,
"Integer 32": .integer32,
"Integer 64": .integer64,
"String": .string,
"Transformable": .transformable
]
init(stringValue: String) throws {
guard let type = AttributeType.typesMapping[stringValue] else {
throw UnknownAttributeTypeError(type: stringValue)
}
self = type
}
}
private struct UnknownAttributeTypeError: Error, CustomStringConvertible {
let type: String
var description: String {
return "Unexpected attribute type: '\(type)'"
}
}
|
mit
|
a317207d7d2ef567b21235e258746205
| 28.813953 | 95 | 0.627925 | 4.405498 | false | false | false | false |
sdrpa/fdps
|
Tests/FDPSTests/FlightCodingTests.swift
|
1
|
2793
|
/**
Created by Sinisa Drpa on 4/18/17.
FDPS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License or any later version.
FDPS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with FDPS. If not, see <http://www.gnu.org/licenses/>
*/
import AircraftKit
import ATCKit
import Measure
import XCTest
@testable import FDPS
class FlightCodingTests: XCTestCase {
func testCoding() {
// Aircraft
let takeOff = Performance.TakeOff(v2: 140, distance: 1600, mtow: 56470)
let climb1 = Performance.Climb(from: 0, to: 5000, ias: 165, rate: 2500)
let climb2 = Performance.Climb(from: 5000, to: 15000, ias: 270, rate: 2000)
let cruise = Performance.Cruise(tas: 429, mach: Mach(0.745), ceiling: 370, range: 1600)
let descent1 = Performance.Descent(from: 660, to: 24000, mach: Mach(0.7), rate: 800)
let descent2 = Performance.Descent(from: 24000, to: 10000, ias: 270, rate: 3500)
let approach = Performance.Approach(v: 130, distance: 1400, apc: "C")
let performance = Performance(takeOff: takeOff, climb: [climb1, climb2], cruise: cruise, descent: [descent1, descent2], approach: approach)
let aircraft = Aircraft(code: .B733, name: "737-300", manufacturer: "BOEING", typeCode: "L2J", wtc: .medium, performance: performance)
// Route
let coordinate = Coordinate(latitude: 44.7866, longitude: 20.4489)
let position = Position(coordinate: coordinate, altitude: 12000)
let vor1 = VOR(title: "XX1", coordinate: coordinate, frequency: 121.5)
let vor2 = VOR(title: "XX2", coordinate: coordinate, frequency: 121.5)
let route = Route(navigationPoints: [AnyNavigationPoint(vor1), AnyNavigationPoint(vor2)])
let flightPlan = FlightPlan(callsign: "ASL123", squawk: 2000, aircraft: aircraft, ADEP: "LYBE", ADES: "LWSK", RFL: 270, route: route)
let value = Flight(callsign: "ASL123", squawk: 2000, position: position, mach: 0.745, heading: 180, flightPlan: flightPlan)
guard let encoded = value.toJSON() else {
XCTFail(); return
}
XCTAssertTrue(JSONSerialization.isValidJSONObject(encoded))
let decoded = Flight(json: encoded)
XCTAssertEqual(value, decoded)
}
static var allTests : [(String, (FlightCodingTests) -> () throws -> Void)] {
return [
("testCoding", testCoding),
]
}
}
|
gpl-3.0
|
427f8d4193b38d12803f76cd28706534
| 45.55 | 147 | 0.67884 | 3.831276 | false | true | false | false |
hanangellove/Spring
|
Spring/DesignableTextField.swift
|
37
|
3663
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Meng To ([email protected])
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
@IBDesignable public class DesignableTextField: SpringTextField {
@IBInspectable public var placeholderColor: UIColor = UIColor.clearColor() {
didSet {
attributedPlaceholder = NSAttributedString(string: placeholder!, attributes: [NSForegroundColorAttributeName: placeholderColor])
layoutSubviews()
}
}
@IBInspectable public var sidePadding: CGFloat = 0 {
didSet {
var padding = UIView(frame: CGRectMake(0, 0, sidePadding, sidePadding))
leftViewMode = UITextFieldViewMode.Always
leftView = padding
rightViewMode = UITextFieldViewMode.Always
rightView = padding
}
}
@IBInspectable public var leftPadding: CGFloat = 0 {
didSet {
var padding = UIView(frame: CGRectMake(0, 0, leftPadding, 0))
leftViewMode = UITextFieldViewMode.Always
leftView = padding
}
}
@IBInspectable public var rightPadding: CGFloat = 0 {
didSet {
var padding = UIView(frame: CGRectMake(0, 0, rightPadding, 0))
rightViewMode = UITextFieldViewMode.Always
rightView = padding
}
}
@IBInspectable public var borderColor: UIColor = UIColor.clearColor() {
didSet {
layer.borderColor = borderColor.CGColor
}
}
@IBInspectable public var borderWidth: CGFloat = 0 {
didSet {
layer.borderWidth = borderWidth
}
}
@IBInspectable public var cornerRadius: CGFloat = 0 {
didSet {
layer.cornerRadius = cornerRadius
}
}
@IBInspectable public var lineHeight: CGFloat = 1.5 {
didSet {
var font = UIFont(name: self.font.fontName, size: self.font.pointSize)
var text = self.text
var paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = lineHeight
var attributedString = NSMutableAttributedString(string: text!)
attributedString.addAttribute(NSParagraphStyleAttributeName, value: paragraphStyle, range: NSMakeRange(0, attributedString.length))
attributedString.addAttribute(NSFontAttributeName, value: font!, range: NSMakeRange(0, attributedString.length))
self.attributedText = attributedString
}
}
}
|
mit
|
a1531f806ed8b5e34f227b3efb220059
| 36 | 143 | 0.648922 | 5.541604 | false | false | false | false |
february29/Learning
|
swift/Fch_Contact/Pods/RxCocoa/RxCocoa/iOS/UIScrollView+Rx.swift
|
15
|
6630
|
//
// UIScrollView+Rx.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 4/3/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
#if !RX_NO_MODULE
import RxSwift
#endif
import UIKit
extension Reactive where Base: UIScrollView {
public typealias EndZoomEvent = (view: UIView?, scale: CGFloat)
public typealias WillEndDraggingEvent = (velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>)
/// Reactive wrapper for `delegate`.
///
/// For more information take a look at `DelegateProxyType` protocol documentation.
public var delegate: DelegateProxy<UIScrollView, UIScrollViewDelegate> {
return RxScrollViewDelegateProxy.proxy(for: base)
}
/// Reactive wrapper for `contentOffset`.
public var contentOffset: ControlProperty<CGPoint> {
let proxy = RxScrollViewDelegateProxy.proxy(for: base)
let bindingObserver = Binder(self.base) { scrollView, contentOffset in
scrollView.contentOffset = contentOffset
}
return ControlProperty(values: proxy.contentOffsetBehaviorSubject, valueSink: bindingObserver)
}
/// Bindable sink for `scrollEnabled` property.
public var isScrollEnabled: Binder<Bool> {
return Binder(self.base) { scrollView, scrollEnabled in
scrollView.isScrollEnabled = scrollEnabled
}
}
/// Reactive wrapper for delegate method `scrollViewDidScroll`
public var didScroll: ControlEvent<Void> {
let source = RxScrollViewDelegateProxy.proxy(for: base).contentOffsetPublishSubject
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewWillBeginDecelerating`
public var willBeginDecelerating: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginDecelerating(_:))).map { _ in }
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewDidEndDecelerating`
public var didEndDecelerating: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndDecelerating(_:))).map { _ in }
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewWillBeginDragging`
public var willBeginDragging: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginDragging(_:))).map { _ in }
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)`
public var willEndDragging: ControlEvent<WillEndDraggingEvent> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillEndDragging(_:withVelocity:targetContentOffset:)))
.map { value -> WillEndDraggingEvent in
let velocity = try castOrThrow(CGPoint.self, value[1])
let targetContentOffsetValue = try castOrThrow(NSValue.self, value[2])
guard let rawPointer = targetContentOffsetValue.pointerValue else { throw RxCocoaError.unknown }
let typedPointer = rawPointer.bindMemory(to: CGPoint.self, capacity: MemoryLayout<CGPoint>.size)
return (velocity, typedPointer)
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewDidEndDragging(_:willDecelerate:)`
public var didEndDragging: ControlEvent<Bool> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndDragging(_:willDecelerate:))).map { value -> Bool in
return try castOrThrow(Bool.self, value[1])
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewDidZoom`
public var didZoom: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidZoom)).map { _ in }
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewDidScrollToTop`
public var didScrollToTop: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidScrollToTop(_:))).map { _ in }
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewDidEndScrollingAnimation`
public var didEndScrollingAnimation: ControlEvent<Void> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndScrollingAnimation(_:))).map { _ in }
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewWillBeginZooming(_:with:)`
public var willBeginZooming: ControlEvent<UIView?> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewWillBeginZooming(_:with:))).map { value -> UIView? in
return try castOptionalOrThrow(UIView.self, value[1] as AnyObject)
}
return ControlEvent(events: source)
}
/// Reactive wrapper for delegate method `scrollViewDidEndZooming(_:with:atScale:)`
public var didEndZooming: ControlEvent<EndZoomEvent> {
let source = delegate.methodInvoked(#selector(UIScrollViewDelegate.scrollViewDidEndZooming(_:with:atScale:))).map { value -> EndZoomEvent in
return (try castOptionalOrThrow(UIView.self, value[1] as AnyObject), try castOrThrow(CGFloat.self, value[2]))
}
return ControlEvent(events: source)
}
/// Installs delegate as forwarding delegate on `delegate`.
/// Delegate won't be retained.
///
/// It enables using normal delegate mechanism with reactive delegate mechanism.
///
/// - parameter delegate: Delegate object.
/// - returns: Disposable object that can be used to unbind the delegate.
public func setDelegate(_ delegate: UIScrollViewDelegate)
-> Disposable {
return RxScrollViewDelegateProxy.installForwardDelegate(delegate, retainDelegate: false, onProxyForObject: self.base)
}
}
#endif
|
mit
|
7e06170d4871e56e5401b0963ef1a58a
| 46.014184 | 152 | 0.664806 | 5.887211 | false | false | false | false |
soapyigu/Swift30Projects
|
Project 17 - ClassicPhotos/ClassicPhotos/PhotoOperations.swift
|
1
|
2845
|
//
// PhotoOperations.swift
// ClassicPhotos
//
// Copyright © 2016 raywenderlich. All rights reserved.
//
import UIKit
/// Represents all the possible states a photo record can be in.
enum PhotoRecordState {
case New, Downloaded, Filtered, Failed
}
class PhotoRecord {
let name: String
let url: URL
var state = PhotoRecordState.New
var image = UIImage(named: "Placeholder")
init(name: String, url: URL) {
self.name = name
self.url = url
}
}
class PendingOperations {
lazy var downloadsInProgress = [IndexPath:Operation]()
lazy var downloadQueue: OperationQueue = {
var queue = OperationQueue()
queue.name = "Download queue"
queue.maxConcurrentOperationCount = 1
return queue
}()
lazy var filtrationsInProgress = [IndexPath:Operation]()
lazy var filtrationQueue: OperationQueue = {
var queue = OperationQueue()
queue.name = "Image Filtration queue"
queue.maxConcurrentOperationCount = 1
return queue
}()
}
class ImageDownloader: Operation {
let photoRecord: PhotoRecord
init(photoRecord: PhotoRecord) {
self.photoRecord = photoRecord
}
/// Main is the function actually perform work.
override func main() {
/// Check for cancellation before starting.
if isCancelled {
return
}
do {
let imageData = try Data(contentsOf: photoRecord.url)
if self.isCancelled {
return
}
if imageData.count > 0 {
photoRecord.image = UIImage(data: imageData)
photoRecord.state = .Downloaded
} else {
photoRecord.state = .Failed
photoRecord.image = UIImage(named: "Failed")
}
} catch let error as NSError{
print(error.domain)
}
}
}
class ImageFiltration: Operation {
let photoRecord: PhotoRecord
init(photoRecord: PhotoRecord) {
self.photoRecord = photoRecord
}
func applySepiaFilter(image: UIImage) -> UIImage? {
let inputImage = CIImage(data: image.pngData()!)
if isCancelled {
return nil
}
let context = CIContext(options:nil)
let filter = CIFilter(name: "CISepiaTone")
filter?.setValue(inputImage, forKey: kCIInputImageKey)
filter?.setValue(0.8, forKey: "inputIntensity")
if isCancelled {
return nil
}
if let outputImage = filter?.outputImage,
let outImage = context.createCGImage(outputImage, from: outputImage.extent) {
return UIImage(cgImage: outImage)
} else {
return nil
}
}
override func main () {
if isCancelled {
return
}
if self.photoRecord.state != .Downloaded {
return
}
if let image = photoRecord.image,
let filteredImage = applySepiaFilter(image: image) {
photoRecord.image = filteredImage
photoRecord.state = .Filtered
}
}
}
|
apache-2.0
|
5018b3bd09f3d74a4b35fdd7cd529a53
| 21.571429 | 83 | 0.648734 | 4.341985 | false | false | false | false |
bryx-inc/GeoJSON.swift
|
Sources/GeoJSON/GeoJSONMulti.swift
|
1
|
1090
|
//
// GeoJSONMultiPolygon.swift
// Bryx 911
//
// Created by Harlan Haskins on 7/7/15.
// Copyright (c) 2015 Bryx. All rights reserved.
//
import Foundation
import CoreLocation
public struct GeoJSONMulti<FeatureType>: GeoJSONFeature where FeatureType: GeoJSONFeature {
public static var type: String { return "Multi" + FeatureType.type }
public let features: [FeatureType]
public init?(dictionary: [String: Any]) {
guard let featureArrays = dictionary["coordinates"] as? [Any] else { return nil }
let features = featureArrays.compactMap { FeatureType.init(dictionary: ["coordinates": $0]) }
self.init(features: features)
}
public init(features: [FeatureType]) {
self.features = features
}
public var geometryCoordinates: [Any] {
return self.features.map { $0.geometryCoordinates }
}
}
public typealias GeoJSONMultiPoint = GeoJSONMulti<GeoJSONPoint>
public typealias GeoJSONMultiPolygon = GeoJSONMulti<GeoJSONPolygon>
public typealias GeoJSONMultiLineString = GeoJSONMulti<GeoJSONLineString>
|
mit
|
ed84d151eaafc89182320446a321421f
| 31.058824 | 101 | 0.709174 | 4.224806 | false | false | false | false |
amosavian/FileProvider
|
Sources/Extensions/HashMAC.swift
|
2
|
18240
|
// Originally based on CryptoSwift by Marcin Krzyżanowski <[email protected]>
// Copyright (C) 2014 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
import Foundation
protocol SHA2Variant {
static var size: Int { get }
static var h: [UInt64] { get }
static var k: [UInt64] { get }
static func resultingArray<T>(_ hh:[T]) -> ArraySlice<T>
static func calculate(_ message: [UInt8]) -> [UInt8]
}
protocol SHA2Variant32: SHA2Variant { }
protocol SHA2Variant64: SHA2Variant { }
extension SHA2Variant32 {
static var size: Int {
return 64
}
static var k: [UInt64] {
return [0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2]
}
// codebeat:disable[ABC]
static func calculate(_ message: [UInt8]) -> [UInt8] {
var tmpMessage = message
let len = Self.size
// Step 1. Append Padding Bits
tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message
// append "0" bit until message length in bits ≡ 448 (mod 512)
var msgLength = tmpMessage.count
var counter = 0
while msgLength % len != (len - 8) {
counter += 1
msgLength += 1
}
tmpMessage.append(contentsOf: [UInt8](repeating: 0, count: counter))
// hash values
var hh: [UInt32] = Self.h.map { UInt32($0) }
let k = Self.k
// append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits.
tmpMessage.append(contentsOf: arrayOfBytes(message.count * 8, length: 64 / 8))
// Process the message in successive 512-bit chunks:
let chunkSizeBytes = 512 / 8 // 64
for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15, big-endian
// Extend the sixteen 32-bit words into sixty-four 32-bit words:
var M:[UInt32] = [UInt32](repeating: 0, count: k.count)
for x in 0..<M.count {
switch (x) {
case 0...15:
let start: Int = chunk.startIndex + (x * MemoryLayout.size(ofValue: M[x]))
let end: Int = start + MemoryLayout.size(ofValue: M[x])
let le = toUInt32Array(chunk[start..<end])[0]
M[x] = le.bigEndian
break
default:
let s0 = rotateRight(M[x-15], n: 7) ^ rotateRight(M[x-15], n: 18) ^ (M[x-15] >> 3) //FIXME: n
let s1 = rotateRight(M[x-2], n: 17) ^ rotateRight(M[x-2], n: 19) ^ (M[x-2] >> 10)
let s2 = M[x-16]
let s3 = M[x-7]
M[x] = s2 &+ s0 &+ s3 &+ s1
break
}
}
var A = hh[0], B = hh[1], C = hh[2], D = hh[3], E = hh[4], F = hh[5], G = hh[6], H = hh[7]
// Main loop
for j in 0..<k.count {
let s0 = rotateRight(A,n: 2) ^ rotateRight(A,n: 13) ^ rotateRight(A,n: 22)
let maj = (A & B) ^ (A & C) ^ (B & C)
let t2 = s0 &+ maj
let s1 = rotateRight(E,n: 6) ^ rotateRight(E,n: 11) ^ rotateRight(E,n: 25)
let ch = (E & F) ^ ((~E) & G)
let t1 = H &+ s1 &+ ch &+ UInt32(k[j]) &+ M[j]
H = G; G = F; F = E; E = D &+ t1
D = C; C = B; B = A; A = t1 &+ t2
}
hh[0] = (hh[0] &+ A)
hh[1] = (hh[1] &+ B)
hh[2] = (hh[2] &+ C)
hh[3] = (hh[3] &+ D)
hh[4] = (hh[4] &+ E)
hh[5] = (hh[5] &+ F)
hh[6] = (hh[6] &+ G)
hh[7] = (hh[7] &+ H)
}
// Produce the final hash value (big-endian) as a 160 bit number:
var result = [UInt8]()
result.reserveCapacity(hh.count / 4)
Self.resultingArray(hh).forEach {
let item = $0.bigEndian
#if swift(>=4.0)
result.append(UInt8(truncatingIfNeeded: item))
result.append(UInt8(truncatingIfNeeded: item >> 8))
result.append(UInt8(truncatingIfNeeded: item >> 16))
result.append(UInt8(truncatingIfNeeded: item >> 24))
#else
result.append(UInt8(item))
result.append(UInt8((item >> 8) & 0xFF))
result.append(UInt8((item >> 16) & 0xFF))
result.append(UInt8((item >> 24) & 0xFF))
#endif
}
return result
}
// codebeat:enable[ABC]
}
extension SHA2Variant64 {
static var size: Int {
return 128
}
static var k: [UInt64] {
return [0x428a2f98d728ae22, 0x7137449123ef65cd, 0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc, 0x3956c25bf348b538,
0x59f111f1b605d019, 0x923f82a4af194f9b, 0xab1c5ed5da6d8118, 0xd807aa98a3030242, 0x12835b0145706fbe,
0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2, 0x72be5d74f27b896f, 0x80deb1fe3b1696b1, 0x9bdc06a725c71235,
0xc19bf174cf692694, 0xe49b69c19ef14ad2, 0xefbe4786384f25e3, 0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
0x2de92c6f592b0275, 0x4a7484aa6ea6e483, 0x5cb0a9dcbd41fbd4, 0x76f988da831153b5, 0x983e5152ee66dfab,
0xa831c66d2db43210, 0xb00327c898fb213f, 0xbf597fc7beef0ee4, 0xc6e00bf33da88fc2, 0xd5a79147930aa725,
0x06ca6351e003826f, 0x142929670a0e6e70, 0x27b70a8546d22ffc, 0x2e1b21385c26c926, 0x4d2c6dfc5ac42aed,
0x53380d139d95b3df, 0x650a73548baf63de, 0x766a0abb3c77b2a8, 0x81c2c92e47edaee6, 0x92722c851482353b,
0xa2bfe8a14cf10364, 0xa81a664bbc423001, 0xc24b8b70d0f89791, 0xc76c51a30654be30, 0xd192e819d6ef5218,
0xd69906245565a910, 0xf40e35855771202a, 0x106aa07032bbd1b8, 0x19a4c116b8d2d0c8, 0x1e376c085141ab53,
0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8, 0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb, 0x5b9cca4f7763e373,
0x682e6ff3d6b2b8a3, 0x748f82ee5defb2fc, 0x78a5636f43172f60, 0x84c87814a1f0ab72, 0x8cc702081a6439ec,
0x90befffa23631e28, 0xa4506cebde82bde9, 0xbef9a3f7b2c67915, 0xc67178f2e372532b, 0xca273eceea26619c,
0xd186b8c721c0c207, 0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178, 0x06f067aa72176fba, 0x0a637dc5a2c898a6,
0x113f9804bef90dae, 0x1b710b35131c471b, 0x28db77f523047d84, 0x32caab7b40c72493, 0x3c9ebe0a15c9bebc,
0x431d67c49c100d4c, 0x4cc5d4becb3e42b6, 0x597f299cfc657e2a, 0x5fcb6fab3ad6faec, 0x6c44198c4a475817]
}
// codebeat:disable[ABC]
static func calculate(_ message: [UInt8]) -> [UInt8] {
var tmpMessage = message
let len = Self.size
// Step 1. Append Padding Bits
tmpMessage.append(0x80) // append one bit (UInt8 with one bit) to message
// append "0" bit until message length in bits ≡ 448 (mod 512)
var msgLength = tmpMessage.count
var counter = 0
while msgLength % len != (len - 8) {
counter += 1
msgLength += 1
}
tmpMessage += [UInt8](repeating: 0, count: counter)
// hash values
var hh: [UInt64] = Self.h
let k = Self.k
// append message length, in a 64-bit big-endian integer. So now the message length is a multiple of 512 bits.
tmpMessage += arrayOfBytes(message.count * 8, length: 64 / 8)
// Process the message in successive 1024-bit chunks:
let chunkSizeBytes = 1024 / 8 // 128
for chunk in BytesSequence(chunkSize: chunkSizeBytes, data: tmpMessage) {
// break chunk into sixteen 64-bit words M[j], 0 ≤ j ≤ 15, big-endian
// Extend the sixteen 64-bit words into eighty 64-bit words:
var M = [UInt64](repeating: 0, count: k.count)
for x in 0..<M.count {
switch (x) {
case 0...15:
let start = chunk.startIndex + (x * MemoryLayout.size(ofValue: M[x]))
let end = start + MemoryLayout.size(ofValue: M[x])
let le = toUInt64Array(chunk[start..<end])[0]
M[x] = le.bigEndian
break
default:
let s0 = rotateRight(M[x-15], n: 1) ^ rotateRight(M[x-15], n: 8) ^ (M[x-15] >> 7)
let s1 = rotateRight(M[x-2], n: 19) ^ rotateRight(M[x-2], n: 61) ^ (M[x-2] >> 6)
let s2 = M[x-16]
let s3 = M[x-7]
M[x] = s2 &+ s0 &+ s3 &+ s1
break
}
}
var A = hh[0], B = hh[1], C = hh[2], D = hh[3], E = hh[4], F = hh[5], G = hh[6], H = hh[7]
// Main loop
for j in 0..<k.count {
let s0 = rotateRight(A,n: 28) ^ rotateRight(A,n: 34) ^ rotateRight(A,n: 39) //FIXME: n:
let maj = (A & B) ^ (A & C) ^ (B & C)
let t2 = s0 &+ maj
let s1 = rotateRight(E,n: 14) ^ rotateRight(E,n: 18) ^ rotateRight(E,n: 41)
let ch = (E & F) ^ ((~E) & G)
let t1 = H &+ s1 &+ ch &+ k[j] &+ UInt64(M[j])
H = G; G = F; F = E; E = D &+ t1
D = C; C = B; B = A; A = t1 &+ t2
}
hh[0] = (hh[0] &+ A)
hh[1] = (hh[1] &+ B)
hh[2] = (hh[2] &+ C)
hh[3] = (hh[3] &+ D)
hh[4] = (hh[4] &+ E)
hh[5] = (hh[5] &+ F)
hh[6] = (hh[6] &+ G)
hh[7] = (hh[7] &+ H)
}
// Produce the final hash value (big-endian)
var result = [UInt8]()
result.reserveCapacity(hh.count / 4)
Self.resultingArray(hh).forEach {
let item = $0.bigEndian
var partialResult = [UInt8]()
partialResult.reserveCapacity(8)
for i in 0..<8 {
let shift = UInt64(8 * i)
partialResult.append(UInt8((item >> shift) & 0xff))
}
result += partialResult
}
return result
}
// codebeat:enable[ABC]
}
final class SHA256 : SHA2Variant32 {
static let h: [UInt64] = [0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19]
static func resultingArray<T>(_ hh: [T]) -> ArraySlice<T> {
return ArraySlice(hh)
}
}
final class SHA384 : SHA2Variant64 {
static let h: [UInt64] = [0xcbbb9d5dc1059ed8, 0x629a292a367cd507, 0x9159015a3070dd17, 0x152fecd8f70e5939, 0x67332667ffc00b31, 0x8eb44a8768581511, 0xdb0c2e0d64f98fa7, 0x47b5481dbefa4fa4]
public static func resultingArray<T>(_ hh: [T]) -> ArraySlice<T> {
return hh[0..<6]
}
}
final class SHA512 : SHA2Variant64 {
static let h: [UInt64] = [0x6a09e667f3bcc908, 0xbb67ae8584caa73b, 0x3c6ef372fe94f82b, 0xa54ff53a5f1d36f1, 0x510e527fade682d1, 0x9b05688c2b3e6c1f, 0x1f83d9abfb41bd6b, 0x5be0cd19137e2179]
static func resultingArray<T>(_ hh: [T]) -> ArraySlice<T> {
return ArraySlice(hh)
}
}
final class SHA2<Variant: SHA2Variant> {
static var size: Int {
return Variant.size
}
static func calculate(_ message: [UInt8]) -> [UInt8] {
return Variant.calculate(message)
}
}
final class HMAC<Variant: SHA2Variant> {
public static func authenticate(message:[UInt8], withKey key: [UInt8]) -> [UInt8] {
var key = key
if (key.count > Variant.size) {
key = Variant.calculate(key)
}
if (key.count < Variant.size) { // keys shorter than blocksize are zero-padded
key = key + [UInt8](repeating: 0, count: Variant.size - key.count)
}
var opad = [UInt8](repeating: 0x5c, count: Variant.size)
for (idx, _) in key.enumerated() {
opad[idx] = key[idx] ^ opad[idx]
}
var ipad = [UInt8](repeating: 0x36, count: Variant.size)
for (idx, _) in key.enumerated() {
ipad[idx] = key[idx] ^ ipad[idx]
}
let ipadAndMessageHash = Variant.calculate(ipad + message)
let finalHash = Variant.calculate(opad + ipadAndMessageHash);
return finalHash
}
static func authenticate(message: String, withKey key: [UInt8]) -> [UInt8] {
return authenticate(message: [UInt8](message.utf8), withKey: key)
}
static func authenticate(message: Data, withKey key: Data) -> Data {
#if swift(>=5.0)
return Data(authenticate(message: Array(message), withKey: Array(key)))
#else
return Data(bytes: authenticate(message: Array(message), withKey: Array(key)))
#endif
}
static func authenticate(message: String, withKey key: Data) -> Data {
#if swift(>=5.0)
return Data(authenticate(message: [UInt8](message.utf8), withKey: Array(key)))
#else
return Data(bytes: authenticate(message: [UInt8](message.utf8), withKey: Array(key)))
#endif
}
}
fileprivate struct BytesSequence: Sequence {
let chunkSize: Int
let data: [UInt8]
init(chunkSize: Int, data: [UInt8]) {
self.chunkSize = chunkSize
self.data = data
}
func makeIterator() -> AnyIterator<ArraySlice<UInt8>> {
var offset:Int = 0
return AnyIterator {
let end = Swift.min(self.chunkSize, self.data.count - offset)
let result = self.data[offset..<offset + end]
offset += result.count
return result.count > 0 ? result : nil
}
}
}
fileprivate func rotateRight(_ x:UInt16, n:UInt16) -> UInt16 {
return (x >> n) | (x << (16 - n))
}
fileprivate func rotateRight(_ x:UInt32, n:UInt32) -> UInt32 {
return (x >> n) | (x << (32 - n))
}
fileprivate func rotateRight(_ x:UInt64, n:UInt64) -> UInt64 {
return ((x >> n) | (x << (64 - n)))
}
fileprivate func toUInt32Array(_ slice: ArraySlice<UInt8>) -> Array<UInt32> {
var result = Array<UInt32>()
result.reserveCapacity(16)
for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout<UInt32>.size) {
let val1:UInt32 = (UInt32(slice[idx.advanced(by: 3)]) << 24)
let val2:UInt32 = (UInt32(slice[idx.advanced(by: 2)]) << 16)
let val3:UInt32 = (UInt32(slice[idx.advanced(by: 1)]) << 8)
let val4:UInt32 = UInt32(slice[idx])
let val:UInt32 = val1 | val2 | val3 | val4
result.append(val)
}
return result
}
fileprivate func toUInt64Array(_ slice: ArraySlice<UInt8>) -> Array<UInt64> {
var result = Array<UInt64>()
result.reserveCapacity(32)
for idx in stride(from: slice.startIndex, to: slice.endIndex, by: MemoryLayout<UInt64>.size) {
var val:UInt64 = 0
val |= UInt64(slice[idx.advanced(by: 7)]) << 56
val |= UInt64(slice[idx.advanced(by: 6)]) << 48
val |= UInt64(slice[idx.advanced(by: 5)]) << 40
val |= UInt64(slice[idx.advanced(by: 4)]) << 32
val |= UInt64(slice[idx.advanced(by: 3)]) << 24
val |= UInt64(slice[idx.advanced(by: 2)]) << 16
val |= UInt64(slice[idx.advanced(by: 1)]) << 8
val |= UInt64(slice[idx.advanced(by: 0)]) << 0
result.append(val)
}
return result
}
fileprivate func arrayOfBytes<T>(_ value: T, length: Int? = nil) -> [UInt8] {
var value = value
return Swift.withUnsafeBytes(of: &value) { (buffer: UnsafeRawBufferPointer) -> [UInt8] in
if let length = length {
return Array(buffer.prefix(length))
} else {
return Array(buffer)
}
}
}
extension String {
public func fp_sha256() -> [UInt8] {
return SHA2<SHA256>.calculate([UInt8](self.utf8))
}
public func fp_sha384() -> [UInt8] {
return SHA2<SHA384>.calculate([UInt8](self.utf8))
}
public func fp_sha512() -> [UInt8] {
return SHA2<SHA512>.calculate([UInt8](self.utf8))
}
}
extension Data {
public func fp_sha256() -> [UInt8] {
return SHA2<SHA256>.calculate(Array(self))
}
public func fp_sha384() -> [UInt8] {
return SHA2<SHA384>.calculate(Array(self))
}
public func fp_sha512() -> [UInt8] {
return SHA2<SHA512>.calculate(Array(self))
}
}
|
mit
|
aad03c2549ed0205917f09fa070d33fa
| 39.957303 | 216 | 0.566882 | 3.150017 | false | false | false | false |
Coderian/SwiftedKML
|
SwiftedKML/Elements/PolyStyle.swift
|
1
|
2487
|
//
// PolyStyle.swift
// SwiftedKML
//
// Created by 佐々木 均 on 2016/02/02.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// KML PolyStyle
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <element name="PolyStyle" type="kml:PolyStyleType" substitutionGroup="kml:AbstractColorStyleGroup"/>
public class PolyStyle :SPXMLElement, AbstractColorStyleGroup, HasXMLElementValue {
public static var elementName: String = "PolyStyle"
public override var parent:SPXMLElement! {
didSet {
// 複数回呼ばれたて同じものがある場合は追加しない
if self.parent.childs.contains(self) == false {
self.parent.childs.insert(self)
switch parent {
case let v as Style: v.value.polyStyle = self
default: break
}
}
}
}
public var value : PolyStyleType
required public init(attributes:[String:String]){
self.value = PolyStyleType(attributes: attributes)
super.init(attributes: attributes)
}
public var abstractObject : AbstractObjectType { return self.value }
public var abstractSubStyle : AbstractSubStyleType { return self.value }
public var abstractColorStyle : AbstractColorStyleType { return self.value }
}
/// KML PolyStyleType
///
/// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd)
///
/// <complexType name="PolyStyleType" final="#all">
/// <complexContent>
/// <extension base="kml:AbstractColorStyleType">
/// <sequence>
/// <element ref="kml:fill" minOccurs="0"/>
/// <element ref="kml:outline" minOccurs="0"/>
/// <element ref="kml:PolyStyleSimpleExtensionGroup" minOccurs="0" maxOccurs="unbounded"/>
/// <element ref="kml:PolyStyleObjectExtensionGroup" minOccurs="0" maxOccurs="unbounded"/>
/// </sequence>
/// </extension>
/// </complexContent>
/// </complexType>
/// <element name="PolyStyleSimpleExtensionGroup" abstract="true" type="anySimpleType"/>
/// <element name="PolyStyleObjectExtensionGroup" abstract="true" substitutionGroup="kml:AbstractObjectGroup"/>
public class PolyStyleType: AbstractColorStyleType {
public var fill: Fill! // = true
public var outline: Outline! // = true
public var polyStyleSimpleExtensionGroup: [AnyObject] = []
public var polyStyleObjectExtensionGroup: [AbstractObjectGroup] = []
}
|
mit
|
04514d939347a01ce98ec5a802fa2375
| 38.193548 | 115 | 0.665432 | 3.95122 | false | false | false | false |
xsunsmile/TwitterApp
|
Twitter/TweetDetailsViewController.swift
|
1
|
2084
|
//
// TweetDetailsViewController.swift
// Twitter
//
// Created by Hao Sun on 2/22/15.
// Copyright (c) 2015 Hao Sun. All rights reserved.
//
import UIKit
class TweetDetailsViewController: UITableViewController {
@IBOutlet weak var userImageView: UIImageView!
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var userHandleLabel: UILabel!
@IBOutlet weak var tweetTextLabel: UILabel!
@IBOutlet weak var tweetTimeLabel: UILabel!
@IBOutlet weak var retweetCountLabel: UILabel!
@IBOutlet weak var favoriteCountLabel: UILabel!
@IBOutlet weak var retweetImageView: UIImageView!
@IBOutlet weak var favoriteImageView: UIImageView!
var tweet: Tweet?
override func viewDidLoad() {
super.viewDidLoad()
tableView.rowHeight = UITableViewAutomaticDimension
var userImageUrl = tweet?.user()?.imageUrl()
if userImageUrl != nil {
userImageView.setImageWithURL(userImageUrl!)
}
userNameLabel.text = tweet?.user()?.name()
userHandleLabel.text = tweet?.user()?.screenName()
tweetTextLabel.text = tweet?.text()
tweetTimeLabel.text = tweet?.createdAtString()
if let count = tweet?.retweetCount() {
retweetCountLabel.text = "\(count)"
}
if let count = tweet?.favoriteCount() {
favoriteCountLabel.text = "\(count)"
}
if let favorited = tweet?.favorited() {
if favorited > 0 {
favoriteImageView.image = UIImage(named: "Favorited")
}
}
if let retweeted = tweet?.retweeted() {
if retweeted > 0 {
retweetImageView.image = UIImage(named: "Retweeted")
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
var vc = segue.destinationViewController as TweetReplyViewController
vc.tweet = tweet
}
}
|
apache-2.0
|
577429bf317533707c30c37fec9b4269
| 30.575758 | 81 | 0.62428 | 5.28934 | false | false | false | false |
xyryx/iweb
|
iweb/StringExtensions.swift
|
1
|
773
|
//
// StringExtensions.swift
// iweb
//
// Created by ಅಜೇಯ on 10/25/15.
// Copyright © 2015 ಅಜೇಯ ಜಯರಾಂ. All rights reserved.
//
import Foundation
extension String {
func beginsWith (_ str: String, caseInsensitive: Bool = false) -> Bool {
let options = caseInsensitive ? NSString.CompareOptions.caseInsensitive : NSString.CompareOptions.literal
if let range = self.range(of: str, options: options) {
return range.lowerBound == self.startIndex
}
return false
}
func endsWith (_ str: String) -> Bool {
if let range = self.range(of: str, options:NSString.CompareOptions.backwards) {
return range.upperBound == self.endIndex
}
return false
}
}
|
mit
|
ddc3fe1513680dae2f1ed2f237d3ffd5
| 27.692308 | 113 | 0.628686 | 3.535545 | false | false | false | false |
pksprojects/ElasticSwift
|
Sources/ElasticSwift/Requests/MultiTermVectorsRequest.swift
|
1
|
8609
|
//
// MultiTermVectorsRequest.swift
//
//
// Created by Prafull Kumar Soni on 10/2/19.
//
import ElasticSwiftCodableUtils
import ElasticSwiftCore
import Foundation
import NIOHTTP1
// MARK: - Multi TermVectors Request Builder
public class MultiTermVectorsRequestBuilder: RequestBuilder {
public typealias RequestType = MultiTermVectorsRequest
private var _index: String?
private var _type: String?
private var _requests: [TermVectorsRequest]?
private var _ids: [String]?
private var _parameters: MultiTermVectorsRequest.Parameters?
public init() {}
@discardableResult
public func set(index: String) -> Self {
_index = index
return self
}
@discardableResult
public func set(type: String) -> Self {
_type = type
return self
}
@discardableResult
public func set(requests: [TermVectorsRequest]) -> Self {
_requests = requests
return self
}
@discardableResult
public func add(request: TermVectorsRequest) -> Self {
if _requests == nil {
_requests = [request]
} else {
_requests?.append(request)
}
return self
}
@discardableResult
public func set(ids: [String]) -> Self {
_ids = ids
return self
}
@discardableResult
public func add(id: String) -> Self {
if _ids == nil {
_ids = [id]
} else {
_ids?.append(id)
}
return self
}
@discardableResult
public func set(parameters: MultiTermVectorsRequest.Parameters?) -> Self {
_parameters = parameters
return self
}
public var index: String? {
return _index
}
public var type: String? {
return _type
}
public var requests: [TermVectorsRequest]? {
return _requests
}
public var ids: [String]? {
return _ids
}
public var parameters: MultiTermVectorsRequest.Parameters? {
return _parameters
}
public func build() throws -> MultiTermVectorsRequest {
return try MultiTermVectorsRequest(withBuilder: self)
}
}
// MARK: - Multi TermVectors Request
public struct MultiTermVectorsRequest: Request {
public var headers = HTTPHeaders()
public let index: String?
public let type: String?
public let requests: [TermVectorsRequest]?
public let parameters: Parameters?
public let ids: [String]?
public var termStatistics: Bool?
public var fieldStatistics: Bool?
public var fields: [String]?
public var offsets: Bool?
public var positions: Bool?
public var payloads: Bool?
public var preference: Bool?
public var routing: String?
public var parent: String?
public var realtime: Bool?
public var version: Int?
public var versionType: VersionType?
internal init(withBuilder builder: MultiTermVectorsRequestBuilder) throws {
guard builder.requests != nil || builder.ids != nil else {
throw RequestBuilderError.atleastOneFieldRequired(["id", "reqeusts"])
}
index = builder.index
type = builder.type
requests = builder.requests
ids = builder.ids
parameters = builder.parameters
}
public var queryParams: [URLQueryItem] {
var params = [URLQueryItem]()
if let termStatistics = self.termStatistics {
params.append(URLQueryItem(name: QueryParams.termStatistics, value: termStatistics))
}
if let fieldStatistics = self.fieldStatistics {
params.append(URLQueryItem(name: QueryParams.fieldStatistics, value: fieldStatistics))
}
if let offsets = self.offsets {
params.append(URLQueryItem(name: QueryParams.offsets, value: offsets))
}
if let positions = self.positions {
params.append(URLQueryItem(name: QueryParams.positions, value: positions))
}
if let payloads = self.payloads {
params.append(URLQueryItem(name: QueryParams.payloads, value: payloads))
}
if let preference = self.preference {
params.append(URLQueryItem(name: QueryParams.preference, value: preference))
}
if let routing = self.routing {
params.append(URLQueryItem(name: QueryParams.routing, value: routing))
}
if let parent = self.parent {
params.append(URLQueryItem(name: QueryParams.parent, value: parent))
}
if let realtime = self.realtime {
params.append(URLQueryItem(name: QueryParams.realTime, value: realtime))
}
if let version = self.version {
params.append(URLQueryItem(name: QueryParams.version, value: version))
}
if let versionType = self.versionType {
params.append(URLQueryItem(name: QueryParams.versionType, value: versionType.rawValue))
}
return params
}
public var method: HTTPMethod {
return .POST
}
public var endPoint: String {
return "_mtermvectors"
}
public func makeBody(_ serializer: Serializer) -> Result<Data, MakeBodyError> {
let docs = requests?.map { Doc($0) }
let body = Body(docs: docs, parameters: parameters, ids: ids)
return serializer.encode(body).mapError { error -> MakeBodyError in
.wrapped(error)
}
}
struct Body: Encodable, Equatable {
public let docs: [Doc]?
public let parameters: Parameters?
public let ids: [String]?
}
struct Doc: Encodable, Equatable {
public let index: String?
public let type: String?
public let id: String?
public let doc: EncodableValue?
public let filter: TermVectorsRequest.Filter?
public let fields: [String]?
public let perFieldAnalyzer: [String: String]?
public var termStatistics: Bool?
public var fieldStatistics: Bool?
public var offsets: Bool?
public var positions: Bool?
public var payloads: Bool?
public var preference: String?
public var routing: String?
public var parent: String?
public var version: Int?
public var versionType: VersionType?
init(_ request: TermVectorsRequest) {
index = request.index
type = request.type
id = request.id
doc = request.doc
filter = request.filter
fields = request.fields
perFieldAnalyzer = request.perFieldAnalyzer
termStatistics = request.termStatistics
fieldStatistics = request.fieldStatistics
offsets = request.offsets
positions = request.positions
payloads = request.payloads
preference = request.preference
routing = request.routing
parent = request.parent
version = request.version
versionType = request.versionType
}
enum CodingKeys: String, CodingKey {
case index = "_index"
case type = "_type"
case id = "_id"
case doc
case filter
case fields
case perFieldAnalyzer = "per_field_analyzer"
case termStatistics = "term_statistics"
case fieldStatistics = "field_statistics"
case offsets
case positions
case payloads
case preference
case routing
case parent
case version
case versionType = "version_type"
}
}
public struct Parameters: Codable, Equatable {
public var termStatistics: Bool?
public var fieldStatistics: Bool?
public var fields: [String]?
public var offsets: Bool?
public var positions: Bool?
public var payloads: Bool?
public var preference: Bool?
public var routing: String?
public var parent: String?
public var realtime: Bool?
public var version: Int?
public var versionType: VersionType?
enum CodingKeys: String, CodingKey {
case termStatistics = "term_statistics"
case fieldStatistics = "field_statistics"
case fields
case offsets
case positions
case payloads
case preference
case routing
case parent
case realtime
case version
case versionType = "version_type"
}
}
}
extension MultiTermVectorsRequest: Equatable {}
|
mit
|
cc94349b09b22082e46d5b8a9bb09900
| 28.788927 | 99 | 0.607852 | 4.930699 | false | false | false | false |
gali8/G8MaterialKitTextField
|
MKTextField/MKTextField.swift
|
1
|
6862
|
//
// MKTextField.swift
// MaterialKit
//
// Created by LeVan Nghia on 11/14/14.
// Copyright (c) 2014 Le Van Nghia. All rights reserved.
//
import UIKit
import QuartzCore
@IBDesignable
class MKTextField : UITextField {
@IBInspectable var padding: CGSize = CGSize(width: 5, height: 5)
@IBInspectable var floatingLabelBottomMargin: CGFloat = 2.0
@IBInspectable var floatingPlaceholderEnabled: Bool = false
@IBInspectable var rippleLocation: MKRippleLocation = .TapLocation {
didSet {
mkLayer.rippleLocation = rippleLocation
}
}
@IBInspectable var aniDuration: Float = 0.65
@IBInspectable var circleAniTimingFunction: MKTimingFunction = .Linear
@IBInspectable var shadowAniEnabled: Bool = true
@IBInspectable var cornerRadius: CGFloat = 2.5 {
didSet {
layer.cornerRadius = cornerRadius
mkLayer.setMaskLayerCornerRadius(cornerRadius)
}
}
// color
@IBInspectable var circleLayerColor: UIColor = UIColor(white: 0.45, alpha: 0.5) {
didSet {
mkLayer.setCircleLayerColor(circleLayerColor)
}
}
@IBInspectable var backgroundLayerColor: UIColor = UIColor(white: 0.75, alpha: 0.25) {
didSet {
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
}
}
// floating label
@IBInspectable var floatingLabelFont: UIFont = UIFont.boldSystemFontOfSize(10.0) {
didSet {
floatingLabel.font = floatingLabelFont
}
}
@IBInspectable var floatingLabelTextColor: UIColor = UIColor.lightGrayColor() {
didSet {
floatingLabel.textColor = floatingLabelTextColor
}
}
@IBInspectable var bottomBorderEnabled: Bool = true {
didSet {
bottomBorderLayer?.removeFromSuperlayer()
bottomBorderLayer = nil
if bottomBorderEnabled {
bottomBorderLayer = CALayer()
bottomBorderLayer?.frame = CGRect(x: 0, y: self.layer.bounds.height - 1, width: self.bounds.width, height: 1)
bottomBorderLayer?.backgroundColor = UIColor.MKColor.Grey.CGColor
self.layer.addSublayer(bottomBorderLayer!)
}
}
}
@IBInspectable var bottomBorderWidth: CGFloat = 1.0
@IBInspectable var bottomBorderColor: UIColor = UIColor.lightGrayColor()
@IBInspectable var bottomBorderHighlightWidth: CGFloat = 1.75
override var placeholder: String? {
didSet {
floatingLabel.text = placeholder
floatingLabel.sizeToFit()
setFloatingLabelOverlapTextField()
}
}
override var bounds: CGRect {
didSet {
mkLayer.superLayerDidResize()
}
}
private lazy var mkLayer: MKLayer = MKLayer(superLayer: self.layer)
private var floatingLabel: UILabel!
private var bottomBorderLayer: CALayer?
override init(frame: CGRect) {
super.init(frame: frame)
setupLayer()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupLayer()
}
private func setupLayer() {
self.cornerRadius = 2.5
self.layer.borderWidth = 1.0
self.borderStyle = .None
mkLayer.circleGrowRatioMax = 1.0
mkLayer.setBackgroundLayerColor(backgroundLayerColor)
mkLayer.setCircleLayerColor(circleLayerColor)
// floating label
floatingLabel = UILabel()
floatingLabel.font = floatingLabelFont
floatingLabel.alpha = 0.0
self.addSubview(floatingLabel)
}
override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent?) -> Bool {
mkLayer.didChangeTapLocation(touch.locationInView(self))
mkLayer.animateScaleForCircleLayer(0.45, toScale: 1.0, timingFunction: MKTimingFunction.Linear, duration: 0.75)
mkLayer.animateAlphaForBackgroundLayer(MKTimingFunction.Linear, duration: 0.75)
return super.beginTrackingWithTouch(touch, withEvent: event)
}
override func layoutSubviews() {
super.layoutSubviews()
if !floatingPlaceholderEnabled {
return
}
if !self.text!.isEmpty {
floatingLabel.textColor = self.isFirstResponder() ? self.tintColor : floatingLabelTextColor
if floatingLabel.alpha == 0 {
self.showFloatingLabel()
}
} else {
self.hideFloatingLabel()
}
bottomBorderLayer?.backgroundColor = self.isFirstResponder() ? self.tintColor.CGColor : bottomBorderColor.CGColor
let borderWidth = self.isFirstResponder() ? bottomBorderHighlightWidth : bottomBorderWidth
bottomBorderLayer?.frame = CGRect(x: 0, y: self.layer.bounds.height - borderWidth, width: self.layer.bounds.width, height: borderWidth)
}
override func textRectForBounds(bounds: CGRect) -> CGRect {
let rect = super.textRectForBounds(bounds)
var newRect = CGRect(x: rect.origin.x + padding.width, y: rect.origin.y,
width: rect.size.width - 2*padding.width, height: rect.size.height)
if !floatingPlaceholderEnabled {
return newRect
}
if !self.text!.isEmpty {
let dTop = floatingLabel.font.lineHeight + floatingLabelBottomMargin
newRect = UIEdgeInsetsInsetRect(newRect, UIEdgeInsets(top: dTop, left: 0.0, bottom: 0.0, right: 0.0))
}
return newRect
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
return self.textRectForBounds(bounds)
}
// MARK - private
private func setFloatingLabelOverlapTextField() {
let textRect = self.textRectForBounds(self.bounds)
var originX = textRect.origin.x
switch self.textAlignment {
case .Center:
originX += textRect.size.width/2 - floatingLabel.bounds.width/2
case .Right:
originX += textRect.size.width - floatingLabel.bounds.width
default:
break
}
floatingLabel.frame = CGRect(x: originX, y: padding.height,
width: floatingLabel.frame.size.width, height: floatingLabel.frame.size.height)
}
private func showFloatingLabel() {
let curFrame = floatingLabel.frame
floatingLabel.frame = CGRect(x: curFrame.origin.x, y: self.bounds.height/2, width: curFrame.width, height: curFrame.height)
UIView.animateWithDuration(0.45, delay: 0.0, options: .CurveEaseOut, animations: {
self.floatingLabel.alpha = 1.0
self.floatingLabel.frame = curFrame
}, completion: nil)
}
private func hideFloatingLabel() {
floatingLabel.alpha = 0.0
}
}
|
mit
|
cab170b0b28cc984744f3745d4f62c3d
| 34.554404 | 143 | 0.637278 | 5.064207 | false | false | false | false |
stefan-vainberg/SlidingImagePuzzle
|
SlidingImagePuzzle/SlidingImagePuzzle/AppDelegate.swift
|
1
|
2922
|
//
// AppDelegate.swift
// SlidingImagePuzzle
//
// Created by Stefan Vainberg on 10/20/14.
// Copyright (c) 2014 Stefan. All rights reserved.
//
import UIKit
import Photos
import AssetsLibrary
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
if let unwrappedWindow = window{
// get photo access. needed later on in the application
let assetsLibrary = ALAssetsLibrary()
assetsLibrary.enumerateGroupsWithTypes(ALAssetsGroupSavedPhotos, usingBlock: { (group, stop) -> Void in
}, failureBlock: { (error) -> Void in
})
let vc = WorkspaceViewController()
unwrappedWindow.backgroundColor = UIColor.whiteColor()
unwrappedWindow.rootViewController = vc
unwrappedWindow.makeKeyAndVisible()
}
else {return false}
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
|
cc0-1.0
|
037e885bf64a2f6f54ba7d393bf03f88
| 42.61194 | 285 | 0.70705 | 5.707031 | false | false | false | false |
brendancboyle/SecTalk-iOS
|
Pods/CryptoSwift/CryptoSwift/Poly1305.swift
|
1
|
8713
|
//
// Poly1305.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 30/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
// http://tools.ietf.org/html/draft-agl-tls-chacha20poly1305-04#section-4
//
// Poly1305 takes a 32-byte, one-time key and a message and produces a 16-byte tag that authenticates the
// message such that an attacker has a negligible chance of producing a valid tag for an inauthentic message.
import Foundation
public class Poly1305 {
let blockSize = 16
private var ctx:Context?
private class Context {
var r = [UInt8](count: 17, repeatedValue: 0)
var h = [UInt8](count: 17, repeatedValue: 0)
var pad = [UInt8](count: 17, repeatedValue: 0)
var buffer = [UInt8](count: 16, repeatedValue: 0)
var final:UInt8 = 0
var leftover:Int = 0
init?(_ key: [UInt8]) {
assert(key.count == 32,"Invalid key length");
if (key.count != 32) {
return nil;
}
for i in 0..<17 {
h[i] = 0
}
r[0] = key[0] & 0xff;
r[1] = key[1] & 0xff;
r[2] = key[2] & 0xff;
r[3] = key[3] & 0x0f;
r[4] = key[4] & 0xfc;
r[5] = key[5] & 0xff;
r[6] = key[6] & 0xff;
r[7] = key[7] & 0x0f;
r[8] = key[8] & 0xfc;
r[9] = key[9] & 0xff;
r[10] = key[10] & 0xff;
r[11] = key[11] & 0x0f;
r[12] = key[12] & 0xfc;
r[13] = key[13] & 0xff;
r[14] = key[14] & 0xff;
r[15] = key[15] & 0x0f;
r[16] = 0
for i in 0..<16 {
pad[i] = key[i + 16]
}
pad[16] = 0
leftover = 0
final = 0
}
deinit {
for i in 0..<buffer.count {
buffer[i] = 0
}
for i in 0..<r.count {
r[i] = 0
h[i] = 0
pad[i] = 0
final = 0
leftover = 0
}
}
}
// MARK: - Internal
/**
Calculate Message Authentication Code (MAC) for message.
Calculation context is discarder on instance deallocation.
:param: key 256-bit key
:param: message Message
:returns: Message Authentication Code
*/
class internal func authenticate(# key: [UInt8], message: [UInt8]) -> [UInt8]? {
return Poly1305(key)?.authenticate(message: message)
}
// MARK: - Private
private init? (_ key: [UInt8]) {
ctx = Context(key)
if (ctx == nil) {
return nil
}
}
private func authenticate(# message:[UInt8]) -> [UInt8]? {
if let ctx = self.ctx {
update(ctx, message: message)
return finish(ctx)
}
return nil
}
/**
Add message to be processed
:param: context Context
:param: message message
:param: bytes length of the message fragment to be processed
*/
private func update(context:Context, message:[UInt8], bytes:Int? = nil) {
var bytes = bytes ?? message.count
var mPos = 0
/* handle leftover */
if (context.leftover > 0) {
var want = blockSize - context.leftover
if (want > bytes) {
want = bytes
}
for i in 0..<want {
context.buffer[context.leftover + i] = message[mPos + i]
}
bytes -= want
mPos += want
context.leftover += want
if (context.leftover < blockSize) {
return
}
blocks(context, m: context.buffer)
context.leftover = 0
}
/* process full blocks */
if (bytes >= blockSize) {
var want = bytes & ~(blockSize - 1)
blocks(context, m: message, startPos: mPos)
mPos += want
bytes -= want;
}
/* store leftover */
if (bytes > 0) {
for i in 0..<bytes {
context.buffer[context.leftover + i] = message[mPos + i]
}
context.leftover += bytes
}
}
private func finish(context:Context) -> [UInt8]? {
var mac = [UInt8](count: 16, repeatedValue: 0);
/* process the remaining block */
if (context.leftover > 0) {
var i = context.leftover
context.buffer[i++] = 1
for (; i < blockSize; i++) {
context.buffer[i] = 0
}
context.final = 1
blocks(context, m: context.buffer)
}
/* fully reduce h */
freeze(context)
/* h = (h + pad) % (1 << 128) */
add(context, c: context.pad)
for i in 0..<mac.count {
mac[i] = context.h[i]
}
return mac
}
// MARK: - Utils
private func add(context:Context, c:[UInt8]) -> Bool {
if (context.h.count != 17 && c.count != 17) {
return false
}
var u:UInt16 = 0
for i in 0..<17 {
u += UInt16(context.h[i]) + UInt16(c[i])
context.h[i] = UInt8.withValue(u)
u = u >> 8
}
return true
}
private func squeeze(context:Context, hr:[UInt32]) -> Bool {
if (context.h.count != 17 && hr.count != 17) {
return false
}
var u:UInt32 = 0
for i in 0..<16 {
u += hr[i];
context.h[i] = UInt8.withValue(u) // crash! h[i] = UInt8(u) & 0xff
u >>= 8;
}
u += hr[16]
context.h[16] = UInt8.withValue(u) & 0x03
u >>= 2
u += (u << 2); /* u *= 5; */
for i in 0..<16 {
u += UInt32(context.h[i])
context.h[i] = UInt8.withValue(u) // crash! h[i] = UInt8(u) & 0xff
u >>= 8
}
context.h[16] += UInt8.withValue(u);
return true
}
private func freeze(context:Context) -> Bool {
assert(context.h.count == 17,"Invalid length")
if (context.h.count != 17) {
return false
}
let minusp:[UInt8] = [0x05,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xfc]
var horig:[UInt8] = [UInt8](count: 17, repeatedValue: 0)
/* compute h + -p */
for i in 0..<17 {
horig[i] = context.h[i]
}
add(context, c: minusp)
/* select h if h < p, or h + -p if h >= p */
let bits:[Bit] = (context.h[16] >> 7).bits()
let invertedBits = bits.map({ (bit) -> Bit in
return bit.inverted()
})
let negative = UInt8(bits: invertedBits)
for i in 0..<17 {
context.h[i] ^= negative & (horig[i] ^ context.h[i]);
}
return true;
}
private func blocks(context:Context, m:[UInt8], startPos:Int = 0) -> Int {
var bytes = m.count
let hibit = context.final ^ 1 // 1 <<128
var mPos = startPos
while (bytes >= Int(blockSize)) {
var hr:[UInt32] = [UInt32](count: 17, repeatedValue: 0)
var u:UInt32 = 0
var c:[UInt8] = [UInt8](count: 17, repeatedValue: 0)
/* h += m */
for i in 0..<16 {
c[i] = m[mPos + i]
}
c[16] = hibit
add(context, c: c)
/* h *= r */
for i in 0..<17 {
u = 0
for j in 0...i {
u = u + UInt32(UInt16(context.h[j])) * UInt32(context.r[i - j]) // u += (unsigned short)st->h[j] * st->r[i - j];
}
for j in (i+1)..<17 {
var v:UInt32 = UInt32(UInt16(context.h[j])) * UInt32(context.r[i + 17 - j]) // unsigned long v = (unsigned short)st->h[j] * st->r[i + 17 - j];
v = ((v << 8) &+ (v << 6))
u = u &+ v
}
hr[i] = u
}
squeeze(context, hr: hr)
mPos += blockSize
bytes -= blockSize
}
return mPos
}
}
|
mit
|
ac00ca755ff857fdb314ac3d0252e16b
| 27.570492 | 163 | 0.427178 | 3.836636 | false | false | false | false |
mownier/pyrobase
|
Pyrobase/PyroAuth.swift
|
1
|
5990
|
//
// PyroAuth.swift
// Pyrobase
//
// Created by Mounir Ybanez on 05/06/2017.
// Copyright © 2017 Ner. All rights reserved.
//
public class PyroAuth {
internal var key: String
internal var request: RequestProtocol
internal var signInPath: String
internal var registerPath: String
internal var refreshPath: String
internal var confirmationCodePath: String
public class func create(key: String, bundleIdentifier: String = "com.ner.Pyrobase", plistName: String = "PyroAuthInfo", request: RequestProtocol = Request.create() ) -> PyroAuth? {
guard let bundle = Bundle(identifier: bundleIdentifier) else {
return nil
}
guard let reader = PlistReader.create(name: plistName, bundle: bundle) else {
return nil
}
var registerPath: String = ""
var signInPath: String = ""
var refreshPath: String = ""
var confirmationCodePath: String = ""
if let readerInfo = reader.data as? [AnyHashable: Any] {
registerPath = (readerInfo["register_path"] as? String) ?? ""
signInPath = (readerInfo["sign_in_path"] as? String) ?? ""
refreshPath = (readerInfo["refresh_path"] as? String) ?? ""
confirmationCodePath = (readerInfo["confirmation_code_path"] as? String) ?? ""
}
let auth = PyroAuth(key: key, request: request, signInPath: signInPath, registerPath: registerPath, refreshPath: refreshPath, confirmationCodePath: confirmationCodePath)
return auth
}
public init(key: String, request: RequestProtocol, signInPath: String, registerPath: String, refreshPath: String, confirmationCodePath: String) {
self.key = key
self.request = request
self.signInPath = signInPath
self.registerPath = registerPath
self.refreshPath = refreshPath
self.confirmationCodePath = confirmationCodePath
}
public func register(email: String, password: String, completion: @escaping (PyroAuthResult<PyroAuthContent>) -> Void) {
let data: [AnyHashable: Any] = ["email": email, "password": password, "returnSecureToken": true]
let path = "\(registerPath)?key=\(key)"
request.write(path: path, method: .post, data: data) { result in
self.handleRequestResult(result, completion: completion)
}
}
public func signIn(email: String, password: String, completion: @escaping (PyroAuthResult<PyroAuthContent>) -> Void) {
let data: [AnyHashable: Any] = ["email": email, "password": password, "returnSecureToken": true]
let path = "\(signInPath)?key=\(key)"
request.write(path: path, method: .post, data: data) { result in
self.handleRequestResult(result, completion: completion)
}
}
public func refresh(token: String, completion: @escaping (PyroAuthResult<PyroAuthTokenContent>) -> Void) {
let data: [AnyHashable: Any] = ["grant_type": "refresh_token", "refresh_token": token]
let path = "\(refreshPath)?key=\(key)"
request.write(path: path, method: .post, data: data) { result in
switch result {
case .succeeded(let info):
guard let resultInfo = info as? [AnyHashable: Any] else {
completion(.failed(PyroAuthError.unexpectedContent))
return
}
guard let accessToken = resultInfo["access_token"] as? String,
let refreshToken = resultInfo["refresh_token"] as? String,
let expiration = resultInfo["expires_in"] as? String else {
return completion(.failed(PyroAuthError.incompleteContent))
}
var content = PyroAuthTokenContent()
content.accessToken = accessToken
content.refreshToken = refreshToken
content.expiration = expiration
completion(.succeeded(content))
case .failed(let info):
completion(.failed(info))
}
}
}
public func sendPasswordReset(email: String, completion: @escaping (PyroAuthResult<Bool>) -> Void) {
let data: [AnyHashable: Any] = ["requestType": "PASSWORD_RESET", "email": email]
let path = "\(confirmationCodePath)?key=\(key)"
request.write(path: path, method: .post, data: data) { result in
switch result {
case .succeeded:
completion(.succeeded(true))
case .failed(let info):
completion(.failed(info))
}
}
}
internal func handleRequestResult(_ result: RequestResult, completion: @escaping (PyroAuthResult<PyroAuthContent>) -> Void) {
switch result {
case .succeeded(let info):
guard let resultInfo = info as? [AnyHashable: Any] else {
completion(.failed(PyroAuthError.unexpectedContent))
return
}
guard let userId = resultInfo["localId"] as? String,
let email = resultInfo["email"] as? String,
let accessToken = resultInfo["idToken"] as? String,
let refreshToken = resultInfo["refreshToken"] as? String,
let expiration = resultInfo["expiresIn"] as? String else {
return completion(.failed(PyroAuthError.incompleteContent))
}
var content = PyroAuthContent()
content.userId = userId
content.email = email
content.accessToken = accessToken
content.refreshToken = refreshToken
content.expiration = expiration
completion(.succeeded(content))
case .failed(let info):
completion(.failed(info))
}
}
}
|
mit
|
a3d17b46a0672084b6c4c0b636ead3ee
| 41.475177 | 185 | 0.588078 | 4.798878 | false | false | false | false |
LoganHollins/SuperStudent
|
SuperStudent/AddAnswerViewController.swift
|
1
|
1623
|
//
// AddAnswerViewController.swift
// SuperStudent
//
// Created by Logan Hollins on 2015-11-28.
// Copyright © 2015 Logan Hollins. All rights reserved.
//
import UIKit
import Alamofire
class AddAnswerViewController: UIViewController {
@IBOutlet weak var questionLabel: UILabel!
@IBOutlet weak var answerField: UITextView!
var question = Question()
override func viewDidLoad() {
super.viewDidLoad()
questionLabel.text = "\(question.title)"
self.answerField.layer.borderWidth = 1
self.answerField.layer.borderColor = UIColor(red: 0.9, green: 0.9, blue: 0.9, alpha: 1.0).CGColor
self.answerField.layer.cornerRadius = 5
}
@IBAction func handleReply(sender: AnyObject) {
let dFormatter = NSDateFormatter()
dFormatter.dateFormat = "yyyy-MM-dd"
let tFormatter = NSDateFormatter()
tFormatter.dateFormat = "hh:mm a"
let currentDate = NSDate()
let parameters : [String : AnyObject] = [
"answer": answerField.text!,
"questionId": question.id,
"date": dFormatter.stringFromDate(currentDate),
"time": tFormatter.stringFromDate(currentDate),
"postedBy": StudentInfo.StudentId,
"upvotes": "0"
]
Alamofire.request(.POST, "https://api.mongolab.com/api/1/databases/rhythmictracks/collections/Answers?apiKey=L4HrujTTG-XOamCKvRJp5RwYMpoJ6xCZ", parameters: parameters, encoding: .JSON)
navigationController?.popViewControllerAnimated(true)
}
}
|
gpl-2.0
|
b6cb7488cf3bf663ddf2ed64e6f54fd4
| 28.509091 | 193 | 0.634402 | 4.268421 | false | false | false | false |
zjjzmw1/robot
|
robot/robot/CodeFragment/Swift下拉上提刷新/RHRefreshHeader.swift
|
1
|
5077
|
//
// RHRefreshHeader.swift
// RHRefresh
//
// Created by xieruihua on 17/4/12.
// Copyright © 2017年 xieruihua. All rights reserved.
//
import UIKit
class RHRefreshHeader: NSObject {
// 已经把这写文字隐藏了 - 新需求不需要展示文字,只是一个箭头就OK了
var refreshLoadingTitle = "刷新数据中..."
var refreshPulldownTitle = "下拉可以刷新"
var refreshReleaseTitle = "松开可以刷新"
var refreshHandler:((Void)->(Void))!
private var scrollView:UIScrollView!
private var headerView:UIView!
private var headerTitle:UILabel!
private var headerImage:UIImageView!
private var loadingView:UIActivityIndicatorView!
private let headerHeight = 35
private var isRefreshing = false
init(refreshScrollView:UIScrollView) {
super.init()
scrollView = refreshScrollView
headerInit()
}
private func headerInit() {
let scrollWidth = scrollView.frame.size.width
let labelWidth = 120
let labelHeight = headerHeight
let imageWidth = 15
let imageHeight = headerHeight
headerView = UIView(frame: CGRect(x: 0, y: -headerHeight, width: Int(scrollWidth), height: headerHeight))
scrollView.addSubview(headerView)
headerTitle = UILabel(frame: CGRect(x: (Int(scrollWidth) - labelWidth) / 2, y: 0, width: labelWidth, height: labelHeight))
headerTitle.isHidden = true // 暂时隐藏 - 新需求不需要刷新的控件
headerTitle.textAlignment = .center
headerTitle.font = UIFont.systemFont(ofSize: 14)
headerTitle.text = refreshPulldownTitle
headerView.addSubview(headerTitle)
headerImage = UIImageView(frame: CGRect(x: (Int(scrollWidth) - labelWidth) / 2 - imageWidth, y: 0, width: imageWidth, height: imageHeight))
headerImage.image = UIImage(named: "arrow")
headerImage.isHidden = false
headerView.addSubview(headerImage)
headerImage.centerX = headerView.centerX;
loadingView = UIActivityIndicatorView(activityIndicatorStyle: .gray)
loadingView.frame = CGRect(x: (Int(scrollWidth) - labelWidth) / 2 - imageWidth, y: 0, width: imageWidth, height: imageHeight)
loadingView.isHidden = true
headerView.addSubview(loadingView)
loadingView.centerX = headerView.centerX
scrollView.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if "contentOffset" != keyPath {
return
}
if scrollView.isDragging && !isRefreshing{
let currentPostionY = scrollView.contentOffset.y
UIView.animate(withDuration: 0.3, animations: {
if currentPostionY < -CGFloat(self.headerHeight*3/2) {
self.headerTitle.text = self.refreshReleaseTitle
self.headerImage.transform = CGAffineTransform(rotationAngle: .pi)
}
else {
self.headerTitle.text = self.refreshPulldownTitle
self.headerImage.transform = CGAffineTransform(rotationAngle: .pi*2)
}
})
}
else {
if headerTitle.text == refreshReleaseTitle {
self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
beginRefresh()
}
}
}
func beginRefresh() {
if !isRefreshing {
isRefreshing = true
headerTitle.text = refreshLoadingTitle
headerImage.isHidden = true
loadingView.isHidden = false
loadingView.startAnimating()
UIView.animate(withDuration: 0.3, animations: {
let offsetY = self.scrollView.contentOffset.y
if offsetY > -CGFloat(self.headerHeight*3/2) {
self.scrollView.contentOffset = CGPoint(x: 0, y: offsetY - CGFloat(self.headerHeight*3/2))
}
self.scrollView.contentInset = UIEdgeInsetsMake(CGFloat(self.headerHeight*3/2), 0, 0, 0)
})
refreshHandler()
}
}
func endRefresh() {
isRefreshing = false
self.headerTitle.text = self.refreshPulldownTitle
self.headerImage.isHidden = false
self.loadingView.stopAnimating()
self.loadingView.isHidden = true
UIView.animate(withDuration: 0.3) {
self.scrollView.contentOffset = CGPoint(x: 0, y: self.scrollView.contentOffset.y + CGFloat(self.headerHeight*3/2))
self.scrollView.contentInset = UIEdgeInsetsMake(0, 0, 0, 0)
self.headerImage.transform = CGAffineTransform(rotationAngle: .pi*2)
}
}
deinit {
scrollView.removeObserver(self, forKeyPath: "contentOffset")
}
}
|
mit
|
fe03446170e1b4cd2312b1720115c274
| 36.801527 | 151 | 0.61773 | 4.927363 | false | false | false | false |
gdelarosa/Safe-Reach
|
Safe Reach/SpiritualVC.swift
|
1
|
4781
|
//
// SpiritualVC.swift
// Safe Reach
//
// Created by Gina De La Rosa on 12/11/16.
// Copyright © 2016 Gina De La Rosa. All rights reserved.
//
import UIKit
class SpiritualVC: UITableViewController {
let imageList = ["allsaints",
"ashram",
"beth",
"chapelofpeace",
"firstcong",
"mthollywood",
"muslimsfor",
"redlandsunited",
"sanb",
"stjames",
"unitarian",
"unity"]
let titleList = ["All Saints Episcopal Church",
"Ashram West",
"Beth Chayim Chadashim",
"Chapel of Peace Christian Church",
"First Congregational Church of Riverside",
"Mt. Hollywood Congregational Church",
"Muslims for Progressive Values",
"Redlands United Church of Christ",
"San Bernardino United Church of Christ",
"St. James Episcopal Church",
"Unitarian Universalist Church of Riverside",
"Unity Fellowship of Christ Church Riverside"]
let descriptionList =
[" A lively, inclusive, and welcoming faith community that celebrates the presense of God in all of life's challenges.",
"Gay centered Spiritual instruction and groups based on traditional Hindu Tantra.",
"An inclusive community of progressive lesbian, gay, bisexual, transgender and heterosexual Jews, our families and friends.",
"An open and affirming body of Christ. LGBTQA family. Located in the annex of Bethel Congregational UCC.",
"We believe we have a lot to offer including meaningful worship, excellent programs, and a wonderful community of people who will walk with you in your journey of faith.",
"An Open and Affirming congregation.",
"GLBT inclusive Muslim voice.",
"An inclusive community in Redlands.",
"An inclusive church in San Bernardino.",
"An inclusive church in Los Angeles.",
"An inclusive church in Riverside.",
"An inclusive church in Riverside."]
override func viewDidLoad() {
super.viewDidLoad()
let imageView = UIImageView(image: UIImage(named: "Triangle"))
imageView.contentMode = UIViewContentMode.scaleAspectFit
let titleView = UIView(frame: CGRect(x: 0, y: 0, width: 50, height: 30))
imageView.frame = titleView.bounds
titleView.addSubview(imageView)
self.navigationItem.titleView = titleView
}
// MARK: - Tableview
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return titleList.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: TableViewCell = tableView.dequeueReusableCell(withIdentifier: "Spiritual") as! TableViewCell
cell.spiritTitle.text = titleList[(indexPath as NSIndexPath).row]
cell.spiritDescription.text = descriptionList[(indexPath as NSIndexPath).row]
let imageName = UIImage(named: imageList[(indexPath as NSIndexPath).row])
cell.spiritImage.image = imageName
return cell
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// store information into string before push to detail view
if (segue.identifier == "SpiritualDetail")
{
// reference detailVC in this vc
let dvc = segue.destination as! SpiritualDetailVC
if let indexPath = self.tableView.indexPathForSelectedRow
{
// convert to string to place in our sent data
let title = titleList[(indexPath as NSIndexPath).row] as String
// now we reference objects in the dvc
dvc.sentTitleData = title
// convert to string to place in our sent data
let description = descriptionList[(indexPath as NSIndexPath).row] as String
// now we reference objects in the dvc
dvc.sentDescriptionData = description
// convert to string to place in our sent data
let imageView = imageList[(indexPath as NSIndexPath).row] as String
// now we reference objects in the dvc
dvc.sentImageData = imageView
}
}
}
}
|
mit
|
0f221050ea5b3396ac53bc379923c6e9
| 42.454545 | 180 | 0.591632 | 4.984359 | false | false | false | false |
SwiftAndroid/swift
|
test/IRGen/generic_types.swift
|
5
|
6046
|
// RUN: %target-swift-frontend %s -emit-ir | FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-runtime
// REQUIRES: CPU=x86_64
import Swift
// CHECK: [[A:%C13generic_types1A]] = type <{ [[REF:%swift.refcounted]], [[INT:%Si]] }>
// CHECK: [[INT]] = type <{ i64 }>
// CHECK: [[B:%C13generic_types1B]] = type <{ [[REF:%swift.refcounted]], [[UNSAFE:%Sp]] }>
// CHECK: [[C:%C13generic_types1C]] = type
// CHECK: [[D:%C13generic_types1D]] = type
// CHECK-LABEL: @_TMPC13generic_types1A = hidden global
// CHECK: %swift.type* (%swift.type_pattern*, i8**)* @create_generic_metadata_A,
// CHECK-native-SAME: i32 160,
// CHECK-objc-SAME: i32 344,
// CHECK-SAME: i16 1,
// CHECK-SAME: i16 16,
// CHECK-SAME: [{{[0-9]+}} x i8*] zeroinitializer,
// CHECK-SAME: void ([[A]]*)* @_TFC13generic_types1AD,
// CHECK-SAME: i8** @_TWVBo,
// CHECK-SAME: i64 0,
// CHECK-SAME: %swift.type* null,
// CHECK-native-SAME: %swift.opaque* null,
// CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 1,
// CHECK-SAME: i32 3,
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 24,
// CHECK-SAME: i16 7,
// CHECK-SAME: i16 0,
// CHECK-SAME: i32 152,
// CHECK-SAME: i32 16,
// CHECK-SAME: %swift.type* null,
// CHECK-SAME: void (%swift.opaque*, [[A]]*)* @_TFC13generic_types1A3run
// CHECK-SAME: %C13generic_types1A* (i64, %C13generic_types1A*)* @_TFC13generic_types1AcfT1ySi_GS0_x_
// CHECK-SAME: }
// CHECK-LABEL: @_TMPC13generic_types1B = hidden global
// CHECK-SAME: %swift.type* (%swift.type_pattern*, i8**)* @create_generic_metadata_B,
// CHECK-native-SAME: i32 152,
// CHECK-objc-SAME: i32 336,
// CHECK-SAME: i16 1,
// CHECK-SAME: i16 16,
// CHECK-SAME: [{{[0-9]+}} x i8*] zeroinitializer,
// CHECK-SAME: void ([[B]]*)* @_TFC13generic_types1BD,
// CHECK-SAME: i8** @_TWVBo,
// CHECK-SAME: i64 0,
// CHECK-SAME: %swift.type* null,
// CHECK-native-SAME: %swift.opaque* null,
// CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 1,
// CHECK-SAME: i32 3,
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 24,
// CHECK-SAME: i16 7,
// CHECK-SAME: i16 0,
// CHECK-SAME: i32 144,
// CHECK-SAME: i32 16,
// CHECK-SAME: %swift.type* null
// CHECK-SAME: }
// CHECK-LABEL: @_TMPC13generic_types1C = hidden global
// CHECK-SAME: void ([[C]]*)* @_TFC13generic_types1CD,
// CHECK-SAME: i8** @_TWVBo,
// CHECK-SAME: i64 0,
// CHECK-SAME: %swift.type* null,
// CHECK-native-SAME: %swift.opaque* null,
// CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 1,
// CHECK-SAME: void (%swift.opaque*, [[A]]*)* @_TFC13generic_types1A3run
// CHECK-SAME: }
// CHECK-LABEL: @_TMPC13generic_types1D = hidden global
// CHECK-SAME: void ([[D]]*)* @_TFC13generic_types1DD,
// CHECK-SAME: i8** @_TWVBo,
// CHECK-SAME: i64 0,
// CHECK-SAME: %swift.type* null,
// CHECK-native-SAME: %swift.opaque* null,
// CHECK-objc-SAME: %swift.opaque* @_objc_empty_cache,
// CHECK-SAME: %swift.opaque* null,
// CHECK-SAME: i64 1,
// CHECK-SAME: void (%Si*, [[D]]*)* @_TTVFC13generic_types1D3runfSiT_
// CHECK-SAME: }
// CHECK-LABEL: define{{( protected)?}} private %swift.type* @create_generic_metadata_A(%swift.type_pattern*, i8**) {{.*}} {
// CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type**
// CHECK: %T = load %swift.type*, %swift.type** [[T0]],
// CHECK-native: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* null)
// CHECK-objc: [[T0:%.*]] = load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_SwiftObject"
// CHECK-objc: [[SUPER:%.*]] = call %objc_class* @rt_swift_getInitializedObjCClass(%objc_class* [[T0]])
// CHECK-objc: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* [[SUPER]])
// CHECK: [[SELF_ARRAY:%.*]] = bitcast %swift.type* [[METADATA]] to i8**
// CHECK: [[T1:%.*]] = getelementptr inbounds i8*, i8** [[SELF_ARRAY]], i32 10
// CHECK: [[T0:%.*]] = bitcast %swift.type* %T to i8*
// CHECK: store i8* [[T0]], i8** [[T1]], align 8
// CHECK: ret %swift.type* [[METADATA]]
// CHECK: }
// CHECK-LABEL: define{{( protected)?}} private %swift.type* @create_generic_metadata_B(%swift.type_pattern*, i8**) {{.*}} {
// CHECK: [[T0:%.*]] = bitcast i8** %1 to %swift.type**
// CHECK: %T = load %swift.type*, %swift.type** [[T0]],
// CHECK-native: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* null)
// CHECK-objc: [[T0:%.*]] = load %objc_class*, %objc_class** @"OBJC_CLASS_REF_$_SwiftObject"
// CHECK-objc: [[SUPER:%.*]] = call %objc_class* @rt_swift_getInitializedObjCClass(%objc_class* [[T0]])
// CHECK-objc: [[METADATA:%.*]] = call %swift.type* @swift_allocateGenericClassMetadata(%swift.type_pattern* %0, i8** %1, %objc_class* [[SUPER]])
// CHECK: [[SELF_ARRAY:%.*]] = bitcast %swift.type* [[METADATA]] to i8**
// CHECK: [[T1:%.*]] = getelementptr inbounds i8*, i8** [[SELF_ARRAY]], i32 10
// CHECK: [[T0:%.*]] = bitcast %swift.type* %T to i8*
// CHECK: store i8* [[T0]], i8** [[T1]], align 8
// CHECK: ret %swift.type* [[METADATA]]
// CHECK: }
class A<T> {
var x = 0
func run(_ t: T) {}
init(y : Int) {}
}
class B<T> {
var ptr : UnsafeMutablePointer<T>
init(ptr: UnsafeMutablePointer<T>) {
self.ptr = ptr
}
deinit {
ptr.deinitialize()
}
}
class C<T> : A<Int> {}
class D<T> : A<Int> {
override func run(_ t: Int) {}
}
struct E<T> {
var x : Int
func foo() { bar() }
func bar() {}
}
class ClassA {}
class ClassB {}
// This type is fixed-size across specializations, but it needs to use
// a different implementation in IR-gen so that types match up.
// It just asserts if we get it wrong.
struct F<T: AnyObject> {
var value: T
}
func testFixed() {
var a = F(value: ClassA()).value
var b = F(value: ClassB()).value
}
|
apache-2.0
|
8735228d622feea4bc6110cfdcad3563
| 38.006452 | 147 | 0.609825 | 2.774667 | false | false | false | false |
AwpSpace/Training-iOS-1
|
TrainingApp1/AppDelegate.swift
|
1
|
6116
|
//
// AppDelegate.swift
// TrainingApp1
//
// Created by Diep Nguyen Hoang on 5/15/16.
// Copyright © 2016 AwpSpace. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "net.awpspace.training.TrainingApp1" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("TrainingApp1", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
|
apache-2.0
|
935f65aa9457685b17abc172b844d85a
| 54.09009 | 291 | 0.72036 | 5.868522 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.