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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pixelmaid/piper | Palette-Knife/State.swift | 2 | 4154 | //
// State.swift
// PaletteKnife
//
// Created by JENNIFER MARY JACOBS on 7/20/16.
// Copyright © 2016 pixelmaid. All rights reserved.
//
import Foundation
class State {
var transitions = [String:StateTransition]()
var constraint_mappings = [String:Constraint]()
let name: String
let id: String
init(id:String,name:String){
self.id = id;
self.name = name;
}
func addConstraintMapping(key:String, reference:Observable<Float>, relativeProperty:Observable<Float>){
let mapping = Constraint(id:key,reference: reference, relativeProperty:relativeProperty)
constraint_mappings[key] = mapping;
}
func removeConstraintMapping(key:String)->Constraint?{
constraint_mappings[key]!.relativeProperty.constrained = false;
return constraint_mappings.removeValueForKey(key)
}
func addStateTransitionMapping(id:String, name:String, reference:Emitter,toState:String)->StateTransition{
let mapping = StateTransition(id:id, name:name, reference:reference,toState:toState)
transitions[id] = mapping;
return mapping;
}
func removeTransitionMapping(key:String)->StateTransition?{
return transitions.removeValueForKey(key)
}
func getConstraintMapping(key:String)->Constraint?{
if let _ = constraint_mappings[key] {
return constraint_mappings[key]
}
else {
return nil
}
}
func getTransitionMapping(key:String)->StateTransition?{
if let _ = transitions[key] {
return transitions[key]
}
else {
return nil
}
}
func hasTransitionKey(key:String)->Bool{
if(transitions[key] != nil){
return true
}
return false
}
func hasConstraintKey(key:String)->Bool{
if(constraint_mappings[key] != nil){
return true
}
return false
}
func toJSON()->String{
var data = "{\"id\":\""+(self.id)+"\","
data += "\"name\":\""+self.name+"\","
data += "\"mappings\":[";
var count = 0;
for (_, mapping) in constraint_mappings{
if(count>0){
data += ","
}
data += mapping.toJSON();
count += 1;
}
data += "]"
data += "}"
return data;
}
}
struct Constraint{
var reference:Observable<Float>
var relativeProperty:Observable<Float>
var id:String
init(id:String, reference:Observable<Float>, relativeProperty:Observable<Float>){
self.reference = reference
self.relativeProperty = relativeProperty
self.id = id;
}
func toJSON()->String{
var data = "{\"id\":\""+(self.id)+"\"}"
return data;
}
}
class Method{
var name: String;
var id: String;
var arguments: [Any]?
init(id:String,name:String,arguments:[Any]?){
self.name = name;
self.id = id;
self.arguments = arguments;
}
func toJSON()->String{
var data = "{\"id\":\""+(self.id)+"\","
data += "\"name\":\""+(self.name)+"\"}"
return data;
}
}
class StateTransition{
var reference:Emitter
var toState: String
var methods = [Method]()
let name: String
let id: String
init(id:String, name:String, reference:Emitter, toState:String){
self.reference = reference
self.toState = toState
self.name = name
self.id = id;
}
func addMethod(id:String, name:String, arguments:[Any]?){
methods.append(Method(id:id, name:name,arguments:arguments));
}
func toJSON()->String{
var data = "{\"id\":\""+(self.id)+"\","
data += "\"name\":\""+self.name+"\","
data += "\"methods\":[";
for i in 0..<methods.count{
if(i>0){
data += ","
}
data += methods[i].toJSON();
}
data += "]"
data += "}"
return data;
}
}
| mit | 5c45df51cd0ad6b9a676e8941f92f163 | 23.145349 | 111 | 0.542018 | 4.494589 | false | false | false | false |
lemberg/connfa-ios | Connfa/Classes/Events/List Base/Cells/ProgramListCollectionCell.swift | 1 | 791 | //
// ProgramListCollectionCell.swift
// Connfa
//
// Created by Volodymyr Hyrka on 11/28/17.
// Copyright © 2017 Lemberg Solution. All rights reserved.
//
import UIKit
class ProgramListCollectionCell: UICollectionViewCell {
static let indentifier = "ProgramListCollectionCell"
@IBOutlet private weak var table: EventsTableView!
var dayList: DayList! {
didSet {
table.delegate = tableController
table.dataSource = tableController
tableController.dayList = dayList
}
}
var tableController: ProgramTableController!
override func awakeFromNib() {
super.awakeFromNib()
tableController = ProgramTableController(tableView: table)
}
override func prepareForReuse() {
table.delegate = nil
table.dataSource = nil
}
}
| apache-2.0 | e5ca3f19a3cb0433eca6797d19296d0d | 22.235294 | 66 | 0.712658 | 4.647059 | false | false | false | false |
Irvel/Actionable-Screenshots | ActionableScreenshots/ActionableScreenshots/Models/Screenshot.swift | 1 | 3671 | //
// Screenshot.swift
// ActionableScreenshots
//
// Created by Jorge Gil Cavazos on 10/22/17.
// Copyright © 2017 Jesus Galvan. All rights reserved.
//
import UIKit
import Photos
import RealmSwift
/**
Store the raw image of a screenshot with it's metadata.
*/
class Screenshot:Object {
@objc dynamic var id: String?
@objc dynamic var text: String?
@objc dynamic var creationDate: Date = Date(timeIntervalSince1970: 0)
@objc dynamic var processed: Bool = false
var tags = List<Tag>()
var hasText: Bool {
get {
return text != nil
}
}
override static func primaryKey() -> String {
return "id"
}
/**
Fetches the UI image associated with this Screenshot instance
- Parameters:
- width: The target width of the image file to fetch
- height: The target height of the image file to fetch
- contentMode: Options for fitting an image’s aspect ratio to a requested size
- fetchOptions: A set of options affecting the delivery of the image
- Returns
- The obtained UIImage
*/
func getImage(width: CGFloat, height: CGFloat, contentMode: PHImageContentMode, fetchOptions: PHImageRequestOptions? = nil) -> UIImage? {
let asset = PHAsset.fetchAssets(withLocalIdentifiers: [id!], options: nil).firstObject
var imageResult: UIImage?
if let targetAsset = asset {
// TODO: Display an activity indicator while the high-res image is being loaded and make the request asynchronously
PHImageManager.default().requestImage(for: targetAsset,
targetSize: CGSize(width: width, height: height),
contentMode: contentMode,
options: fetchOptions) {
(image: UIImage?, info: [AnyHashable: Any]?) -> Void in imageResult = image }
}
return imageResult
}
/**
Associate a new Tag with this Screenshot instance
*/
func addTag(tagString: String) {
var tag = Tag()
tag.id = tagString
tag.type = .userInput
let realm = try! Realm()
try! realm.write {
realm.add(tag, update: true)
}
tag = realm.object(ofType: Tag.self, forPrimaryKey: tag.id)!
try! realm.write {
if !self.tags.contains(tag) {
self.tags.append(tag)
}
}
}
/**
Associate a list of Tags with this Screenshot instance
*/
func addTags(from tagList: [Tag]) {
let realm = try! Realm()
try! realm.write {
for tag in tagList {
realm.add(tag, update: true)
}
}
for tagLabel in tagList {
let tag = realm.object(ofType: Tag.self, forPrimaryKey: tagLabel.id)!
try! realm.write {
if !self.tags.contains(tag) {
self.tags.append(tag)
}
}
}
}
/**
Request the deletion of this image asset from the device
*/
func deleteImageFromDevice() {
let asset = PHAsset.fetchAssets(withLocalIdentifiers: [id!], options: nil).firstObject
if let targetAsset = asset {
let enumeration: NSArray = [targetAsset]
do {
try PHPhotoLibrary.shared().performChangesAndWait {
PHAssetChangeRequest.deleteAssets(enumeration)
}
} catch {
assert(true)
}
}
}
}
| gpl-3.0 | d024376dcca4d67b4c6429f22f71ca61 | 31.460177 | 141 | 0.556161 | 4.950067 | false | false | false | false |
angu/SwiftyStorj | SwiftyStorj/StorjTestApp/ViewModels/ShowImageViewModel.swift | 1 | 975 | //
// ShowImageViewModel.swift
// SwiftyStorj
//
// Created by Andrea Tullis on 14/07/2017.
// Copyright © 2017 angu2111. All rights reserved.
//
import Foundation
import UIKit
import SwiftyStorj
public protocol ShowImagePresenter: class {
func didDownloadImage(image: UIImage)
}
public class ShowImgeViewModel {
let file: String
let bucket: String
let storjWrapper: StorjWrapper
public weak var presenter: ShowImagePresenter?
init(with storjWrapper: StorjWrapper, bucket: String, file: String) {
self.storjWrapper = storjWrapper
self.file = file
self.bucket = bucket
}
public func loadImage() {
storjWrapper.downloadFile(file, fromBucket: bucket) {[weak self] (data, error) in
guard let data = data else { return }
guard let image = UIImage(data: data) else { return }
self?.presenter?.didDownloadImage(image: image)
}
}
}
| lgpl-2.1 | a4039404ea4f2cd05bc2e4b95e272fe2 | 25.324324 | 89 | 0.650924 | 4.144681 | false | false | false | false |
zerdzhong/LeetCode | swift/LeetCode.playground/Pages/25_Reverse_Nodes_in_k-Group.xcplaygroundpage/Contents.swift | 1 | 2981 | //: [Previous](@previous)
//https://leetcode.com/problems/reverse-nodes-in-k-group/
import Foundation
/**
* Definition for singly-linked list.
*/
public class ListNode {
public var val: Int
public var next: ListNode?
public init(_ val: Int) {
self.val = val
self.next = nil
}
public func message() -> String{
var msg = "\(self.val)"
var nextNode = self
while nextNode.next != nil {
nextNode = nextNode.next!
msg += "->\(nextNode.val)"
}
return msg
}
}
class Solution {
func length(list :ListNode?) -> Int {
var cur = list
var length = 0
while cur != nil {
length = length + 1
cur = cur?.next
}
return length
}
func nodeAt(list: ListNode?, index: Int) -> ListNode? {
var count = 0
var head = list
while count < index {
head = head?.next
count += 1
}
return head
}
func reverseList(list head: ListNode?, length length: Int) -> (ListNode?, ListNode?) {
var reverseCount = 0;
var currentNode = head
var nextNode = currentNode?.next
while nextNode != nil && reverseCount < length - 1 {
let thirdNode = nextNode?.next
nextNode?.next = currentNode
currentNode = nextNode
nextNode = thirdNode
reverseCount += 1
}
head?.next = nil
return (currentNode, head)
}
func reverseKGroup(_ head: ListNode?, _ k: Int) -> ListNode? {
guard length(list: head) >= k else {
return head
}
var res = head
var pre_tail = head
var cur_group = head
var next_group = nodeAt(list: cur_group, index: k)
if length(list: cur_group) >= k {
let (group_head, group_tail) = reverseList(list: head, length: k)
group_tail?.next = next_group
pre_tail = group_tail
res = group_head
}
cur_group = next_group
while cur_group != nil {
next_group = nodeAt(list: cur_group, index: k)
if length(list: cur_group) >= k {
let (group_head, group_tail) = reverseList(list: cur_group, length: k)
group_tail?.next = next_group
pre_tail?.next = group_head
pre_tail = group_tail
}
cur_group = next_group
}
return res
}
}
var list1 = ListNode(1)
list1.next = ListNode(2)
//list1.next?.next = ListNode(3)
//list1.next?.next?.next = ListNode(4)
//list1.next?.next?.next?.next = ListNode(5)
list1.message()
//Solution().reverseList(list: list1, length: 2).0?.message()
Solution().reverseKGroup(list1, 2)?.message()
//: [Next](@next)
| mit | d8178a9ecd2a9e5a63e594035829a69e | 23.841667 | 90 | 0.503522 | 4.204513 | false | false | false | false |
Donkey-Tao/SinaWeibo | SinaWeibo/SinaWeibo/Classes/Home/TFHomeViewCell.swift | 1 | 4485 | //
// TFHomeViewCell.swift
// SinaWeibo
//
// Created by Donkey-Tao on 2016/10/3.
// Copyright © 2016年 http://taofei.me All rights reserved.
//
import UIKit
import SDWebImage
let edgeMargin : CGFloat = 15
let imageItemMargin : CGFloat = 10
class TFHomeViewCell: UITableViewCell {
//MARK:- 控件属性
@IBOutlet weak var avartaImageView: UIImageView!
@IBOutlet weak var vertifierImageView: UIImageView!
@IBOutlet weak var nickNameLabel: UILabel!
@IBOutlet weak var mumbershipImageView: UIImageView!
@IBOutlet weak var createTimeLabel: UILabel!
@IBOutlet weak var sourceLabel: UILabel!
@IBOutlet weak var contentLabel: UILabel!
@IBOutlet weak var picView: TFPicCollectionView!
//MARK:- 控件约束
@IBOutlet weak var picViewWconstant: NSLayoutConstraint!
@IBOutlet weak var picViewHconstant: NSLayoutConstraint!
//MARK:- 自定义属性
var viewModel : TFStatusViewModel?{
didSet{
//1.nil值校验
guard let viewModel = viewModel else {
return
}
//2.设置头像
avartaImageView.sd_setImage(with: viewModel.profileURL, placeholderImage: UIImage(named : "avatar_default_small"))
//3.设置认证图标
vertifierImageView.image = viewModel.verifiedImage
//4.设置昵称
nickNameLabel.text = viewModel.status?.user?.screen_name
//5.设置会员图标
mumbershipImageView.image = viewModel.vipImage
//6.设置时间
createTimeLabel.text = viewModel.created_at_text
//7.设置来源
sourceLabel.text = viewModel.source_text
//8.设置内容
contentLabel.text = viewModel.status?.text
//9.设置昵称的文字颜色
nickNameLabel.textColor = viewModel.vipImage == nil ? UIColor.black : UIColor.orange
//10.计算picView的宽度和高度约束
let picViewSize = calculatePicViewSize(count: viewModel.picURLs.count)
picViewWconstant.constant = picViewSize.width
picViewHconstant.constant = picViewSize.height
//11.将配图地址传过去
picView.picURLs = viewModel.picURLs
}
}
//MARK:- 约束的属性
@IBOutlet weak var textLabelConstant: NSLayoutConstraint!
//MARK:- 系统回调函数
override func awakeFromNib() {
super.awakeFromNib()
//设置微博正文的宽度约束
textLabelConstant.constant = UIScreen.main.bounds.width - edgeMargin * 2
//1.取出picView对应的layout并将其转为流水布局
let layout = picView.collectionViewLayout as! UICollectionViewFlowLayout
let imageViewWH = (UIScreen.main.bounds.width - 2 * edgeMargin - 2 * imageItemMargin) / 3
layout.itemSize = CGSize(width: imageViewWH, height: imageViewWH)
}
}
//MARK:- 计算方法
extension TFHomeViewCell{
///计算picView的宽度和高度
func calculatePicViewSize(count : Int) -> CGSize{
let layout = picView.collectionViewLayout as! UICollectionViewFlowLayout
//1.没有配图
if count == 0 {
return CGSize.zero
}
//单张配图
if count == 1 {
//取出图片
let image = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: viewModel?.picURLs.first?.absoluteString)
layout.itemSize = CGSize(width: (image?.size.width)!*2, height: (image?.size.height)!*2)
return CGSize(width: (image?.size.width)!*2, height: (image?.size.height)!*2)
}
//2.计算出imageViewWH
let imageViewWH = (UIScreen.main.bounds.width - 2 * edgeMargin - 2 * imageItemMargin) / 3
layout.itemSize = CGSize(width: imageViewWH, height: imageViewWH)
//3.四张配图的情况
if count == 4 {
let picViewW = imageViewWH * 2 + imageItemMargin
return CGSize(width: picViewW, height: picViewW)
}
//4.其他张配图
//4.1先计算行数
let rows = CGFloat((count - 1) / 3 + 1)
//4.2计算picView的高度
let picViewH = rows * imageViewWH + (rows - 1) * imageItemMargin
let picViewW = UIScreen.main.bounds.width - 2 * edgeMargin
return CGSize(width: picViewW, height: picViewH)
}
}
| mit | 46bf8b51dcc3899bfca4f8e0ac184c60 | 32.564516 | 130 | 0.618693 | 4.645089 | false | false | false | false |
IngmarStein/swift | test/decl/ext/generic.swift | 2 | 3626 | // RUN: %target-parse-verify-swift
protocol P1 { associatedtype AssocType }
protocol P2 : P1 { }
protocol P3 { }
struct X<T : P1, U : P2, V> {
struct Inner<A, B : P3> { } // expected-error{{generic type 'Inner' cannot be nested in type 'X'}}
struct NonGenericInner { } // expected-error{{nested in generic type}}
}
extension Int : P1 {
typealias AssocType = Int
}
extension Double : P2 {
typealias AssocType = Double
}
extension X<Int, Double, String> { } // expected-error{{constrained extension must be declared on the unspecialized generic type 'X' with constraints specified by a 'where' clause}}
// Lvalue check when the archetypes are not the same.
struct LValueCheck<T> {
let x = 0
}
extension LValueCheck {
init(newY: Int) {
x = 42
}
}
// Member type references into another extension.
struct MemberTypeCheckA<T> { }
protocol MemberTypeProto {
associatedtype AssocType
func foo(_ a: AssocType)
init(_ assoc: MemberTypeCheckA<AssocType>)
}
struct MemberTypeCheckB<T> : MemberTypeProto {
func foo(_ a: T) {}
typealias Element = T
var t1: T
}
extension MemberTypeCheckB {
typealias Underlying = MemberTypeCheckA<T>
}
extension MemberTypeCheckB {
init(_ x: Underlying) { }
}
extension MemberTypeCheckB {
var t2: Element { return t1 }
}
// rdar://problem/19795284
extension Array {
var pairs: [(Element, Element)] {
get {
return []
}
}
}
// rdar://problem/21001937
struct GenericOverloads<T, U> {
var t: T
var u: U
init(t: T, u: U) { self.t = t; self.u = u }
func foo() { }
var prop: Int { return 0 }
subscript (i: Int) -> Int { return i }
}
extension GenericOverloads where T : P1, U : P2 {
init(t: T, u: U) { self.t = t; self.u = u }
func foo() { }
var prop: Int { return 1 }
subscript (i: Int) -> Int { return i }
}
extension Array where Element : Hashable {
var worseHashEver: Int {
var result = 0
for elt in self {
result = (result << 1) ^ elt.hashValue
}
return result
}
}
func notHashableArray<T>(_ x: [T]) {
x.worseHashEver // expected-error{{type 'T' does not conform to protocol 'Hashable'}}
}
func hashableArray<T : Hashable>(_ x: [T]) {
// expected-warning @+1 {{unused}}
x.worseHashEver // okay
}
func intArray(_ x: [Int]) {
// expected-warning @+1 {{unused}}
x.worseHashEver
}
class GenericClass<T> { }
extension GenericClass where T : Equatable {
func foo(_ x: T, y: T) -> Bool { return x == y }
}
func genericClassEquatable<T : Equatable>(_ gc: GenericClass<T>, x: T, y: T) {
_ = gc.foo(x, y: y)
}
func genericClassNotEquatable<T>(_ gc: GenericClass<T>, x: T, y: T) {
gc.foo(x, y: y) // expected-error{{type 'T' does not conform to protocol 'Equatable'}}
}
// FIXME: Future direction
extension Array where Element == String { } // expected-error{{same-type requirement makes generic parameter 'Element' non-generic}}
extension GenericClass : P3 where T : P3 { } // expected-error{{extension of type 'GenericClass' with constraints cannot have an inheritance clause}}
extension GenericClass where Self : P3 { }
// expected-error@-1{{'Self' is only available in a protocol or as the result of a method in a class; did you mean 'GenericClass'?}} {{30-34=GenericClass}}
// expected-error@-2{{type 'GenericClass' in conformance requirement does not refer to a generic parameter or associated type}}
protocol P4 {
associatedtype T
init(_: T)
}
protocol P5 { }
struct S4<Q>: P4 {
init(_: Q) { }
}
extension S4 where T : P5 {} // expected-FIXME-error{{type 'T' in conformance requirement does not refer to a generic parameter or associated type}}
| apache-2.0 | 94df817b70ff311d3af81dc52a4924ef | 22.393548 | 181 | 0.663265 | 3.395131 | false | false | false | false |
HTWDD/HTWDresden-iOS | HTWDD/Components/RoomOccupancy/Main/RoomOccupancyDetailViewController.swift | 1 | 2470 | //
// RoomOccupancyDetailViewController.swift
// HTWDD
//
// Created by Mustafa Karademir on 29.07.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import UIKit
import RxSwift
import RealmSwift
class RoomOccupancyDetailViewController: UITableViewController {
// MARK: - Properties
var context: HasRoomOccupancy!
var roomName: String!
var viewModel: RoomOccupancyDetailViewModel!
private var items: [Occupancies] = [] {
didSet {
tableView.reloadData()
}
}
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
setup()
viewModel
.load(id: roomName.uid)
.subscribe(onNext: { [weak self] items in
guard let self = self else { return }
self.items = items
})
.disposed(by: rx_disposeBag)
}
override func viewDidAppear(_ animated: Bool) {
tableView.apply {
$0.estimatedRowHeight = 230
$0.rowHeight = UITableView.automaticDimension
}
}
}
// MARK: - Setup
extension RoomOccupancyDetailViewController {
private func setup() {
title = roomName.uppercased()
tableView.apply {
$0.separatorStyle = .none
$0.backgroundColor = UIColor.htw.veryLightGrey
$0.register(RoomOccupanciesHeaderViewCell.self)
$0.register(RoomOccupanciesViewCell.self)
}
}
}
// MARK: - TableView DataSource
extension RoomOccupancyDetailViewController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cell.backgroundColor = .clear
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch items[indexPath.row] {
case .header(let model):
let cell = tableView.dequeueReusableCell(RoomOccupanciesHeaderViewCell.self, for: indexPath)!
cell.setup(with: model)
return cell
case .occupancy(let model):
let cell = tableView.dequeueReusableCell(RoomOccupanciesViewCell.self, for: indexPath)!
cell.setup(with: model)
return cell
}
}
}
| gpl-2.0 | 640532b6d28abb82c6c5e49ab455b7c0 | 27.709302 | 121 | 0.617659 | 4.997976 | false | false | false | false |
zhxnlai/ZLSwipeableViewSwift | ZLSwipeableViewSwiftDemo/ZLSwipeableViewSwiftDemo/ShouldSwipeDemoViewController.swift | 1 | 985 | //
// ShouldSwipeDemoViewController.swift
// ZLSwipeableViewSwiftDemo
//
// Created by Zhixuan Lai on 6/17/15.
// Copyright © 2015 Zhixuan Lai. All rights reserved.
//
import UIKit
class ShouldSwipeDemoViewController: ZLSwipeableViewController {
var shouldSwipe = true
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Should Swipe 👍"
Timer.scheduledTimer(timeInterval: 3, target: self, selector: #selector(handleTimer), userInfo: nil, repeats: true)
let defaultHandler = swipeableView.shouldSwipeView
swipeableView.shouldSwipeView = {(view: UIView, movement: Movement, swipeableView: ZLSwipeableView) in
self.shouldSwipe && defaultHandler(view, movement, swipeableView)
}
}
// MARK: - Actions
@objc func handleTimer() {
self.shouldSwipe = !self.shouldSwipe
self.title = "Should Swipe " + (self.shouldSwipe ? "👍" : "👎")
}
}
| mit | 76517032bcf88d4cf95ad056a900afec | 27.676471 | 123 | 0.65641 | 4.642857 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet | SwiftGL-Demo/Source/iOS/ReferenceImageViewController.swift | 1 | 2185 | //
// ReferenceImageViewController.swift
// SwiftGL
//
// Created by jerry on 2015/7/14.
// Copyright (c) 2015年 Jerry Chan. All rights reserved.
//
import UIKit
import SpriteKit
class ReferenceImageViewController: UIViewController {
//@IBOutlet
var imageView: SKView!
var scene:ReferenceImageScene!
override func viewDidAppear(_ animated: Bool) {
if imageView != nil
{
imageView.removeFromSuperview()
}
imageView = SKView(frame: CGRect(x: 0, y: 0, width: 1024, height: 724))
view.addSubview(imageView)
scene = ReferenceImageScene(size: view.bounds.size)
let skView = imageView as SKView
//skView.showsFPS = true
//skView.showsNodeCount = true
skView.presentScene(scene)
}
@IBAction func toolModeSegControlValueChanged(_ sender: UISegmentedControl) {
scene.rectToolMode = ReferenceImageScene.RectToolMode(rawValue: sender.selectedSegmentIndex)!
}
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func toggleButtonTouched(_ sender: UIBarButtonItem) {
saveRefImage()
}
@IBAction func doneButtonTouched(_ sender: UIBarButtonItem) {
saveRect()
performSegue(withIdentifier: "showPaintView", sender: self)
}
func saveRect()
{
RefImgManager.instance.rectImg = getImage()
}
func saveRefImage()
{
RefImgManager.instance.refImg = getImage()
scene.removeRefImg()
}
func getImage()->UIImage!
{
//UIGraphicsBeginImageContext(imageView.bounds.size)
UIGraphicsBeginImageContextWithOptions(imageView.bounds.size, false, UIScreen.main.scale)
if imageView.drawHierarchy(in: imageView.bounds, afterScreenUpdates: true)==true
{
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
return nil
}
@IBAction func refreshButtonTouched(_ sender: UIBarButtonItem) {
scene.cleanUp()
}
}
| mit | 05f7940e7c8975050b60093fae7de235 | 24.383721 | 101 | 0.620705 | 5.148585 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet | SwiftGL/Vec4.swift | 1 | 32673 | //
// Vec4.swift
// SwiftGL
//
// Created by Scott Bennett on 2014-06-08.
// Copyright (c) 2014 Scott Bennett. All rights reserved.
//
import Darwin
import CoreGraphics
public struct Vec4 {
public var x, y, z, w: Float
public init() {
self.x = 0
self.y = 0
self.z = 0
self.w = 0
}
// Explicit Initializers
public init(point:CGPoint)
{
self.x = Float(point.x)
self.y = Float(point.y)
self.z = 0
self.w = 0
}
public init(s: Float) {
self.x = s
self.y = s
self.z = s
self.w = s
}
public init(x: Float) {
self.x = x
self.y = 0
self.z = 0
self.w = 1
}
public init(x: Float, y: Float) {
self.x = x
self.y = y
self.z = 0
self.w = 1
}
public init(x: Float, y: Float, z: Float) {
self.x = x
self.y = y
self.z = z
self.w = 1
}
public init(x: Float, y: Float, z: Float, w: Float) {
self.x = x
self.y = y
self.z = z
self.w = w
}
public init(xy: Vec2, z: Float, w: Float) {
self.x = xy.x
self.y = xy.y
self.z = z
self.w = w
}
public init(x: Float, yz: Vec2, w: Float) {
self.x = x
self.y = yz.x
self.z = yz.y
self.w = w
}
public init(x: Float, y: Float, zw: Vec2) {
self.x = x
self.y = y
self.z = zw.x
self.w = zw.y
}
public init(xy: Vec2, zw: Vec2) {
self.x = xy.x
self.y = xy.y
self.z = zw.x
self.w = zw.y
}
public init(xyz: Vec3, w: Float) {
self.x = xyz.x
self.y = xyz.y
self.z = xyz.z
self.w = w
}
public init(x: Float, yzw: Vec3) {
self.x = x
self.y = yzw.x
self.z = yzw.y
self.w = yzw.z
}
// Implicit Initializers
public init(_ x: Float) {
self.x = x
self.y = 0
self.z = 0
self.w = 1
}
public init(_ x: Float, _ y: Float) {
self.x = x
self.y = y
self.z = 0
self.w = 1
}
public init(_ x: Float, _ y: Float, _ z: Float) {
self.x = x
self.y = y
self.z = z
self.w = 1
}
public init(_ x: Float, _ y: Float, _ z: Float, _ w: Float) {
self.x = x
self.y = y
self.z = z
self.w = w
}
public init(_ xy: Vec2, _ z: Float, _ w: Float) {
self.x = xy.x
self.y = xy.y
self.z = z
self.w = w
}
public init(_ x: Float, _ yz: Vec2, _ w: Float) {
self.x = x
self.y = yz.x
self.z = yz.y
self.w = w
}
public init(_ x: Float, _ y: Float, _ zw: Vec2) {
self.x = x
self.y = y
self.z = zw.x
self.w = zw.y
}
public init(_ xy: Vec2, _ zw: Vec2) {
self.x = xy.x
self.y = xy.y
self.z = zw.x
self.w = zw.y
}
public init(_ xyz: Vec3, _ w: Float) {
self.x = xyz.x
self.y = xyz.y
self.z = xyz.z
self.w = w
}
public init(_ x: Float, _ yzw: Vec3) {
self.x = x
self.y = yzw.x
self.z = yzw.y
self.w = yzw.z
}
public var length2: Float {
get {
return x * x + y * y + z * z + w * w
}
}
public var length: Float {
get {
return sqrt(self.length2)
}
set {
self = length * normalize(self)
}
}
// Swizzle (Vec2) Properties
public var xx: Vec2 {get {return Vec2(x: x, y: x)}}
public var yx: Vec2 {get {return Vec2(x: y, y: x)} set(v) {self.y = v.x; self.x = v.y}}
public var zx: Vec2 {get {return Vec2(x: z, y: x)} set(v) {self.z = v.x; self.x = v.y}}
public var wx: Vec2 {get {return Vec2(x: w, y: x)} set(v) {self.w = v.x; self.x = v.y}}
public var xy: Vec2 {get {return Vec2(x: x, y: y)} set(v) {self.x = v.x; self.y = v.y}}
public var yy: Vec2 {get {return Vec2(x: y, y: y)}}
public var zy: Vec2 {get {return Vec2(x: z, y: y)} set(v) {self.z = v.x; self.y = v.y}}
public var wy: Vec2 {get {return Vec2(x: w, y: y)} set(v) {self.w = v.x; self.y = v.y}}
public var xz: Vec2 {get {return Vec2(x: x, y: z)} set(v) {self.x = v.x; self.z = v.y}}
public var yz: Vec2 {get {return Vec2(x: y, y: z)} set(v) {self.y = v.x; self.z = v.y}}
public var zz: Vec2 {get {return Vec2(x: z, y: z)}}
public var wz: Vec2 {get {return Vec2(x: w, y: z)} set(v) {self.w = v.x; self.z = v.y}}
public var xw: Vec2 {get {return Vec2(x: x, y: w)} set(v) {self.x = v.x; self.w = v.y}}
public var yw: Vec2 {get {return Vec2(x: y, y: w)} set(v) {self.y = v.x; self.w = v.y}}
public var zw: Vec2 {get {return Vec2(x: z, y: w)} set(v) {self.z = v.x; self.w = v.y}}
public var ww: Vec2 {get {return Vec2(x: w, y: w)}}
// Swizzle (Vec3) Properties
public var xxx: Vec3 {get {return Vec3(x: x, y: x, z: x)}}
public var yxx: Vec3 {get {return Vec3(x: y, y: x, z: x)}}
public var zxx: Vec3 {get {return Vec3(x: z, y: x, z: x)}}
public var wxx: Vec3 {get {return Vec3(x: w, y: x, z: x)}}
public var xyx: Vec3 {get {return Vec3(x: x, y: y, z: x)}}
public var yyx: Vec3 {get {return Vec3(x: y, y: y, z: x)}}
public var zyx: Vec3 {get {return Vec3(x: z, y: y, z: x)} set(v) {self.z = v.x; self.y = v.y; self.x = v.z}}
public var wyx: Vec3 {get {return Vec3(x: w, y: y, z: x)} set(v) {self.w = v.x; self.y = v.y; self.x = v.z}}
public var xzx: Vec3 {get {return Vec3(x: x, y: z, z: x)}}
public var yzx: Vec3 {get {return Vec3(x: y, y: z, z: x)} set(v) {self.y = v.x; self.z = v.y; self.x = v.z}}
public var zzx: Vec3 {get {return Vec3(x: z, y: z, z: x)}}
public var wzx: Vec3 {get {return Vec3(x: w, y: z, z: x)} set(v) {self.w = v.x; self.z = v.y; self.x = v.z}}
public var xwx: Vec3 {get {return Vec3(x: x, y: w, z: x)}}
public var ywx: Vec3 {get {return Vec3(x: y, y: w, z: x)} set(v) {self.y = v.x; self.w = v.y; self.x = v.z}}
public var zwx: Vec3 {get {return Vec3(x: z, y: w, z: x)} set(v) {self.z = v.x; self.w = v.y; self.x = v.z}}
public var wwx: Vec3 {get {return Vec3(x: w, y: w, z: x)}}
public var xxy: Vec3 {get {return Vec3(x: x, y: x, z: y)}}
public var yxy: Vec3 {get {return Vec3(x: y, y: x, z: y)}}
public var zxy: Vec3 {get {return Vec3(x: z, y: x, z: y)} set(v) {self.z = v.x; self.x = v.y; self.y = v.z}}
public var wxy: Vec3 {get {return Vec3(x: w, y: x, z: y)} set(v) {self.w = v.x; self.x = v.y; self.y = v.z}}
public var xyy: Vec3 {get {return Vec3(x: x, y: y, z: y)}}
public var yyy: Vec3 {get {return Vec3(x: y, y: y, z: y)}}
public var zyy: Vec3 {get {return Vec3(x: z, y: y, z: y)}}
public var wyy: Vec3 {get {return Vec3(x: w, y: y, z: y)}}
public var xzy: Vec3 {get {return Vec3(x: x, y: z, z: y)} set(v) {self.x = v.x; self.z = v.y; self.y = v.z}}
public var yzy: Vec3 {get {return Vec3(x: y, y: z, z: y)}}
public var zzy: Vec3 {get {return Vec3(x: z, y: z, z: y)}}
public var wzy: Vec3 {get {return Vec3(x: w, y: z, z: y)} set(v) {self.w = v.x; self.z = v.y; self.y = v.z}}
public var xwy: Vec3 {get {return Vec3(x: x, y: w, z: y)} set(v) {self.x = v.x; self.w = v.y; self.y = v.z}}
public var ywy: Vec3 {get {return Vec3(x: y, y: w, z: y)}}
public var zwy: Vec3 {get {return Vec3(x: z, y: w, z: y)} set(v) {self.z = v.x; self.w = v.y; self.y = v.z}}
public var wwy: Vec3 {get {return Vec3(x: w, y: w, z: y)}}
public var xxz: Vec3 {get {return Vec3(x: x, y: x, z: z)}}
public var yxz: Vec3 {get {return Vec3(x: y, y: x, z: z)} set(v) {self.y = v.x; self.x = v.y; self.z = v.z}}
public var zxz: Vec3 {get {return Vec3(x: z, y: x, z: z)}}
public var wxz: Vec3 {get {return Vec3(x: w, y: x, z: z)} set(v) {self.w = v.x; self.x = v.y; self.z = v.z}}
public var xyz: Vec3 {get {return Vec3(x: x, y: y, z: z)} set(v) {self.x = v.x; self.y = v.y; self.z = v.z}}
public var yyz: Vec3 {get {return Vec3(x: y, y: y, z: z)}}
public var zyz: Vec3 {get {return Vec3(x: z, y: y, z: z)}}
public var wyz: Vec3 {get {return Vec3(x: w, y: y, z: z)} set(v) {self.w = v.x; self.y = v.y; self.z = v.z}}
public var xzz: Vec3 {get {return Vec3(x: x, y: z, z: z)}}
public var yzz: Vec3 {get {return Vec3(x: y, y: z, z: z)}}
public var zzz: Vec3 {get {return Vec3(x: z, y: z, z: z)}}
public var wzz: Vec3 {get {return Vec3(x: w, y: z, z: z)}}
public var xwz: Vec3 {get {return Vec3(x: x, y: w, z: z)} set(v) {self.x = v.x; self.w = v.y; self.z = v.z}}
public var ywz: Vec3 {get {return Vec3(x: y, y: w, z: z)} set(v) {self.y = v.x; self.w = v.y; self.z = v.z}}
public var zwz: Vec3 {get {return Vec3(x: z, y: w, z: z)}}
public var wwz: Vec3 {get {return Vec3(x: w, y: w, z: z)}}
public var xxw: Vec3 {get {return Vec3(x: x, y: x, z: w)}}
public var yxw: Vec3 {get {return Vec3(x: y, y: x, z: w)} set(v) {self.y = v.x; self.x = v.y; self.w = v.z}}
public var zxw: Vec3 {get {return Vec3(x: z, y: x, z: w)} set(v) {self.z = v.x; self.x = v.y; self.w = v.z}}
public var wxw: Vec3 {get {return Vec3(x: w, y: x, z: w)}}
public var xyw: Vec3 {get {return Vec3(x: x, y: y, z: w)} set(v) {self.x = v.x; self.y = v.y; self.w = v.z}}
public var yyw: Vec3 {get {return Vec3(x: y, y: y, z: w)}}
public var zyw: Vec3 {get {return Vec3(x: z, y: y, z: w)} set(v) {self.z = v.x; self.y = v.y; self.w = v.z}}
public var wyw: Vec3 {get {return Vec3(x: w, y: y, z: w)}}
public var xzw: Vec3 {get {return Vec3(x: x, y: z, z: w)} set(v) {self.x = v.x; self.z = v.y; self.w = v.z}}
public var yzw: Vec3 {get {return Vec3(x: y, y: z, z: w)} set(v) {self.y = v.x; self.z = v.y; self.w = v.z}}
public var zzw: Vec3 {get {return Vec3(x: z, y: z, z: w)}}
public var wzw: Vec3 {get {return Vec3(x: w, y: z, z: w)}}
public var xww: Vec3 {get {return Vec3(x: x, y: w, z: w)}}
public var yww: Vec3 {get {return Vec3(x: y, y: w, z: w)}}
public var zww: Vec3 {get {return Vec3(x: z, y: w, z: w)}}
public var www: Vec3 {get {return Vec3(x: w, y: w, z: w)}}
// Swizzle (Vec4) Properties
public var xxxx: Vec4 {get {return Vec4(x: x, y: x, z: x, w: x)}}
public var yxxx: Vec4 {get {return Vec4(x: y, y: x, z: x, w: x)}}
public var zxxx: Vec4 {get {return Vec4(x: z, y: x, z: x, w: x)}}
public var wxxx: Vec4 {get {return Vec4(x: w, y: x, z: x, w: x)}}
public var xyxx: Vec4 {get {return Vec4(x: x, y: y, z: x, w: x)}}
public var yyxx: Vec4 {get {return Vec4(x: y, y: y, z: x, w: x)}}
public var zyxx: Vec4 {get {return Vec4(x: z, y: y, z: x, w: x)}}
public var wyxx: Vec4 {get {return Vec4(x: w, y: y, z: x, w: x)}}
public var xzxx: Vec4 {get {return Vec4(x: x, y: z, z: x, w: x)}}
public var yzxx: Vec4 {get {return Vec4(x: y, y: z, z: x, w: x)}}
public var zzxx: Vec4 {get {return Vec4(x: z, y: z, z: x, w: x)}}
public var wzxx: Vec4 {get {return Vec4(x: w, y: z, z: x, w: x)}}
public var xwxx: Vec4 {get {return Vec4(x: x, y: w, z: x, w: x)}}
public var ywxx: Vec4 {get {return Vec4(x: y, y: w, z: x, w: x)}}
public var zwxx: Vec4 {get {return Vec4(x: z, y: w, z: x, w: x)}}
public var wwxx: Vec4 {get {return Vec4(x: w, y: w, z: x, w: x)}}
public var xxyx: Vec4 {get {return Vec4(x: x, y: x, z: y, w: x)}}
public var yxyx: Vec4 {get {return Vec4(x: y, y: x, z: y, w: x)}}
public var zxyx: Vec4 {get {return Vec4(x: z, y: x, z: y, w: x)}}
public var wxyx: Vec4 {get {return Vec4(x: w, y: x, z: y, w: x)}}
public var xyyx: Vec4 {get {return Vec4(x: x, y: y, z: y, w: x)}}
public var yyyx: Vec4 {get {return Vec4(x: y, y: y, z: y, w: x)}}
public var zyyx: Vec4 {get {return Vec4(x: z, y: y, z: y, w: x)}}
public var wyyx: Vec4 {get {return Vec4(x: w, y: y, z: y, w: x)}}
public var xzyx: Vec4 {get {return Vec4(x: x, y: z, z: y, w: x)}}
public var yzyx: Vec4 {get {return Vec4(x: y, y: z, z: y, w: x)}}
public var zzyx: Vec4 {get {return Vec4(x: z, y: z, z: y, w: x)}}
public var wzyx: Vec4 {get {return Vec4(x: w, y: z, z: y, w: x)} set(v) {self.w = v.x; self.z = v.y; self.y = v.z; self.x = v.w}}
public var xwyx: Vec4 {get {return Vec4(x: x, y: w, z: y, w: x)}}
public var ywyx: Vec4 {get {return Vec4(x: y, y: w, z: y, w: x)}}
public var zwyx: Vec4 {get {return Vec4(x: z, y: w, z: y, w: x)} set(v) {self.z = v.x; self.w = v.y; self.y = v.z; self.x = v.w}}
public var wwyx: Vec4 {get {return Vec4(x: w, y: w, z: y, w: x)}}
public var xxzx: Vec4 {get {return Vec4(x: x, y: x, z: z, w: x)}}
public var yxzx: Vec4 {get {return Vec4(x: y, y: x, z: z, w: x)}}
public var zxzx: Vec4 {get {return Vec4(x: z, y: x, z: z, w: x)}}
public var wxzx: Vec4 {get {return Vec4(x: w, y: x, z: z, w: x)}}
public var xyzx: Vec4 {get {return Vec4(x: x, y: y, z: z, w: x)}}
public var yyzx: Vec4 {get {return Vec4(x: y, y: y, z: z, w: x)}}
public var zyzx: Vec4 {get {return Vec4(x: z, y: y, z: z, w: x)}}
public var wyzx: Vec4 {get {return Vec4(x: w, y: y, z: z, w: x)} set(v) {self.w = v.x; self.y = v.y; self.z = v.z; self.x = v.w}}
public var xzzx: Vec4 {get {return Vec4(x: x, y: z, z: z, w: x)}}
public var yzzx: Vec4 {get {return Vec4(x: y, y: z, z: z, w: x)}}
public var zzzx: Vec4 {get {return Vec4(x: z, y: z, z: z, w: x)}}
public var wzzx: Vec4 {get {return Vec4(x: w, y: z, z: z, w: x)}}
public var xwzx: Vec4 {get {return Vec4(x: x, y: w, z: z, w: x)}}
public var ywzx: Vec4 {get {return Vec4(x: y, y: w, z: z, w: x)} set(v) {self.y = v.x; self.w = v.y; self.z = v.z; self.x = v.w}}
public var zwzx: Vec4 {get {return Vec4(x: z, y: w, z: z, w: x)}}
public var wwzx: Vec4 {get {return Vec4(x: w, y: w, z: z, w: x)}}
public var xxwx: Vec4 {get {return Vec4(x: x, y: x, z: w, w: x)}}
public var yxwx: Vec4 {get {return Vec4(x: y, y: x, z: w, w: x)}}
public var zxwx: Vec4 {get {return Vec4(x: z, y: x, z: w, w: x)}}
public var wxwx: Vec4 {get {return Vec4(x: w, y: x, z: w, w: x)}}
public var xywx: Vec4 {get {return Vec4(x: x, y: y, z: w, w: x)}}
public var yywx: Vec4 {get {return Vec4(x: y, y: y, z: w, w: x)}}
public var zywx: Vec4 {get {return Vec4(x: z, y: y, z: w, w: x)} set(v) {self.z = v.x; self.y = v.y; self.w = v.z; self.x = v.w}}
public var wywx: Vec4 {get {return Vec4(x: w, y: y, z: w, w: x)}}
public var xzwx: Vec4 {get {return Vec4(x: x, y: z, z: w, w: x)}}
public var yzwx: Vec4 {get {return Vec4(x: y, y: z, z: w, w: x)} set(v) {self.y = v.x; self.z = v.y; self.w = v.z; self.x = v.w}}
public var zzwx: Vec4 {get {return Vec4(x: z, y: z, z: w, w: x)}}
public var wzwx: Vec4 {get {return Vec4(x: w, y: z, z: w, w: x)}}
public var xwwx: Vec4 {get {return Vec4(x: x, y: w, z: w, w: x)}}
public var ywwx: Vec4 {get {return Vec4(x: y, y: w, z: w, w: x)}}
public var zwwx: Vec4 {get {return Vec4(x: z, y: w, z: w, w: x)}}
public var wwwx: Vec4 {get {return Vec4(x: w, y: w, z: w, w: x)}}
public var xxxy: Vec4 {get {return Vec4(x: x, y: x, z: x, w: y)}}
public var yxxy: Vec4 {get {return Vec4(x: y, y: x, z: x, w: y)}}
public var zxxy: Vec4 {get {return Vec4(x: z, y: x, z: x, w: y)}}
public var wxxy: Vec4 {get {return Vec4(x: w, y: x, z: x, w: y)}}
public var xyxy: Vec4 {get {return Vec4(x: x, y: y, z: x, w: y)}}
public var yyxy: Vec4 {get {return Vec4(x: y, y: y, z: x, w: y)}}
public var zyxy: Vec4 {get {return Vec4(x: z, y: y, z: x, w: y)}}
public var wyxy: Vec4 {get {return Vec4(x: w, y: y, z: x, w: y)}}
public var xzxy: Vec4 {get {return Vec4(x: x, y: z, z: x, w: y)}}
public var yzxy: Vec4 {get {return Vec4(x: y, y: z, z: x, w: y)}}
public var zzxy: Vec4 {get {return Vec4(x: z, y: z, z: x, w: y)}}
public var wzxy: Vec4 {get {return Vec4(x: w, y: z, z: x, w: y)} set(v) {self.w = v.x; self.z = v.y; self.x = v.z; self.y = v.w}}
public var xwxy: Vec4 {get {return Vec4(x: x, y: w, z: x, w: y)}}
public var ywxy: Vec4 {get {return Vec4(x: y, y: w, z: x, w: y)}}
public var zwxy: Vec4 {get {return Vec4(x: z, y: w, z: x, w: y)} set(v) {self.z = v.x; self.w = v.y; self.x = v.z; self.y = v.w}}
public var wwxy: Vec4 {get {return Vec4(x: w, y: w, z: x, w: y)}}
public var xxyy: Vec4 {get {return Vec4(x: x, y: x, z: y, w: y)}}
public var yxyy: Vec4 {get {return Vec4(x: y, y: x, z: y, w: y)}}
public var zxyy: Vec4 {get {return Vec4(x: z, y: x, z: y, w: y)}}
public var wxyy: Vec4 {get {return Vec4(x: w, y: x, z: y, w: y)}}
public var xyyy: Vec4 {get {return Vec4(x: x, y: y, z: y, w: y)}}
public var yyyy: Vec4 {get {return Vec4(x: y, y: y, z: y, w: y)}}
public var zyyy: Vec4 {get {return Vec4(x: z, y: y, z: y, w: y)}}
public var wyyy: Vec4 {get {return Vec4(x: w, y: y, z: y, w: y)}}
public var xzyy: Vec4 {get {return Vec4(x: x, y: z, z: y, w: y)}}
public var yzyy: Vec4 {get {return Vec4(x: y, y: z, z: y, w: y)}}
public var zzyy: Vec4 {get {return Vec4(x: z, y: z, z: y, w: y)}}
public var wzyy: Vec4 {get {return Vec4(x: w, y: z, z: y, w: y)}}
public var xwyy: Vec4 {get {return Vec4(x: x, y: w, z: y, w: y)}}
public var ywyy: Vec4 {get {return Vec4(x: y, y: w, z: y, w: y)}}
public var zwyy: Vec4 {get {return Vec4(x: z, y: w, z: y, w: y)}}
public var wwyy: Vec4 {get {return Vec4(x: w, y: w, z: y, w: y)}}
public var xxzy: Vec4 {get {return Vec4(x: x, y: x, z: z, w: y)}}
public var yxzy: Vec4 {get {return Vec4(x: y, y: x, z: z, w: y)}}
public var zxzy: Vec4 {get {return Vec4(x: z, y: x, z: z, w: y)}}
public var wxzy: Vec4 {get {return Vec4(x: w, y: x, z: z, w: y)} set(v) {self.w = v.x; self.x = v.y; self.z = v.z; self.y = v.w}}
public var xyzy: Vec4 {get {return Vec4(x: x, y: y, z: z, w: y)}}
public var yyzy: Vec4 {get {return Vec4(x: y, y: y, z: z, w: y)}}
public var zyzy: Vec4 {get {return Vec4(x: z, y: y, z: z, w: y)}}
public var wyzy: Vec4 {get {return Vec4(x: w, y: y, z: z, w: y)}}
public var xzzy: Vec4 {get {return Vec4(x: x, y: z, z: z, w: y)}}
public var yzzy: Vec4 {get {return Vec4(x: y, y: z, z: z, w: y)}}
public var zzzy: Vec4 {get {return Vec4(x: z, y: z, z: z, w: y)}}
public var wzzy: Vec4 {get {return Vec4(x: w, y: z, z: z, w: y)}}
public var xwzy: Vec4 {get {return Vec4(x: x, y: w, z: z, w: y)} set(v) {self.x = v.x; self.w = v.y; self.z = v.z; self.y = v.w}}
public var ywzy: Vec4 {get {return Vec4(x: y, y: w, z: z, w: y)}}
public var zwzy: Vec4 {get {return Vec4(x: z, y: w, z: z, w: y)}}
public var wwzy: Vec4 {get {return Vec4(x: w, y: w, z: z, w: y)}}
public var xxwy: Vec4 {get {return Vec4(x: x, y: x, z: w, w: y)}}
public var yxwy: Vec4 {get {return Vec4(x: y, y: x, z: w, w: y)}}
public var zxwy: Vec4 {get {return Vec4(x: z, y: x, z: w, w: y)} set(v) {self.z = v.x; self.x = v.y; self.w = v.z; self.y = v.w}}
public var wxwy: Vec4 {get {return Vec4(x: w, y: x, z: w, w: y)}}
public var xywy: Vec4 {get {return Vec4(x: x, y: y, z: w, w: y)}}
public var yywy: Vec4 {get {return Vec4(x: y, y: y, z: w, w: y)}}
public var zywy: Vec4 {get {return Vec4(x: z, y: y, z: w, w: y)}}
public var wywy: Vec4 {get {return Vec4(x: w, y: y, z: w, w: y)}}
public var xzwy: Vec4 {get {return Vec4(x: x, y: z, z: w, w: y)} set(v) {self.x = v.x; self.z = v.y; self.w = v.z; self.y = v.w}}
public var yzwy: Vec4 {get {return Vec4(x: y, y: z, z: w, w: y)}}
public var zzwy: Vec4 {get {return Vec4(x: z, y: z, z: w, w: y)}}
public var wzwy: Vec4 {get {return Vec4(x: w, y: z, z: w, w: y)}}
public var xwwy: Vec4 {get {return Vec4(x: x, y: w, z: w, w: y)}}
public var ywwy: Vec4 {get {return Vec4(x: y, y: w, z: w, w: y)}}
public var zwwy: Vec4 {get {return Vec4(x: z, y: w, z: w, w: y)}}
public var wwwy: Vec4 {get {return Vec4(x: w, y: w, z: w, w: y)}}
public var xxxz: Vec4 {get {return Vec4(x: x, y: x, z: x, w: z)}}
public var yxxz: Vec4 {get {return Vec4(x: y, y: x, z: x, w: z)}}
public var zxxz: Vec4 {get {return Vec4(x: z, y: x, z: x, w: z)}}
public var wxxz: Vec4 {get {return Vec4(x: w, y: x, z: x, w: z)}}
public var xyxz: Vec4 {get {return Vec4(x: x, y: y, z: x, w: z)}}
public var yyxz: Vec4 {get {return Vec4(x: y, y: y, z: x, w: z)}}
public var zyxz: Vec4 {get {return Vec4(x: z, y: y, z: x, w: z)}}
public var wyxz: Vec4 {get {return Vec4(x: w, y: y, z: x, w: z)} set(v) {self.w = v.x; self.y = v.y; self.x = v.z; self.z = v.w}}
public var xzxz: Vec4 {get {return Vec4(x: x, y: z, z: x, w: z)}}
public var yzxz: Vec4 {get {return Vec4(x: y, y: z, z: x, w: z)}}
public var zzxz: Vec4 {get {return Vec4(x: z, y: z, z: x, w: z)}}
public var wzxz: Vec4 {get {return Vec4(x: w, y: z, z: x, w: z)}}
public var xwxz: Vec4 {get {return Vec4(x: x, y: w, z: x, w: z)}}
public var ywxz: Vec4 {get {return Vec4(x: y, y: w, z: x, w: z)} set(v) {self.y = v.x; self.w = v.y; self.x = v.z; self.z = v.w}}
public var zwxz: Vec4 {get {return Vec4(x: z, y: w, z: x, w: z)}}
public var wwxz: Vec4 {get {return Vec4(x: w, y: w, z: x, w: z)}}
public var xxyz: Vec4 {get {return Vec4(x: x, y: x, z: y, w: z)}}
public var yxyz: Vec4 {get {return Vec4(x: y, y: x, z: y, w: z)}}
public var zxyz: Vec4 {get {return Vec4(x: z, y: x, z: y, w: z)}}
public var wxyz: Vec4 {get {return Vec4(x: w, y: x, z: y, w: z)} set(v) {self.w = v.x; self.x = v.y; self.y = v.z; self.z = v.w}}
public var xyyz: Vec4 {get {return Vec4(x: x, y: y, z: y, w: z)}}
public var yyyz: Vec4 {get {return Vec4(x: y, y: y, z: y, w: z)}}
public var zyyz: Vec4 {get {return Vec4(x: z, y: y, z: y, w: z)}}
public var wyyz: Vec4 {get {return Vec4(x: w, y: y, z: y, w: z)}}
public var xzyz: Vec4 {get {return Vec4(x: x, y: z, z: y, w: z)}}
public var yzyz: Vec4 {get {return Vec4(x: y, y: z, z: y, w: z)}}
public var zzyz: Vec4 {get {return Vec4(x: z, y: z, z: y, w: z)}}
public var wzyz: Vec4 {get {return Vec4(x: w, y: z, z: y, w: z)}}
public var xwyz: Vec4 {get {return Vec4(x: x, y: w, z: y, w: z)} set(v) {self.x = v.x; self.w = v.y; self.y = v.z; self.z = v.w}}
public var ywyz: Vec4 {get {return Vec4(x: y, y: w, z: y, w: z)}}
public var zwyz: Vec4 {get {return Vec4(x: z, y: w, z: y, w: z)}}
public var wwyz: Vec4 {get {return Vec4(x: w, y: w, z: y, w: z)}}
public var xxzz: Vec4 {get {return Vec4(x: x, y: x, z: z, w: z)}}
public var yxzz: Vec4 {get {return Vec4(x: y, y: x, z: z, w: z)}}
public var zxzz: Vec4 {get {return Vec4(x: z, y: x, z: z, w: z)}}
public var wxzz: Vec4 {get {return Vec4(x: w, y: x, z: z, w: z)}}
public var xyzz: Vec4 {get {return Vec4(x: x, y: y, z: z, w: z)}}
public var yyzz: Vec4 {get {return Vec4(x: y, y: y, z: z, w: z)}}
public var zyzz: Vec4 {get {return Vec4(x: z, y: y, z: z, w: z)}}
public var wyzz: Vec4 {get {return Vec4(x: w, y: y, z: z, w: z)}}
public var xzzz: Vec4 {get {return Vec4(x: x, y: z, z: z, w: z)}}
public var yzzz: Vec4 {get {return Vec4(x: y, y: z, z: z, w: z)}}
public var zzzz: Vec4 {get {return Vec4(x: z, y: z, z: z, w: z)}}
public var wzzz: Vec4 {get {return Vec4(x: w, y: z, z: z, w: z)}}
public var xwzz: Vec4 {get {return Vec4(x: x, y: w, z: z, w: z)}}
public var ywzz: Vec4 {get {return Vec4(x: y, y: w, z: z, w: z)}}
public var zwzz: Vec4 {get {return Vec4(x: z, y: w, z: z, w: z)}}
public var wwzz: Vec4 {get {return Vec4(x: w, y: w, z: z, w: z)}}
public var xxwz: Vec4 {get {return Vec4(x: x, y: x, z: w, w: z)}}
public var yxwz: Vec4 {get {return Vec4(x: y, y: x, z: w, w: z)} set(v) {self.y = v.x; self.x = v.y; self.w = v.z; self.z = v.w}}
public var zxwz: Vec4 {get {return Vec4(x: z, y: x, z: w, w: z)}}
public var wxwz: Vec4 {get {return Vec4(x: w, y: x, z: w, w: z)}}
public var xywz: Vec4 {get {return Vec4(x: x, y: y, z: w, w: z)} set(v) {self.x = v.x; self.y = v.y; self.w = v.z; self.z = v.w}}
public var yywz: Vec4 {get {return Vec4(x: y, y: y, z: w, w: z)}}
public var zywz: Vec4 {get {return Vec4(x: z, y: y, z: w, w: z)}}
public var wywz: Vec4 {get {return Vec4(x: w, y: y, z: w, w: z)}}
public var xzwz: Vec4 {get {return Vec4(x: x, y: z, z: w, w: z)}}
public var yzwz: Vec4 {get {return Vec4(x: y, y: z, z: w, w: z)}}
public var zzwz: Vec4 {get {return Vec4(x: z, y: z, z: w, w: z)}}
public var wzwz: Vec4 {get {return Vec4(x: w, y: z, z: w, w: z)}}
public var xwwz: Vec4 {get {return Vec4(x: x, y: w, z: w, w: z)}}
public var ywwz: Vec4 {get {return Vec4(x: y, y: w, z: w, w: z)}}
public var zwwz: Vec4 {get {return Vec4(x: z, y: w, z: w, w: z)}}
public var wwwz: Vec4 {get {return Vec4(x: w, y: w, z: w, w: z)}}
public var xxxw: Vec4 {get {return Vec4(x: x, y: x, z: x, w: w)}}
public var yxxw: Vec4 {get {return Vec4(x: y, y: x, z: x, w: w)}}
public var zxxw: Vec4 {get {return Vec4(x: z, y: x, z: x, w: w)}}
public var wxxw: Vec4 {get {return Vec4(x: w, y: x, z: x, w: w)}}
public var xyxw: Vec4 {get {return Vec4(x: x, y: y, z: x, w: w)}}
public var yyxw: Vec4 {get {return Vec4(x: y, y: y, z: x, w: w)}}
public var zyxw: Vec4 {get {return Vec4(x: z, y: y, z: x, w: w)} set(v) {self.z = v.x; self.y = v.y; self.x = v.z; self.w = v.w}}
public var wyxw: Vec4 {get {return Vec4(x: w, y: y, z: x, w: w)}}
public var xzxw: Vec4 {get {return Vec4(x: x, y: z, z: x, w: w)}}
public var yzxw: Vec4 {get {return Vec4(x: y, y: z, z: x, w: w)} set(v) {self.y = v.x; self.z = v.y; self.x = v.z; self.w = v.w}}
public var zzxw: Vec4 {get {return Vec4(x: z, y: z, z: x, w: w)}}
public var wzxw: Vec4 {get {return Vec4(x: w, y: z, z: x, w: w)}}
public var xwxw: Vec4 {get {return Vec4(x: x, y: w, z: x, w: w)}}
public var ywxw: Vec4 {get {return Vec4(x: y, y: w, z: x, w: w)}}
public var zwxw: Vec4 {get {return Vec4(x: z, y: w, z: x, w: w)}}
public var wwxw: Vec4 {get {return Vec4(x: w, y: w, z: x, w: w)}}
public var xxyw: Vec4 {get {return Vec4(x: x, y: x, z: y, w: w)}}
public var yxyw: Vec4 {get {return Vec4(x: y, y: x, z: y, w: w)}}
public var zxyw: Vec4 {get {return Vec4(x: z, y: x, z: y, w: w)} set(v) {self.z = v.x; self.x = v.y; self.y = v.z; self.w = v.w}}
public var wxyw: Vec4 {get {return Vec4(x: w, y: x, z: y, w: w)}}
public var xyyw: Vec4 {get {return Vec4(x: x, y: y, z: y, w: w)}}
public var yyyw: Vec4 {get {return Vec4(x: y, y: y, z: y, w: w)}}
public var zyyw: Vec4 {get {return Vec4(x: z, y: y, z: y, w: w)}}
public var wyyw: Vec4 {get {return Vec4(x: w, y: y, z: y, w: w)}}
public var xzyw: Vec4 {get {return Vec4(x: x, y: z, z: y, w: w)} set(v) {self.x = v.x; self.z = v.y; self.y = v.z; self.w = v.w}}
public var yzyw: Vec4 {get {return Vec4(x: y, y: z, z: y, w: w)}}
public var zzyw: Vec4 {get {return Vec4(x: z, y: z, z: y, w: w)}}
public var wzyw: Vec4 {get {return Vec4(x: w, y: z, z: y, w: w)}}
public var xwyw: Vec4 {get {return Vec4(x: x, y: w, z: y, w: w)}}
public var ywyw: Vec4 {get {return Vec4(x: y, y: w, z: y, w: w)}}
public var zwyw: Vec4 {get {return Vec4(x: z, y: w, z: y, w: w)}}
public var wwyw: Vec4 {get {return Vec4(x: w, y: w, z: y, w: w)}}
public var xxzw: Vec4 {get {return Vec4(x: x, y: x, z: z, w: w)}}
public var yxzw: Vec4 {get {return Vec4(x: y, y: x, z: z, w: w)} set(v) {self.y = v.x; self.x = v.y; self.z = v.z; self.w = v.w}}
public var zxzw: Vec4 {get {return Vec4(x: z, y: x, z: z, w: w)}}
public var wxzw: Vec4 {get {return Vec4(x: w, y: x, z: z, w: w)}}
public var xyzw: Vec4 {get {return Vec4(x: x, y: y, z: z, w: w)} set(v) {self.x = v.x; self.y = v.y; self.z = v.z; self.w = v.w}}
public var yyzw: Vec4 {get {return Vec4(x: y, y: y, z: z, w: w)}}
public var zyzw: Vec4 {get {return Vec4(x: z, y: y, z: z, w: w)}}
public var wyzw: Vec4 {get {return Vec4(x: w, y: y, z: z, w: w)}}
public var xzzw: Vec4 {get {return Vec4(x: x, y: z, z: z, w: w)}}
public var yzzw: Vec4 {get {return Vec4(x: y, y: z, z: z, w: w)}}
public var zzzw: Vec4 {get {return Vec4(x: z, y: z, z: z, w: w)}}
public var wzzw: Vec4 {get {return Vec4(x: w, y: z, z: z, w: w)}}
public var xwzw: Vec4 {get {return Vec4(x: x, y: w, z: z, w: w)}}
public var ywzw: Vec4 {get {return Vec4(x: y, y: w, z: z, w: w)}}
public var zwzw: Vec4 {get {return Vec4(x: z, y: w, z: z, w: w)}}
public var wwzw: Vec4 {get {return Vec4(x: w, y: w, z: z, w: w)}}
public var xxww: Vec4 {get {return Vec4(x: x, y: x, z: w, w: w)}}
public var yxww: Vec4 {get {return Vec4(x: y, y: x, z: w, w: w)}}
public var zxww: Vec4 {get {return Vec4(x: z, y: x, z: w, w: w)}}
public var wxww: Vec4 {get {return Vec4(x: w, y: x, z: w, w: w)}}
public var xyww: Vec4 {get {return Vec4(x: x, y: y, z: w, w: w)}}
public var yyww: Vec4 {get {return Vec4(x: y, y: y, z: w, w: w)}}
public var zyww: Vec4 {get {return Vec4(x: z, y: y, z: w, w: w)}}
public var wyww: Vec4 {get {return Vec4(x: w, y: y, z: w, w: w)}}
public var xzww: Vec4 {get {return Vec4(x: x, y: z, z: w, w: w)}}
public var yzww: Vec4 {get {return Vec4(x: y, y: z, z: w, w: w)}}
public var zzww: Vec4 {get {return Vec4(x: z, y: z, z: w, w: w)}}
public var wzww: Vec4 {get {return Vec4(x: w, y: z, z: w, w: w)}}
public var xwww: Vec4 {get {return Vec4(x: x, y: w, z: w, w: w)}}
public var ywww: Vec4 {get {return Vec4(x: y, y: w, z: w, w: w)}}
public var zwww: Vec4 {get {return Vec4(x: z, y: w, z: w, w: w)}}
public var wwww: Vec4 {get {return Vec4(x: w, y: w, z: w, w: w)}}
}
// Make it easier to interpret Vec4 as a string
extension Vec4: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {get {return "(\(x), \(y), \(z), \(w))"}}
public var debugDescription: String {get {return "Vec4(x: \(x), y: \(y), z: \(z), w: \(w))"}}
}
extension Vec4{
public var tojson:String{get{return "{\"x\":\(x),\"y\":\(y),\"z\":\(z),\"w\":\(w)}"}}
}
// Vec2 Prefix Operators
public prefix func - (v: Vec4) -> Vec4 {return Vec4(x: -v.x, y: -v.y, z: -v.z, w: -v.w)}
// Vec2 Infix Operators
public func + (a: Vec4, b: Vec4) -> Vec4 {return Vec4(x: a.x + b.x, y: a.y + b.y, z: a.z + b.z, w: a.w + b.w)}
public func - (a: Vec4, b: Vec4) -> Vec4 {return Vec4(x: a.x - b.x, y: a.y - b.y, z: a.z - b.z, w: a.w - b.w)}
public func * (a: Vec4, b: Vec4) -> Vec4 {return Vec4(x: a.x * b.x, y: a.y * b.y, z: a.z * b.z, w: a.w * b.w)}
public func / (a: Vec4, b: Vec4) -> Vec4 {return Vec4(x: a.x / b.x, y: a.y / b.y, z: a.z / b.z, w: a.w / b.w)}
// Vec2 Scalar Operators
public func * (s: Float, v: Vec4) -> Vec4 {return Vec4(x: s * v.x, y: s * v.y, z: s * v.z, w: s * v.w)}
public func * (v: Vec4, s: Float) -> Vec4 {return Vec4(x: v.x * s, y: v.y * s, z: v.z * s, w: v.w * s)}
public func / (v: Vec4, s: Float) -> Vec4 {return Vec4(x: v.x / s, y: v.y / s, z: v.z / s, w: v.w / s)}
// Vec4 Assignment Operators
public func += (a: inout Vec4, b: Vec4) {a = a + b}
public func -= (a: inout Vec4, b: Vec4) {a = a - b}
public func *= (a: inout Vec4, b: Vec4) {a = a * b}
public func /= (a: inout Vec4, b: Vec4) {a = a / b}
public func *= (a: inout Vec4, b: Float) {a = a * b}
public func /= (a: inout Vec4, b: Float) {a = a / b}
// Functions which operate on Vec2
public func length(_ v: Vec4) -> Float {return v.length}
public func length2(_ v: Vec4) -> Float {return v.length2}
public func normalize(_ v: Vec4) -> Vec4 {return v / v.length}
public func dot(_ a: Vec4, b: Vec4) -> Float {return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w}
public func clamp(_ value: Vec4, min: Float, max: Float) -> Vec4 {return Vec4(clamp(value.x, min: min, max: max), clamp(value.y, min: min, max: max), clamp(value.z, min: min, max: max), clamp(value.w, min: min, max: max))}
public func mix(_ a: Vec4, b: Vec4, t: Float) -> Vec4 {return a + (b - a) * t}
public func smoothstep(_ a: Vec4, b: Vec4, t: Float) -> Vec4 {return mix(a, b: b, t: t * t * (3 - 2 * t))}
public func clamp(_ value: Vec4, min: Vec4, max: Vec4) -> Vec4 {return Vec4(clamp(value.x, min: min.x, max: max.x), clamp(value.y, min: min.y, max: max.y), clamp(value.z, min: min.z, max: max.z), clamp(value.w, min: min.w, max: max.w))}
public func mix(_ a: Vec4, b: Vec4, t: Vec4) -> Vec4 {return a + (b - a) * t}
public func smoothstep(_ a: Vec4, b: Vec4, t: Vec4) -> Vec4 {return mix(a, b: b, t: t * t * (Vec4(s: 3) - 2 * t))}
| mit | 43ee89883169aa7bf0b3108040d9b1fc | 55.332759 | 236 | 0.527592 | 2.28259 | false | false | false | false |
iAugux/Zoom-Contacts | Phonetic/GradientView.swift | 1 | 2018 | //
// GradientView.swift
// Phonetic
//
// Created by Augus on 1/30/16.
// Copyright © 2016 iAugus. All rights reserved.
//
import UIKit
import SnapKit
class GradientView: UIView {
private var gradient: CAGradientLayer!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = UIColor.clearColor()
addBlurEffect()
}
override func drawRect(rect: CGRect) {
super.drawRect(rect)
// configureGradientView(rect)
}
override func layoutSubviews() {
super.layoutSubviews()
// gradient?.frame = frame
}
private func configureGradientView(frame: CGRect) {
gradient = CAGradientLayer()
gradient.frame = frame
gradient.colors = [UIColor(red:0.0894, green:0.4823, blue:0.9112, alpha:0.1).CGColor,
UIColor(red:0.6142, green:0.0611, blue:0.3474, alpha:0.1).CGColor]
layer.insertSublayer(gradient, atIndex: 1)
}
private func addBlurEffect() {
let bgImageView = UIImageView(image: UIImage(named: "wave_placeholder"))
bgImageView.contentMode = .ScaleAspectFill
insertSubview(bgImageView, atIndex: 0)
bgImageView.snp_makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsetsZero)
}
guard UIDevice.currentDevice().isBlurSupported() && !UIAccessibilityIsReduceTransparencyEnabled() else {
let overlayView = UIView(frame: frame)
overlayView.backgroundColor = UIColor(red: 0.498, green: 0.498, blue: 0.498, alpha: 0.926)
insertSubview(overlayView, atIndex: 1)
return
}
let effect = UIBlurEffect(style: .Light)
let blurView = UIVisualEffectView(effect: effect)
blurView.alpha = 0.96
insertSubview(blurView, atIndex: 1)
blurView.snp_makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsetsZero)
}
}
}
| mit | a7b15c129b0acce06915ee1eaac61380 | 29.560606 | 112 | 0.616758 | 4.482222 | false | false | false | false |
SwiftKit/Reactant | TVPrototyping/Components/CollectionView/CollectionViewController.swift | 2 | 2632 | //
// CollectionViewController.swift
// TVPrototyping
//
// Created by Matous Hybl on 03/11/2017.
// Copyright © 2017 Brightify. All rights reserved.
//
import Reactant
final class CollectionViewController: ControllerBase<Void, CollectionRootView> {
override func afterInit() {
rootView.componentState = .items(["Cell 1", "Cell 2", "Cell 3", "Cell 4", "Cell 5", "Cell 6"])
tabBarItem = UITabBarItem(title: "Collection", image: nil, tag: 0)
}
}
final class CollectionRootView: SimpleCollectionView<CollectionCell>, RootView {
@objc
init() {
super.init(cellFactory: CollectionCell.init, reloadable: false)
loadingIndicator.activityIndicatorViewStyle = .whiteLarge
collectionView.allowsSelection = true
collectionViewLayout.itemSize = CGSize(width: 400, height: 300)
collectionView.rx.didUpdateFocusInContextWithAnimationCoordinator
.subscribe(onNext: { [weak self] context, coordinator in
self?.updateFocus(context: context, coordinator: coordinator)
}).disposed(by: lifetimeDisposeBag)
}
func updateFocus(context: UICollectionViewFocusUpdateContext, coordinator: UIFocusAnimationCoordinator) {
if let previousIndexPath = context.previouslyFocusedIndexPath,
let cell = collectionView.cellForItem(at: previousIndexPath) {
cell.contentView.layer.borderWidth = 0.0
cell.contentView.layer.shadowRadius = 0.0
cell.contentView.layer.shadowOpacity = 0
}
if let indexPath = context.nextFocusedIndexPath,
let cell = collectionView.cellForItem(at: indexPath) {
cell.contentView.layer.borderWidth = 8.0
cell.contentView.layer.borderColor = UIColor.black.cgColor
cell.contentView.layer.shadowColor = UIColor.black.cgColor
cell.contentView.layer.shadowRadius = 10.0
cell.contentView.layer.shadowOpacity = 0.9
cell.contentView.layer.shadowOffset = CGSize(width: 0, height: 0)
collectionView.scrollToItem(at: indexPath, at: [.centeredHorizontally, .centeredVertically], animated: true)
}
}
}
final class CollectionCell: ViewBase<String, Void> {
private let label = UILabel()
override var canBecomeFocused: Bool {
return true
}
override func update() {
label.text = componentState
}
override func loadView() {
children(label)
}
override func setupConstraints() {
label.snp.makeConstraints { make in
make.center.equalToSuperview()
}
}
}
| mit | 3a8ccc9dd3abae087197939339c182fd | 30.698795 | 120 | 0.670087 | 4.908582 | false | false | false | false |
OpsLabJPL/MarsImagesIOS | MarsImagesIOS/ImageSelectionMenuViewController.swift | 1 | 1185 | //
// ImageSelectionMenuViewController.swift
// MarsImages
//
// Created by Powell, Mark W (397F) on 11/23/17.
// Copyright © 2017 Mark Powell. All rights reserved.
//
import UIKit
class ImageSelectionMenuViewController : UITableViewController {
var imageNames:[String] = [] {
didSet {
tableView.reloadData()
}
}
var imageVC:MarsImageViewController!
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return imageNames.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "imageNameCell")!
cell.textLabel?.text = imageNames[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let row = indexPath.row
let name = imageNames[row]
if name == "Anaglyph" {
imageVC.showAnaglyph()
} else {
imageVC.setImageAt(row, name)
}
dismiss(animated: true, completion: nil)
}
}
| apache-2.0 | 103437996a8747ef25f6b120f8b9bf7a | 27.190476 | 109 | 0.643581 | 4.832653 | false | false | false | false |
fhisa/CocoaStudy | 20150905/LayoutSampleWithCode/LayoutSampleWithCode/ViewController.swift | 1 | 7044 | //
// ViewController.swift
// LayoutSampleWithFSC
//
// Created by fhisa on 2015/09/03.
// Copyright (c) 2015 Hisakuni Fujimoto. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var baseView: UIView!
var mainView: UIView!
var infoView: UIView!
var miniView: UIView!
override func viewDidLoad() {
super.viewDidLoad()
mainView = createView(UIColor.cyanColor())
baseView.addSubview(mainView)
infoView = createView(UIColor.greenColor())
baseView.addSubview(infoView)
miniView = createView(UIColor.yellowColor())
baseView.addSubview(miniView)
setupPortraitLayout()
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
if size.height > size.width {
setupPortraitLayout()
}
else {
setupLandscapeLayout()
}
}
private func createView(bgcolor: UIColor) -> UIView {
let view = UIView()
view.setTranslatesAutoresizingMaskIntoConstraints(false)
view.backgroundColor = bgcolor
view.layer.borderColor = UIColor.redColor().CGColor
view.layer.borderWidth = 1
return view
}
private func setupPortraitLayout() {
switch traitCollection.userInterfaceIdiom {
case .Phone:
setupPhonePortraitLayout()
case .Pad:
setupPadPortraitLayout()
default:
println("unknown device:\(traitCollection.userInterfaceIdiom.rawValue)")
}
}
private func setupLandscapeLayout() {
switch traitCollection.userInterfaceIdiom {
case .Phone:
setupPhoneLandscapeLayout()
case .Pad:
setupPadLandscapeLayout()
default:
println("unknown device:\(traitCollection.userInterfaceIdiom.rawValue)")
}
}
private func setupPhonePortraitLayout() {
mainView.hidden = false
infoView.hidden = false
miniView.hidden = true
baseView.removeConstraints(baseView.constraints())
baseView.addConstraints([
NSLayoutConstraint(
item: mainView, attribute: .Height,
relatedBy: .Equal,
toItem: baseView, attribute: .Height,
multiplier: 3.0 / 4.0, constant: 0),
NSLayoutConstraint(
item: mainView, attribute: .Leading,
relatedBy: .Equal,
toItem: baseView, attribute: .Leading,
multiplier: 1, constant: 8),
NSLayoutConstraint(
item: mainView, attribute: .Top,
relatedBy: .Equal,
toItem: baseView, attribute: .Top,
multiplier: 1, constant: 8),
NSLayoutConstraint(
item: mainView, attribute: .Trailing,
relatedBy: .Equal,
toItem: baseView, attribute: .Trailing,
multiplier: 1, constant: -8),
NSLayoutConstraint(
item: infoView, attribute: .Top,
relatedBy: .Equal,
toItem: mainView, attribute: .Bottom,
multiplier: 1, constant: 8),
NSLayoutConstraint(
item: infoView, attribute: .Leading,
relatedBy: .Equal,
toItem: baseView, attribute: .Leading,
multiplier: 1, constant: 8),
NSLayoutConstraint(
item: infoView, attribute: .Trailing,
relatedBy: .Equal,
toItem: baseView, attribute: .Trailing,
multiplier: 1, constant: -8),
NSLayoutConstraint(
item: infoView, attribute: .Bottom,
relatedBy: .Equal,
toItem: baseView, attribute: .Bottom,
multiplier: 1, constant: -8),
])
}
private func setupPhoneLandscapeLayout() {
mainView.hidden = false
infoView.hidden = false
miniView.hidden = false
baseView.removeConstraints(baseView.constraints())
baseView.addConstraints([
NSLayoutConstraint(
item: mainView, attribute: .Width,
relatedBy: .Equal,
toItem: baseView, attribute: .Width,
multiplier: 2.0 / 3.0, constant: 0),
NSLayoutConstraint(
item: mainView, attribute: .Top,
relatedBy: .Equal,
toItem: baseView, attribute: .Top,
multiplier: 1, constant: 8),
NSLayoutConstraint(
item: mainView, attribute: .Trailing,
relatedBy: .Equal,
toItem: baseView, attribute: .Trailing,
multiplier: 1, constant: -8),
NSLayoutConstraint(
item: mainView, attribute: .Bottom,
relatedBy: .Equal,
toItem: baseView, attribute: .Bottom,
multiplier: 1, constant: -8),
NSLayoutConstraint(
item: infoView, attribute: .Height,
relatedBy: .Equal,
toItem: mainView, attribute: .Height,
multiplier: 4.0 / 7.0, constant: 0),
NSLayoutConstraint(
item: infoView, attribute: .Top,
relatedBy: .Equal,
toItem: baseView, attribute: .Top,
multiplier: 1, constant: 8),
NSLayoutConstraint(
item: infoView, attribute: .Leading,
relatedBy: .Equal,
toItem: baseView, attribute: .Leading,
multiplier: 1, constant: 8),
NSLayoutConstraint(
item: infoView, attribute: .Trailing,
relatedBy: .Equal,
toItem: mainView, attribute: .Leading,
multiplier: 1, constant: -8),
NSLayoutConstraint(
item: miniView, attribute: .Leading,
relatedBy: .Equal,
toItem: baseView, attribute: .Leading,
multiplier: 1, constant: 8),
NSLayoutConstraint(
item: miniView, attribute: .Top,
relatedBy: .Equal,
toItem: infoView, attribute: .Bottom,
multiplier: 1, constant: 8),
NSLayoutConstraint(
item: miniView, attribute: .Trailing,
relatedBy: .Equal,
toItem: mainView, attribute: .Leading,
multiplier: 1, constant: -8),
NSLayoutConstraint(
item: miniView, attribute: .Bottom,
relatedBy: .Equal,
toItem: baseView, attribute: .Bottom,
multiplier: 1, constant: -8),
])
}
private func setupPadPortraitLayout() {
setupPhonePortraitLayout()
}
private func setupPadLandscapeLayout() {
setupPhoneLandscapeLayout()
}
}
| mit | 54182f67bf9e7855f8039559ce20ab9e | 34.756345 | 136 | 0.548978 | 5.60828 | false | false | false | false |
CoderST/DYZB | DYZB/DYZB/Class/Tools/STPageView/STPageView.swift | 1 | 2942 | //
// STPageView.swift
// STPageView
//
// Created by xiudou on 2016/12/5.
// Copyright © 2016年 CoderST. All rights reserved.
// 主要的View
import UIKit
class STPageView: UIView {
// MARK:- 定义属性
fileprivate var titles : [String]
fileprivate var childsVC : [UIViewController]
fileprivate weak var parentVC : UIViewController?
fileprivate var style : STPageViewStyle
fileprivate var titleView : STTitlesView!
fileprivate var titleViewParentView : Any?
// MARK:- 自定义构造函数
// frame : 给定的尺寸
// titles : 标题的内容数组
// childsVC : 对应标题控制器数组
// parentVC : 父类控制器
// style : 指定样式
// parentView : titleView被添加上的父类
init(frame: CGRect, titles : [String], childsVC : [UIViewController], parentVC : UIViewController, style : STPageViewStyle, titleViewParentView : Any?) {
// 初始化前一定要给属性赋值,不然会报super dont init 错误
self.titles = titles
self.parentVC = parentVC
self.childsVC = childsVC
self.style = style
self.titleViewParentView = titleViewParentView
super.init(frame: frame)
stupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension STPageView {
fileprivate func stupUI(){
// 1 创建TitlesView
stupTitleView()
// 2 创建内容View
setupContentView()
}
fileprivate func stupTitleView(){
let titleviewF = CGRect(x: 0, y: 0, width: frame.width, height: style.titleViewHeight)
titleView = STTitlesView(frame: titleviewF, titles: titles, style: style)
titleView.backgroundColor = style.titleViewBackgroundColor
if titleViewParentView == nil{
addSubview(titleView)
}else{
guard let parentView = titleViewParentView as? UIView else { return }
parentView.addSubview(titleView)
}
}
fileprivate func setupContentView(){
var contentViewY : CGFloat = 0
var contentViewH : CGFloat = 0
if titleViewParentView == nil{
contentViewY = style.titleViewHeight
contentViewH = frame.height - style.titleViewHeight
}else {
contentViewY = 0
contentViewH = frame.height
}
let contentViewF = CGRect(x: 0, y: contentViewY, width: frame.width, height: contentViewH)
guard let parentVC = parentVC else {
print("请检查传入的parentVC")
return
}
let contentView = STContentView(frame: contentViewF, childsVC: childsVC, parentVC: parentVC, style: style)
addSubview(contentView)
titleView.delegate = contentView
contentView.delegate = titleView
}
}
| mit | 647304a4bd9834aafc3903268e5c45d7 | 28.860215 | 157 | 0.621894 | 4.854895 | false | false | false | false |
aonawale/SwiftDataStore | Sources/SwiftDataStore/Store.swift | 1 | 9722 | //
// Store.swift
// SwiftDataStore
//
// Created by Ahmed Onawale on 2/4/17.
// Copyright © 2017 Ahmed Onawale. All rights reserved.
//
fileprivate enum CacheType: String {
case adapter
case serializer
case record
}
fileprivate struct LookupKey: Hashable {
let hashValue: Int
let cacheType: CacheType
let cacheName: String
init<T: Record>(cacheType: CacheType, type: T.Type) {
self.cacheType = cacheType
let name = String(describing: type).lowercased()
self.cacheName = "\(cacheType.rawValue):\(name)"
self.hashValue = cacheName.hashValue
}
}
fileprivate extension LookupKey {
static func ==(lhs: LookupKey, rhs: LookupKey) -> Bool {
return lhs.cacheName == rhs.cacheName
}
}
fileprivate final class InstanceCache {
private lazy var cache = [LookupKey: Cacheable]()
func get<T: Record>(cacheType: CacheType, type: T.Type) -> Cacheable {
let lookupKey = LookupKey(cacheType: cacheType, type: type)
var instance = cache[lookupKey]
if let instance = instance {
return instance
}
instance = cacheType == .adapter ? adapterInstance(for: type) : serializerInstance(for: type)
cache[lookupKey] = instance
return instance!
}
private func serializerInstance<T: Record>(for type: T.Type) -> Cacheable {
return type.serializerType.init()
}
private func adapterInstance<T: Record>(for type: T.Type) -> Cacheable {
return type.adapterType.init()
}
}
fileprivate extension Dictionary {
func get(_ key: Key) -> RecordSet {
guard let recordSet = self[key] as? RecordSet else { return RecordSet() }
return recordSet
}
}
fileprivate final class RecordManager {
private lazy var records = Dictionary<LookupKey, RecordSet>()
@discardableResult func load<T: Record>(_ record: T) -> T {
let type = type(of: record)
let lookupKey = LookupKey(cacheType: .record, type: type)
var recordSet = records.get(lookupKey)
recordSet.insert(record)
records[lookupKey] = recordSet
return record
}
func get<T: Record>(_ type: T.Type) -> [T] {
let lookupKey = LookupKey(cacheType: .record, type: type)
return records.get(lookupKey).elements as? [T] ?? []
}
func get<T: Record>(_ type: T.Type, id: ID) -> T? {
let lookupKey = LookupKey(cacheType: .record, type: type)
return records.get(lookupKey)[id] as? T
}
func remove<T: Record>(all type: T.Type) {
let lookupKey = LookupKey(cacheType: .record, type: type)
records[lookupKey] = RecordSet()
}
func remove<T: Record>(_ record: T) {
let type = type(of: record.self)
let lookupKey = LookupKey(cacheType: .record, type: type)
var recordSet = records.get(lookupKey)
recordSet.remove(record)
records[lookupKey] = recordSet
}
}
public final class Store {
public static let shared = Store()
private let recordManager = RecordManager()
private let instanceCache = InstanceCache()
// Disable initialization
private init() {}
@discardableResult func create<T: Record>(record: T, adapterOptions: AnyHashableJSON = [:],
completion: @escaping (T?, Error?) -> Void) -> URLSessionDataTask? {
let type = type(of: record)
let snapshot = Snapshot(record: record, adapterOptions: adapterOptions)
let _completion = handler(for: type, request: .create, completion: completion)
return adapter(for: type).create(type: type, store: self, snapshot: snapshot, completion: _completion)
}
@discardableResult func find<T: Record>(all type: T.Type, adapterOptions: AnyHashableJSON = [:],
completion: @escaping (RecordArray<T>?, Error?) -> Void) -> URLSessionDataTask? {
let snapshot = Snapshot(adapterOptions: adapterOptions)
let _completion = handler(for: type, request: .findAll, completion: completion)
return adapter(for: type).find(all: type, store: self, snapshot: snapshot, completion: _completion)
}
@discardableResult func find<T: Record>(record type: T.Type, id: ID, adapterOptions: AnyHashableJSON = [:],
completion: @escaping (T?, Error?) -> Void) -> URLSessionDataTask? {
let snapshot = Snapshot(adapterOptions: adapterOptions)
let _completion = handler(for: type, request: .find(id), completion: completion)
return adapter(for: type).find(type: type, id: id, store: self, snapshot: snapshot, completion: _completion)
}
private func handler<T: Record>(for type: T.Type, request: Request, completion: @escaping (RecordArray<T>?, Error?) -> Void) -> DataCompletion {
return { data, error in
guard let data = data, error == nil else { return completion(nil, error) }
do {
let records: RecordArray<T> = try self.serializer(for: type).normalize(response: data, for: type, request: request)
completion(try self.push(records: records), nil)
} catch {
completion(nil, error)
}
}
}
private func handler<T: Record>(for type: T.Type, request: Request, completion: @escaping (T?, Error?) -> Void) -> DataCompletion {
return { data, error in
guard let data = data, error == nil else { return completion(nil, error) }
do {
let record: T = try self.serializer(for: type).normalize(response: data, for: type, request: request)
completion(try self.push(record: record), nil)
} catch {
completion(nil, error)
}
}
}
@discardableResult func push<T: Record>(payload: [JSON], for type: T.Type) throws -> RecordArray<T> {
return RecordArray(try payload.map { try push(payload: $0, for: type) })
}
/**
Push a raw `JSON` payload into the store.
This method can be used both to push in brand new
records, as well as to update existing records.
- Parameters:
- payload: The payload to push ito the store.
- for: The type class of the payload being pushed.
- Returns: A record of the pushed payload.
```
```
*/
@discardableResult func push<T: Record>(payload: JSON, for type: T.Type) throws -> T {
let record = try serializer(for: type).normalize(type: type, hash: payload)
return try push(record: record)
}
/// Push a records into the store.
/// - Parameter record: The record to push ito the store.
/// - Returns: The pushed records.
@discardableResult func push<T: Record>(record: T) throws -> T {
guard record.id != nil else {
throw StoreError.invalidRecord("You cannot push a record without id into the store.")
}
return recordManager.load(record)
}
/// Push some records into the store.
/// - Parameter records: The records to push ito the store.
/// - Returns: A `RecordArray` of the pushed records.
@discardableResult func push<S: Sequence & Collection, T: Record>(records: S) throws -> RecordArray<T> where S.Iterator.Element == T {
let _records = try records.map { try self.push(record: $0) }
return RecordArray(_records)
}
/// This method returns an instance of serializer for the specified type.
/// - Parameter for: The record type class.
/// - Returns: An instance of serializer for the specified type.
func serializer<T: Record>(for type: T.Type) -> Serializer {
return instanceCache.get(cacheType: .serializer, type: type) as! Serializer
}
/// This method returns an instance of adapter for the specified type.
/// - Parameter for: The record type class.
/// - Returns: An instance of adapter for the specified type.
func adapter<T: Record>(for type: T.Type) -> Adapter {
return instanceCache.get(cacheType: .adapter, type: type) as! Adapter
}
/// This method will remove the records from the store.
/// - Parameter record: The record to remove.
func unload<T: Record>(record: T) {
recordManager.remove(record)
}
/// This method will remove all records of the given type from the store.
/// - Parameter all: The record type class.
func unload<T: Record>(all type: T.Type) {
recordManager.remove(all: type)
}
/// This method will synchronously return all records for the specified type
/// in the store. It will not make a request to fetch records from the server.
/// Multiple calls to this function with the same record type will always return
/// the same records.
/// - Parameter all: The record type class.
/// - Returns: A `RecordArray` of the specified type.
func peek<T: Record>(all type: T.Type) -> RecordArray<T> {
return RecordArray(recordManager.get(type))
}
/// This method will synchronously return the record with the specifed id from
/// the store if it's available, otherwise it will return `nil`. A record is
/// available if it has been fetched earlier, or pushed manually into the store.
/// - Complexity: O(1)
/// - Parameters:
/// - record: The record type class.
/// - id: The id of the record.
/// - Returns: A Record if it's available in the store, otherwise nil.
func peek<T: Record>(record type: T.Type, id: ID) -> T? {
return recordManager.get(type, id: id)
}
}
| bsd-2-clause | afd603d38b923cad826e79cd735035b0 | 39.169421 | 148 | 0.622055 | 4.368989 | false | false | false | false |
richeterre/SwiftGoal | SwiftGoal/Views/MatchesViewController.swift | 2 | 6975 | //
// MatchesViewController.swift
// SwiftGoal
//
// Created by Martin Richter on 10/05/15.
// Copyright (c) 2015 Martin Richter. All rights reserved.
//
import DZNEmptyDataSet
import ReactiveCocoa
import Result
class MatchesViewController: UITableViewController, DZNEmptyDataSetDelegate, DZNEmptyDataSetSource {
private let matchCellIdentifier = "MatchCell"
private let viewModel: MatchesViewModel
// MARK: - Lifecycle
init(viewModel: MatchesViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("NSCoding is not supported")
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
tableView.allowsSelection = false
tableView.allowsSelectionDuringEditing = true
tableView.rowHeight = 60
tableView.tableFooterView = UIView() // Prevent empty rows at bottom
tableView.emptyDataSetDelegate = self
tableView.emptyDataSetSource = self
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self,
action: #selector(refreshControlTriggered),
forControlEvents: .ValueChanged
)
tableView.registerClass(MatchCell.self, forCellReuseIdentifier: matchCellIdentifier)
self.navigationItem.leftBarButtonItem = self.editButtonItem()
self.navigationItem.rightBarButtonItem = UIBarButtonItem(
barButtonSystemItem: .Add,
target: self,
action: #selector(addMatchButtonTapped)
)
bindViewModel()
}
// MARK: - Bindings
private func bindViewModel() {
self.title = viewModel.title
viewModel.active <~ isActive()
viewModel.contentChangesSignal
.observeOn(UIScheduler())
.observeNext({ [weak self] changeset in
guard let tableView = self?.tableView else { return }
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths(changeset.deletions, withRowAnimation: .Automatic)
tableView.reloadRowsAtIndexPaths(changeset.modifications, withRowAnimation: .Automatic)
tableView.insertRowsAtIndexPaths(changeset.insertions, withRowAnimation: .Automatic)
tableView.endUpdates()
})
viewModel.isLoading.producer
.observeOn(UIScheduler())
.startWithNext({ [weak self] isLoading in
if !isLoading {
self?.refreshControl?.endRefreshing()
}
})
viewModel.alertMessageSignal
.observeOn(UIScheduler())
.observeNext({ [weak self] alertMessage in
let alertController = UIAlertController(
title: "Oops!",
message: alertMessage,
preferredStyle: .Alert
)
alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
self?.presentViewController(alertController, animated: true, completion: nil)
})
}
// MARK: User Interaction
func addMatchButtonTapped() {
let newMatchViewModel = viewModel.editViewModelForNewMatch()
let newMatchViewController = EditMatchViewController(viewModel: newMatchViewModel)
let newMatchNavigationController = UINavigationController(rootViewController: newMatchViewController)
self.presentViewController(newMatchNavigationController, animated: true, completion: nil)
}
func refreshControlTriggered() {
viewModel.refreshObserver.sendNext(())
}
// MARK: DZNEmptyDataSetDelegate
func emptyDataSetDidTapButton(scrollView: UIScrollView!) {
if let settingsURL = NSURL(string: UIApplicationOpenSettingsURLString) {
UIApplication.sharedApplication().openURL(settingsURL)
}
}
// MARK: DZNEmptyDataSetSource
func titleForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! {
let text = "No matches yet!"
let attributes = [
NSFontAttributeName: UIFont(name: "OpenSans-Semibold", size: 30)!
]
return NSAttributedString(string: text, attributes: attributes)
}
func descriptionForEmptyDataSet(scrollView: UIScrollView!) -> NSAttributedString! {
let text = "Check your storage settings, then tap the “+” button to get started."
let attributes = [
NSFontAttributeName: UIFont(name: "OpenSans", size: 20)!,
NSForegroundColorAttributeName: UIColor.lightGrayColor()
]
return NSAttributedString(string: text, attributes: attributes)
}
func buttonTitleForEmptyDataSet(scrollView: UIScrollView!, forState state: UIControlState) -> NSAttributedString! {
let text = "Open App Settings"
let attributes = [
NSFontAttributeName: UIFont(name: "OpenSans", size: 20)!,
NSForegroundColorAttributeName: (state == .Normal
? Color.primaryColor
: Color.lighterPrimaryColor)
]
return NSAttributedString(string: text, attributes: attributes)
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return viewModel.numberOfSections()
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfMatchesInSection(section)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(matchCellIdentifier, forIndexPath: indexPath) as! MatchCell
cell.homePlayersLabel.text = viewModel.homePlayersAtIndexPath(indexPath)
cell.resultLabel.text = viewModel.resultAtIndexPath(indexPath)
cell.awayPlayersLabel.text = viewModel.awayPlayersAtIndexPath(indexPath)
return cell
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
viewModel.deleteAction.apply(indexPath).start()
}
}
// MARK: UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let editMatchViewModel = viewModel.editViewModelForMatchAtIndexPath(indexPath)
let editMatchViewController = EditMatchViewController(viewModel: editMatchViewModel)
let editMatchNavigationController = UINavigationController(rootViewController: editMatchViewController)
self.presentViewController(editMatchNavigationController, animated: true, completion: nil)
}
}
| mit | 2ab07726148e050dcc6c9bee2f74348c | 36.079787 | 157 | 0.678525 | 5.983691 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/InputBar/Emoji/RecentlyUsedEmojis.swift | 1 | 2766 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
final class RecentlyUsedEmojiSection: NSObject, EmojiSection {
let type: EmojiSectionType = .recent
private(set) var emoji = [Emoji]()
private let backing: NSMutableOrderedSet
private let capacity: Int
init(capacity: Int, elements: [Emoji] = []) {
self.capacity = capacity
self.backing = NSMutableOrderedSet(array: elements)
super.init()
updateContent()
}
@discardableResult func register(_ element: Emoji) -> Bool {
switch backing.index(of: element) {
case 0: return false // No update neccessary if the first element is already the new one
case NSNotFound: backing.insert(element, at: 0)
case let idx: backing.moveObjects(at: IndexSet(integer: idx), to: 0)
}
updateContent()
return true
}
private func updateContent() {
defer { emoji = backing.array as! [Emoji] }
guard backing.count > capacity else { return }
backing.removeObjects(at: IndexSet(integersIn: capacity..<backing.count))
}
}
final class RecentlyUsedEmojiPeristenceCoordinator {
static func loadOrCreate() -> RecentlyUsedEmojiSection {
return loadFromDisk() ?? RecentlyUsedEmojiSection(capacity: 15)
}
static func store(_ section: RecentlyUsedEmojiSection) {
guard let emojiUrl = url,
let directoryUrl = URL.directoryURL(directory) else { return }
FileManager.default.createAndProtectDirectory(at: directoryUrl)
(section.emoji as NSArray).write(to: emojiUrl, atomically: true)
}
private static func loadFromDisk() -> RecentlyUsedEmojiSection? {
guard let emojiUrl = url else { return nil }
guard let emoji = NSArray(contentsOf: emojiUrl) as? [Emoji] else { return nil }
return RecentlyUsedEmojiSection(capacity: 15, elements: emoji)
}
private static var directory: String = "emoji"
private static var url: URL? = {
return URL.directoryURL(directory)?.appendingPathComponent("recently_used.plist")
}()
}
| gpl-3.0 | da00e32a0e78bd25d57ffa7e17015ca7 | 33.148148 | 96 | 0.686551 | 4.633166 | false | false | false | false |
nixzhu/MonkeyKing | Sources/MonkeyKing/AnyActivity.swift | 1 | 1257 |
import UIKit
open class AnyActivity: UIActivity {
private let type: UIActivity.ActivityType
private let title: String
private let image: UIImage
private let message: MonkeyKing.Message
private let completionHandler: MonkeyKing.DeliverCompletionHandler
public init(type: UIActivity.ActivityType, title: String, image: UIImage, message: MonkeyKing.Message, completionHandler: @escaping MonkeyKing.DeliverCompletionHandler) {
self.type = type
self.title = title
self.image = image
self.message = message
self.completionHandler = completionHandler
super.init()
}
open override class var activityCategory: UIActivity.Category {
return .share
}
open override var activityType: UIActivity.ActivityType? {
return type
}
open override var activityTitle: String? {
return title
}
open override var activityImage: UIImage? {
return image
}
open override func canPerform(withActivityItems activityItems: [Any]) -> Bool {
return message.canBeDelivered
}
open override func perform() {
MonkeyKing.deliver(message, completionHandler: completionHandler)
activityDidFinish(true)
}
}
| mit | 38ebf2417e636f3a19928df21bab5e34 | 26.326087 | 174 | 0.691329 | 5.39485 | false | false | false | false |
loganSims/wsdot-ios-app | wsdot/CameraPageContainerViewController.swift | 1 | 3816 | //
// CameraPageContainerViewController.swift
// WSDOT
//
// Copyright (c) 2016 Washington State Department of Transportation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
import UIKit
import GoogleMobileAds
import EasyTipView
// Container for the CameraPageVV so we can display an ad banner below it
class CameraPageContainerViewController: UIViewController, GADBannerViewDelegate {
@IBOutlet weak var bannerView: DFPBannerView!
var adTarget: String = "traffic"
@IBOutlet weak var rightTipViewAnchor: UIView!
@IBOutlet weak var leftTipViewAnchor: UIView!
var tipView = EasyTipView(text: "")
var cameras: [CameraItem] = []
var selectedCameraIndex = 0
override func viewDidLoad() {
super.viewDidLoad()
bannerView.adUnitID = ApiKeys.getAdId()
bannerView.adSize = getFullWidthAdaptiveAdSize()
bannerView.rootViewController = self
let request = DFPRequest()
request.customTargeting = ["wsdotapp":adTarget]
bannerView.load(request)
bannerView.delegate = self
}
// Pass data along to the embedded vc
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let vc = segue.destination as? CameraPageViewController, segue.identifier == "EmbedSegue" {
vc.cameras = self.cameras
vc.selectedCameraIndex = self.selectedCameraIndex
vc.containingVC = self
}
}
func dismissTipView(){
tipView.dismiss()
}
}
extension CameraPageContainerViewController: EasyTipViewDelegate {
public func easyTipViewDidDismiss(_ tipView: EasyTipView) {
UserDefaults.standard.set(true, forKey: UserDefaultsKeys.hasSeenCameraSwipeTipView)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
tipView.dismiss()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if ((cameras.count > 1) && (!UserDefaults.standard.bool(forKey: UserDefaultsKeys.hasSeenCameraSwipeTipView) && !UIAccessibility.isVoiceOverRunning)){
var preferences = EasyTipView.Preferences()
preferences.drawing.font = EasyTipView.globalPreferences.drawing.font
preferences.drawing.foregroundColor = EasyTipView.globalPreferences.drawing.foregroundColor
preferences.drawing.backgroundColor = EasyTipView.globalPreferences.drawing.backgroundColor
if (selectedCameraIndex != cameras.count - 1) {
preferences.drawing.arrowPosition = EasyTipView.ArrowPosition.right
tipView = EasyTipView(text: "Swipe to view your other cameras.", preferences: preferences, delegate: self)
tipView.show(forView: self.rightTipViewAnchor)
} else {
preferences.drawing.arrowPosition = EasyTipView.ArrowPosition.left
tipView = EasyTipView(text: "Swipe to view your other cameras.", preferences: preferences, delegate: self)
tipView.show(forView: self.leftTipViewAnchor)
}
}
}
}
| gpl-3.0 | 1e7c589e37d5d6363af5e0e99b2dcf48 | 37.545455 | 157 | 0.68239 | 5.094793 | false | false | false | false |
RemyDCF/tpg-offline | tpg offline/JSON Models/BusRoute.swift | 1 | 3251 | //
// Thermometer.swift
// tpgoffline
//
// Created by Rémy Da Costa Faro on 14/06/2017.
// Copyright © 2018 Rémy Da Costa Faro DA COSTA FARO. All rights reserved.
//
import UIKit
struct BusRouteGroup: Codable {
var steps: [BusRoute]
var lineCode: String
var destination: String
public init(steps: [BusRoute], lineCode: String, destination: String) {
self.steps = steps
self.lineCode = lineCode
self.destination = destination
if !(self.steps.isEmpty) {
self.steps[0].first = true
self.steps[steps.endIndex - 1].last = true
}
}
enum CodingKeys: String, CodingKey {
case steps
case lineCode
case destination = "destinationName"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let steps = try container.decode([BusRoute].self, forKey: .steps)
let lineCode = try container.decode(String.self, forKey: .lineCode)
let destination = try container.decode(String.self, forKey: .destination)
self.init(steps: steps, lineCode: lineCode, destination: destination)
}
}
struct BusRoute: Codable {
struct Stop: Codable {
let code: String
let name: String
let connections: [Connection]
enum CodingKeys: String, CodingKey { // swiftlint:disable:this nesting
case code = "stopCode"
case name = "stopName"
case connections
}
static func == (lhd: BusRoute.Stop, rhd: BusRoute.Stop) -> Bool {
return lhd.code == rhd.code && lhd.name == rhd.code
}
}
enum Reliability: String, Codable {
case reliable = "F"
case theoretical = "T"
}
var stop: BusRoute.Stop
var timestamp: Date
var arrivalTime: String
var first: Bool
var last: Bool
var reliability: Reliability
public init(stop: BusRoute.Stop,
arrivalTime: String,
timestamp: Date,
first: Bool,
last: Bool,
reliability: Reliability) {
self.stop = stop
self.timestamp = timestamp
self.first = first
self.last = last
self.arrivalTime = arrivalTime
self.reliability = reliability
if Int(self.arrivalTime) ?? 0 > 60 {
let hour = (Int(self.arrivalTime) ?? 0) / 60
let minutes = (Int(self.arrivalTime) ?? 0) % 60
self.arrivalTime = "\(hour)h\(minutes < 10 ? "0\(minutes)" : "\(minutes)")"
}
}
enum CodingKeys: String, CodingKey {
case stop
case timestamp
case arrivalTime
case reliability
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let stop = try container.decode(BusRoute.Stop.self, forKey: .stop)
let timestamp = try container.decode(Date.self, forKey: .timestamp)
let reliability = (try? container.decode(Reliability.self, forKey: .reliability))
?? .reliable
let arrivalTime: String
do {
arrivalTime = try container.decode(String.self, forKey: .arrivalTime)
} catch {
arrivalTime = ""
}
let first = false
let last = false
self.init(stop: stop,
arrivalTime: arrivalTime,
timestamp: timestamp,
first: first,
last: last,
reliability: reliability)
}
}
| mit | 524f3253be18df9ae51778edf02b75ea | 26.066667 | 85 | 0.639778 | 4.070175 | false | false | false | false |
BrandonMA/SwifterUI | SwifterUI/SwifterUI/UILibrary/DataManagers/SFDataManager.swift | 1 | 9019 | //
// SFDataManager.swift
// SwifterUI
//
// Created by brandon maldonado alonso on 8/22/18.
// Copyright © 2018 Brandon Maldonado Alonso. All rights reserved.
//
import UIKit
import DeepDiff
public protocol SFDataManagerDelegate: class {
func insertSection(at index: Int)
func moveSection(from: Int, to: Int)
func deleteSection(at index: Int)
func updateSection(at index: Int)
func insertItem(at indexPath: IndexPath)
func moveItem(from: IndexPath, to: IndexPath)
func deleteItem(at indexPath: IndexPath)
func updateItem(at index: IndexPath)
func updateSection<DataType: SFDataType>(with changes: [Change<DataType>], index: Int)
func forceUpdate()
}
open class SFDataManager<DataType: SFDataType> {
// MARK: - Instance Properties
public typealias ContentType = [SFDataSection<DataType>]
private var iterator: Int = 0
/**
Main storage of data, you should not modify it directly.
*/
public final var data: ContentType = []
public final weak var delegate: SFDataManagerDelegate?
// MARK: - Initializers
public init() {}
// MARK: - Instace Methods
open func forceUpdate(dataSections: ContentType) {
data = dataSections
delegate?.forceUpdate()
}
open func forceUpdate(data: [[DataType]]) {
self.data = data.compactMap({ return SFDataSection<DataType>(content: $0) })
delegate?.forceUpdate()
}
@discardableResult
public final func update(dataSections: ContentType) -> [[Change<DataType>]] {
let changes = dataSections.enumerated().map { (index, dataSection) -> [Change<DataType>] in
return self.update(dataSection: dataSection, index: index)
}
return changes
}
@discardableResult
public final func update(data: [[DataType]]) -> [[Change<DataType>]] {
let changes = data.enumerated().map { (index, dataSection) -> [Change<DataType>] in
let dataSection = SFDataSection<DataType>(content: dataSection, identifier: "")
return self.update(dataSection: dataSection, index: index)
}
return changes
}
@discardableResult
private func update(dataSection: SFDataSection<DataType>, index: Int?) -> [Change<DataType>] {
var changes: [Change<DataType>] = []
if let index = index, self.data.count > index {
let oldDataSection = self.data[index]
changes = diff(old: oldDataSection.content, new: dataSection.content)
self.data[index] = dataSection
delegate?.updateSection(with: changes, index: index)
} else {
insertSection(dataSection, at: nextLastSectionIndex)
}
return changes
}
}
// MARK: - Collection && IteratorProtocol
extension SFDataManager: Collection, IteratorProtocol {
public typealias Element = ContentType.Element
public typealias Index = ContentType.Index
public var startIndex: Index { return data.startIndex }
public var endIndex: Index { return data.endIndex }
public subscript(index: Index) -> ContentType.Element {
return data[index]
}
public func index(after i: Index) -> Index {
return data.index(after: i)
}
public func next() -> SFDataSection<DataType>? {
if iterator == count {
return nil
} else {
defer { iterator += 1 }
return data[iterator]
}
}
public func removeAll() {
data.removeAll()
delegate?.forceUpdate()
}
}
// MARK: - Computed Properties
public extension SFDataManager {
final var flatData: [DataType] { return data.flatMap { return $0.content } }
var lastSectionIndex: Int { return count == 0 ? 0 : count - 1 }
var nextLastSectionIndex: Int { return count == 0 ? 0 : count }
var lastItemIndex: IndexPath {
if count == 0 {
return IndexPath(item: 0, section: 0)
} else {
let lastSection = data[lastSectionIndex]
let lastItemIndex = lastSection.count == 0 ? 0 : lastSection.count - 1
return IndexPath(item: lastItemIndex, section: lastSectionIndex)
}
}
var nextLastItemIndex: IndexPath {
if count == 0 {
return IndexPath(item: 0, section: 0)
} else {
var nextLastItemIndex = lastItemIndex
nextLastItemIndex.item += 1
return nextLastItemIndex
}
}
var last: SFDataSection<DataType>? {
return data.last
}
var lastItem: DataType? {
if isEmpty {
return nil
} else {
let item = data[lastItemIndex.section].content[lastItemIndex.row]
return item
}
}
}
// MARK: - Sections
public extension SFDataManager {
func insertSection(_ section: SFDataSection<DataType>, at index: Int? = nil) {
let index = index ?? nextLastSectionIndex
data.insert(section, at: index)
delegate?.insertSection(at: index)
}
func moveSection(from: Int, to: Int) {
data.move(from: from, to: to)
delegate?.moveSection(from: from, to: to)
}
func deleteSection(at index: Int) {
data.remove(at: index)
delegate?.deleteSection(at: index)
}
func updateSection(_ section: SFDataSection<DataType>? = nil, at index: Int) {
if let section = section {
data[index] = section
}
delegate?.updateSection(at: index)
}
func getSection(where predicate: (SFDataSection<DataType>) -> Bool) -> SFDataSection<DataType>? {
for section in self {
if predicate(section) {
return section
}
}
return nil
}
func contains(section: SFDataSection<DataType>) -> Bool {
return contains(where: { (currentSection) -> Bool in
return currentSection.identifier == section.identifier && currentSection.content == section.content
})
}
}
// MARK: - Items
public extension SFDataManager {
func insertItem(_ item: DataType, at indexPath: IndexPath? = nil) {
let indexPath = indexPath ?? nextLastItemIndex
if indexPath.section > self.lastSectionIndex || count == 0 {
insertSection(SFDataSection<DataType>(), at: lastSectionIndex)
}
data[indexPath.section].content.insert(item, at: indexPath.row)
delegate?.insertItem(at: indexPath)
}
func moveItem(from: IndexPath, to: IndexPath) {
let item = data[from.section].content[from.item] // Get item to move
data[from.section].content.remove(at: from.item) // Remove it from old indexPath
data[to.section].content.insert(item, at: to.item) // Insert it to new indexPath
delegate?.moveItem(from: from, to: to)
}
func deleteItem(at indexPath: IndexPath) {
let section = data[indexPath.section]
if section.count == 1 {
deleteSection(at: indexPath.section)
} else {
data[indexPath.section].content.remove(at: indexPath.item)
delegate?.deleteItem(at: indexPath)
}
}
func updateItem(_ item: DataType? = nil, at indexPath: IndexPath) {
if let item = item {
data[indexPath.section].content[indexPath.row] = item
}
delegate?.updateItem(at: indexPath)
}
func moveItem(_ item: DataType, to: IndexPath) {
guard let indexPath = getIndex(of: item) else { return }
moveItem(from: indexPath, to: to)
}
func deleteItem(_ item: DataType) {
guard let indexPath = getIndex(of: item) else { return }
let section = [indexPath.section]
if section.count == 1 {
self.deleteSection(at: indexPath.section)
} else {
self.deleteItem(at: indexPath)
}
}
func updateItem(_ item: DataType) {
guard let indexPath = getIndex(of: item) else { return }
updateItem(item, at: indexPath)
}
func getIndex(of item: DataType) -> IndexPath? {
for (sectionIndex, section) in enumerated() {
for (itemIndex, sectionItem) in section.enumerated() where item == sectionItem {
return IndexPath(item: itemIndex, section: sectionIndex)
}
}
return nil
}
func getItem(where predicate: (DataType) -> Bool) -> DataType? {
for item in flatData {
if predicate(item) {
return item
}
}
return nil
}
func getItem(at indexPath: IndexPath) -> DataType {
return data[indexPath.section].content[indexPath.row]
}
func contains(item: DataType) -> Bool {
return contains { return $0.contains(item) }
}
}
| mit | a7159777b6da672e29efc312e9a34784 | 29.160535 | 111 | 0.596917 | 4.726415 | false | false | false | false |
machelix/SwiftySideMenu | Demo/Timeline/Timeline/AppDelegate.swift | 5 | 2637 | //
// AppDelegate.swift
// Timeline
//
// Created by Hossam Ghareeb on 8/14/15.
// Copyright © 2015 Hossam Ghareeb. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let rootVC = self.window?.rootViewController as! SwiftySideMenuViewController;
let centerVC = rootVC.storyboard?.instantiateViewControllerWithIdentifier("Center");
let leftVC = rootVC.storyboard?.instantiateViewControllerWithIdentifier("Left");
rootVC.centerViewController = centerVC;
rootVC.leftViewController = leftVC;
rootVC.centerEndScale = 0.4;
rootVC.leftSpringAnimationSpeed = 20;
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:.
}
}
| mit | f2c1ed93bcd061ef454428b4040d8433 | 45.245614 | 285 | 0.73786 | 5.656652 | false | false | false | false |
GregoryMaks/RingLabsTestTask | RingTask/Classes/Flow/RedditFlow/UI/RedditTopListingCell.swift | 1 | 3084 | //
// RedditTopListingCell.swift
// RingTask
//
// Created by Gregory on 8/13/17.
// Copyright © 2017 Gregory M. All rights reserved.
//
import UIKit
class RedditTopListingCell: UITableViewCell, NibLoadableView, Reusable {
private struct Constants {
static func noThumbnailImage() -> UIImage? {
return UIImage(named: "NoThumbnail")
}
}
// MARK: - Outlets
@IBOutlet private weak var thumbnailImageView: UIImageView!
@IBOutlet private weak var imageActivityIndicator: UIActivityIndicatorView!
@IBOutlet private weak var titleLabel: UILabel!
@IBOutlet private weak var authorDateLabel: UILabel!
@IBOutlet private weak var commentsLabel: UILabel!
// MARK: - Private properties
private var imageLoadingDataTask: URLSessionDataTask?
private var failedToLoadImageOnce = false
// MARK: - Public properties
var model: RedditPostServerModel? {
didSet {
updateContent()
}
}
// MARK: - Lifecycle
override func prepareForReuse() {
model = nil
cancelImageLoading()
failedToLoadImageOnce = false
}
// MARK: - Public methods
func startLoadingImage(imageLoadingService: ImageLoadingServiceProtocol) {
guard let imageUrl = model?.thumbnailUrl, failedToLoadImageOnce == false else {
return
}
imageActivityIndicator.startAnimating()
imageLoadingDataTask = imageLoadingService.loadImage(for: imageUrl) { [weak self] result in
guard let `self` = self else { return }
switch result {
case .success(let image):
self.thumbnailImageView.image = image
case .failure(_):
self.thumbnailImageView.image = Constants.noThumbnailImage()
self.failedToLoadImageOnce = true
}
self.imageActivityIndicator.stopAnimating()
}
}
func cancelImageLoading() {
guard let imageLoadingDataTask = imageLoadingDataTask else {
return
}
imageActivityIndicator.stopAnimating()
imageLoadingDataTask.cancel()
failedToLoadImageOnce = false
}
// MARK: - Private methods
private func updateContent() {
guard let model = model else {
thumbnailImageView.image = nil
imageActivityIndicator.stopAnimating()
titleLabel.text = nil
authorDateLabel.text = nil
commentsLabel.text = nil
return
}
titleLabel.text = model.title
authorDateLabel.text = AuthorDateFormatter().stringValue(forAuthor: model.author, date: model.createdAt)
commentsLabel.text = CommentFormatter().commentString(fromCommentCount: model.commentsCount)
if model.thumbnailUrl == nil {
thumbnailImageView.image = Constants.noThumbnailImage()
}
}
}
| mit | 1287cf77db6704c444b4f9015bb5ef6a | 27.546296 | 112 | 0.607525 | 5.795113 | false | false | false | false |
iWeslie/Ant | Ant/Ant/LunTan/Detials/Controller/SecondHandDVC.swift | 1 | 8540 | //
// SecondHandDVC.swift
// Ant
//
// Created by Weslie on 2017/8/4.
// Copyright © 2017年 LiuXinQiang. All rights reserved.
//
import UIKit
class SecondHandDVC: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView?
var modelInfo: LunTanDetialModel?
override func viewDidLoad() {
super.viewDidLoad()
loadDetialTableView()
let view = Menu()
self.tabBarController?.tabBar.isHidden = true
view.frame = CGRect(x: 0, y: screenHeight - 124, width: screenWidth, height: 60)
self.view.addSubview(view)
}
func loadDetialTableView() {
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height - 60)
self.tableView = UITableView(frame: frame, style: .grouped)
self.tableView?.delegate = self
self.tableView?.dataSource = self
self.tableView?.backgroundColor = UIColor.init(white: 0.9, alpha: 1)
self.tableView?.separatorStyle = .singleLine
tableView?.register(UINib(nibName: "SecondHandBasicInfo", bundle: nil), forCellReuseIdentifier: "secondHandBasicInfo")
tableView?.register(UINib(nibName: "SecondHandDetial", bundle: nil), forCellReuseIdentifier: "secondHandDetial")
tableView?.register(UINib(nibName: "LocationInfo", bundle: nil), forCellReuseIdentifier: "locationInfo")
tableView?.register(UINib(nibName: "DetialControduction", bundle: nil), forCellReuseIdentifier: "detialControduction")
tableView?.register(UINib(nibName: "ConnactOptions", bundle: nil), forCellReuseIdentifier: "connactOptions")
tableView?.register(UINib(nibName: "MessageHeader", bundle: nil), forCellReuseIdentifier: "messageHeader")
tableView?.register(UINib(nibName: "MessagesCell", bundle: nil), forCellReuseIdentifier: "messagesCell")
tableView?.separatorStyle = .singleLine
self.view.addSubview(tableView!)
}
func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0: return 3
case 2: return 5
case 4: return 10
default: return 1
}
}
func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
switch section {
case 0:
let frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.width * 0.6)
let urls = [
"http://img3.cache.netease.com/photo/0009/2016-05-27/BO1HVHOV0AI20009.jpg",
"http://img3.cache.netease.com/photo/0009/2016-05-27/BO1HVIJ30AI20009.png",
"http://img5.cache.netease.com/photo/0009/2016-05-27/BO1HVLIM0AI20009.jpg",
"http://img6.cache.netease.com/photo/0009/2016-05-27/BO1HVJCD0AI20009.jpg",
"http://img2.cache.netease.com/photo/0009/2016-05-27/BO1HVPUT0AI20009.png"
]
var urlArray: [URL] = [URL]()
for str in urls {
let url = URL(string: str)
urlArray.append(url!)
}
return LoopView(images: urlArray, frame: frame, isAutoScroll: true)
case 1:
let detialHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView
detialHeader?.DetialHeaderLabel.text = "详情介绍"
return detialHeader
case 2:
let connactHeader = Bundle.main.loadNibNamed("DetialHeaderView", owner: nil, options: nil)?.first as? DetialHeaderView
connactHeader?.DetialHeaderLabel.text = "联系人方式"
return connactHeader
default:
return nil
}
}
func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if section == 2 {
return Bundle.main.loadNibNamed("Share", owner: nil, options: nil)?.first as? UIView
} else {
return nil
}
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
switch section {
case 0:
return UIScreen.main.bounds.width * 0.6
case 1:
return 30
case 2:
return 30
case 3:
return 10
case 4:
return 0.00001
default:
return 0.00001
}
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if section == 2 {
return 140
} else {
return 0.00001
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell: UITableViewCell?
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: cell = tableView.dequeueReusableCell(withIdentifier: "secondHandBasicInfo")
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets.zero
}
case 1: cell = tableView.dequeueReusableCell(withIdentifier: "secondHandDetial")
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets.zero
}
case 2: cell = tableView.dequeueReusableCell(withIdentifier: "locationInfo")
default: break
}
case 1: cell = tableView.dequeueReusableCell(withIdentifier: "detialControduction")
case 2:
let connactoptions = tableView.dequeueReusableCell(withIdentifier: "connactOptions") as! ConnactOptions
// guard modelInfo.con else {
// <#statements#>
// }
if let contact = modelInfo?.connactDict[indexPath.row] {
if let key = contact.first?.key{
connactoptions.con_Ways.text = key
}
}
if let value = modelInfo?.connactDict[indexPath.row].first?.value {
connactoptions.con_Detial.text = value
}
switch modelInfo?.connactDict[indexPath.row].first?.key {
case "联系人"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_profile")
case "电话"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_phone")
case "微信"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_wechat")
case "QQ"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_qq")
case "邮箱"?:
connactoptions.con_Image.image = #imageLiteral(resourceName: "luntan_detial_icon_connact_email")
default:
break
}
cell = connactoptions
if (cell?.responds(to: #selector(setter: UITableViewCell.separatorInset)))! {
cell?.separatorInset = UIEdgeInsets(top: 0, left: 50, bottom: 0, right: 0)
}
case 3: cell = tableView.dequeueReusableCell(withIdentifier: "messageHeader")
case 4: cell = tableView.dequeueReusableCell(withIdentifier: "messagesCell")
default: break
}
return cell!
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
switch indexPath.section {
case 0:
switch indexPath.row {
case 0: return 60
case 1: return 90
case 2: return 40
default: return 20
}
case 1:
return detialHeight + 10
case 2:
return 50
case 3:
return 40
case 4:
return 120
default:
return 20
}
}
}
| apache-2.0 | 0b6fc4c4d2879cf47663df0e6d2e3318 | 36.122271 | 130 | 0.57405 | 4.916715 | false | false | false | false |
dmitrinesterenko/Phony | Phony/Recorder.swift | 1 | 2296 | //
// Recorder.swift
// Phony
//
// Created by Dmitri Nesterenko on 5/2/15.
// Copyright (c) 2015 Dmitri Nesterenko. All rights reserved.
//
import Foundation
import AVFoundation
// TODO: Singleton class
class Recorder{
var audioRecorder:AVAudioRecorder!
var recorded: Array<NSURL> = []
var durationToRecord: NSTimeInterval = 0.0
//MARK: Actions
func record(duration: NSTimeInterval){
//TODO: Think about moving most of this into init()
var audioSession:AVAudioSession = AVAudioSession.sharedInstance()
durationToRecord = duration
audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, error: nil)
audioSession.setActive(true, error: nil)
var recordSettings = [
AVFormatIDKey:kAudioFormatAppleIMA4,
AVSampleRateKey:44100.0,
AVNumberOfChannelsKey:2,
AVEncoderBitRateKey:12800,
AVLinearPCMBitDepthKey:16,
AVEncoderAudioQualityKey:AVAudioQuality.Max.rawValue
]
//TODO: This is to also send over the recording as a record to an external DB
var id = IdManager.generateId()
var url = FileManager.recordingStoragePath(id)
//TODO: This has to stay inside record() to make user a new recording is created each time
//TODO: This can be the way to refactor the initializer but initialize a new recording each time
//audioRecorder.url
var error: NSError?
audioRecorder = AVAudioRecorder(
URL:url,
settings: recordSettings as [NSObject:AnyObject],
error: &error)
if let e = error {
println(e.localizedDescription)
} else {
recorded.append(url)
audioRecorder.record()
Conductor.playAfter(duration){
self.stop()
}
}
}
var currentTime : NSTimeInterval{
return audioRecorder.currentTime
}
func stop(){
if audioRecorder.recording {
audioRecorder.stop()
Log.debug("Recording stopped")
}
}
func recording() -> Bool {
return audioRecorder.recording
}
}
| gpl-2.0 | bb2374930700456bf6b5a87752a6cfed | 26.333333 | 104 | 0.597997 | 5.351981 | false | false | false | false |
dekatotoro/FluxWithRxSwiftSample | Pods/APIKit/Sources/APIKit/BodyParameters/Data+InputStream.swift | 4 | 918 | import Foundation
enum InputStreamError: Error {
case invalidDataCapacity(Int)
case unreadableStream(InputStream)
}
extension Data {
init(inputStream: InputStream, capacity: Int = Int(UInt16.max)) throws {
var data = Data(capacity: capacity)
let bufferSize = Swift.min(Int(UInt16.max), capacity)
let buffer = UnsafeMutablePointer<UInt8>.allocate(capacity: bufferSize)
var readSize: Int
repeat {
readSize = inputStream.read(buffer, maxLength: bufferSize)
switch readSize {
case let x where x > 0:
data.append(buffer, count: readSize)
case let x where x < 0:
throw InputStreamError.unreadableStream(inputStream)
default:
break
}
} while readSize > 0
buffer.deallocate(capacity: bufferSize)
self.init(data)
}
}
| mit | b11b334a4995d648271ec1adad0fe234 | 24.5 | 79 | 0.604575 | 4.806283 | false | false | false | false |
KeithPiTsui/Pavers | Pavers/Sources/CryptoSwift/Blowfish.swift | 2 | 23887 | //
// Blowfish.swift
// CryptoSwift
//
// Copyright (C) 2014-2017 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.
//
// https://en.wikipedia.org/wiki/Blowfish_(cipher)
// Based on Paul Kocher implementation
//
public final class Blowfish {
public enum Error: Swift.Error {
/// Data padding is required
case dataPaddingRequired
/// Invalid key or IV
case invalidKeyOrInitializationVector
/// Invalid IV
case invalidInitializationVector
}
public static let blockSize: Int = 8 // 64 bit
fileprivate let blockMode: BlockMode
fileprivate let padding: Padding
private var decryptWorker: BlockModeWorker!
private var encryptWorker: BlockModeWorker!
private let N = 16 // rounds
private var P: Array<UInt32>
private var S: Array<Array<UInt32>>
private let origP: Array<UInt32> = [
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822,
0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377,
0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5,
0xb5470917, 0x9216d5d9, 0x8979fb1b,
]
private let origS: Array<Array<UInt32>> = [
[
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
],
[
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
],
[
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
],
[
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6,
],
]
public init(key: Array<UInt8>, blockMode: BlockMode = .CBC(iv: Array<UInt8>(repeating: 0, count: Blowfish.blockSize)), padding: Padding) throws {
precondition(key.count >= 5 && key.count <= 56)
self.blockMode = blockMode
self.padding = padding
S = origS
P = origP
expandKey(key: key)
try setupBlockModeWorkers()
}
private func setupBlockModeWorkers() throws {
encryptWorker = try blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: encrypt)
switch blockMode {
case .CFB, .OFB, .CTR:
decryptWorker = try blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: encrypt)
default:
decryptWorker = try blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: decrypt)
}
}
private func reset() {
S = origS
P = origP
// todo expand key
}
private func expandKey(key: Array<UInt8>) {
var j = 0
for i in 0..<(N + 2) {
var data: UInt32 = 0x0
for _ in 0..<4 {
data = (data << 8) | UInt32(key[j])
j += 1
if j >= key.count {
j = 0
}
}
P[i] ^= data
}
var datal: UInt32 = 0
var datar: UInt32 = 0
for i in stride(from: 0, to: N + 2, by: 2) {
encryptBlowfishBlock(l: &datal, r: &datar)
P[i] = datal
P[i + 1] = datar
}
for i in 0..<4 {
for j in stride(from: 0, to: 256, by: 2) {
encryptBlowfishBlock(l: &datal, r: &datar)
S[i][j] = datal
S[i][j + 1] = datar
}
}
}
fileprivate func encrypt(block: ArraySlice<UInt8>) -> Array<UInt8>? {
var result = Array<UInt8>()
var l = UInt32(bytes: block[block.startIndex..<block.startIndex.advanced(by: 4)])
var r = UInt32(bytes: block[block.startIndex.advanced(by: 4)..<block.startIndex.advanced(by: 8)])
encryptBlowfishBlock(l: &l, r: &r)
// because everything is too complex to be solved in reasonable time o_O
result += [
UInt8((l >> 24) & 0xff),
UInt8((l >> 16) & 0xff),
]
result += [
UInt8((l >> 8) & 0xff),
UInt8((l >> 0) & 0xff),
]
result += [
UInt8((r >> 24) & 0xff),
UInt8((r >> 16) & 0xff),
]
result += [
UInt8((r >> 8) & 0xff),
UInt8((r >> 0) & 0xff),
]
return result
}
fileprivate func decrypt(block: ArraySlice<UInt8>) -> Array<UInt8>? {
var result = Array<UInt8>()
var l = UInt32(bytes: block[block.startIndex..<block.startIndex.advanced(by: 4)])
var r = UInt32(bytes: block[block.startIndex.advanced(by: 4)..<block.startIndex.advanced(by: 8)])
decryptBlowfishBlock(l: &l, r: &r)
// because everything is too complex to be solved in reasonable time o_O
result += [
UInt8((l >> 24) & 0xff),
UInt8((l >> 16) & 0xff),
]
result += [
UInt8((l >> 8) & 0xff),
UInt8((l >> 0) & 0xff),
]
result += [
UInt8((r >> 24) & 0xff),
UInt8((r >> 16) & 0xff),
]
result += [
UInt8((r >> 8) & 0xff),
UInt8((r >> 0) & 0xff),
]
return result
}
/// Encrypts the 8-byte padded buffer
///
/// - Parameters:
/// - l: left half
/// - r: right half
fileprivate func encryptBlowfishBlock(l: inout UInt32, r: inout UInt32) {
var Xl = l
var Xr = r
for i in 0..<N {
Xl = Xl ^ P[i]
Xr = F(x: Xl) ^ Xr
(Xl, Xr) = (Xr, Xl)
}
(Xl, Xr) = (Xr, Xl)
Xr = Xr ^ P[self.N]
Xl = Xl ^ P[self.N + 1]
l = Xl
r = Xr
}
/// Decrypts the 8-byte padded buffer
///
/// - Parameters:
/// - l: left half
/// - r: right half
fileprivate func decryptBlowfishBlock(l: inout UInt32, r: inout UInt32) {
var Xl = l
var Xr = r
for i in (2...N + 1).reversed() {
Xl = Xl ^ P[i]
Xr = F(x: Xl) ^ Xr
(Xl, Xr) = (Xr, Xl)
}
(Xl, Xr) = (Xr, Xl)
Xr = Xr ^ P[1]
Xl = Xl ^ P[0]
l = Xl
r = Xr
}
private func F(x: UInt32) -> UInt32 {
let f1 = S[0][Int(x >> 24) & 0xff]
let f2 = S[1][Int(x >> 16) & 0xff]
let f3 = S[2][Int(x >> 8) & 0xff]
let f4 = S[3][Int(x & 0xff)]
return ((f1 &+ f2) ^ f3) &+ f4
}
}
extension Blowfish: Cipher {
/// Encrypt the 8-byte padded buffer, block by block. Note that for amounts of data larger than a block, it is not safe to just call encrypt() on successive blocks.
///
/// - Parameter bytes: Plaintext data
/// - Returns: Encrypted data
public func encrypt<C: Collection>(_ bytes: C) throws -> Array<UInt8> where C.Element == UInt8, C.IndexDistance == Int, C.Index == Int {
let bytes = padding.add(to: Array(bytes), blockSize: Blowfish.blockSize) // FIXME: Array(bytes) copies
var out = Array<UInt8>()
out.reserveCapacity(bytes.count)
for chunk in bytes.batched(by: Blowfish.blockSize) {
out += encryptWorker.encrypt(chunk)
}
if blockMode.options.contains(.paddingRequired) && (out.count % Blowfish.blockSize != 0) {
throw Error.dataPaddingRequired
}
return out
}
/// Decrypt the 8-byte padded buffer
///
/// - Parameter bytes: Ciphertext data
/// - Returns: Plaintext data
public func decrypt<C: Collection>(_ bytes: C) throws -> Array<UInt8> where C.Element == UInt8, C.IndexDistance == Int, C.Index == Int {
if blockMode.options.contains(.paddingRequired) && (bytes.count % Blowfish.blockSize != 0) {
throw Error.dataPaddingRequired
}
var out = Array<UInt8>()
out.reserveCapacity(bytes.count)
for chunk in Array(bytes).batched(by: Blowfish.blockSize) {
out += decryptWorker.decrypt(chunk) // FIXME: copying here is innefective
}
out = padding.remove(from: out, blockSize: Blowfish.blockSize)
return out
}
}
| mit | 4e746e891e1c4a9cbf40590af14a74c0 | 43.39777 | 217 | 0.624885 | 2.374826 | false | false | false | false |
watson-developer-cloud/ios-sdk | Sources/NaturalLanguageUnderstandingV1/Models/EmotionScores.swift | 1 | 1708 | /**
* (C) Copyright IBM Corp. 2017, 2020.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
**/
import Foundation
/**
EmotionScores.
*/
public struct EmotionScores: Codable, Equatable {
/**
Anger score from 0 to 1. A higher score means that the text is more likely to convey anger.
*/
public var anger: Double?
/**
Disgust score from 0 to 1. A higher score means that the text is more likely to convey disgust.
*/
public var disgust: Double?
/**
Fear score from 0 to 1. A higher score means that the text is more likely to convey fear.
*/
public var fear: Double?
/**
Joy score from 0 to 1. A higher score means that the text is more likely to convey joy.
*/
public var joy: Double?
/**
Sadness score from 0 to 1. A higher score means that the text is more likely to convey sadness.
*/
public var sadness: Double?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case anger = "anger"
case disgust = "disgust"
case fear = "fear"
case joy = "joy"
case sadness = "sadness"
}
}
| apache-2.0 | 275bb3224a1b564698f57a63db1508f2 | 28.448276 | 100 | 0.666276 | 4.115663 | false | false | false | false |
GalinaCode/Nutriction-Cal | NutritionCal/Nutrition Cal/NDBConvenience.swift | 1 | 6487 | //
// NDBConvenience.swift
// Nutrition Cal
//
// Created by Galina Petrova on 03/25/16.
// Copyright © 2015 Galina Petrova. All rights reserved.
//
// United States Department of Agriculture
// Agricultural Research Service
// National Nutrient Database for Standard Reference Release 28
// visit to: http://ndb.nal.usda.gov/ndb/doc/index for documentation and help
import Foundation
import CoreData
extension NDBClient {
func NDBItemsFromString(searchString: String, type: NDBSearchType, completionHandler: (success: Bool, result: AnyObject?, errorString: String?) -> Void) {
let escapedSearchString = searchString.stringByReplacingOccurrencesOfString(" ", withString: "+").stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())!.lowercaseString
var searchType: String {
switch type {
case .ByFoodName: return "n"
case .ByRelevance: return "r"
}
}
let params: [String : AnyObject] = [
NDBParameterKeys.format : NDBParameterValues.json,
NDBParameterKeys.searchTerm : escapedSearchString,
NDBParameterKeys.sort : searchType,
NDBParameterKeys.limit : NDBConstants.resultsLimit,
NDBParameterKeys.offset : 0,
NDBParameterKeys.apiKey : NDBConstants.apiKey
]
let urlString = NDBConstants.baseURL + NDBMethods.search + NDBClient.escapedParameters(params)
let request = NSURLRequest(URL: NSURL(string: urlString)!)
print(request.URL!)
let session = NSURLSession.sharedSession()
sharedTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
/* GUARD: Was there an error? */
guard (error == nil) else {
print("There was an error with your request: \(error!.localizedDescription)")
completionHandler(success: false, result: nil, errorString: error?.localizedDescription)
return
}
var parsedResults: AnyObject?
NDBClient.parseJSONWithCompletionHandler(data!, completionHandler: { (result, error) -> Void in
/* GUARD: Was there an error? */
guard (error == nil) else {
print("Error parsing JSON: \(error!.localizedDescription)")
completionHandler(success: false, result: nil, errorString: error?.localizedDescription)
return
}
parsedResults = result
})
if let errors = parsedResults?.valueForKey("errors") {
if let error = errors.valueForKey("error") {
if let message = error.valueForKey("message") {
let errorMessage = message.firstObject as! NSString
completionHandler(success: false, result: nil, errorString: errorMessage as String)
return
}
}
}
if let error = parsedResults!.valueForKey("error") {
if let message = error.valueForKey("message") {
let errorMessage = message as! NSString
completionHandler(success: false, result: nil, errorString: errorMessage as String)
return
}
}
guard let list = parsedResults?.valueForKey("list") as? [String: AnyObject] else {
print("Couldn't find list in: \(parsedResults)")
completionHandler(success: false, result: nil, errorString: "Couldn't find list in parsedResults")
return
}
guard let items = list["item"] as? NSArray else {
print("Couldn't find item in: \(list)")
completionHandler(success: false, result: nil, errorString: "Couldn't find item in list")
return
}
completionHandler(success: true, result: items, errorString: nil)
}
sharedTask!.resume()
}
func NDBReportForItem(ndbNo: String, type: NDBReportType, completionHandler: (success: Bool, result: AnyObject?, errorString: String?) -> Void) {
var reportType: String {
switch type {
case .Basic: return "b"
case .Full: return "f"
}
}
let params: [String : AnyObject] = [
NDBParameterKeys.format : NDBParameterValues.json,
NDBParameterKeys.NDBNo : ndbNo,
NDBParameterKeys.reportType : reportType,
NDBParameterKeys.apiKey : NDBConstants.apiKey
]
let urlString = NDBConstants.baseURL + NDBMethods.reports + NDBClient.escapedParameters(params)
let request = NSURLRequest(URL: NSURL(string: urlString)!)
print(request.URL!)
let session = NSURLSession.sharedSession()
sharedTask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
/* GUARD: Was there an error? */
guard (error == nil) else {
print("There was an error with your request: \(error!.localizedDescription)")
completionHandler(success: false, result: nil, errorString: error?.localizedDescription)
return
}
var parsedResults: AnyObject?
NDBClient.parseJSONWithCompletionHandler(data!, completionHandler: { (result, error) -> Void in
/* GUARD: Was there an error? */
guard (error == nil) else {
print("Error parsing JSON: \(error!.localizedDescription)")
completionHandler(success: false, result: nil, errorString: error?.localizedDescription)
return
}
parsedResults = result
})
if let errors = parsedResults?.valueForKey("errors") {
if let error = errors.valueForKey("error") {
if let message = error.valueForKey("message") {
let errorMessage = message.firstObject as! NSString
completionHandler(success: false, result: nil, errorString: errorMessage as String)
return
}
}
completionHandler(success: false, result: nil, errorString: nil)
return
}
if let error = parsedResults?.valueForKey("error") {
if let message = error.valueForKey("message") {
let errorMessage = message as! NSString
completionHandler(success: false, result: nil, errorString: errorMessage as String)
return
}
}
guard let report = parsedResults?.valueForKey("report") as? [String: AnyObject] else {
print("Error finding report")
completionHandler(success: false, result: nil, errorString: "Error finding report")
return
}
guard let food = report["food"] as? [String: AnyObject] else {
print("Error finding food")
completionHandler(success: false, result: nil, errorString: "Error finding food")
return
}
guard let nutrients = food["nutrients"] as? NSArray else {
print("Error finding nutrients")
completionHandler(success: false, result: nil, errorString: "Error finding nutrients")
return
}
completionHandler(success: true, result: nutrients, errorString: nil)
}
sharedTask!.resume()
}
}
| apache-2.0 | 9e94b2bb22026270057e087114031b38 | 30.950739 | 213 | 0.689485 | 4.192631 | false | false | false | false |
OrielBelzer/StepCoin | HDAugmentedReality/Classes/ARViewController.swift | 1 | 49104 | //
// ARViewController.swift
// HDAugmentedRealityDemo
//
// Created by Danijel Huis on 23/04/15.
// Copyright (c) 2015 Danijel Huis. All rights reserved.
//
import UIKit
import AVFoundation
import CoreLocation
/**
* Augmented reality view controller.
*
* How to use:
* 1. Initialize controller and set datasource(and other properties if needed)
* 2. Use setAnnotations method to set annotations
* 3. Present controller modally
* 4. Implement ARDataSource to provide annotation views in your data source
*
* Properties maxVerticalLevel, maxVisibleAnnotations and maxDistance can be used to optimize performance.
* Use trackingManager.userDistanceFilter and trackingManager.reloadDistanceFilter to set how often data is refreshed/reloaded.
* All properties are documented.
*
* https://github.com/DanijelHuis/HDAugmentedReality.git
*
*/
open class ARViewController: UIViewController, ARTrackingManagerDelegate
{
/// Data source
open weak var dataSource: ARDataSource?
/// Orientation mask for view controller. Make sure orientations are enabled in project settings also.
open var interfaceOrientationMask: UIInterfaceOrientationMask = UIInterfaceOrientationMask.all
/**
* Defines in how many vertical levels can annotations be stacked. Default value is 5.
* Annotations are initially vertically arranged by distance from user, but if two annotations visibly collide with each other,
* then farther annotation is put higher, meaning it is moved onto next vertical level. If annotation is moved onto level higher
* than this value, it will not be visible.
* NOTE: This property greatly impacts performance because collision detection is heavy operation, use it in range 1-10.
* Max value is 10.
*/
open var maxVerticalLevel = 0
{
didSet
{
if(maxVerticalLevel > MAX_VERTICAL_LEVELS)
{
maxVerticalLevel = MAX_VERTICAL_LEVELS
}
}
}
/// Total maximum number of visible annotation views. Default value is 100. Max value is 500
open var maxVisibleAnnotations = 0
{
didSet
{
if(maxVisibleAnnotations > MAX_VISIBLE_ANNOTATIONS)
{
maxVisibleAnnotations = MAX_VISIBLE_ANNOTATIONS
}
}
}
/**
* Maximum distance(in meters) for annotation to be shown.
* If the distance from annotation to user's location is greater than this value, than that annotation will not be shown.
* Also, this property, in conjunction with maxVerticalLevel, defines how are annotations aligned vertically. Meaning
* annotation that are closer to this value will be higher.
* Default value is 0 meters, which means that distances of annotations don't affect their visiblity.
*/
open var maxDistance: Double = 0
/// Class for managing geographical calculations. Use it to set properties like reloadDistanceFilter, userDistanceFilter and altitudeSensitive
fileprivate(set) open var trackingManager: ARTrackingManager = ARTrackingManager()
/// Image for close button. If not set, default one is used.
//public var closeButtonImage = UIImage(named: "hdar_close", inBundle: NSBundle(forClass: ARViewController.self), compatibleWithTraitCollection: nil)
open var closeButtonImage: UIImage?
{
didSet
{
closeButton?.setImage(self.closeButtonImage, for: UIControlState())
}
}
/// Enables map debugging and some other debugging features, set before controller is shown
@available(*, deprecated, message: "Will be removed in next version, use uiOptions.debugEnabled.")
open var debugEnabled = false
{
didSet
{
self.uiOptions.debugEnabled = debugEnabled
}
}
/**
Smoothing factor for heading in range 0-1. It affects horizontal movement of annotaion views. The lower the value the bigger the smoothing.
Value of 1 means no smoothing, should be greater than 0.
*/
open var headingSmoothingFactor: Double = 1
/**
Called every 5 seconds after location tracking is started but failed to deliver location. It is also called when tracking has just started with timeElapsed = 0.
The timer is restarted when app comes from background or on didAppear.
*/
open var onDidFailToFindLocation: ((_ timeElapsed: TimeInterval, _ acquiredLocationBefore: Bool) -> Void)?
/**
Some ui options. Set it before controller is shown, changes made afterwards are disregarded.
*/
open var uiOptions = UiOptions()
open var didCloseCamera = false
//===== Private
fileprivate var initialized: Bool = false
fileprivate var cameraSession: AVCaptureSession = AVCaptureSession()
fileprivate var overlayView: OverlayView = OverlayView()
fileprivate var displayTimer: CADisplayLink?
fileprivate var cameraLayer: AVCaptureVideoPreviewLayer? // Will be set in init
fileprivate var annotationViews: [ARAnnotationView] = []
fileprivate var previosRegion: Int = 0
fileprivate var degreesPerScreen: CGFloat = 0
fileprivate var shouldReloadAnnotations: Bool = false
fileprivate var reloadInProgress = false
fileprivate var reloadToken: Int = 0
fileprivate var reloadLock = NSRecursiveLock()
fileprivate var annotations: [ARAnnotation] = []
fileprivate var activeAnnotations: [ARAnnotation] = []
fileprivate var closeButton: UIButton?
fileprivate var currentHeading: Double = 0
fileprivate var lastLocation: CLLocation?
fileprivate var debugLabel: UILabel?
fileprivate var debugMapButton: UIButton?
fileprivate var didLayoutSubviews: Bool = false
//==========================================================================================================================================================
// MARK: Init
//==========================================================================================================================================================
init()
{
super.init(nibName: nil, bundle: nil)
self.initializeInternal()
}
required public init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
self.initializeInternal()
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?)
{
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.initializeInternal()
}
internal func initializeInternal()
{
if self.initialized
{
return
}
self.initialized = true;
// Default values
self.trackingManager.delegate = self
self.maxVerticalLevel = 5
self.maxVisibleAnnotations = 100
self.maxDistance = 0
NotificationCenter.default.addObserver(self, selector: #selector(ARViewController.locationNotification(_:)), name: NSNotification.Name(rawValue: "kNotificationLocationSet"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ARViewController.appWillEnterForeground(_:)), name: NSNotification.Name.UIApplicationWillEnterForeground, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(ARViewController.appDidEnterBackground(_:)), name: NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
self.initialize()
}
/// Intended for use in subclasses, no need to call super
internal func initialize()
{
}
deinit
{
NotificationCenter.default.removeObserver(self)
self.stopCamera()
}
//==========================================================================================================================================================
// MARK: View's lifecycle
//==========================================================================================================================================================
open override func viewWillAppear(_ animated: Bool)
{
super.viewWillAppear(animated)
onViewWillAppear() // Doing like this to prevent subclassing problems
}
open override func viewDidAppear(_ animated: Bool)
{
super.viewDidAppear(animated)
self.didCloseCamera = false
self.reloadAnnotations()
onViewDidAppear() // Doing like this to prevent subclassing problems
}
open override func viewDidDisappear(_ animated: Bool)
{
super.viewDidDisappear(animated)
onViewDidDisappear() // Doing like this to prevent subclassing problems
}
open override func viewDidLayoutSubviews()
{
super.viewDidLayoutSubviews()
onViewDidLayoutSubviews()
}
fileprivate func onViewWillAppear()
{
// Camera layer if not added
if self.cameraLayer?.superlayer == nil { self.loadCamera() }
// Overlay
if self.overlayView.superview == nil { self.loadOverlay() }
// Set orientation and start camera
self.setOrientation(UIApplication.shared.statusBarOrientation)
self.layoutUi()
self.startCamera(notifyLocationFailure: true)
}
fileprivate func onViewDidAppear()
{
}
fileprivate func onViewDidDisappear()
{
stopCamera()
}
internal func closeButtonTap()
{
self.presentingViewController?.dismiss(animated: true, completion: nil)
self.didCloseCamera = true
self.trackingManager.stopTracking()
}
open override var prefersStatusBarHidden : Bool
{
return true
}
fileprivate func onViewDidLayoutSubviews()
{
// Executed only first time when everything is layouted
if !self.didLayoutSubviews
{
self.didLayoutSubviews = true
// Close button
if self.uiOptions.closeButtonEnabled { self.addCloseButton() }
// Debug
// if self.uiOptions.debugEnabled { self.addDebugUi() }
// Layout
self.layoutUi()
self.view.layoutIfNeeded()
}
self.degreesPerScreen = (self.view.bounds.size.width / OVERLAY_VIEW_WIDTH) * 360.0
}
internal func appDidEnterBackground(_ notification: Notification)
{
if(self.view.window != nil)
{
self.trackingManager.stopTracking()
}
}
internal func appWillEnterForeground(_ notification: Notification)
{
if(self.view.window != nil)
{
// Removing all from screen and restarting location manager.
for annotation in self.annotations
{
annotation.annotationView = nil
}
for annotationView in self.annotationViews
{
annotationView.removeFromSuperview()
}
self.annotationViews = []
self.shouldReloadAnnotations = true;
self.trackingManager.stopTracking()
// Start tracking
self.trackingManager.startTracking(notifyLocationFailure: true)
}
}
//==========================================================================================================================================================
// MARK: Annotations and annotation views
//==========================================================================================================================================================
/**
* Sets annotations. Note that annotations with invalid location will be kicked.
*
* - parameter annotations: Annotations
*/
open func setAnnotations(_ annotations: [ARAnnotation])
{
var validAnnotations: [ARAnnotation] = []
// Don't use annotations without valid location
for annotation in annotations
{
if annotation.location != nil && CLLocationCoordinate2DIsValid(annotation.location!.coordinate)
{
validAnnotations.append(annotation)
}
}
self.annotations = validAnnotations
self.reloadAnnotations()
}
open func getAnnotations() -> [ARAnnotation]
{
return self.annotations
}
/// Creates annotations views and recalculates all variables(distances, azimuths, vertical levels) if user location is available, else it will reload when it gets user location.
open func reloadAnnotations()
{
if self.trackingManager.userLocation != nil && self.isViewLoaded
{
self.shouldReloadAnnotations = false
self.reload(calculateDistanceAndAzimuth: true, calculateVerticalLevels: true, createAnnotationViews: true)
}
else
{
self.shouldReloadAnnotations = true
}
}
/// Creates annotation views. All views are created at once, for active annotations. This reduces lag when rotating.
fileprivate func createAnnotationViews()
{
var annotationViews: [ARAnnotationView] = []
let activeAnnotations = self.activeAnnotations // Which annotations are active is determined by number of properties - distance, vertical level etc.
// Removing existing annotation views
for annotationView in self.annotationViews
{
annotationView.removeFromSuperview()
}
// Destroy views for inactive anntotations
for annotation in self.annotations
{
if(!annotation.active)
{
annotation.annotationView = nil
}
}
// Create views for active annotations
for annotation in activeAnnotations
{
// Don't create annotation view for annotation that doesn't have valid location. Note: checked before, should remove
if annotation.location == nil || !CLLocationCoordinate2DIsValid(annotation.location!.coordinate)
{
continue
}
var annotationView: ARAnnotationView? = nil
if annotation.annotationView != nil
{
annotationView = annotation.annotationView
}
else
{
annotationView = self.dataSource?.ar(self, viewForAnnotation: annotation)
}
if annotationView != nil
{
annotation.annotationView = annotationView
annotationView!.annotation = annotation
annotationViews.append(annotationView!)
}
}
self.annotationViews = annotationViews
}
fileprivate func calculateDistanceAndAzimuthForAnnotations(sort: Bool, onlyForActiveAnnotations: Bool)
{
if self.trackingManager.userLocation == nil
{
return
}
let userLocation = self.trackingManager.userLocation!
let array = (onlyForActiveAnnotations && self.activeAnnotations.count > 0) ? self.activeAnnotations : self.annotations
for annotation in array
{
if annotation.location == nil // This should never happen bcs we remove all annotations with invalid location in setAnnotation
{
annotation.distanceFromUser = 0
annotation.azimuth = 0
continue
}
// Distance
annotation.distanceFromUser = annotation.location!.distance(from: userLocation)
// Azimuth
let azimuth = self.trackingManager.azimuthFromUserToLocation(annotation.location!)
annotation.azimuth = azimuth
}
if sort
{
//self.annotations = self.annotations.sorted { $0.distanceFromUser < $1.distanceFromUser }
let sortedArray: NSMutableArray = NSMutableArray(array: self.annotations)
let sortDesc = NSSortDescriptor(key: "distanceFromUser", ascending: true)
sortedArray.sort(using: [sortDesc])
self.annotations = sortedArray as [AnyObject] as! [ARAnnotation]
}
}
fileprivate func updateAnnotationsForCurrentHeading()
{
//===== Removing views not in viewport, adding those that are. Also removing annotations view vertical level > maxVerticalLevel
let degreesDelta = Double(degreesPerScreen)
for annotationView in self.annotationViews
{
if annotationView.annotation != nil
{
let delta = deltaAngle(currentHeading, angle2: annotationView.annotation!.azimuth)
if fabs(delta) < degreesDelta && annotationView.annotation!.verticalLevel <= self.maxVerticalLevel
{
if annotationView.superview == nil
{
self.overlayView.addSubview(annotationView)
}
}
else
{
if annotationView.superview != nil
{
annotationView.removeFromSuperview()
}
}
}
}
//===== Fix position of annoations near Norh(critical regions). Explained in xPositionForAnnotationView
let threshold: Double = 40
var currentRegion: Int = 0
if currentHeading < threshold // 0-40
{
currentRegion = 1
}
else if currentHeading > (360 - threshold) // 320-360
{
currentRegion = -1
}
if currentRegion != self.previosRegion
{
if self.annotationViews.count > 0
{
// This will just call positionAnnotationViews
self.reload(calculateDistanceAndAzimuth: false, calculateVerticalLevels: false, createAnnotationViews: false)
}
}
self.previosRegion = currentRegion
}
fileprivate func positionAnnotationViews()
{
for annotationView in self.annotationViews
{
let x = self.xPositionForAnnotationView(annotationView, heading: self.trackingManager.heading)
let y = self.yPositionForAnnotationView(annotationView)
annotationView.frame = CGRect(x: x, y: y, width: annotationView.bounds.size.width, height: annotationView.bounds.size.height)
//annotationView.frame = CGRect(x: x, y: y, width: 50, height: 48)
}
}
fileprivate func xPositionForAnnotationView(_ annotationView: ARAnnotationView, heading: Double) -> CGFloat
{
if annotationView.annotation == nil { return 0 }
let annotation = annotationView.annotation!
// Azimuth
let azimuth = annotation.azimuth
// Calculating x position
var xPos: CGFloat = CGFloat(azimuth) * H_PIXELS_PER_DEGREE - annotationView.bounds.size.width / 2.0
// Fixing position in critical areas (near north).
// If current heading is right of north(< 40), annotations that are between 320 - 360 wont be visible so we change their position so they are visible.
// Also if current heading is left of north (320 - 360), annotations that are between 0 - 40 wont be visible so we change their position so they are visible.
// This is needed because all annotation view are on same ovelay view so views at start and end of overlay view cannot be visible at the same time.
let threshold: Double = 40
if heading < threshold
{
if annotation.azimuth > (360 - threshold)
{
xPos = -(OVERLAY_VIEW_WIDTH - xPos);
}
}
else if heading > (360 - threshold)
{
if annotation.azimuth < threshold
{
xPos = OVERLAY_VIEW_WIDTH + xPos;
}
}
return xPos
}
fileprivate func yPositionForAnnotationView(_ annotationView: ARAnnotationView) -> CGFloat
{
if annotationView.annotation == nil { return 0 }
let annotation = annotationView.annotation!
let annotationViewHeight: CGFloat = annotationView.bounds.size.height
var yPos: CGFloat = (self.view.bounds.size.height * 0.65) - (annotationViewHeight * CGFloat(annotation.verticalLevel))
yPos -= CGFloat( powf(Float(annotation.verticalLevel), 2) * 4)
return yPos
}
fileprivate func calculateVerticalLevels()
{
// Lot faster with NS stuff than swift collection classes
let dictionary: NSMutableDictionary = NSMutableDictionary()
// Creating dictionary for each vertical level
for level in stride(from: 0, to: self.maxVerticalLevel + 1, by: 1)
{
let array = NSMutableArray()
dictionary[Int(level)] = array
}
// Putting each annotation in its dictionary(each level has its own dictionary)
for i in stride(from: 0, to: self.activeAnnotations.count, by: 1)
{
let annotation = self.activeAnnotations[i] as ARAnnotation
if annotation.verticalLevel <= self.maxVerticalLevel
{
let array = dictionary[annotation.verticalLevel] as? NSMutableArray
array?.add(annotation)
}
}
// Calculating annotation view's width in degrees. Assuming all annotation views have same width
var annotationWidthInDegrees: Double = 0
if let annotationWidth = self.getAnyAnnotationView()?.bounds.size.width
{
annotationWidthInDegrees = Double(annotationWidth / H_PIXELS_PER_DEGREE)
}
if annotationWidthInDegrees < 5 { annotationWidthInDegrees = 5 }
// Doing the shit
var minVerticalLevel: Int = Int.max
for level in stride(from: 0, to: self.maxVerticalLevel + 1, by: 1)
{
let annotationsForCurrentLevel = dictionary[(level as Int)] as! NSMutableArray
let annotationsForNextLevel = dictionary[((level + 1) as Int)] as? NSMutableArray
for i in stride(from: 0, to: annotationsForCurrentLevel.count, by: 1)
{
let annotation1 = annotationsForCurrentLevel[i] as! ARAnnotation
if annotation1.verticalLevel != level { continue } // Can happen if it was moved to next level by previous annotation, it will be handled in next loop
for j in stride(from: (i+1), to: annotationsForCurrentLevel.count, by: 1)
{
let annotation2 = annotationsForCurrentLevel[j] as! ARAnnotation
if annotation1 == annotation2 || annotation2.verticalLevel != level
{
continue
}
// Check if views are colliding horizontally. Using azimuth instead of view position in pixel bcs of performance.
var deltaAzimuth = deltaAngle(annotation1.azimuth, angle2: annotation2.azimuth)
deltaAzimuth = fabs(deltaAzimuth)
if deltaAzimuth > annotationWidthInDegrees
{
// No collision
continue
}
// Current annotation is farther away from user than comparing annotation, current will be pushed to the next level
if annotation1.distanceFromUser > annotation2.distanceFromUser
{
annotation1.verticalLevel += 1
if annotationsForNextLevel != nil
{
annotationsForNextLevel?.add(annotation1)
}
// Current annotation was moved to next level so no need to continue with this level
break
}
// Compared annotation will be pushed to next level because it is furher away
else
{
annotation2.verticalLevel += 1
if annotationsForNextLevel != nil
{
annotationsForNextLevel?.add(annotation2)
}
}
}
if annotation1.verticalLevel == level
{
minVerticalLevel = Int(fmin(Float(minVerticalLevel), Float(annotation1.verticalLevel)))
}
}
}
// Lower all annotation if there is no lower level annotations
for annotation in self.activeAnnotations
{
if annotation.verticalLevel <= self.maxVerticalLevel
{
annotation.verticalLevel -= minVerticalLevel
}
}
}
/// It is expected that annotations are sorted by distance before this method is called
fileprivate func setInitialVerticalLevels()
{
if self.activeAnnotations.count == 0
{
return
}
// Fetch annotations filtered by maximumDistance and maximumAnnotationsOnScreen
let activeAnnotations = self.activeAnnotations
var minDistance = activeAnnotations.first!.distanceFromUser
var maxDistance = activeAnnotations.last!.distanceFromUser
if self.maxDistance > 0
{
minDistance = 0;
maxDistance = self.maxDistance;
}
var deltaDistance = maxDistance - minDistance
let maxLevel: Double = Double(self.maxVerticalLevel)
// First reset vertical levels for all annotations
for annotation in self.annotations
{
annotation.verticalLevel = self.maxVerticalLevel + 1
}
if deltaDistance <= 0 { deltaDistance = 1 }
// Calculate vertical levels for active annotations
for annotation in activeAnnotations
{
let verticalLevel = Int(((annotation.distanceFromUser - minDistance) / deltaDistance) * maxLevel)
annotation.verticalLevel = verticalLevel
}
}
fileprivate func getAnyAnnotationView() -> ARAnnotationView?
{
var anyAnnotationView: ARAnnotationView? = nil
if let annotationView = self.annotationViews.first
{
anyAnnotationView = annotationView
}
else if let annotation = self.activeAnnotations.first
{
anyAnnotationView = self.dataSource?.ar(self, viewForAnnotation: annotation)
}
return anyAnnotationView
}
//==========================================================================================================================================================
// MARK: Main logic
//==========================================================================================================================================================
fileprivate func reload(calculateDistanceAndAzimuth: Bool, calculateVerticalLevels: Bool, createAnnotationViews: Bool)
{
//NSLog("==========")
if calculateDistanceAndAzimuth
{
// Sort by distance is needed only if creating new views
let sort = createAnnotationViews
// Calculations for all annotations should be done only when creating annotations views
let onlyForActiveAnnotations = !createAnnotationViews
self.calculateDistanceAndAzimuthForAnnotations(sort: sort, onlyForActiveAnnotations: onlyForActiveAnnotations)
}
if(createAnnotationViews)
{
self.activeAnnotations = filteredAnnotations(nil, maxVisibleAnnotations: self.maxVisibleAnnotations, maxDistance: self.maxDistance)
self.setInitialVerticalLevels()
}
if calculateVerticalLevels
{
self.calculateVerticalLevels()
}
if createAnnotationViews
{
self.createAnnotationViews()
}
self.positionAnnotationViews()
// Calling bindUi on every annotation view so it can refresh its content,
// doing this every time distance changes, in case distance is needed for display.
if calculateDistanceAndAzimuth
{
for annotationView in self.annotationViews
{
annotationView.bindUi()
}
}
}
/// Determines which annotations are active and which are inactive. If some of the input parameters is nil, then it won't filter by that parameter.
fileprivate func filteredAnnotations(_ maxVerticalLevel: Int?, maxVisibleAnnotations: Int?, maxDistance: Double?) -> [ARAnnotation]
{
let nsAnnotations: NSMutableArray = NSMutableArray(array: self.annotations)
var filteredAnnotations: [ARAnnotation] = []
var count = 0
let checkMaxVisibleAnnotations = maxVisibleAnnotations != nil
let checkMaxVerticalLevel = maxVerticalLevel != nil
let checkMaxDistance = maxDistance != nil
for nsAnnotation in nsAnnotations
{
let annotation = nsAnnotation as! ARAnnotation
// filter by maxVisibleAnnotations
if(checkMaxVisibleAnnotations && count >= maxVisibleAnnotations!)
{
annotation.active = false
continue
}
// filter by maxVerticalLevel and maxDistance
if (!checkMaxVerticalLevel || annotation.verticalLevel <= maxVerticalLevel!) &&
(!checkMaxDistance || self.maxDistance == 0 || annotation.distanceFromUser <= maxDistance!)
{
filteredAnnotations.append(annotation)
annotation.active = true
count += 1;
}
else
{
annotation.active = false
}
}
return filteredAnnotations
}
//==========================================================================================================================================================
// MARK: Events: ARLocationManagerDelegate/Display timer
//==========================================================================================================================================================
internal func displayTimerTick()
{
let filterFactor: Double = headingSmoothingFactor
let newHeading = self.trackingManager.heading
// Picking up the pace if device is being rotated fast or heading of device is at the border(North). It is needed
// to do this on North border because overlayView changes its position and we don't want it to animate full circle.
if(self.headingSmoothingFactor == 1 || fabs(currentHeading - self.trackingManager.heading) > 50)
{
currentHeading = self.trackingManager.heading
}
else
{
// Smoothing out heading
currentHeading = (newHeading * filterFactor) + (currentHeading * (1.0 - filterFactor))
}
self.overlayView.frame = self.overlayFrame()
self.updateAnnotationsForCurrentHeading()
logText("Heading: \(self.trackingManager.heading)")
}
internal func arTrackingManager(_ trackingManager: ARTrackingManager, didUpdateUserLocation: CLLocation?)
{
if let location = trackingManager.userLocation
{
self.lastLocation = location
CoinsController().reloadCoinsFromServerWithinCoordinatesRange(longitude: String(location.coordinate.longitude), latitude: String(location.coordinate.latitude), forceReload: true) { (responseObject:[AnyObject], error:String) in
self.reloadAnnotations()
}
}
// shouldReloadAnnotations will be true if reloadAnnotations was called before location was fetched
if self.shouldReloadAnnotations
{
self.reloadAnnotations()
}
// Refresh only if we have annotations
else if self.activeAnnotations.count > 0
{
self.reload(calculateDistanceAndAzimuth: true, calculateVerticalLevels: true, createAnnotationViews: false)
}
// Debug view, indicating that update was done
if(self.uiOptions.debugEnabled)
{
let view = UIView()
view.frame = CGRect(x: self.view.bounds.size.width - 80, y: 10, width: 30, height: 30)
view.backgroundColor = UIColor.red
self.view.addSubview(view)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC))
{
view.removeFromSuperview()
}
}
}
internal func arTrackingManager(_ trackingManager: ARTrackingManager, didUpdateReloadLocation: CLLocation?)
{
// Manual reload?
if didUpdateReloadLocation != nil && self.dataSource != nil && self.dataSource!.responds(to: #selector(ARDataSource.ar(_:shouldReloadWithLocation:)))
{
let annotations = self.dataSource?.ar?(self, shouldReloadWithLocation: didUpdateReloadLocation!)
if let annotations = annotations
{
setAnnotations(annotations);
}
}
else
{
self.reloadAnnotations()
}
// Debug view, indicating that reload was done
if(self.uiOptions.debugEnabled)
{
let view = UIView()
view.frame = CGRect(x: self.view.bounds.size.width - 80, y: 10, width: 30, height: 30)
view.backgroundColor = UIColor.blue
self.view.addSubview(view)
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(1.5 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC))
{
view.removeFromSuperview()
}
}
}
internal func arTrackingManager(_ trackingManager: ARTrackingManager, didFailToFindLocationAfter elapsedSeconds: TimeInterval)
{
self.onDidFailToFindLocation?(elapsedSeconds, self.lastLocation != nil)
}
internal func logText(_ text: String)
{
self.debugLabel?.text = text
}
//==========================================================================================================================================================
// MARK: Camera
//==========================================================================================================================================================
fileprivate func loadCamera()
{
self.cameraLayer?.removeFromSuperlayer()
self.cameraLayer = nil
//===== Video device/video input
let captureSessionResult = ARViewController.createCaptureSession()
guard captureSessionResult.error == nil, let session = captureSessionResult.session else
{
print("HDAugmentedReality: Cannot create capture session, use createCaptureSession method to check if device is capable for augmented reality.")
return
}
self.cameraSession = session
//===== View preview layer
if let cameraLayer = AVCaptureVideoPreviewLayer(session: self.cameraSession)
{
cameraLayer.videoGravity = AVLayerVideoGravityResizeAspectFill
self.view.layer.insertSublayer(cameraLayer, at: 0)
self.cameraLayer = cameraLayer
}
}
/// Tries to find back video device and add video input to it. This method can be used to check if device has hardware available for augmented reality.
open class func createCaptureSession() -> (session: AVCaptureSession?, error: NSError?)
{
var error: NSError?
var captureSession: AVCaptureSession?
var backVideoDevice: AVCaptureDevice?
let videoDevices = AVCaptureDevice.devices(withMediaType: AVMediaTypeVideo)
// Get back video device
if let videoDevices = videoDevices
{
for captureDevice in videoDevices
{
if (captureDevice as AnyObject).position == AVCaptureDevicePosition.back
{
backVideoDevice = captureDevice as? AVCaptureDevice
break
}
}
}
if backVideoDevice != nil
{
var videoInput: AVCaptureDeviceInput!
do {
videoInput = try AVCaptureDeviceInput(device: backVideoDevice)
} catch let error1 as NSError {
error = error1
videoInput = nil
}
if error == nil
{
captureSession = AVCaptureSession()
if captureSession!.canAddInput(videoInput)
{
captureSession!.addInput(videoInput)
}
else
{
error = NSError(domain: "HDAugmentedReality", code: 10002, userInfo: ["description": "Error adding video input."])
}
}
else
{
error = NSError(domain: "HDAugmentedReality", code: 10001, userInfo: ["description": "Error creating capture device input. Please go to your iPhone settings and enable Camera for StepCoin"])
}
}
else
{
error = NSError(domain: "HDAugmentedReality", code: 10000, userInfo: ["description": "Back video device not found."])
}
return (session: captureSession, error: error)
}
fileprivate func startCamera(notifyLocationFailure: Bool)
{
self.cameraSession.startRunning()
self.trackingManager.startTracking(notifyLocationFailure: notifyLocationFailure)
self.displayTimer = CADisplayLink(target: self, selector: #selector(ARViewController.displayTimerTick))
self.displayTimer?.add(to: RunLoop.current, forMode: RunLoopMode.defaultRunLoopMode)
}
fileprivate func stopCamera()
{
self.cameraSession.stopRunning()
self.trackingManager.stopTracking()
self.displayTimer?.invalidate()
self.displayTimer = nil
}
//==========================================================================================================================================================
// MARK: Overlay
//==========================================================================================================================================================
/// Overlay view is used to host annotation views.
fileprivate func loadOverlay()
{
self.overlayView.removeFromSuperview()
self.overlayView = OverlayView()
self.view.addSubview(self.overlayView)
/*self.overlayView.backgroundColor = UIColor.greenColor().colorWithAlphaComponent(0.1)
for i in 0...36
{
let view = UIView()
view.frame = CGRectMake( CGFloat(i * 10) * H_PIXELS_PER_DEGREE , 50, 10, 10)
view.backgroundColor = UIColor.redColor()
self.overlayView.addSubview(view)
}*/
}
fileprivate func overlayFrame() -> CGRect
{
let x: CGFloat = self.view.bounds.size.width / 2 - (CGFloat(currentHeading) * H_PIXELS_PER_DEGREE)
let y: CGFloat = (CGFloat(self.trackingManager.pitch) * VERTICAL_SENS) + 60.0
let newFrame = CGRect(x: x, y: y, width: OVERLAY_VIEW_WIDTH, height: self.view.bounds.size.height)
return newFrame
}
fileprivate func layoutUi()
{
self.cameraLayer?.frame = self.view.bounds
self.overlayView.frame = self.overlayFrame()
}
//==========================================================================================================================================================
//MARK: Rotation/Orientation
//==========================================================================================================================================================
open override var shouldAutorotate : Bool
{
return true
}
open override var supportedInterfaceOrientations : UIInterfaceOrientationMask
{
return UIInterfaceOrientationMask(rawValue: self.interfaceOrientationMask.rawValue)
}
open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator)
{
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition:
{
(coordinatorContext) in
self.setOrientation(UIApplication.shared.statusBarOrientation)
})
{
[unowned self] (coordinatorContext) in
self.layoutAndReloadOnOrientationChange()
}
}
internal func layoutAndReloadOnOrientationChange()
{
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
self.layoutUi()
self.reload(calculateDistanceAndAzimuth: false, calculateVerticalLevels: false, createAnnotationViews: false)
CATransaction.commit()
}
fileprivate func setOrientation(_ orientation: UIInterfaceOrientation)
{
if self.cameraLayer?.connection?.isVideoOrientationSupported != nil
{
if let videoOrientation = AVCaptureVideoOrientation(rawValue: Int(orientation.rawValue))
{
self.cameraLayer?.connection?.videoOrientation = videoOrientation
}
}
if let deviceOrientation = CLDeviceOrientation(rawValue: Int32(orientation.rawValue))
{
self.trackingManager.orientation = deviceOrientation
}
}
//==========================================================================================================================================================
//MARK: UI
//==========================================================================================================================================================
func addCloseButton()
{
self.closeButton?.removeFromSuperview()
if self.closeButtonImage == nil
{
let bundle = Bundle(for: ARViewController.self)
let path = bundle.path(forResource: "hdar_close", ofType: "png")
if let path = path
{
self.closeButtonImage = UIImage(contentsOfFile: path)
}
}
// Close button - make it customizable
let closeButton: UIButton = UIButton(type: UIButtonType.custom)
closeButton.setImage(closeButtonImage, for: UIControlState());
closeButton.frame = CGRect(x: self.view.bounds.size.width - 45, y: 5,width: 40,height: 40)
closeButton.addTarget(self, action: #selector(ARViewController.closeButtonTap), for: UIControlEvents.touchUpInside)
closeButton.autoresizingMask = [UIViewAutoresizing.flexibleLeftMargin, UIViewAutoresizing.flexibleBottomMargin]
self.view.addSubview(closeButton)
self.closeButton = closeButton
}
//==========================================================================================================================================================
//MARK: Debug
//==========================================================================================================================================================
/// Called from DebugMapViewController when user fakes location.
internal func locationNotification(_ sender: Notification)
{
if let location = sender.userInfo?["location"] as? CLLocation
{
self.trackingManager.startDebugMode(location)
self.reloadAnnotations()
self.dismiss(animated: true, completion: nil)
}
}
/// Opening DebugMapViewController
// internal func debugButtonTap()
// {
// let bundle = Bundle(for: DebugMapViewController.self)
// let mapViewController = DebugMapViewController(nibName: "DebugMapViewController", bundle: bundle)
// self.present(mapViewController, animated: true, completion: nil)
// mapViewController.addAnnotations(self.annotations)
// }
// func addDebugUi()
// {
// self.debugLabel?.removeFromSuperview()
// self.debugMapButton?.removeFromSuperview()
//
// let debugLabel = UILabel()
// debugLabel.backgroundColor = UIColor.white
// debugLabel.textColor = UIColor.black
// debugLabel.font = UIFont.boldSystemFont(ofSize: 10)
// debugLabel.frame = CGRect(x: 5, y: self.view.bounds.size.height - 50, width: self.view.bounds.size.width - 10, height: 45)
// debugLabel.numberOfLines = 0
// debugLabel.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleTopMargin, UIViewAutoresizing.flexibleLeftMargin, UIViewAutoresizing.flexibleRightMargin]
// debugLabel.textAlignment = NSTextAlignment.left
// view.addSubview(debugLabel)
// self.debugLabel = debugLabel
//
// let debugMapButton: UIButton = UIButton(type: UIButtonType.custom)
// debugMapButton.frame = CGRect(x: 5,y: 5,width: 40,height: 40);
// debugMapButton.addTarget(self, action: #selector(ARViewController.debugButtonTap), for: UIControlEvents.touchUpInside)
// debugMapButton.setTitle("map", for: UIControlState())
// debugMapButton.backgroundColor = UIColor.white.withAlphaComponent(0.5)
// debugMapButton.setTitleColor(UIColor.black, for: UIControlState())
// self.view.addSubview(debugMapButton)
// self.debugMapButton = debugMapButton
// }
//==========================================================================================================================================================
//MARK: OverlayView class
//==========================================================================================================================================================
/// Normal UIView that registers taps on subviews out of its bounds.
fileprivate class OverlayView: UIView
{
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView?
{
if(!self.clipsToBounds && !self.isHidden)
{
for subview in self.subviews.reversed()
{
let subPoint = subview.convert(point, from: self)
if let result:UIView = subview.hitTest(subPoint, with:event)
{
return result;
}
}
}
return nil
}
}
//==========================================================================================================================================================
//MARK: UiOptions
//==========================================================================================================================================================
public struct UiOptions
{
/// Enables/Disables debug UI, like heading label, map button, some views when updating/reloading.
public var debugEnabled = false
/// Enables/Disables close button.
public var closeButtonEnabled = true
}
}
| mit | aaaf5826e77e28f33f478f762a30b926 | 39.649007 | 238 | 0.555006 | 6.233845 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClientUnitTests/Spec/User/UserFollowersRequestSpec.swift | 1 | 2364 | //
// UserFollowersRequestSpec.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// 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 Quick
import Nimble
@testable import CreatubblesAPIClient
class UserFollowersRequestSpec: QuickSpec {
fileprivate let page = 1
fileprivate let pageCount = 10
fileprivate let userId = "TestUserId"
override func spec() {
describe("User followers Request") {
it("Should have a proper endpoint") {
let request = FetchUserFollowersRequest(page: self.page, perPage: self.pageCount, userId: self.userId)
expect(request.endpoint) == "users/"+self.userId+"/followers"
}
it("Should have proper method") {
let request = FetchUserFollowersRequest(userId: self.userId)
expect(request.method) == RequestMethod.get
}
it("Should have proper parameters set") {
let request = FetchUserFollowersRequest(page: self.page, perPage: self.pageCount, userId: self.userId)
let params = request.parameters
expect(params["page"] as? Int) == self.page
expect(params["per_page"] as? Int) == self.pageCount
}
}
}
}
| mit | 925125bd28816a3d88e3587284334aec | 41.981818 | 118 | 0.672589 | 4.699801 | false | false | false | false |
fromkk/FKValidator | Classes/FKValidator.swift | 1 | 988 | //
// FKValidator.swift
// FKValidator
//
// Created by Kazuya Ueoka on 2015/12/13.
// Copyright © 2015年 fromKK. All rights reserved.
//
import Foundation
open class FKValidator :NSObject
{
open var rules: Array <FKValidatorRule> = []
open var errors :Array <NSError> = []
@discardableResult
open func addRule(_ rule :FKValidatorRule) -> Self
{
self.rules.append(rule)
return self
}
@discardableResult
open func addRules(_ rules :Array<FKValidatorRule>) -> Self
{
for rule in rules
{
self.addRule(rule)
}
return self
}
open func run(_ value :String) -> Bool
{
var result :Bool = true
self.errors = []
for rule in self.rules
{
if (false == rule.run(value) )
{
result = false
self.errors.append(rule.error)
}
}
return result
}
}
| mit | 68b8b0d2269571480fc09b7d5eae86cb | 19.520833 | 63 | 0.525888 | 4.156118 | false | false | false | false |
qinting513/SwiftNote | swift之Alamofire-SwiftyJONS-Kingfisher/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift | 6 | 13274 | //
// ImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
// MARK: - Extension methods.
/**
* Set image to use from web.
*/
extension Kingfisher where Base: ImageView {
/**
Set an image with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
@discardableResult
public func setImage(with resource: Resource?,
placeholder: Image? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
guard let resource = resource else {
completionHandler?(nil, nil, .none, nil)
return .empty
}
var options = options ?? KingfisherEmptyOptionsInfo
if !options.keepCurrentImageWhileLoading {
base.image = placeholder
}
let maybeIndicator = indicator
maybeIndicator?.startAnimatingView()
setWebURL(resource.downloadURL)
if shouldPreloadAllGIF() {
options.append(.preloadAllGIFData)
}
let task = KingfisherManager.shared.retrieveImage(
with: resource,
options: options,
progressBlock: { receivedSize, totalSize in
if let progressBlock = progressBlock {
progressBlock(receivedSize, totalSize)
}
},
completionHandler: {[weak base] image, error, cacheType, imageURL in
DispatchQueue.main.safeAsync {
guard let strongBase = base, imageURL == self.webURL else {
return
}
self.setImageTask(nil)
guard let image = image else {
maybeIndicator?.stopAnimatingView()
completionHandler?(nil, error, cacheType, imageURL)
return
}
guard let transitionItem = options.firstMatchIgnoringAssociatedValue(.transition(.none)),
case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else
{
maybeIndicator?.stopAnimatingView()
strongBase.image = image
completionHandler?(image, error, cacheType, imageURL)
return
}
#if !os(macOS)
UIView.transition(with: strongBase, duration: 0.0, options: [],
animations: { maybeIndicator?.stopAnimatingView() },
completion: { _ in
UIView.transition(with: strongBase, duration: transition.duration,
options: [transition.animationOptions, .allowUserInteraction],
animations: {
// Set image property in the animation.
transition.animations?(strongBase, image)
},
completion: { finished in
transition.completion?(finished)
completionHandler?(image, error, cacheType, imageURL)
})
})
#endif
}
})
setImageTask(task)
return task
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func cancelDownloadTask() {
imageTask?.downloadTask?.cancel()
}
func shouldPreloadAllGIF() -> Bool {
return true
}
}
// MARK: - Associated Object
private var lastURLKey: Void?
private var indicatorKey: Void?
private var indicatorTypeKey: Void?
private var imageTaskKey: Void?
extension Kingfisher where Base: ImageView {
/// Get the image URL binded to this image view.
public var webURL: URL? {
return objc_getAssociatedObject(base, &lastURLKey) as? URL
}
fileprivate func setWebURL(_ url: URL) {
objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
public var indicatorType: IndicatorType {
get {
let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box<IndicatorType?>)?.value
return indicator ?? .none
}
set {
switch newValue {
case .none:
indicator = nil
case .activity:
indicator = ActivityIndicator()
case .image(let data):
indicator = ImageIndicator(imageData: data)
case .custom(let anIndicator):
indicator = anIndicator
}
objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `indicatorType` is `.none`.
public fileprivate(set) var indicator: Indicator? {
get {
return (objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator?>)?.value
}
set {
// Remove previous
if let previousIndicator = indicator {
previousIndicator.view.removeFromSuperview()
}
// Add new
if var newIndicator = newValue {
newIndicator.view.frame = base.frame
newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY)
newIndicator.view.isHidden = true
base.addSubview(newIndicator.view)
}
// Save in associated object
objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate var imageTask: RetrieveImageTask? {
return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask
}
fileprivate func setImageTask(_ task: RetrieveImageTask?) {
objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Deprecated. Only for back compatibility.
/**
* Set image to use from web. Deprecated. Use `kf` namespacing instead.
*/
extension ImageView {
/**
Set an image with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.setImage` instead.", renamed: "kf.setImage")
@discardableResult
public func kf_setImage(with resource: Resource?,
placeholder: Image? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask")
public func kf_cancelDownloadTask() { kf.cancelDownloadTask() }
/// Get the image URL binded to this image view.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL")
public var kf_webURL: URL? { return kf.webURL }
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicatorType` instead.", renamed: "kf.indicatorType")
public var kf_indicatorType: IndicatorType {
get { return kf.indicatorType }
set { kf.indicatorType = newValue }
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicator` instead.", renamed: "kf.indicator")
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `kf_indicatorType` is `.none`.
public private(set) var kf_indicator: Indicator? {
get { return kf.indicator }
set { kf.indicator = newValue }
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.imageTask")
fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setImageTask")
fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setWebURL")
fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.shouldPreloadAllGIF")
func shouldPreloadAllGIF() -> Bool { return kf.shouldPreloadAllGIF() }
}
| apache-2.0 | 3a7d87de196e963b991ff19caea8b674 | 44.930796 | 173 | 0.604867 | 5.589053 | false | false | false | false |
EgzonArifi/ToDoList | Sources/App/Controllers/ApiController.swift | 1 | 1310 | import Vapor
import HTTP
final class ApiController: ResourceRepresentable {
func index(request: Request) throws -> ResponseRepresentable {
return try JSON(node: Acronym.all().makeNode())
}
func create(request: Request) throws -> ResponseRepresentable {
var acronym = try request.acronym()
try acronym.save()
return acronym
}
func show(request: Request, acronym: Acronym) throws -> ResponseRepresentable {
return acronym
}
func update(request: Request, acronym: Acronym) throws -> ResponseRepresentable {
let new = try request.acronym()
var acronym = acronym
acronym.short = new.short
acronym.long = new.long
try acronym.save()
return acronym
}
func delete(request: Request, acronym: Acronym) throws -> ResponseRepresentable {
try acronym.delete()
return JSON([:])
}
func makeResource() -> Resource<Acronym> {
return Resource(
index: index,
store: create,
show: show,
modify: update,
destroy: delete
)
}
}
extension Request {
func acronym() throws -> Acronym {
guard let json = json else { throw Abort.badRequest }
return try Acronym(node: json)
}
}
| mit | d0b65238cb4d8efc38f1adf5247215f7 | 24.686275 | 85 | 0.60687 | 4.906367 | false | false | false | false |
JGiola/swift-corelibs-foundation | Foundation/NSLock.swift | 1 | 9282 | // 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
#if os(macOS) || os(iOS)
import Darwin
#elseif os(Linux) || CYGWIN
import Glibc
#endif
import CoreFoundation
public protocol NSLocking {
func lock()
func unlock()
}
#if CYGWIN
private typealias _MutexPointer = UnsafeMutablePointer<pthread_mutex_t?>
private typealias _ConditionVariablePointer = UnsafeMutablePointer<pthread_cond_t?>
#else
private typealias _MutexPointer = UnsafeMutablePointer<pthread_mutex_t>
private typealias _ConditionVariablePointer = UnsafeMutablePointer<pthread_cond_t>
#endif
open class NSLock: NSObject, NSLocking {
internal var mutex = _MutexPointer.allocate(capacity: 1)
#if os(macOS) || os(iOS)
private var timeoutCond = _ConditionVariablePointer.allocate(capacity: 1)
private var timeoutMutex = _MutexPointer.allocate(capacity: 1)
#endif
public override init() {
pthread_mutex_init(mutex, nil)
#if os(macOS) || os(iOS)
pthread_cond_init(timeoutCond, nil)
pthread_mutex_init(timeoutMutex, nil)
#endif
}
deinit {
pthread_mutex_destroy(mutex)
mutex.deinitialize(count: 1)
mutex.deallocate()
#if os(macOS) || os(iOS)
deallocateTimedLockData(cond: timeoutCond, mutex: timeoutMutex)
#endif
}
open func lock() {
pthread_mutex_lock(mutex)
}
open func unlock() {
pthread_mutex_unlock(mutex)
#if os(macOS) || os(iOS)
// Wakeup any threads waiting in lock(before:)
pthread_mutex_lock(timeoutMutex)
pthread_cond_broadcast(timeoutCond)
pthread_mutex_unlock(timeoutMutex)
#endif
}
open func `try`() -> Bool {
return pthread_mutex_trylock(mutex) == 0
}
open func lock(before limit: Date) -> Bool {
if pthread_mutex_trylock(mutex) == 0 {
return true
}
#if os(macOS) || os(iOS)
return timedLock(mutex: mutex, endTime: limit, using: timeoutCond, with: timeoutMutex)
#else
guard var endTime = timeSpecFrom(date: limit) else {
return false
}
return pthread_mutex_timedlock(mutex, &endTime) == 0
#endif
}
open var name: String?
}
extension NSLock {
internal func synchronized<T>(_ closure: () -> T) -> T {
self.lock()
defer { self.unlock() }
return closure()
}
}
open class NSConditionLock : NSObject, NSLocking {
internal var _cond = NSCondition()
internal var _value: Int
internal var _thread: pthread_t?
public convenience override init() {
self.init(condition: 0)
}
public init(condition: Int) {
_value = condition
}
open func lock() {
let _ = lock(before: Date.distantFuture)
}
open func unlock() {
_cond.lock()
_thread = nil
_cond.broadcast()
_cond.unlock()
}
open var condition: Int {
return _value
}
open func lock(whenCondition condition: Int) {
let _ = lock(whenCondition: condition, before: Date.distantFuture)
}
open func `try`() -> Bool {
return lock(before: Date.distantPast)
}
open func tryLock(whenCondition condition: Int) -> Bool {
return lock(whenCondition: condition, before: Date.distantPast)
}
open func unlock(withCondition condition: Int) {
_cond.lock()
_thread = nil
_value = condition
_cond.broadcast()
_cond.unlock()
}
open func lock(before limit: Date) -> Bool {
_cond.lock()
while _thread != nil {
if !_cond.wait(until: limit) {
_cond.unlock()
return false
}
}
_thread = pthread_self()
_cond.unlock()
return true
}
open func lock(whenCondition condition: Int, before limit: Date) -> Bool {
_cond.lock()
while _thread != nil || _value != condition {
if !_cond.wait(until: limit) {
_cond.unlock()
return false
}
}
_thread = pthread_self()
_cond.unlock()
return true
}
open var name: String?
}
open class NSRecursiveLock: NSObject, NSLocking {
internal var mutex = _MutexPointer.allocate(capacity: 1)
#if os(macOS) || os(iOS)
private var timeoutCond = _ConditionVariablePointer.allocate(capacity: 1)
private var timeoutMutex = _MutexPointer.allocate(capacity: 1)
#endif
public override init() {
super.init()
#if CYGWIN
var attrib : pthread_mutexattr_t? = nil
#else
var attrib = pthread_mutexattr_t()
#endif
withUnsafeMutablePointer(to: &attrib) { attrs in
pthread_mutexattr_settype(attrs, Int32(PTHREAD_MUTEX_RECURSIVE))
pthread_mutex_init(mutex, attrs)
}
}
deinit {
pthread_mutex_destroy(mutex)
mutex.deinitialize(count: 1)
mutex.deallocate()
#if os(macOS) || os(iOS)
deallocateTimedLockData(cond: timeoutCond, mutex: timeoutMutex)
#endif
}
open func lock() {
pthread_mutex_lock(mutex)
}
open func unlock() {
pthread_mutex_unlock(mutex)
#if os(macOS) || os(iOS)
// Wakeup any threads waiting in lock(before:)
pthread_mutex_lock(timeoutMutex)
pthread_cond_broadcast(timeoutCond)
pthread_mutex_unlock(timeoutMutex)
#endif
}
open func `try`() -> Bool {
return pthread_mutex_trylock(mutex) == 0
}
open func lock(before limit: Date) -> Bool {
if pthread_mutex_trylock(mutex) == 0 {
return true
}
#if os(macOS) || os(iOS)
return timedLock(mutex: mutex, endTime: limit, using: timeoutCond, with: timeoutMutex)
#else
guard var endTime = timeSpecFrom(date: limit) else {
return false
}
return pthread_mutex_timedlock(mutex, &endTime) == 0
#endif
}
open var name: String?
}
open class NSCondition: NSObject, NSLocking {
internal var mutex = _MutexPointer.allocate(capacity: 1)
internal var cond = _ConditionVariablePointer.allocate(capacity: 1)
public override init() {
pthread_mutex_init(mutex, nil)
pthread_cond_init(cond, nil)
}
deinit {
pthread_mutex_destroy(mutex)
pthread_cond_destroy(cond)
mutex.deinitialize(count: 1)
cond.deinitialize(count: 1)
mutex.deallocate()
cond.deallocate()
}
open func lock() {
pthread_mutex_lock(mutex)
}
open func unlock() {
pthread_mutex_unlock(mutex)
}
open func wait() {
pthread_cond_wait(cond, mutex)
}
open func wait(until limit: Date) -> Bool {
guard var timeout = timeSpecFrom(date: limit) else {
return false
}
return pthread_cond_timedwait(cond, mutex, &timeout) == 0
}
open func signal() {
pthread_cond_signal(cond)
}
open func broadcast() {
pthread_cond_broadcast(cond)
}
open var name: String?
}
private func timeSpecFrom(date: Date) -> timespec? {
guard date.timeIntervalSinceNow > 0 else {
return nil
}
let nsecPerSec: Int64 = 1_000_000_000
let interval = date.timeIntervalSince1970
let intervalNS = Int64(interval * Double(nsecPerSec))
return timespec(tv_sec: Int(intervalNS / nsecPerSec),
tv_nsec: Int(intervalNS % nsecPerSec))
}
#if os(macOS) || os(iOS)
private func deallocateTimedLockData(cond: _ConditionVariablePointer, mutex: _MutexPointer) {
pthread_cond_destroy(cond)
cond.deinitialize(count: 1)
cond.deallocate()
pthread_mutex_destroy(mutex)
mutex.deinitialize(count: 1)
mutex.deallocate()
}
// Emulate pthread_mutex_timedlock using pthread_cond_timedwait.
// lock(before:) passes a condition variable/mutex pair to use.
// unlock() will use pthread_cond_broadcast() to wake any waits in progress.
private func timedLock(mutex: _MutexPointer, endTime: Date,
using timeoutCond: _ConditionVariablePointer,
with timeoutMutex: _MutexPointer) -> Bool {
var timeSpec = timeSpecFrom(date: endTime)
while var ts = timeSpec {
let lockval = pthread_mutex_lock(timeoutMutex)
precondition(lockval == 0)
let waitval = pthread_cond_timedwait(timeoutCond, timeoutMutex, &ts)
precondition(waitval == 0 || waitval == ETIMEDOUT)
let unlockval = pthread_mutex_unlock(timeoutMutex)
precondition(unlockval == 0)
if waitval == ETIMEDOUT {
return false
}
let tryval = pthread_mutex_trylock(mutex)
precondition(tryval == 0 || tryval == EBUSY)
if tryval == 0 { // The lock was obtained.
return true
}
// pthread_cond_timedwait didnt timeout so wait some more.
timeSpec = timeSpecFrom(date: endTime)
}
return false
}
#endif
| apache-2.0 | e92899babd5abcacab55e610da78845b | 26.061224 | 94 | 0.615061 | 4.169811 | false | false | false | false |
juanm95/Soundwich | Quaggify/PlaylistViewController.swift | 1 | 7634 | //
// PlaylistViewController.swift
// Quaggify
//
// Created by Jonathan Bijos on 05/02/17.
// Copyright © 2017 Quaggie. All rights reserved.
//
import UIKit
class PlaylistViewController: ViewController {
var playlist: Playlist? {
didSet {
guard let playlist = playlist else {
return
}
if let name = playlist.name {
navigationItem.title = name
}
collectionView.reloadData()
}
}
var spotifyObject: SpotifyObject<PlaylistTrack>?
var limit = 20
var offset = 0
var isFetching = false
let lineSpacing: CGFloat = 16
let interItemSpacing: CGFloat = 8
let contentInset: CGFloat = 8
lazy var collectionView: UICollectionView = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.scrollDirection = .vertical
flowLayout.minimumLineSpacing = self.lineSpacing
flowLayout.minimumInteritemSpacing = self.interItemSpacing
let cv = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
cv.keyboardDismissMode = .onDrag
cv.alwaysBounceVertical = true
cv.showsVerticalScrollIndicator = false
cv.contentInset = UIEdgeInsets(top: self.contentInset, left: self.contentInset, bottom: self.contentInset, right: self.contentInset)
cv.backgroundColor = ColorPalette.black
cv.delegate = self
cv.dataSource = self
cv.register(TrackCell.self, forCellWithReuseIdentifier: TrackCell.identifier)
cv.register(PlaylistHeaderView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: PlaylistHeaderView.identifier)
return cv
}()
override func viewDidLoad() {
super.viewDidLoad()
setupViews()
fetchTracks()
}
override func willTransition(to newCollection: UITraitCollection, with coordinator: UIViewControllerTransitionCoordinator) {
collectionView.collectionViewLayout.invalidateLayout()
}
// MARK: Layout
override func setupViews() {
super.setupViews()
view.addSubview(collectionView)
collectionView.anchor(view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
}
}
// MARK: Actions
extension PlaylistViewController {
func fetchTracks () {
isFetching = true
API.fetchPlaylistTracks(playlist: playlist, limit: limit, offset: offset) { [weak self] (spotifyObject, error) in
guard let strongSelf = self else {
return
}
strongSelf.isFetching = false
strongSelf.offset += strongSelf.limit
if let error = error {
print(error)
Alert.shared.show(title: "Error", message: "Error communicating with the server")
} else if let spotifyObject = spotifyObject, let items = spotifyObject.items {
if strongSelf.spotifyObject == nil {
strongSelf.spotifyObject = spotifyObject
} else {
strongSelf.spotifyObject?.items?.append(contentsOf: items)
strongSelf.spotifyObject?.next = spotifyObject.next
strongSelf.spotifyObject?.total = spotifyObject.total
}
strongSelf.collectionView.reloadData()
//save the spotifyobject to globals
//print(spotifyObject?.items?[1].track?.id)
/* print((self?.playlist?.uri)!)
//print(strongSelf.spotifyObject?.href)
print("made it here playlistt")
var trackName = (self?.playlist?.uri)!
trackName += ":autoplay:true"
/*var trackName = "spotify:"
trackName += (User.current.id)!
trackName += ":playlist:"
trackName += (self?.playlist?.id)!
trackName += ":tracks:autoplay:true"*/
// print(trackName)*/
/* var trackName = "spotify:track:"
trackName += (spotifyObject?.items?[1].track?.id)!
print (trackName)
thePlayer.spotifyPlayer?.playSpotifyURI(trackName, startingWith: 0, startingWithPosition: 0, callback: { (error) in
if (error != nil) {
print("playing!")
}
})*/
}
}
}
func removeFromPlaylist (track: Track?, position: Int?) {
API.removePlaylistTrack(track: track, position: position, playlist: playlist) { [weak self] (snapshotId, error) in
guard let strongSelf = self else {
return
}
if let error = error {
print(error)
Alert.shared.show(title: "Error", message: "Error communicating with the server")
} else if let snapshotId = snapshotId {
strongSelf.playlist?.snapshotId = snapshotId
if let position = position {
strongSelf.spotifyObject?.items?.remove(at: position)
if let total = strongSelf.playlist?.tracks?.total {
strongSelf.playlist?.tracks?.total = total - 1
}
}
strongSelf.collectionView.reloadData()
}
}
}
}
// MARK: UICollectionViewDelegate
extension PlaylistViewController: UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
thePlayer.PP = true
thePlayer.trackList = spotifyObject
thePlayer.indeX = indexPath.item
if(!thePlayer.start){
thePlayer.nowPlaying = TrackViewController()
}
thePlayer.nowPlaying?.track = spotifyObject?.items?[safe: indexPath.item]?.track
navigationController?.tabBarController?.selectedIndex = 1
//if(!thePlayer.start){
// }
}
}
// MARK: UICollectionViewDataSource
extension PlaylistViewController: UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return spotifyObject?.items?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: TrackCell.identifier, for: indexPath) as? TrackCell {
let track = spotifyObject?.items?[safe: indexPath.item]?.track
cell.track = track
cell.position = indexPath.item
if let totalItems = spotifyObject?.items?.count, indexPath.item == totalItems - 1, spotifyObject?.next != nil {
if !isFetching {
fetchTracks()
}
}
return cell
}
return UICollectionViewCell()
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
if let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: UICollectionElementKindSectionHeader, withReuseIdentifier: PlaylistHeaderView.identifier, for: indexPath) as? PlaylistHeaderView {
headerView.playlist = playlist
return headerView
}
default: break
}
return UICollectionReusableView()
}
}
// MARK: UICollectionViewDelegateFlowLayout
extension PlaylistViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: view.frame.width - (contentInset * 2), height: 72)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: view.frame.width, height: 320)
}
}
| mit | da1ff09474d9111d61b60a5f1800d0df | 32.04329 | 223 | 0.687017 | 5.286011 | false | false | false | false |
937447974/YJCocoa | YJCocoa/Classes/AppFrameworks/UIKit/Extension/UIButtonExt.swift | 1 | 2639 | //
// UIButtonExt.swift
// YJCocoa
//
// HomePage:https://github.com/937447974/YJCocoa
// YJ技术支持群:557445088
//
// Created by 阳君 on 2019/6/19.
// Copyright © 2016-现在 YJCocoa. All rights reserved.
//
import UIKit
public typealias UIButtonTouchClosure = (_ button: UIButton) -> ()
@objc
public extension UIButton {
/// 设置标题
/// - parameter title: 标题
/// - parameter font: 字体大小
/// - parameter color: 字体颜色
/// - parameter highlightedColor: 点击高亮,默认 color 的 0.75 透明度
func setTitle(_ title: String, font: UIFont? = nil, color: UIColor? = nil, highlightedColor: UIColor? = nil) {
self.setTitle(title, for: .normal)
if let font = font {
self.titleLabel?.font = font
}
if let color = color {
self.setTitleColor(color, highlightedColor: highlightedColor)
}
}
/// 设置字体颜色
/// - parameter color: 默认色
/// - parameter highlighted: 高亮色,默认 color 的 0.75 透明度
func setTitleColor(_ color: UIColor, highlightedColor: UIColor? = nil) {
self.setTitleColor(color, for: .normal)
self.setTitleColor(highlightedColor ?? color.withAlphaComponent(0.75), for: .highlighted)
}
/// 设置图片
/// - parameter image: 标题
/// - parameter highlightedImage: 高亮图片,默认 image 的 0.75 透明度
func setImage(_ image: UIImage?, highlightedImage: UIImage? = nil) {
self.setImage(image, for: .normal)
let highlightedImage = highlightedImage ?? image?.withAlphaComponent(0.75)
self.setImage(highlightedImage, for: .highlighted)
}
/// 设置图片
/// - parameter image: 标题
/// - parameter selectedImage: 选中的图片
func setImage(_ image: UIImage?, selectedImage: UIImage?) {
self.setImage(image, for: .normal)
self.setImage(selectedImage, for: .selected)
}
// 设置背景图片
/// - parameter color: 默认色
/// - parameter highlightedColor: 高亮色,默认 color 的 0.75 透明度
func setBackgroundImage(_ color: UIColor, highlightedColor: UIColor? = nil) {
let highlightedColor = highlightedColor ?? color.withAlphaComponent(0.75)
if let normalImage = UIImage.image(with: color, size: self.frameSize) {
self.setBackgroundImage(normalImage, for: .normal)
self.setBackgroundImage(UIImage.image(with: highlightedColor, size: self.frameSize), for: .highlighted)
} else {
self.backgroundColor = color
}
}
}
| mit | 8e43047943f2b93f6b401498600d1183 | 32.861111 | 115 | 0.630435 | 4.24 | false | false | false | false |
yanyuqingshi/ios-charts | Charts/Classes/Data/LineRadarChartDataSet.swift | 1 | 1518 | //
// LineRadarChartDataSet.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import CoreGraphics.CGBase
import UIKit.UIColor
public class LineRadarChartDataSet: BarLineScatterCandleChartDataSet
{
public var fillColor = UIColor(red: 140.0/255.0, green: 234.0/255.0, blue: 255.0/255.0, alpha: 1.0)
public var fillAlpha = CGFloat(0.33)
private var _lineWidth = CGFloat(1.0)
public var drawFilledEnabled = false
/// line width of the chart (min = 0.2, max = 10)
/// :default: 1
public var lineWidth: CGFloat
{
get
{
return _lineWidth;
}
set
{
_lineWidth = newValue;
if (_lineWidth < 0.2)
{
_lineWidth = 0.5;
}
if (_lineWidth > 10.0)
{
_lineWidth = 10.0;
}
}
}
public var isDrawFilledEnabled: Bool
{
return drawFilledEnabled;
}
// MARK: NSCopying
public override func copyWithZone(zone: NSZone) -> AnyObject
{
var copy = super.copyWithZone(zone) as! LineRadarChartDataSet;
copy.fillColor = fillColor;
copy._lineWidth = _lineWidth;
copy.drawFilledEnabled = drawFilledEnabled;
return copy;
}
}
| apache-2.0 | 7960d352912ed57fa36530a42aba879a | 23.483871 | 103 | 0.581028 | 4.324786 | false | false | false | false |
robertoseidenberg/MixerBox | MixerBox/MetalView+Drawing.swift | 1 | 1347 | #if !(SIMULATOR)
import Metal
#endif
extension MetalView {
func redraw() {
#if !(SIMULATOR)
if isDrawing == false {
isDrawing = true
if let drawable = metalLayer.nextDrawable() {
let descriptor = MTLRenderPassDescriptor()
descriptor.colorAttachments[0].texture = drawable.texture
descriptor.colorAttachments[0].clearColor = MTLClearColor(red: 0.85, green: 0.85, blue: 0.85, alpha: 1)
descriptor.colorAttachments[0].storeAction = .store
descriptor.colorAttachments[0].loadAction = .clear
guard let commandBuffer = commandQueue.makeCommandBuffer() else {
fatalError("Unexpected nil value: commandBuffer")
}
guard let encoder = commandBuffer.makeRenderCommandEncoder(descriptor: descriptor) else {
fatalError("Unexpected nil value: encoder")
}
encoder.setRenderPipelineState(pipeline)
updateFragmentBytes(forEncoder: encoder)
encoder.setVertexBuffer(vertexBuffer, offset: 0, index: 1)
encoder.drawPrimitives(type: .triangleStrip, vertexStart: 0, vertexCount: 4)
encoder.endEncoding()
commandBuffer.present(drawable)
commandBuffer.addCompletedHandler { _ in
self.isDrawing = false
}
commandBuffer.commit()
}
}
#endif
}
}
| mit | 1e621ece24403caf36e36af681366704 | 27.659574 | 111 | 0.6585 | 5.06391 | false | false | false | false |
rplankenhorn/BrightFreddy | Pod/Classes/Service+Freddy.swift | 1 | 3621 | //
// Service.swift
// Pods
//
// Created by Robbie Plankenhorn on 3/10/16.
//
//
import Foundation
import BrightFutures
import Freddy
import Result
extension Service {
// MARK: Get JSON Object
public class func getJSONObject(path: String, headers: [String : String] = [:], dotPath: String? = nil) -> Future<JSON, NSError> {
return get(fullURLWithPath(path), headers: headers).flatMap { response -> Result<JSON, NSError> in
do {
let json = try response.bodyJSON()
if let dotPath = dotPath, let jsonDotPathObject = json[dotPath] {
return Result.Success(jsonDotPathObject)
} else {
return Result.Success(json)
}
} catch {
return Result.Failure(NSError(domain: "", code: 0, userInfo: nil))
}
}
}
// MARK: Get Object
public class func getObject<T: JSONDecodable>(type: T.Type, path: String, headers: [String : String] = [:], dotPath: String? = nil) -> Future<T, NSError> {
return getJSONObject(path, headers: headers, dotPath: dotPath).flatMap { json -> Result<T, NSError> in
do {
let object = try T(json: json)
return Result.Success(object)
} catch {
return Result.Failure(NSError(domain: "", code: 0, userInfo: nil))
}
}
}
// MARK: Get Objects
public class func getObjects<T: JSONDecodable>(type: T.Type, path: String, headers: [String : String] = [:], dotPath: String? = nil) -> Future<[T], NSError> {
return getJSONObject(path, headers: headers).flatMap { json -> Result<[T], NSError> in
do {
if case .Array(let jsonObjects) = json {
var objects = [T]()
for jsonObject in jsonObjects {
objects.append(try T(json: jsonObject))
}
return Result.Success(objects)
}
} catch {
}
return Result.Failure(NSError(domain: "", code: 0, userInfo: nil))
}
}
}
extension Service {
// MARK: Post JSON Object
public class func postJSONObject(object: JSON, path: String, headers: [String : String] = [:]) -> Future<JSON, NSError> {
do {
let body = try object.serialize()
return post(fullURLWithPath(path), body: body, headers: headers).flatMap { response -> Result<JSON, NSError> in
do {
let json = try response.bodyJSON()
return Result.Success(json)
} catch {
return Result.Failure(NSError(domain: "", code: 0, userInfo: nil))
}
}
} catch {
return Promise<JSON, NSError>().completeWith(NSError(domain: "", code: 0, userInfo: nil)).future
}
}
// MARK: Post Object
public class func postObject<T: JSONEncodable, D: JSONDecodable>(object: T, path: String, headers: [String : String] = [:]) -> Future<D, NSError> {
return postJSONObject(object.toJSON(), path: path, headers: headers).flatMap { json -> Result<D, NSError> in
do {
let object = try D(json: json)
return Result.Success(object)
} catch {
return Result.Failure(NSError(domain: "", code: 0, userInfo: nil))
}
}
}
} | mit | ccd9b50d7b35f40e3c1ae99ebd26c588 | 33.826923 | 162 | 0.516984 | 4.636364 | false | false | false | false |
gewill/GWCollectionViewFloatCellLayout | Demo/AppDelegate.swift | 1 | 2527 | //
// AppDelegate.swift
// Demo
//
// Created by Will on 2/10/17.
// Copyright © 2017 Will. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window!.backgroundColor = UIColor.white
let mainController: CollectionViewController = CollectionViewController(nibName: "CollectionViewController", bundle: nil)
let nav = UINavigationController(rootViewController: mainController)
self.window!.rootViewController = nav
self.window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 044383cf7a4843f5dbc467e5197857f1 | 44.927273 | 285 | 0.739113 | 5.753986 | false | false | false | false |
ddaguro/clintonconcord | OIMApp/SignInViewController.swift | 1 | 22469 | //
// SignInViewController.swift
// OIMApp
//
// Created by Linh NGUYEN on 5/7/15.
// Copyright (c) 2015 Persistent Systems. All rights reserved.
//
import Foundation
import UIKit
import LocalAuthentication
import WatchConnectivity
class SignInViewController : UIViewController, UITextFieldDelegate, WCSessionDelegate {
@IBOutlet var titleLabel : UILabel!
@IBOutlet var facebookButton : UIButton!
@IBOutlet var twitterButton : UIButton!
@IBOutlet var noAccountButton : UIButton!
@IBOutlet var bgImageView : UIImageView!
@IBOutlet var signInButton : UIButton!
@IBOutlet var forgotPassword : UIButton!
@IBOutlet var passwordContainer : UIView!
@IBOutlet var passwordLabel : UILabel!
@IBOutlet var passwordTextField : UITextField!
@IBOutlet var passwordUnderline : UIView!
@IBOutlet var userContainer : UIView!
@IBOutlet var userLabel : UILabel!
@IBOutlet var userTextField : UITextField!
@IBOutlet var userUnderline : UIView!
var api : API!
var users : [Users]!
let transitionOperator = TransitionOperator()
var FIDOusername : String = ""
var FIDOpassword : String = ""
private var session: WCSession? = WCSession.isSupported() ? WCSession.defaultSession() : nil
override func viewDidLoad() {
super.viewDidLoad()
ReadAPIEndpoint()
if (WCSession.isSupported()) {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}
facebookButton.hidden = false
twitterButton.hidden = false
titleLabel.hidden = true
noAccountButton.setTitle("Sign In with FIDO", forState: .Normal)
noAccountButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
noAccountButton.titleLabel?.font = UIFont(name: MegaTheme.semiBoldFontName, size: 22)
noAccountButton.layer.borderWidth = 3
noAccountButton.layer.borderColor = UIColor.whiteColor().CGColor
noAccountButton.layer.cornerRadius = 5
noAccountButton.addTarget(self, action: "LoggedInFIDO", forControlEvents: .TouchUpInside)
bgImageView.image = UIImage(named: "login-bg")
bgImageView.contentMode = .ScaleAspectFill
userContainer.backgroundColor = UIColor.clearColor()
userLabel.text = "Username"
userLabel.font = UIFont(name: MegaTheme.fontName, size: 20)
userLabel.textColor = UIColor.whiteColor()
userTextField.delegate = self
userTextField.text = myLoginId
userTextField.font = UIFont(name: MegaTheme.fontName, size: 20)
userTextField.textColor = UIColor.whiteColor()
passwordContainer.backgroundColor = UIColor.clearColor()
passwordLabel.text = "Password"
passwordLabel.font = UIFont(name: MegaTheme.fontName, size: 20)
passwordLabel.textColor = UIColor.whiteColor()
passwordTextField.delegate = self
passwordTextField.text = ""
passwordTextField.font = UIFont(name: MegaTheme.fontName, size: 20)
passwordTextField.textColor = UIColor.whiteColor()
passwordTextField.secureTextEntry = true
forgotPassword.setTitle("", forState: .Normal)
forgotPassword.setTitleColor(UIColor.whiteColor(), forState: .Normal)
forgotPassword.titleLabel?.font = UIFont(name: MegaTheme.semiBoldFontName, size: 15)
signInButton.setTitle("Sign In", forState: .Normal)
signInButton.setTitleColor(UIColor.whiteColor(), forState: .Normal)
signInButton.titleLabel?.font = UIFont(name: MegaTheme.semiBoldFontName, size: 22)
signInButton.layer.borderWidth = 3
signInButton.layer.borderColor = UIColor.whiteColor().CGColor
signInButton.layer.cornerRadius = 5
signInButton.addTarget(self, action: "LoggedIn", forControlEvents: .TouchUpInside)
twitterButton.setTitle("Ver 1.4.2", forState: .Normal)
twitterButton.setTitleColor(self.UIColorFromHex(0x37474f, alpha: 1.0), forState: .Normal)
twitterButton.titleLabel?.font = UIFont(name: MegaTheme.semiBoldFontName, size: 10)
twitterButton.addTarget(self, action: "buttonSaveAction", forControlEvents: .TouchUpInside)
facebookButton.setTitle("...", forState: .Normal)
facebookButton.setTitleColor(self.UIColorFromHex(0x37474f, alpha: 1.0), forState: .Normal)
facebookButton.titleLabel?.font = UIFont(name: MegaTheme.semiBoldFontName, size: 10)
facebookButton.addTarget(self, action: "buttonResetAction", forControlEvents: .TouchUpInside)
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: "DismissKeyboard")
view.addGestureRecognizer(tap)
for key in NSUserDefaults.standardUserDefaults().dictionaryRepresentation().keys {
NSUserDefaults.standardUserDefaults().removeObjectForKey(key)
}
UIApplication.sharedApplication().registerForRemoteNotifications()
}
func textFieldShouldReturn(userText: UITextField) -> Bool {
self.view.endEditing(true)
self.LoggedIn()
return false
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
func dismiss(){
dismissViewControllerAnimated(true, completion: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let controller = segue.destinationViewController as! DashboardViewController
controller.nagivationStyleToPresent = "presentTableNavigation"
}
func LoggedIn(){
ReadAPIEndpoint()
self.api = API()
let url = myAPIEndpoint + "/users/login"
let username = userTextField.text
let password = passwordTextField.text
let paramstring = "username=" + username! + "&password=" + password!
if username != "" {
api.LogIn(username!, params: paramstring, url : url) { (succeeded: Bool, msg: String) -> () in
let alert = UIAlertController(title: "Success!", message: msg, preferredStyle: .Alert)
//-->self.presentViewController(alert, animated: true, completion: nil) uncomment code if we want to display alert on success.
if(succeeded) {
let url = myAPIEndpoint + "/users/" + username!
self.api.loadUser(username!, apiUrl: url, completion : self.didLoadUsers)
if myLoginId != username {
myFIDO = false
}
NSUserDefaults.standardUserDefaults().setObject(username, forKey: "requestorUserId")
NSUserDefaults.standardUserDefaults().synchronize()
myLoginId = NSUserDefaults.standardUserDefaults().objectForKey("requestorUserId") as! String
if self.session == self.validSession {
WCSession.defaultSession().transferUserInfo(["data" : username! + "," + password! + "," + myAPIEndpoint ])
}
self.SaveLogin(username!, pwd: password!)
}
else {
alert.title = "Failed : ("
alert.message = msg
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if(succeeded)
{
self.performSegueWithIdentifier("SegueDashboard", sender: self)
} else {
self.presentViewController(alert, animated: true, completion: nil)
}
})
}
} else {
let alert = UIAlertController(title: "Failed : (", message: "Incorrect username and password", preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in }
alert.addAction(OKAction)
self.presentViewController(alert, animated: true) { }
}
}
func LoggedInFIDO(){
if self.ReadLogin() {
if myLoginId != self.userTextField.text {
let alert = UIAlertView(title: "Failed \u{1F44E}", message: "FIDO UAF Authenication Failed", delegate: nil, cancelButtonTitle: "Okay")
alert.show()
dismissViewControllerAnimated(true, completion: nil)
} else {
let context = LAContext()
var error: NSError?
ReadAPIEndpoint()
// check if Touch ID is available
if context.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: &error) {
//try context.canEvaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, error: &error)
let reason = "Authenticate with Touch ID"
context.evaluatePolicy(.DeviceOwnerAuthenticationWithBiometrics, localizedReason: reason, reply:
{(succes: Bool, error: NSError?) in
dispatch_async(dispatch_get_main_queue(), {
if succes {
myFIDO = true
//var alert = UIAlertView(title: "Success \u{1F44D}", message: "FIDO UAF Authenication Succeeded", delegate: nil, cancelButtonTitle: "Okay")
//alert.show()
self.api = API()
let url = myAPIEndpoint + "/users/login"
//self.ReadLogin()
//var username = self.userTextField.text
//var password = "Oracle123"
let username = self.FIDOusername
let password = self.FIDOpassword
let paramstring = "username=" + username + "&password=" + password
if username != "" {
self.api.LogIn(username, params: paramstring, url : url) { (succeeded: Bool, msg: String) -> () in
let alert = UIAlertView(title: "Success!", message: msg, delegate: nil, cancelButtonTitle: "Okay")
if(succeeded) {
alert.title = "Success!"
alert.message = msg
//load user object
self.users = [Users]()
let url = myAPIEndpoint + "/users/" + username
self.api.loadUser(username, apiUrl: url, completion : self.didLoadUsers)
let appGroupID = "group.com.persistent.plat-sol.OIGApp"
if let defaults = NSUserDefaults(suiteName: appGroupID) {
defaults.setValue(username, forKey: "userLogin")
}
NSUserDefaults.standardUserDefaults().setObject(username, forKey: "requestorUserId")
NSUserDefaults.standardUserDefaults().synchronize()
myLoginId = NSUserDefaults.standardUserDefaults().objectForKey("requestorUserId") as! String
if self.session == self.validSession {
WCSession.defaultSession().transferUserInfo(["data" : username + "," + password + "," + myAPIEndpoint ])
}
}
else {
alert.title = "Failed : ("
alert.message = msg
}
// Move to the UI thread
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if(succeeded)
{
self.performSegueWithIdentifier("SegueDashboard", sender: self)
} else {
alert.show()
}
})
}
} else {
let alert = UIAlertView(title: "Failed : (", message: "Incorrect username and password", delegate: nil, cancelButtonTitle: "Okay")
alert.show()
}
}
else {
//self.showAlertController("Touch ID Authentication Failed")
}
})
})
}
}
} else {
let alert = UIAlertView(title: "Please Register for FIOD", message: "This user account is not registered for FIDO UAF, or the application was upgraded and re-registration is required. Please sign in with your Username and Password and re-register for FIDO UAF.", delegate: nil, cancelButtonTitle: "Okay")
alert.show()
dismissViewControllerAnimated(true, completion: nil)
}
}
func didLoadUsers(loadedUsers: [Users]){
users = [Users]()
for usr in loadedUsers {
users.append(usr)
NSUserDefaults.standardUserDefaults().setObject(usr.DisplayName, forKey: "DisplayName")
NSUserDefaults.standardUserDefaults().setObject(usr.Title, forKey: "Title")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
func DismissKeyboard(){
view.endEditing(true)
}
func SaveLogin (usr: String, pwd: String) {
let file = "userlogin.txt"
if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) {
let dir = dirs[0] as NSString!
let path = dir.stringByAppendingPathComponent(file);
let text = usr + "," + pwd
do {
try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
} catch {
}
}
}
func ReadLogin() -> Bool {
let file = "userlogin.txt"
if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) {
let dir = dirs[0] as NSString!
let path = dir.stringByAppendingPathComponent(file);
let text = try? String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
if text != nil {
let loginInfo: String = text!
let loginInfoArray = loginInfo.componentsSeparatedByString(",")
let username: String = loginInfoArray[0]
let password: String = loginInfoArray[1]
FIDOusername = username
FIDOpassword = password
return true
} else {
return false
}
}
return false
}
private var validSession: WCSession? {
// paired - the user has to have their device paired to the watch
// watchAppInstalled - the user must have your watch app installed
// Note: if the device is paired, but your watch app is not installed
// consider prompting the user to install it for a better experience
if let session = session where session.paired && session.watchAppInstalled {
return session
}
return nil
}
func buttonSaveAction()
{
if myAPIEndpoint != "" {
}
ReadAPIEndpoint()
let alerttitle : String! = "Server Configuration"
let alertmsg : String! = "Set custom server"
var doalert : DOAlertController
doalert = DOAlertController(title: alerttitle, message: alertmsg, preferredStyle: .Alert)
doalert.addTextFieldWithConfigurationHandler { textField in
//textField.placeholder = " Enter RESTful API Endpoint "
textField.text = myAPIEndpoint.lowercaseString
}
let saveAction = DOAlertAction(title: "OK", style: .Default) { action in
let textField = doalert.textFields![0] as! UITextField
let file = "apiEndpoint.txt"
if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) {
let dir = dirs[0] as NSString!
let path = dir.stringByAppendingPathComponent(file);
let text = textField.text!
do {
try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
} catch {
}
}
}
let cancelAction = DOAlertAction(title: "Cancel", style: .Cancel) { action in
}
doalert.addAction(cancelAction)
doalert.addAction(saveAction)
presentViewController(doalert, animated: true, completion: nil)
}
func buttonResetAction()
{
let alerttitle : String! = "Server Configuration"
let alertmsg : String! = "Would you like to reset server to default?"
var doalert : DOAlertController
doalert = DOAlertController(title: alerttitle, message: alertmsg, preferredStyle: .Alert)
let saveAction = DOAlertAction(title: "Reset", style: .Default) { action in
let file = "apiEndpoint.txt"
if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) {
let dir = dirs[0] as NSString!
let path = dir.stringByAppendingPathComponent(file);
let text = "http://ec2-52-25-57-202.us-west-2.compute.amazonaws.com:9441/idaas/im/v1"
do {
try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
} catch {
}
}
}
let cancelAction = DOAlertAction(title: "Cancel", style: .Cancel) { action in
}
doalert.addAction(cancelAction)
doalert.addAction(saveAction)
presentViewController(doalert, animated: true, completion: nil)
}
func ReadAPIEndpoint() -> Bool {
let file = "apiEndpoint.txt"
if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) {
let dir = dirs[0] as NSString!
let path = dir.stringByAppendingPathComponent(file);
//print(path)
let text = try? String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
var url = ""
if text != nil {
url = text!
myAPIEndpoint = url
return true
} else {
// step 1 - set endpoint to session on initial load
url = "http://ec2-52-25-57-202.us-west-2.compute.amazonaws.com:9441/idaas/im/v1"
myAPIEndpoint = url
// step 2 - write to local device for subsuquent acces
let file = "apiEndpoint.txt"
if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) {
let dir = dirs[0] as NSString!
let path = dir.stringByAppendingPathComponent(file);
let text = "http://ec2-52-25-57-202.us-west-2.compute.amazonaws.com:9441/idaas/im/v1"
do {
try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
} catch {
}
}
return false
}
}
return false
}
func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor {
let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
let blue = CGFloat(rgbValue & 0xFF)/256.0
return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}
} | mit | fd8a686e0b580b8a729685a7b11e642a | 44.578093 | 317 | 0.524723 | 6.147469 | false | false | false | false |
proversity-org/edx-app-ios | Source/OEXRouter+Swift.swift | 1 | 28064 | //
// OEXRouter+Swift.swift
// edX
//
// Created by Akiva Leffert on 5/7/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import WebKit
// The router is an indirection point for navigation throw our app.
// New router logic should live here so it can be written in Swift.
// We should gradually migrate the existing router class here and then
// get rid of the objc version
enum CourseHTMLBlockSubkind {
case Base
case Problem
}
enum CourseBlockDisplayType {
case Unknown
case Outline
case Unit
case Video
case HTML(CourseHTMLBlockSubkind)
case Discussion(DiscussionModel)
var isUnknown : Bool {
switch self {
case .Unknown: return true
default: return false
}
}
}
extension CourseBlock {
var displayType : CourseBlockDisplayType {
switch self.type {
case .Unknown("recap"): return .HTML(.Base)
case .Unknown(_), .HTML: return multiDevice ? .HTML(.Base) : .Unknown
case .Problem: return multiDevice ? .HTML(.Problem) : .Unknown
case .Course: return .Outline
case .Chapter: return .Outline
case .Section: return .Outline
case .Unit: return .Unit
case let .Video(summary): return (summary.isSupportedVideo) ? .Video : .Unknown
case let .Discussion(discussionModel): return .Discussion(discussionModel)
}
}
}
extension OEXRouter {
func showCoursewareForCourseWithID(courseID : String, fromController controller : UIViewController) {
showContainerForBlockWithID(blockID: nil, type: CourseBlockDisplayType.Outline, parentID: nil, courseID : courseID, fromController: controller)
}
func unitControllerForCourseID(courseID : String, blockID : CourseBlockID?, initialChildID : CourseBlockID?, forMode mode: CourseOutlineMode? = .full) -> CourseContentPageViewController {
let contentPageController = CourseContentPageViewController(environment: environment, courseID: courseID, rootID: blockID, initialChildID: initialChildID, forMode: mode ?? .full)
return contentPageController
}
func showContainerForBlockWithID(blockID : CourseBlockID?, type : CourseBlockDisplayType, parentID : CourseBlockID?, courseID : CourseBlockID, fromController controller: UIViewController, forMode mode: CourseOutlineMode? = .full) {
switch type {
case .Outline:
let outlineController = controllerForBlockWithID(blockID: blockID, type: type, courseID: courseID, forMode: mode)
controller.navigationController?.pushViewController(outlineController, animated: true)
case .Unit:
let outlineController = controllerForBlockWithID(blockID: blockID, type: type, courseID: courseID, forMode: mode)
controller.navigationController?.pushViewController(outlineController, animated: true)
case .HTML:
fallthrough
case .Video:
fallthrough
case .Unknown:
let pageController = unitControllerForCourseID(courseID: courseID, blockID: parentID, initialChildID: blockID, forMode: mode)
if let delegate = controller as? CourseContentPageViewControllerDelegate {
pageController.navigationDelegate = delegate
}
controller.navigationController?.pushViewController(pageController, animated: true)
case .Discussion:
let pageController = unitControllerForCourseID(courseID: courseID, blockID: parentID, initialChildID: blockID)
if let delegate = controller as? CourseContentPageViewControllerDelegate {
pageController.navigationDelegate = delegate
}
controller.navigationController?.pushViewController(pageController, animated: true)
}
}
private func controllerForBlockWithID(blockID : CourseBlockID?, type : CourseBlockDisplayType, courseID : String, forMode mode: CourseOutlineMode? = .full) -> UIViewController {
switch type {
case .Outline:
let outlineController = CourseOutlineViewController(environment: self.environment, courseID: courseID, rootID: blockID, forMode: mode)
return outlineController
case .Unit:
return unitControllerForCourseID(courseID: courseID, blockID: blockID, initialChildID: nil, forMode: mode)
case .HTML:
let controller = HTMLBlockViewController(blockID: blockID, courseID : courseID, environment : environment)
return controller
case .Video:
let controller = VideoBlockViewController(environment: environment, blockID: blockID, courseID: courseID)
return controller
case .Unknown:
let controller = CourseUnknownBlockViewController(blockID: blockID, courseID : courseID, environment : environment)
return controller
case let .Discussion(discussionModel):
let controller = DiscussionBlockViewController(blockID: blockID, courseID: courseID, topicID: discussionModel.topicID, environment: environment)
return controller
}
}
func controllerForBlock(block : CourseBlock, courseID : String) -> UIViewController {
return controllerForBlockWithID(blockID: block.blockID, type: block.displayType, courseID: courseID)
}
@objc(showMyCoursesAnimated:pushingCourseWithID:) func showMyCourses(animated: Bool = true, pushingCourseWithID courseID: String? = nil) {
let controller = EnrolledTabBarViewController(environment: environment)
showContentStack(withRootController: controller, animated: animated)
if let courseID = courseID {
showCourseWithID(courseID: courseID, fromController: controller, animated: false)
}
}
@objc func showEnrolledTabBarView() {
let controller = EnrolledTabBarViewController(environment: environment)
showContentStack(withRootController: controller, animated: false)
}
func showCourseDates(controller:UIViewController, courseID: String) {
let courseDates = CourseDatesViewController(environment: environment, courseID: courseID)
controller.navigationController?.pushViewController(courseDates, animated: true)
}
func showCourseVideos(controller:UIViewController, courseID: String) {
showContainerForBlockWithID(blockID: nil, type: CourseBlockDisplayType.Outline, parentID: nil, courseID : courseID, fromController: controller, forMode: .video)
}
// MARK: Deep Linking
//Method can be use to navigate on particular tab of course dashboard with deep link type
func showCourse(with deeplink: DeepLink, courseID: String, from controller: UIViewController) {
var courseDashboardController = controller.navigationController?.viewControllers.compactMap({ (controller) -> UIViewController? in
if controller is CourseDashboardViewController {
return controller
}
return nil
}).first
if let dashboardController = courseDashboardController as? CourseDashboardViewController, dashboardController.courseID == deeplink.courseId {
controller.navigationController?.setToolbarHidden(true, animated: false)
controller.navigationController?.popToViewController(dashboardController, animated: true)
}
else {
if let controllers = controller.navigationController?.viewControllers, let enrolledTabBarController = controllers.first as? EnrolledTabBarViewController {
popToRoot(controller: controller)
enrolledTabBarController.switchTab(with: deeplink.type)
let dashboardController = CourseDashboardViewController(environment: environment, courseID: courseID)
courseDashboardController = dashboardController
enrolledTabBarController.navigationController?.pushViewController(dashboardController, animated: true)
}
}
if let dashboardController = courseDashboardController as? CourseDashboardViewController {
dashboardController.switchTab(with: deeplink.type)
}
}
func showProgram(with type: DeepLinkType, url: URL? = nil, from controller: UIViewController) {
var controller = controller
if let controllers = controller.navigationController?.viewControllers, let enrolledTabBarView = controllers.first as? EnrolledTabBarViewController {
popToRoot(controller: controller)
let programView = enrolledTabBarView.switchTab(with: type)
controller = programView
} else {
let enrolledTabBarControler = EnrolledTabBarViewController(environment: environment)
controller = enrolledTabBarControler
showContentStack(withRootController: enrolledTabBarControler, animated: false)
}
if let url = url, type == .programDetail {
showProgramDetails(with: url, from: controller)
}
}
func showAnnouncment(from controller : UIViewController, courseID : String) {
let announcementViewController = CourseAnnouncementsViewController(environment: environment, courseID: courseID)
controller.navigationController?.pushViewController(announcementViewController, animated: true)
}
private func popToRoot(controller: UIViewController) {
controller.navigationController?.setToolbarHidden(true, animated: false)
controller.navigationController?.popToRootViewController(animated: true)
}
func showDiscoveryController(from controller: UIViewController, type: DeepLinkType, isUserLoggedIn: Bool, pathID: String?) {
let bottomBar = BottomBarView(environment: environment)
var discoveryController = discoveryViewController(bottomBar: bottomBar, searchQuery: nil)
if isUserLoggedIn {
// Pop out all views and switches enrolledCourses tab on the bases of link type
if let controllers = controller.navigationController?.viewControllers, let enrolledTabBarView = controllers.first as? EnrolledTabBarViewController {
popToRoot(controller: controller)
discoveryController = enrolledTabBarView.switchTab(with: type)
}
else {
//Create new stack of views and switch tab
let enrolledTabController = EnrolledTabBarViewController(environment: environment)
showContentStack(withRootController: enrolledTabController, animated: false)
discoveryController = enrolledTabController.switchTab(with: type)
}
}
else {
if let controllers = controller.navigationController?.viewControllers, let discoveryView = controllers.first as? DiscoveryViewController {
popToRoot(controller: controller)
discoveryController = discoveryView
}
else if let discoveryController = discoveryController {
showControllerFromStartupScreen(controller: discoveryController)
}
}
// Switch segment tab on discovery view
if let discoveryController = discoveryController as? DiscoveryViewController {
discoveryController.switchSegment(with: type)
}
// If the pathID is given the detail view will open
if let pathID = pathID, let discoveryController = discoveryController {
showDiscoveryDetail(from: discoveryController, type: type, pathID: pathID, bottomBar: bottomBar)
}
}
func showDiscoveryDetail(from controller: UIViewController, type: DeepLinkType, pathID: String, bottomBar: UIView?) {
if type == .courseDetail {
showCourseDetails(from: controller, with: pathID, bottomBar: bottomBar)
}
else if type == .programDiscoveryDetail {
showProgramDetail(from: controller, with: pathID, bottomBar: bottomBar)
}
else if type == .degreeDiscoveryDetail {
showProgramDetail(from: controller, with: pathID, bottomBar: bottomBar, type: .degree)
}
}
func showDiscussionResponsesFromViewController(controller: UIViewController, courseID : String, thread : DiscussionThread, isDiscussionBlackedOut: Bool) {
let storyboard = UIStoryboard(name: "DiscussionResponses", bundle: nil)
let responsesViewController = storyboard.instantiateInitialViewController() as! DiscussionResponsesViewController
responsesViewController.environment = environment
responsesViewController.courseID = courseID
responsesViewController.thread = thread
responsesViewController.isDiscussionBlackedOut = isDiscussionBlackedOut
controller.navigationController?.pushViewController(responsesViewController, animated: true)
}
func showDiscussionResponses(from controller: UIViewController, courseID: String, threadID: String, isDiscussionBlackedOut: Bool, completion: (()->Void)?) {
let storyboard = UIStoryboard(name: "DiscussionResponses", bundle: nil)
let responsesViewController = storyboard.instantiateInitialViewController() as! DiscussionResponsesViewController
responsesViewController.environment = environment
responsesViewController.courseID = courseID
responsesViewController.threadID = threadID
responsesViewController.isDiscussionBlackedOut = isDiscussionBlackedOut
controller.navigationController?.delegate = self
if let completion = completion {
controller.navigationController?.pushViewController(viewController: responsesViewController, completion: completion)
}
}
func showDiscussionComments(from controller: UIViewController, courseID: String, commentID: String, threadID: String) {
let discussionCommentController = DiscussionCommentsViewController(environment: environment, courseID: courseID, commentID: commentID, threadID: threadID)
if let delegate = controller as? DiscussionCommentsViewControllerDelegate {
discussionCommentController.delegate = delegate
}
controller.navigationController?.pushViewController(discussionCommentController, animated: true)
}
func showDiscussionCommentsFromViewController(controller: UIViewController, courseID : String, response : DiscussionComment, closed : Bool, thread: DiscussionThread, isDiscussionBlackedOut: Bool) {
let commentsVC = DiscussionCommentsViewController(environment: environment, courseID : courseID, responseItem: response, closed: closed, thread: thread, isDiscussionBlackedOut: isDiscussionBlackedOut)
if let delegate = controller as? DiscussionCommentsViewControllerDelegate {
commentsVC.delegate = delegate
}
controller.navigationController?.pushViewController(commentsVC, animated: true)
}
func showDiscussionNewCommentFromController(controller: UIViewController, courseID : String, thread:DiscussionThread, context: DiscussionNewCommentViewController.Context) {
let newCommentViewController = DiscussionNewCommentViewController(environment: environment, courseID : courseID, thread:thread, context: context)
if let delegate = controller as? DiscussionNewCommentViewControllerDelegate {
newCommentViewController.delegate = delegate
}
controller.present(ForwardingNavigationController(rootViewController: newCommentViewController), animated: true, completion: nil)
}
func showPostsFromController(controller : UIViewController, courseID : String, topic: DiscussionTopic) {
let postsController = PostsViewController(environment: environment, courseID: courseID, topic: topic)
controller.navigationController?.pushViewController(postsController, animated: true)
}
func showDiscussionPosts(from controller: UIViewController, courseID: String, topicID: String) {
let postsController = PostsViewController(environment: environment, courseID: courseID, topicID: topicID)
controller.navigationController?.pushViewController(postsController, animated: true)
}
func showAllPostsFromController(controller : UIViewController, courseID : String, followedOnly following : Bool) {
let postsController = PostsViewController(environment: environment, courseID: courseID, following : following)
controller.navigationController?.pushViewController(postsController, animated: true)
}
func showPostsFromController(controller : UIViewController, courseID : String, queryString : String) {
let postsController = PostsViewController(environment: environment, courseID: courseID, queryString : queryString)
controller.navigationController?.pushViewController(postsController, animated: true)
}
func showDiscussionTopicsFromController(controller: UIViewController, courseID : String) {
let topicsController = DiscussionTopicsViewController(environment: environment, courseID: courseID)
controller.navigationController?.pushViewController(topicsController, animated: true)
}
func showDiscussionNewPostFromController(controller: UIViewController, courseID : String, selectedTopic : DiscussionTopic?) {
let newPostController = DiscussionNewPostViewController(environment: environment, courseID: courseID, selectedTopic: selectedTopic)
if let delegate = controller as? DiscussionNewPostViewControllerDelegate {
newPostController.delegate = delegate
}
controller.present(ForwardingNavigationController(rootViewController: newPostController), animated: true, completion: nil)
}
func showHandoutsFromController(controller : UIViewController, courseID : String) {
let handoutsViewController = CourseHandoutsViewController(environment: environment, courseID: courseID)
controller.navigationController?.pushViewController(handoutsViewController, animated: true)
}
func showMySettings(controller: UIViewController? = nil) {
let settingController = OEXMySettingsViewController(nibName: nil, bundle: nil)
controller?.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
controller?.navigationController?.pushViewController(settingController, animated: true)
}
func showAccount(controller: UIViewController? = nil, modalTransitionStylePresent: Bool = false) {
let accountController = AccountViewController(environment: environment)
if modalTransitionStylePresent {
controller?.present(ForwardingNavigationController(rootViewController: AccountViewController(environment:environment)), animated: true, completion: nil)
}
else {
showContentStack(withRootController: accountController, animated: true)
}
}
func showProfileForUsername(controller: UIViewController? = nil, username : String, editable: Bool = true, modal: Bool = false) {
OEXAnalytics.shared().trackProfileViewed(username: username)
let editable = self.environment.session.currentUser?.username == username
let profileController = UserProfileViewController(environment: environment, username: username, editable: editable)
if modal {
controller?.present(ForwardingNavigationController(rootViewController: profileController), animated: true, completion: nil)
}
else {
if let controller = controller {
controller.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
controller.navigationController?.pushViewController(profileController, animated: true)
} else {
showContentStack(withRootController: profileController, animated: true)
}
}
}
func showProfileEditorFromController(controller : UIViewController) {
guard let profile = environment.dataManager.userProfileManager.feedForCurrentUser().output.value else {
return
}
let editController = UserProfileEditViewController(profile: profile, environment: environment)
controller.navigationController?.pushViewController(editController, animated: true)
}
func showCertificate(url: NSURL, title: String?, fromController controller: UIViewController) {
let c = CertificateViewController(environment: environment)
c.title = title
controller.navigationController?.pushViewController(c, animated: true)
c.loadRequest(request: URLRequest(url: url as URL) as NSURLRequest)
}
func showCourseWithID(courseID : String, fromController: UIViewController, animated: Bool = true) {
let controller = CourseDashboardViewController(environment: environment, courseID: courseID)
fromController.navigationController?.pushViewController(controller, animated: animated)
}
func showCourseCatalog(fromController: UIViewController? = nil, bottomBar: UIView? = nil, searchQuery: String? = nil) {
guard let controller = discoveryViewController(bottomBar: bottomBar, searchQuery: searchQuery) else { return }
if let fromController = fromController {
fromController.tabBarController?.selectedIndex = EnrolledTabBarViewController.courseCatalogIndex
} else {
showControllerFromStartupScreen(controller: controller)
}
self.environment.analytics.trackUserFindsCourses()
}
func showAllSubjects(from controller: UIViewController? = nil, delegate: SubjectsViewControllerDelegate?) {
let subjectsVC = SubjectsViewController(environment:environment)
subjectsVC.delegate = delegate
controller?.navigationController?.pushViewController(subjectsVC, animated: true)
}
func discoveryViewController(bottomBar: UIView? = nil, searchQuery: String? = nil) -> UIViewController? {
let isCourseDiscoveryEnabled = environment.config.discovery.course.isEnabled
let isProgramDiscoveryEnabled = environment.config.discovery.program.isEnabled
let isDegreeDiscveryEnabled = environment.config.discovery.degree.isEnabled
if (isCourseDiscoveryEnabled && isProgramDiscoveryEnabled && isDegreeDiscveryEnabled) ||
(isCourseDiscoveryEnabled && isProgramDiscoveryEnabled) ||
(isCourseDiscoveryEnabled && isDegreeDiscveryEnabled) {
return DiscoveryViewController(with: environment, bottomBar: bottomBar, searchQuery: searchQuery)
}
else if isCourseDiscoveryEnabled {
return environment.config.discovery.course.type == .webview ? OEXFindCoursesViewController(environment: environment, showBottomBar: true, bottomBar: bottomBar, searchQuery: searchQuery) : CourseCatalogViewController(environment: environment)
}
return nil
}
func showProgramDetail(from controller: UIViewController, with pathId: String, bottomBar: UIView?, type: ProgramDiscoveryScreen? = .program) {
let programDetailViewController = ProgramsDiscoveryViewController(with: environment, pathId: pathId, bottomBar: bottomBar?.copy() as? UIView, type: type)
pushViewController(controller: programDetailViewController, fromController: controller)
}
private func showControllerFromStartupScreen(controller: UIViewController) {
let backButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil)
backButton.oex_setAction({
controller.dismiss(animated: true, completion: nil)
})
controller.navigationItem.leftBarButtonItem = backButton
let navController = ForwardingNavigationController(rootViewController: controller)
present(navController, from:nil, completion: nil)
}
func showCourseCatalogDetail(courseID: String, fromController: UIViewController) {
let detailController = CourseCatalogDetailViewController(environment: environment, courseID: courseID)
fromController.navigationController?.pushViewController(detailController, animated: true)
}
func showAppReviewIfNeeded(fromController: UIViewController) {
if RatingViewController.canShowAppReview(environment: environment){
let reviewController = RatingViewController(environment: environment)
reviewController.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
reviewController.providesPresentationContextTransitionStyle = true
reviewController.definesPresentationContext = true
if let controller = fromController as? RatingViewControllerDelegate {
reviewController.delegate = controller
}
fromController.present(reviewController, animated: false, completion: nil)
}
}
func showWhatsNew(fromController controller : UIViewController) {
let whatsNewController = WhatsNewViewController(environment: environment)
controller.present(whatsNewController, animated: true, completion: nil)
}
// MARK: - LOGIN / LOGOUT
@objc func showSplash() {
removeCurrentContentController()
let splashController: UIViewController
if !environment.config.isRegistrationEnabled {
splashController = loginViewController()
}
else if environment.config.newLogistrationFlowEnabled {
splashController = StartupViewController(environment: environment)
} else {
splashController = OEXLoginSplashViewController(environment: environment)
}
makeContentControllerCurrent(splashController)
}
func pushViewController(controller: UIViewController, fromController: UIViewController) {
fromController.navigationController?.pushViewController(controller, animated: true)
}
@objc public func logout() {
invalidateToken()
environment.session.closeAndClear()
environment.session.removeAllWebData()
showLoggedOutScreen()
}
func invalidateToken() {
if let refreshToken = environment.session.token?.refreshToken, let clientID = environment.config.oauthClientID() {
let networkRequest = LogoutApi.invalidateToken(refreshToken: refreshToken, clientID: clientID)
environment.networkManager.taskForRequest(networkRequest) { result in }
}
}
// MARK: - Debug
func showDebugPane() {
let debugMenu = DebugMenuViewController(environment: environment)
showContentStack(withRootController: debugMenu, animated: true)
}
public func showProgramDetails(with url: URL, from controller: UIViewController) {
let programDetailsController = ProgramsViewController(environment: environment, programsURL: url, viewType: .detail)
controller.navigationController?.pushViewController(programDetailsController, animated: true)
}
@objc public func showCourseDetails(from controller: UIViewController, with coursePathID: String, bottomBar: UIView?) {
let courseInfoViewController = OEXCourseInfoViewController(environment: environment, pathID: coursePathID, bottomBar: bottomBar?.copy() as? UIView)
controller.navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
controller.navigationController?.pushViewController(courseInfoViewController, animated: true)
}
}
extension OEXRouter: UINavigationControllerDelegate {
public func navigationController(_ navigationController: UINavigationController, didShow viewController: UIViewController, animated: Bool) {
viewController.navigationController?.completionHandler()
}
}
| apache-2.0 | 5b7b15c2afedb84280afc4f11cc035e7 | 52.151515 | 253 | 0.719641 | 6.087636 | false | false | false | false |
JakeLin/SwiftWeather | SwiftWeather/ForecastView.swift | 1 | 2664 | //
// Created by Jake Lin on 8/22/15.
// Copyright © 2015 Jake Lin. All rights reserved.
//
import UIKit
@IBDesignable class ForecastView: UIView {
// Our custom view from the XIB file
var view: UIView!
@IBOutlet weak var timeLabel: UILabel!
@IBOutlet weak var iconLabel: UILabel!
@IBOutlet weak var temperatureLabel: UILabel!
// MARK: - init
override init(frame: CGRect) {
super.init(frame: frame)
view = loadViewFromNib()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
view = loadViewFromNib()
}
func loadViewFromNib() -> UIView {
let bundle = Bundle(for: type(of: self))
let nib = UINib(nibName: nibName(), bundle: bundle)
// swiftlint:disable force_cast
let view = nib.instantiate(withOwner: self, options: nil)[0] as! UIView
// swiftlint:enable force_cast
view.frame = bounds
view.autoresizingMask = [.flexibleWidth, .flexibleHeight]
addSubview(view)
return view
}
// MARK: - ViewModel
var viewModel: ForecastViewModel? {
didSet {
viewModel?.time.observe {
[unowned self] in
self.timeLabel.text = $0
}
viewModel?.iconText.observe {
[unowned self] in
self.iconLabel.text = $0
}
viewModel?.temperature.observe {
[unowned self] in
self.temperatureLabel.text = $0
}
}
}
func loadViewModel(_ viewModel: ForecastViewModel) {
self.viewModel = viewModel
}
// MARK: - IBInspectable
@IBInspectable var time: String? {
get {
return timeLabel.text
}
set {
timeLabel.text = newValue
}
}
@IBInspectable var icon: String? {
get {
return iconLabel.text
}
set {
iconLabel.text = newValue
}
}
@IBInspectable var temperature: String? {
get {
return temperatureLabel.text
}
set {
temperatureLabel.text = newValue
}
}
@IBInspectable var timeColor: UIColor {
get {
return timeLabel.textColor
}
set {
timeLabel.textColor = newValue
}
}
@IBInspectable var iconColor: UIColor {
get {
return iconLabel.textColor
}
set {
iconLabel.textColor = newValue
}
}
@IBInspectable var temperatureColor: UIColor {
get {
return temperatureLabel.textColor
}
set {
temperatureLabel.textColor = newValue
}
}
@IBInspectable var bgColor: UIColor {
get {
return view.backgroundColor!
}
set {
view.backgroundColor = newValue
}
}
// MARK: - Private
fileprivate func nibName() -> String {
return String(describing: type(of: self))
}
}
| mit | 39bb5758da3878e81282a5af2bd576f4 | 18.158273 | 75 | 0.618851 | 4.337134 | false | false | false | false |
pawanpoudel/SwiftNews | SwiftNews/ExternalDependencies/Server/NetworkCommunicator.swift | 1 | 1955 | import Foundation
let NetworkCommunicatorErrorDomain = "NetworkCommunicatorErrorDomain"
class NetworkCommunicator {
private var completionHandler: ((NSData?, NSError?) -> Void)!
private var httpResponse: NSHTTPURLResponse?
private var downloadedData: NSData?
func performRequest(request: NSURLRequest, completionHandler: (NSData?, NSError?) -> Void) {
self.completionHandler = completionHandler
let session = NSURLSession.sharedSession()
let dataTrask = session.dataTaskWithRequest(request) { (data, response, error) -> Void in
if error != nil {
completionHandler(nil, error)
}
else {
self.downloadedData = data
self.httpResponse = response as? NSHTTPURLResponse
self.evaluateResponse()
}
}
}
private func evaluateResponse() {
if isSuccessfulResponse() {
completionHandler(downloadedData, nil)
}
else {
let error = buildErrorWithHttpStatusCode()
completionHandler(nil, error)
}
}
private func buildErrorWithHttpStatusCode() -> NSError {
let errorMessage = "Server returned non-200 status code."
let userInfo = [NSLocalizedDescriptionKey : errorMessage]
return NSError(domain: NetworkCommunicatorErrorDomain,
code: httpResponse!.statusCode,
userInfo: userInfo)
}
private func isSuccessfulResponse() -> Bool {
let regExp = NSRegularExpression(pattern: "2[0-9][0-9]", options: nil, error: nil)
let statusString = String(httpResponse!.statusCode)
if let firstMatch = regExp?.firstMatchInString(statusString,
options: nil, range:
NSRange(location: 0, length: count(statusString)))
{
return true
}
return false
}
}
| mit | 4705a41f734f63b5911239ff691eefa9 | 32.706897 | 97 | 0.609719 | 5.634006 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Jetpack/Jetpack Restore/Restore Options/JetpackBackupOptionsViewController.swift | 2 | 4354 | import UIKit
import CocoaLumberjack
import Gridicons
import WordPressFlux
import WordPressUI
import WordPressShared
class JetpackBackupOptionsViewController: BaseRestoreOptionsViewController {
// MARK: - Properties
weak var backupStatusDelegate: JetpackBackupStatusViewControllerDelegate?
// MARK: - Private Properties
private lazy var coordinator: JetpackBackupOptionsCoordinator = {
return JetpackBackupOptionsCoordinator(site: self.site,
rewindID: self.activity.rewindID,
restoreTypes: self.restoreTypes,
view: self)
}()
// MARK: - Initialization
override init(site: JetpackSiteRef, activity: Activity) {
let restoreOptionsConfiguration = JetpackRestoreOptionsConfiguration(
title: NSLocalizedString("Download Backup", comment: "Title for the Jetpack Download Backup Site Screen"),
iconImage: UIImage.gridicon(.history),
messageTitle: NSLocalizedString("Create downloadable backup", comment: "Label that describes the download backup action"),
messageDescription: NSLocalizedString("%1$@ is the selected point to create a downloadable backup.", comment: "Description for the download backup action. $1$@ is a placeholder for the selected date."),
generalSectionHeaderText: NSLocalizedString("Choose the items to download", comment: "Downloadable items: general section title"),
buttonTitle: NSLocalizedString("Create downloadable file", comment: "Button title for download backup action"),
warningButtonTitle: nil,
isRestoreTypesConfigurable: true
)
super.init(site: site, activity: activity, configuration: restoreOptionsConfiguration)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - View Lifecycle
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
WPAnalytics.track(.backupDownloadOpened, properties: ["source": presentedFrom])
}
// MARK: - Override
override func actionButtonTapped() {
WPAnalytics.track(.backupDownloadConfirmed, properties: ["restore_types": [
"themes": restoreTypes.themes,
"plugins": restoreTypes.plugins,
"uploads": restoreTypes.uploads,
"sqls": restoreTypes.sqls,
"roots": restoreTypes.roots,
"contents": restoreTypes.contents
]])
coordinator.prepareBackup()
}
}
extension JetpackBackupOptionsViewController: JetpackBackupOptionsView {
func showNoInternetConnection() {
ReachabilityUtils.showAlertNoInternetConnection()
WPAnalytics.track(.backupFileDownloadError, properties: ["cause": "offline"])
}
func showBackupAlreadyRunning() {
let title = NSLocalizedString("There's a backup currently being prepared, please wait before starting the next one", comment: "Text displayed when user tries to create a downloadable backup when there is already one being prepared")
let notice = Notice(title: title)
ActionDispatcher.dispatch(NoticeAction.post(notice))
WPAnalytics.track(.backupFileDownloadError, properties: ["cause": "other"])
}
func showBackupRequestFailed() {
let errorTitle = NSLocalizedString("Backup failed", comment: "Title for error displayed when preparing a backup fails.")
let errorMessage = NSLocalizedString("We couldn't create your backup. Please try again later.", comment: "Message for error displayed when preparing a backup fails.")
let notice = Notice(title: errorTitle, message: errorMessage)
ActionDispatcher.dispatch(NoticeAction.post(notice))
WPAnalytics.track(.backupFileDownloadError, properties: ["cause": "remote"])
}
func showBackupStarted(for downloadID: Int) {
let statusVC = JetpackBackupStatusViewController(site: site,
activity: activity,
downloadID: downloadID)
statusVC.delegate = backupStatusDelegate
self.navigationController?.pushViewController(statusVC, animated: true)
}
}
| gpl-2.0 | aacdd1c83805fb817954beea2a47ea7a | 43.886598 | 240 | 0.674322 | 5.789894 | false | true | false | false |
dvor/Antidote | Antidote/TabBarProfileItem.swift | 1 | 2536 | // 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 SnapKit
private struct Constants {
static let ImageSize = 32.0
}
class TabBarProfileItem: TabBarAbstractItem {
override var selected: Bool {
didSet {
imageViewWithStatus.imageView.tintColor = theme.colorForType(selected ? .TabItemActive : .TabItemInactive)
}
}
var userStatus: UserStatus = .offline {
didSet {
imageViewWithStatus.userStatusView.userStatus = userStatus
}
}
var userImage: UIImage? {
didSet {
if let image = userImage {
imageViewWithStatus.imageView.image = image
}
else {
imageViewWithStatus.imageView.image = UIImage.templateNamed("tab-bar-profile")
}
}
}
fileprivate let theme: Theme
fileprivate var imageViewWithStatus: ImageViewWithStatus!
fileprivate var button: UIButton!
init(theme: Theme) {
self.theme = theme
super.init(frame: CGRect.zero)
backgroundColor = .clear
createViews()
installConstraints()
}
required convenience init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// Accessibility
extension TabBarProfileItem {
override var accessibilityLabel: String? {
get {
return String(localized: "profile_title")
}
set {}
}
override var accessibilityValue: String? {
get {
return userStatus.toString()
}
set {}
}
}
// Actions
extension TabBarProfileItem {
func buttonPressed() {
didTapHandler?()
}
}
private extension TabBarProfileItem {
func createViews() {
imageViewWithStatus = ImageViewWithStatus()
imageViewWithStatus.userStatusView.theme = theme
addSubview(imageViewWithStatus)
button = UIButton()
button.backgroundColor = .clear
button.addTarget(self, action: #selector(TabBarProfileItem.buttonPressed), for: .touchUpInside)
addSubview(button)
}
func installConstraints() {
imageViewWithStatus.snp.makeConstraints {
$0.center.equalTo(self)
$0.size.equalTo(Constants.ImageSize)
}
button.snp.makeConstraints {
$0.edges.equalTo(self)
}
}
}
| mit | 6eadc465bea39f67039328429cde6867 | 23.384615 | 118 | 0.619479 | 5.04175 | false | false | false | false |
Virpik/T | src/UI/TableView/TableViewModel/TableViewModel.ManagerMoveCells.swift | 1 | 5658 | //
// TableViewModel.ManagerMoveCells.swift
// T
//
// Created by Virpik on 02/02/2018.
//
import Foundation
extension TableViewModel {
public class ManagerMoveCells: NSObject, UIGestureRecognizerDelegate {
struct DataSourse {
var getRowModel: ((IndexPath) -> AnyRowModel?)
}
private enum _TypeScroll {
case up
case down
}
public var handlers: MoveHandlers?
/// если true - ячейки не будут перемещатся, сам факт перемещения будет зафиксирова
public var isSnaphotOnly: Bool = false
/// Контекс перемещаемой ячейки, задается при событии began, Gesture
public var atContext: GestureContext?
/// Контекст, захваченый при событии change, Gesture, необходим для определения текущей локации
public var toContext: GestureContext?
private var longPressGestue: UILongPressGestureRecognizer!
public var cellMoviesPressDuration: TimeInterval {
get {
return self.longPressGestue.minimumPressDuration
}
set(value) {
self.longPressGestue.minimumPressDuration = value
}
}
private var tableView: UITableView
private var dataSourse: DataSourse
private var _activeGContext: GestureContext?
private var _activeCContext: CellContext? {
return self._activeGContext?.cellContext
}
init(tableView: UITableView, dataSourse: DataSourse) {
self.tableView = tableView
self.dataSourse = dataSourse
super.init()
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(self._gestureActions))
gesture.minimumPressDuration = 0.01
gesture.delegate = self
self.tableView.addGestureRecognizer(gesture)
self.longPressGestue = gesture
}
public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let gesture = gestureRecognizer as? UILongPressGestureRecognizer else {
return false
}
let context = GestureContext(gesture: gesture, tableView: self.tableView, getRowModel: self.dataSourse.getRowModel)
guard let cellContext = context.cellContext else {
return false
}
return cellContext.isMoving
}
@objc private func _gestureActions(gesture: UILongPressGestureRecognizer) {
let state = gesture.state
let getRowModelBlock = self.dataSourse.getRowModel
let context = GestureContext(gesture: gesture, tableView: self.tableView, getRowModel: getRowModelBlock)
switch state {
case .began:
self._beginMove(context: context)
case .changed:
self._move(context: context)
default:
self._endMoving(context: context)
}
}
private func _beginMove(context: GestureContext) {
guard let cContext = context.cellContext else {
return
}
if !cContext.isMoving {
return
}
self._activeGContext = context
self.handlers?.handlerBeginMove?(cContext)
}
private func _move(context: GestureContext) {
guard let atGContext = self._activeGContext else {
return
}
guard let atCContext = atGContext.cellContext else {
return
}
/// Обновляем location перемещаемого контекста на текущий
self._activeGContext?.cellContext?.location = context.location
/// call handlerMove
self.handlers?.handlerMove?(atCContext, context.cellContext)
let toGContext = context
guard let toCContet = toGContext.cellContext else {
return
}
if !toCContet.isMoving {
return
}
if self.isSnaphotOnly {
return
}
let atIndexPath = atCContext.indexPath
let toIndexPath = toCContet.indexPath
if atIndexPath != toIndexPath {
/// Обновляем indexPath контекста, перемещаемой ячейки
self._activeGContext?.cellContext?.indexPath = toCContet.indexPath
self.handlers?.handlerDidMove?(atCContext, toCContet)
self.tableView.moveRow(at: atIndexPath, to: toIndexPath)
}
}
private func _endMoving(context: GestureContext) {
guard let activeContext = self._activeCContext else {
return
}
self.handlers?.handlerEndMove?( activeContext, context.cellContext)
self._activeGContext = nil
}
}
}
| mit | 412d19b6031188e37d4ee60fb4d8df13 | 31.8 | 127 | 0.539542 | 6.06047 | false | false | false | false |
realm/SwiftLint | Source/SwiftLintFramework/Rules/Style/MultilineParametersRuleExamples.swift | 1 | 11359 | internal struct MultilineParametersRuleExamples {
static let nonTriggeringExamples: [Example] = [
Example("func foo() { }"),
Example("func foo(param1: Int) { }"),
Example("func foo(param1: Int, param2: Bool) { }"),
Example("func foo(param1: Int, param2: Bool, param3: [String]) { }"),
Example("""
func foo(param1: Int,
param2: Bool,
param3: [String]) { }
"""),
Example("""
func foo(_ param1: Int, param2: Int, param3: Int) -> (Int) -> Int {
return { x in x + param1 + param2 + param3 }
}
"""),
Example("static func foo() { }"),
Example("static func foo(param1: Int) { }"),
Example("static func foo(param1: Int, param2: Bool) { }"),
Example("static func foo(param1: Int, param2: Bool, param3: [String]) { }"),
Example("""
static func foo(param1: Int,
param2: Bool,
param3: [String]) { }
"""),
Example("protocol Foo {\n\tfunc foo() { }\n}"),
Example("protocol Foo {\n\tfunc foo(param1: Int) { }\n}"),
Example("protocol Foo {\n\tfunc foo(param1: Int, param2: Bool) { }\n}"),
Example("protocol Foo {\n\tfunc foo(param1: Int, param2: Bool, param3: [String]) { }\n}"),
Example("""
protocol Foo {
func foo(param1: Int,
param2: Bool,
param3: [String]) { }
}
"""),
Example("protocol Foo {\n\tstatic func foo(param1: Int, param2: Bool, param3: [String]) { }\n}"),
Example("""
protocol Foo {
static func foo(param1: Int,
param2: Bool,
param3: [String]) { }
}
"""),
Example("protocol Foo {\n\tclass func foo(param1: Int, param2: Bool, param3: [String]) { }\n}"),
Example("""
protocol Foo {
class func foo(param1: Int,
param2: Bool,
param3: [String]) { }
}
"""),
Example("enum Foo {\n\tfunc foo() { }\n}"),
Example("enum Foo {\n\tfunc foo(param1: Int) { }\n}"),
Example("enum Foo {\n\tfunc foo(param1: Int, param2: Bool) { }\n}"),
Example("enum Foo {\n\tfunc foo(param1: Int, param2: Bool, param3: [String]) { }\n}"),
Example("""
enum Foo {
func foo(param1: Int,
param2: Bool,
param3: [String]) { }
}
"""),
Example("enum Foo {\n\tstatic func foo(param1: Int, param2: Bool, param3: [String]) { }\n}"),
Example("""
enum Foo {
static func foo(param1: Int,
param2: Bool,
param3: [String]) { }
}
"""),
Example("struct Foo {\n\tfunc foo() { }\n}"),
Example("struct Foo {\n\tfunc foo(param1: Int) { }\n}"),
Example("struct Foo {\n\tfunc foo(param1: Int, param2: Bool) { }\n}"),
Example("struct Foo {\n\tfunc foo(param1: Int, param2: Bool, param3: [String]) { }\n}"),
Example("""
struct Foo {
func foo(param1: Int,
param2: Bool,
param3: [String]) { }
}
"""),
Example("struct Foo {\n\tstatic func foo(param1: Int, param2: Bool, param3: [String]) { }\n}"),
Example("""
struct Foo {
static func foo(param1: Int,
param2: Bool,
param3: [String]) { }
}
"""),
Example("class Foo {\n\tfunc foo() { }\n}"),
Example("class Foo {\n\tfunc foo(param1: Int) { }\n}"),
Example("class Foo {\n\tfunc foo(param1: Int, param2: Bool) { }\n}"),
Example("class Foo {\n\tfunc foo(param1: Int, param2: Bool, param3: [String]) { }\n\t}"),
Example("""
class Foo {
func foo(param1: Int,
param2: Bool,
param3: [String]) { }
}
"""),
Example("class Foo {\n\tclass func foo(param1: Int, param2: Bool, param3: [String]) { }\n}"),
Example("""
class Foo {
class func foo(param1: Int,
param2: Bool,
param3: [String]) { }
}
"""),
Example("""
class Foo {
class func foo(param1: Int,
param2: Bool,
param3: @escaping (Int, Int) -> Void = { _, _ in }) { }
}
"""),
Example("""
class Foo {
class func foo(param1: Int,
param2: Bool,
param3: @escaping (Int) -> Void = { _ in }) { }
}
"""),
Example("""
class Foo {
class func foo(param1: Int,
param2: Bool,
param3: @escaping ((Int) -> Void)? = nil) { }
}
"""),
Example("""
class Foo {
class func foo(param1: Int,
param2: Bool,
param3: @escaping ((Int) -> Void)? = { _ in }) { }
}
"""),
Example("""
class Foo {
class func foo(param1: Int,
param2: @escaping ((Int) -> Void)? = { _ in },
param3: Bool) { }
}
"""),
Example("""
class Foo {
class func foo(param1: Int,
param2: @escaping ((Int) -> Void)? = { _ in },
param3: @escaping (Int, Int) -> Void = { _, _ in }) { }
}
"""),
Example("""
class Foo {
class func foo(param1: Int,
param2: Bool,
param3: @escaping (Int) -> Void = { (x: Int) in }) { }
}
"""),
Example("""
class Foo {
class func foo(param1: Int,
param2: Bool,
param3: @escaping (Int, (Int) -> Void) -> Void = { (x: Int, f: (Int) -> Void) in }) { }
}
"""),
Example("""
class Foo {
init(param1: Int,
param2: Bool,
param3: @escaping ((Int) -> Void)? = { _ in }) { }
}
"""),
Example("func foo() { }",
configuration: ["allows_single_line": false]),
Example("func foo(param1: Int) { }",
configuration: ["allows_single_line": false]),
Example("""
protocol Foo {
func foo(param1: Int,
param2: Bool,
param3: [String]) { }
}
""", configuration: ["allows_single_line": false]),
Example("""
protocol Foo {
func foo(
param1: Int
) { }
}
""", configuration: ["allows_single_line": false]),
Example("""
protocol Foo {
func foo(
param1: Int,
param2: Bool,
param3: [String]
) { }
}
""", configuration: ["allows_single_line": false])
]
static let triggeringExamples: [Example] = [
Example("""
func ↓foo(_ param1: Int,
param2: Int, param3: Int) -> (Int) -> Int {
return { x in x + param1 + param2 + param3 }
}
"""),
Example("""
protocol Foo {
func ↓foo(param1: Int,
param2: Bool, param3: [String]) { }
}
"""),
Example("""
protocol Foo {
func ↓foo(param1: Int, param2: Bool,
param3: [String]) { }
}
"""),
Example("""
protocol Foo {
static func ↓foo(param1: Int,
param2: Bool, param3: [String]) { }
}
"""),
Example("""
protocol Foo {
static func ↓foo(param1: Int, param2: Bool,
param3: [String]) { }
}
"""),
Example("""
protocol Foo {
class func ↓foo(param1: Int,
param2: Bool, param3: [String]) { }
}
"""),
Example("""
protocol Foo {
class func ↓foo(param1: Int, param2: Bool,
param3: [String]) { }
}
"""),
Example("""
enum Foo {
func ↓foo(param1: Int,
param2: Bool, param3: [String]) { }
}
"""),
Example("""
enum Foo {
func ↓foo(param1: Int, param2: Bool,
param3: [String]) { }
}
"""),
Example("""
enum Foo {
static func ↓foo(param1: Int,
param2: Bool, param3: [String]) { }
}
"""),
Example("""
enum Foo {
static func ↓foo(param1: Int, param2: Bool,
param3: [String]) { }
}
"""),
Example("""
struct Foo {
func ↓foo(param1: Int,
param2: Bool, param3: [String]) { }
}
"""),
Example("""
struct Foo {
func ↓foo(param1: Int, param2: Bool,
param3: [String]) { }
}
"""),
Example("""
struct Foo {
static func ↓foo(param1: Int,
param2: Bool, param3: [String]) { }
}
"""),
Example("""
struct Foo {
static func ↓foo(param1: Int, param2: Bool,
param3: [String]) { }
}
"""),
Example("""
class Foo {
func ↓foo(param1: Int,
param2: Bool, param3: [String]) { }
}
"""),
Example("""
class Foo {
func ↓foo(param1: Int, param2: Bool,
param3: [String]) { }
}
"""),
Example("""
class Foo {
class func ↓foo(param1: Int,
param2: Bool, param3: [String]) { }
}
"""),
Example("""
class Foo {
class func ↓foo(param1: Int, param2: Bool,
param3: [String]) { }
}
"""),
Example("""
class Foo {
class func ↓foo(param1: Int,
param2: Bool, param3: @escaping (Int, Int) -> Void = { _, _ in }) { }
}
"""),
Example("""
class Foo {
class func ↓foo(param1: Int,
param2: Bool, param3: @escaping (Int) -> Void = { (x: Int) in }) { }
}
"""),
Example("""
class Foo {
↓init(param1: Int, param2: Bool,
param3: @escaping ((Int) -> Void)? = { _ in }) { }
}
"""),
Example("func ↓foo(param1: Int, param2: Bool) { }",
configuration: ["allows_single_line": false]),
Example("func ↓foo(param1: Int, param2: Bool, param3: [String]) { }",
configuration: ["allows_single_line": false])
]
}
| mit | 46716e1d1e92baeb61bbb8c6355d10f9 | 32.267647 | 113 | 0.396251 | 4.282847 | false | false | false | false |
shyamalschandra/swix | swix_ios_app/swix_ios_app/swix/matrix/m-helper-functions.swift | 6 | 4445 | //
// helper-functions.swift
// swix
//
// Created by Scott Sievert on 8/9/14.
// Copyright (c) 2014 com.scott. All rights reserved.
//
import Foundation
// NORMs
func norm(x:matrix, ord:String="assumed to be 'fro' for Frobenius")->Double{
if ord == "fro" {return norm(x.flat, ord:2)}
assert(false, "Norm type assumed to be \"fro\" for Forbenius norm!")
return -1
}
func norm(x:matrix, ord:Double=2)->Double{
if ord == inf {return max(sum(abs(x), axis:1))}
else if ord == -inf {return min(sum(abs(x), axis:1))}
else if ord == 1 {return max(sum(abs(x), axis:0))}
else if ord == -1 {return min(sum(abs(x), axis:0))}
else if ord == 2 {
// compute only the largest singular value?
let (_, s, _) = svd(x, compute_uv:false)
return s[0]
}
else if ord == -2 {
// compute only the smallest singular value?
let (_, s, _) = svd(x, compute_uv:false)
return s[-1]
}
assert(false, "Invalid norm for matrices")
return -1
}
func det(x:matrix)->Double{
var result:CDouble = 0.0
CVWrapper.det(!x, n:x.shape.0.cint, m:x.shape.1.cint, result:&result)
return result
}
// basics
func argwhere(idx: matrix) -> ndarray{
return argwhere(idx.flat)
}
func flipud(x:matrix)->matrix{
let y = x.copy()
CVWrapper.flip(!x, into:!y, how:"ud", m:x.shape.0.cint, n:x.shape.1.cint)
return y
}
func fliplr(x:matrix)->matrix{
let y = x.copy()
CVWrapper.flip(!x, into:!y, how:"lr", m:x.shape.0.cint, n:x.shape.1.cint)
return y
}
func rot90(x:matrix, k:Int=1)->matrix{
// k is assumed to be less than or equal to 3
let y = x.copy()
if k == 1 {return fliplr(x).T}
if k == 2 {return flipud(fliplr(y))}
if k == 3 {return flipud(x).T}
assert(false, "k is assumed to satisfy 1 <= k <= 3")
return y
}
// modifying matrices, modifying equations
func transpose (x: matrix) -> matrix{
let m = x.shape.1
let n = x.shape.0
let y = zeros((m, n))
vDSP_mtransD(!x, 1.stride, !y, 1.stride, m.length, n.length)
return y
}
func kron(A:matrix, B:matrix)->matrix{
// an O(n^4) operation!
func assign_kron_row(A:matrix, B:matrix,inout C:matrix, p:Int, m:Int, m_max:Int){
var row = (m+0)*(p+0) + p-0
row = m_max*m + 1*p
let i = arange(B.shape.1 * A.shape.1)
let n1 = arange(A.shape.1)
let q1 = arange(B.shape.1)
let (n, q) = meshgrid(n1, y: q1)
C[row, i] = A[m, n.flat] * B[p, q.flat]
}
var C = zeros((A.shape.0*B.shape.0, A.shape.1*B.shape.1))
for p in 0..<A.shape.1{
for m in 0..<B.shape.1{
assign_kron_row(A, B: B, C: &C, p: p, m: m, m_max: A.shape.1)
}
}
return C
}
func tril(x: matrix) -> ndarray{
let (m, n) = x.shape
let (mm, nn) = meshgrid(arange(m), y: arange(n))
var i = mm - nn
let j = (i < 0+S2_THRESHOLD)
i[argwhere(j)] <- 0
i[argwhere(1-j)] <- 1
return argwhere(i)
}
func triu(x: matrix)->ndarray{
let (m, n) = x.shape
let (mm, nn) = meshgrid(arange(m), y: arange(n))
var i = mm - nn
let j = (i > 0-S2_THRESHOLD)
i[argwhere(j)] <- 0
i[argwhere(1-j)] <- 1
return argwhere(i)
}
// PRINTING
func println(x: matrix, prefix:String="matrix([", postfix:String="])", newline:String="\n", format:String="%.3f", printWholeMatrix:Bool=false){
print(prefix, terminator: "")
var pre:String
var post:String
var printedSpacer = false
for i in 0..<x.shape.0{
// pre and post nice -- internal variables
if i==0 {pre = ""}
else {pre = " "}
if i==x.shape.0-1 {post=postfix}
else {post = "],"}
if printWholeMatrix || x.shape.0 < 16 || i<4-1 || i>x.shape.0-4{
print(x[i, 0..<x.shape.1], prefix:pre, postfix:post, format: format, printWholeMatrix:printWholeMatrix)
}
else if printedSpacer==false{
printedSpacer=true
Swift.print(" ...,")
}
}
print(newline, terminator: "")
}
func max(x: matrix, axis:Int = -1)->Double{
return x.max()
}
func min(x: matrix, axis:Int = -1)->Double{
return x.min()
}
func print(x: matrix, prefix:String="matrix([", postfix:String="])", newline:String="\n", format:String="%.3f", printWholeMatrix:Bool=false){
println(x, prefix:prefix, postfix:postfix, newline:"", format:format, printWholeMatrix:printWholeMatrix)
}
| mit | cb15d7a0be35cf95a38c6609147e19eb | 29.238095 | 143 | 0.568054 | 2.901436 | false | false | false | false |
bmichotte/HSTracker | HSTracker/Utility/BoardDamage/BoardCard.swift | 1 | 4142 | //
// BoardCard.swift
// HSTracker
//
// Created by Benjamin Michotte on 9/06/16.
// Copyright © 2016 Benjamin Michotte. All rights reserved.
//
import Foundation
class BoardCard: IBoardEntity {
private var _armor = 0
private var _cantAttack = false
private var _damageTaken = 0
private var _durability = 0
private var _frozen = false
private var _health = 0
private var _stdAttack = 0
private(set) var cardId = ""
private(set) var taunt = false
private(set) var charge = false
private(set) var windfury = false
private(set) var cardType = ""
private(set) var name = ""
private(set) var attack = 0
private(set) var health = 0
private(set) var include = false
private(set) var attacksThisTurn = 0
private(set) var exhausted = false
private(set) var zone = ""
init(entity: Entity, active: Bool = true) {
let card = Cards.by(cardId: entity.cardId)
let cardName = card != nil ? card!.name : ""
name = entity.name.isBlank ? cardName : entity.name!
_stdAttack = entity[.atk]
_health = entity[.health]
_armor = entity[.armor]
_durability = entity[.durability]
_damageTaken = entity[.damage]
exhausted = entity[.exhausted] == 1
_cantAttack = entity[.cant_attack] == 1
_frozen = entity[.frozen] == 1
charge = entity[.charge] == 1
windfury = entity[.windfury] == 1
attacksThisTurn = entity[.num_attacks_this_turn]
cardId = entity.cardId
taunt = entity[.taunt] == 1
if let _zone = Zone(rawValue: entity[.zone]) {
zone = "\(_zone)"
}
if let _cardType = CardType(rawValue: entity[.cardtype]) {
cardType = "\(_cardType)"
}
health = calculateHealth(isWeapon: entity.isWeapon)
attack = calculateAttack(active: active, isWeapon: entity.isWeapon)
include = isAbleToAttack(active: active, isWeapon: entity.isWeapon)
}
private func calculateHealth(isWeapon: Bool) -> Int {
return isWeapon ? _durability - _damageTaken : _health + _armor - _damageTaken
}
private func calculateAttack(active: Bool, isWeapon: Bool) -> Int {
// V-07-TR-0N is a special case Mega-Windfury
if !cardId.isBlank && cardId == "GVG_111t" {
return V07TRONAttack(active: active)
}
// for weapons check for windfury and number of hits left
if isWeapon {
if windfury && health >= 2 && attacksThisTurn == 0 {
return _stdAttack * 2
}
}
// for minions with windfury that haven't already attacked, double attack
else if windfury && (!active || attacksThisTurn == 0) {
return _stdAttack * 2
}
return _stdAttack
}
private func isAbleToAttack(active: Bool, isWeapon: Bool) -> Bool {
// TODO: if frozen on turn, may be able to attack next turn
// don't include weapons if an active turn, count Hero instead
if _cantAttack || _frozen || (isWeapon && active) {
return false
}
if !active {
// include everything that can attack if not an active turn
return true
}
if exhausted {
// newly played card could be given charge
return charge && attacksThisTurn == 0
}
// sometimes cards seem to be in wrong zone while in play,
// these cards don't become exhausted, so check attacks.
if zone.lowercased() == "deck" || zone.lowercased() == "hand" {
return (!windfury || attacksThisTurn < 2) && (windfury || attacksThisTurn < 1)
}
return true
}
private func V07TRONAttack(active: Bool) -> Int {
guard active else {
return _stdAttack * 4
}
switch attacksThisTurn {
case 0: return _stdAttack * 4
case 1: return _stdAttack * 3
case 2: return _stdAttack * 2
default: return _stdAttack
}
}
}
| mit | fbb5bba35e5c1867e68014125862b9ed | 32.395161 | 90 | 0.573533 | 4.530635 | false | false | false | false |
stephentyrone/swift | test/IRGen/synthesized_conformance_future.swift | 3 | 5193 | // RUN: %target-swift-frontend -prespecialize-generic-metadata -target %module-target-future -emit-ir %s -swift-version 4 | %FileCheck %s -DINT=i%target-ptrsize -DALIGNMENT=%target-alignment
// REQUIRES: OS=macosx || OS=ios || OS=tvos || OS=watchos || OS=linux-gnu
// UNSUPPORTED: CPU=i386 && OS=ios
// UNSUPPORTED: CPU=armv7 && OS=ios
// UNSUPPORTED: CPU=armv7s && OS=ios
struct Struct<T> {
var x: T
}
extension Struct: Equatable where T: Equatable {}
extension Struct: Hashable where T: Hashable {}
extension Struct: Codable where T: Codable {}
enum Enum<T> {
case a(T), b(T)
}
extension Enum: Equatable where T: Equatable {}
extension Enum: Hashable where T: Hashable {}
final class Final<T> {
var x: T
init(x: T) { self.x = x }
}
extension Final: Encodable where T: Encodable {}
extension Final: Decodable where T: Decodable {}
class Nonfinal<T> {
var x: T
init(x: T) { self.x = x }
}
extension Nonfinal: Encodable where T: Encodable {}
func doEquality<T: Equatable>(_: T) {}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s30synthesized_conformance_future8equalityyyF"()
public func equality() {
// CHECK: [[Struct_Equatable:%.*]] = call i8** @"$s30synthesized_conformance_future6StructVySiGACyxGSQAASQRzlWl"()
// CHECK-NEXT: call swiftcc void @"$s30synthesized_conformance_future10doEqualityyyxSQRzlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{[^,]*}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: {{(\[4 x i8\],)?}}
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s30synthesized_conformance_future6StructVySiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: i8** [[Struct_Equatable]]
// CHECK-SAME: )
doEquality(Struct(x: 1))
// CHECK: [[Enum_Equatable:%.*]] = call i8** @"$s30synthesized_conformance_future4EnumOySiGACyxGSQAASQRzlWl"()
// CHECK-NEXT: call swiftcc void @"$s30synthesized_conformance_future10doEqualityyyxSQRzlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{%[^,]+}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: [[INT]],
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s30synthesized_conformance_future4EnumOySiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: i8** [[Enum_Equatable]]
// CHECK-SAME: )
doEquality(Enum.a(1))
}
func doEncodable<T: Encodable>(_: T) {}
// CHECK-LABEL: define{{( dllexport| protected)?}} swiftcc void @"$s30synthesized_conformance_future9encodableyyF"()
public func encodable() {
// CHECK: [[Struct_Encodable:%.*]] = call i8** @"$s30synthesized_conformance_future6StructVySiGACyxGSEAASeRzSERzlWl"()
// CHECK-NEXT: call swiftcc void @"$s30synthesized_conformance_future11doEncodableyyxSERzlF"(
// CHECK-SAME: %swift.opaque* noalias nocapture {{[^,]*}},
// CHECK-SAME: %swift.type* getelementptr inbounds (
// CHECK-SAME: %swift.full_type,
// CHECK-SAME: %swift.full_type* bitcast (
// CHECK-SAME: <{
// CHECK-SAME: i8**,
// CHECK-SAME: [[INT]],
// CHECK-SAME: %swift.type_descriptor*,
// CHECK-SAME: %swift.type*,
// CHECK-SAME: i32,
// CHECK-SAME: {{(\[4 x i8\],)?}}
// CHECK-SAME: i64
// CHECK-SAME: }>* @"$s30synthesized_conformance_future6StructVySiGMf"
// CHECK-SAME: to %swift.full_type*
// CHECK-SAME: ),
// CHECK-SAME: i32 0,
// CHECK-SAME: i32 1
// CHECK-SAME: ),
// CHECK-SAME: i8** [[Struct_Encodable]]
// CHECK-SAME: )
doEncodable(Struct(x: 1))
// CHECK: [[Final_Encodable:%.*]] = call i8** @"$s30synthesized_conformance_future5FinalCySiGACyxGSEAASERzlWl"()
// CHECK-NEXT: call swiftcc void @"$s30synthesized_conformance_future11doEncodableyyxSERzlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* {{%.*}}, i8** [[Final_Encodable]])
doEncodable(Final(x: 1))
// CHECK: [[Nonfinal_Encodable:%.*]] = call i8** @"$s30synthesized_conformance_future8NonfinalCySiGACyxGSEAASERzlWl"()
// CHECK-NEXT: call swiftcc void @"$s30synthesized_conformance_future11doEncodableyyxSERzlF"(%swift.opaque* noalias nocapture {{%.*}}, %swift.type* {{%.*}}, i8** [[Nonfinal_Encodable]])
doEncodable(Nonfinal(x: 1))
}
| apache-2.0 | aa434f790af1db7bf9ca7f0c80043ae1 | 42.275 | 190 | 0.599846 | 3.485235 | false | false | false | false |
puyanLiu/LPYFramework | 第三方框架改造/YHAlertView/YHAlertView/YHAlertView.swift | 1 | 16691 | //
// YHAlertView.swift
// YHAlertView
//
// Created by samuelandkevin on 2017/5/12.
// Copyright © 2017年 samuelandkevin. All rights reserved.
// https://github.com/samuelandkevin/YHAlertView
import Foundation
import UIKit
typealias YHAlertViewClickButtonBlock = ((_ alertView:YHAlertView,_ buttonIndex:Int)->Void)?
enum YHAlertAnimationOptions {
case none
case zoom // 先放大,再缩小,在还原
case topToCenter // 从上到中间
}
protocol YHAlertViewDelegate {
// Called when a button is clicked. The view will be automatically dismissed after this call returns
func alertView(alertView:YHAlertView,clickedButtonAtIndex:Int)
}
class YHAlertView : UIView{
// MARK: - Public Property
public var delegate : YHAlertViewDelegate?//weak
public var animationOption:YHAlertAnimationOptions = .none
// background visual
public var visual = false {
willSet(newValue){
if newValue == true {
_effectView.backgroundColor = UIColor.clear
}else {
_effectView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 102.0/255)
}
}
}
// backgroudColor visual
public var visualBGColor = UIColor(red: 0, green: 0, blue: 0, alpha: 102.0/255) {
willSet(newValue){
_effectView.backgroundColor = newValue
}
}
public var messageTextAlignment: NSTextAlignment = .center {
didSet {
_labelMessage.textAlignment = messageTextAlignment
}
}
// MARK: - Private Property
/** 1.视图的宽高 */
private let _screenWidth = UIScreen.main.bounds.size.width
private let _screenHeight = UIScreen.main.bounds.size.height
private let _contentWidth:CGFloat = 270.0
private let _contentHeight:CGFloat = 88.0
private let _margin: CGFloat = 15
/** 2.视图容器 */
private var _contentView:UIView!
/** 3.标题视图 */
private var _labelTitle:UILabel!
/** 4.内容视图 */
private var _labelMessage:UILabel!
/** 5.处理delegate传值 */
private var _arrayButton:[UIButton] = []
/** 6.虚化视图 */
private var _effectView:UIVisualEffectView!
/** 7.显示的数据 */
private var _title:String!
private var _message:String?
private var _cancelButtonTitle:String?
private var _otherButtonTitles:[String] = []
private var _clickButtonBlock:YHAlertViewClickButtonBlock
// MARK: - init
override init(frame: CGRect) {
_contentView = UIView()
_contentView.frame = CGRect(x: 0.0, y: 0.0, width: _contentWidth, height: _contentHeight)
_contentView.center = CGPoint(x: _screenWidth/2, y: _screenHeight/2)
_contentView.backgroundColor = UIColor.white
_contentView.layer.cornerRadius = 10
_contentView.layer.masksToBounds = true
_contentView.autoresizingMask = [.flexibleTopMargin,.flexibleBottomMargin,.flexibleLeftMargin,.flexibleRightMargin]
_labelTitle = UILabel()
_labelTitle.frame = CGRect(x: 16, y: 22, width: _contentWidth-32, height: 0)
_labelTitle.textColor = UIColor.black
_labelTitle.textAlignment = messageTextAlignment
_labelTitle.numberOfLines = 0
_labelTitle.font = UIFont.systemFont(ofSize: 15)
_labelMessage = UILabel()
_labelMessage.frame = CGRect(x: 16, y: 22, width: _contentWidth-32, height: 0)
_labelMessage.textColor = UIColor.black
_labelMessage.textAlignment = .center
_labelMessage.numberOfLines = 0
_labelMessage.font = UIFont.systemFont(ofSize: 13)
_effectView = UIVisualEffectView()
_effectView.frame = CGRect(x: 0, y: 0, width: _screenWidth, height: _screenHeight)
_effectView.effect = nil
_effectView.autoresizingMask = [.flexibleWidth,.flexibleHeight]
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public convenience init(title:String?,message:String?,delegate:YHAlertViewDelegate?,cancelButtonTitle:String?,otherButtonTitles:[String]){
self.init()
_arrayButton = [UIButton]()
//标题
_title = title
let labelX:CGFloat = 16
let labelY:CGFloat = 20
let labelW:CGFloat = _contentWidth - 2 * labelX
if let title = _title {
_labelTitle.text = title
_labelTitle.sizeToFit()
let size = _labelTitle.frame.size
_labelTitle.frame = CGRect(x: labelX, y: labelY, width: labelW, height: size.height)
}
//消息
_message = message
if let message = message {
let style = NSMutableParagraphStyle()
style.firstLineHeadIndent = 30 // 缩进
style.lineSpacing = 8 // 行距
let messageText = NSMutableAttributedString.init(string: message)
messageText.addAttribute(NSParagraphStyleAttributeName, value: style, range: NSRange.init(location: 0, length: messageText.length))
// 字间距
messageText.addAttribute(NSKernAttributeName, value: 0.8, range: NSRange.init(location: 0, length: messageText.length))
_labelMessage.attributedText = messageText
}
_labelMessage.sizeToFit()
let sizeMessage = _labelMessage.frame.size
if (_title != nil) {
_labelMessage.frame = CGRect(x: labelX, y: _labelTitle.frame.maxY + _margin, width: labelW, height: sizeMessage.height)
} else {
_labelMessage.frame = CGRect(x: labelX, y: _labelTitle.frame.maxY, width: labelW, height: sizeMessage.height)
}
self.delegate = delegate
animationOption = .none
_cancelButtonTitle = cancelButtonTitle
for eachObject in otherButtonTitles{
_otherButtonTitles.append(eachObject)
}
_setupDefault()
_setupButton()
}
open class func show(title:String?,message:String?,cancelButtonTitle:String?,otherButtonTitles:String ... ,clickButtonBlock:YHAlertViewClickButtonBlock){
let alertView = YHAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: otherButtonTitles)
alertView._clickButtonBlock = clickButtonBlock
alertView.show()
}
open class func show(title:String?,message:String?,cancelButtonTitle:String?,otherButtonTitle:String,clickButtonBlock:YHAlertViewClickButtonBlock){
let alertView = YHAlertView(title: title, message: message, delegate: nil, cancelButtonTitle: cancelButtonTitle, otherButtonTitles: [otherButtonTitle])
alertView._clickButtonBlock = clickButtonBlock
alertView.show()
}
// shows popup alert animated.
open func show(){
UIApplication.shared.keyWindow?.addSubview(self)
switch animationOption {
case .none:
_contentView.alpha = 0.0
UIView.animate(withDuration: 0.34, animations: { [unowned self] in
if self.visual == true {
self._effectView.effect = UIBlurEffect(style: .dark)
}
self._contentView.alpha = 1.0
})
break
case .zoom:
self._contentView.layer.setValue(0, forKeyPath: "transform.scale")
UIView.animate(withDuration: 0.75, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: .curveEaseIn, animations: {
[unowned self] in
if self.visual == true {
self._effectView.effect = UIBlurEffect(style: .dark)
}
self._contentView.layer.setValue(1.0, forKeyPath: "transform.scale")
}, completion: { _ in
})
break
case .topToCenter:
let startPoint = CGPoint(x: center.x, y: _contentView.frame.height)
_contentView.layer.position = startPoint
UIView.animate(withDuration: 0.75, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1.0, options: .curveEaseIn, animations: { [unowned self] in
if self.visual == true {
self._effectView.effect = UIBlurEffect(style: .dark)
}
self._contentView.layer.position = self.center
}, completion: { _ in
})
break
}
}
// MARK: - Private Method
fileprivate func _setupDefault(){
frame = CGRect(x: 0, y: 0, width: _screenWidth, height: _screenHeight)
self.autoresizingMask = [.flexibleWidth,.flexibleHeight]
backgroundColor = UIColor.clear
visual = true
animationOption = .none
addSubview(_effectView)
addSubview(_contentView)
_contentView.backgroundColor = UIColor.white
_contentView.addSubview(_labelTitle)
_contentView.addSubview(_labelMessage)
}
private func _setupButton(){
let buttonY = _labelMessage.frame.maxY + 20
var countRow = 0
if _cancelButtonTitle?.isEmpty == false {
countRow = 1;
}
countRow += _otherButtonTitles.count
switch countRow {
case 0:
_contentView.addSubview(_button(frame: CGRect(x: 0, y: buttonY, width: _contentWidth, height:_contentHeight/2), title: "", target: self, action: #selector(_clickCancel(sender:))))
let height = _contentHeight/2 + buttonY
_contentView.frame = CGRect(x: 0, y: 0, width:_contentWidth, height: height)
_contentView.center = self.center
break
case 2:
var titleCancel:String
var titleOther:String
if _cancelButtonTitle?.isEmpty == false {
titleCancel = _cancelButtonTitle ?? ""
titleOther = _otherButtonTitles[0]
}else {
titleCancel = _otherButtonTitles[0]
titleOther = _otherButtonTitles.last!
}
let buttonWidth: CGFloat = (_contentWidth - _margin * 3) / 2
let buttonCancel = _button(frame: CGRect(x: _margin, y: buttonY, width: buttonWidth, height: _contentHeight/2), title: titleCancel, target: target, action: #selector(_clickCancel(sender:)))
let buttonOther = _button(frame: CGRect(x: _margin * 2 + buttonWidth, y: buttonY, width: buttonWidth, height: _contentHeight/2), title: titleOther, target: self, action: #selector(_clickOther(sender:)))
_contentView.addSubview(buttonOther)
_contentView.addSubview(buttonCancel)
let height = _contentHeight/2 + buttonY + _margin
_contentView.frame = CGRect(x: 0, y: 0, width: _contentWidth, height: height)
_contentView.center = self.center
break
default:
for number in 0..<countRow {
var title = ""
var selector:Selector
if _otherButtonTitles.count > number {
title = _otherButtonTitles[number]
selector = #selector(_clickOther(sender:))
}else{
title = _cancelButtonTitle ?? ""
selector = #selector(_clickCancel(sender:))
}
let button = _button(frame: CGRect(x: _margin, y: (CGFloat(number)*_contentHeight/2 + buttonY), width: _contentWidth - 2 * _margin, height: _contentHeight/2), title: title, target: self, action: selector)
_arrayButton.append(button)
_contentView.addSubview(button)
}
var height = _contentHeight/2 + buttonY + _margin
if countRow > 2 {
height = CGFloat(countRow) * (_contentHeight/2) + buttonY
}
_contentView.frame = CGRect(x: 0, y: 0, width: _contentWidth, height: height)
_contentView.center = self.center
break
}
}
private func _image(color:UIColor) -> UIImage?{
let rect = CGRect(x: 0.0, y: 0.0, width: 1.0, height: 1.0)
UIGraphicsBeginImageContext(rect.size)
guard let context = UIGraphicsGetCurrentContext() else {
UIGraphicsEndImageContext()
return nil
}
context.setFillColor(color.cgColor)
context.fill(rect)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
private func _button(frame:CGRect,title:String,target:Any,action:Selector) -> UIButton{
let button = UIButton(type: .custom)
button.frame = frame
button.setTitleColor(UIColor.white, for: .normal)
button.setTitle(title, for: .normal)
button.backgroundColor = UIColor.orange
button.layer.cornerRadius = 8
button.clipsToBounds = true
button.setBackgroundImage(_image(color: UIColor.init(red: 235.0/255, green: 235.0/255, blue: 235.0/255, alpha: 1.0)), for: .highlighted)
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.addTarget(target, action: action, for: .touchUpInside)
return button
}
private func _remove(){
switch animationOption {
case .none:
UIView.animate(withDuration: 0.3, animations: {
[unowned self] in
if self.visual == true {
self._effectView.effect = nil
}
self._contentView.alpha = 0.0
}, completion: { [unowned self] (finished:Bool) in
self.removeFromSuperview()
})
break
case .zoom:
UIView.animate(withDuration: 0.3, animations: {
self._contentView.alpha = 0.0
if self.visual == true {
self._effectView.effect = nil
}
}, completion: { [unowned self] (finished:Bool) in
self.removeFromSuperview()
})
break
case .topToCenter:
let endPoint = CGPoint(x: center.x, y: frame.height+_contentView.frame.height)
UIView.animate(withDuration: 0.3, animations: {
if self.visual == true {
self._effectView.effect = nil
}
self._contentView.layer.position = endPoint
}, completion: {[unowned self] (finished:Bool)in
self.removeFromSuperview()
})
break
}
}
// MARK: - Action
func _clickOther(sender:UIButton){
var buttonIndex:Int = 0
if _cancelButtonTitle?.isEmpty == false {
buttonIndex = 1
}
if _arrayButton.count > 0 {
buttonIndex += _arrayButton.index(of: sender) ?? 0
}
delegate?.alertView(alertView: self, clickedButtonAtIndex: buttonIndex)
if let aBlock = _clickButtonBlock {
aBlock(self,buttonIndex)
}
_remove()
}
func _clickCancel(sender:UIButton){
delegate?.alertView(alertView: self, clickedButtonAtIndex: 0)
if let aBlock = _clickButtonBlock {
aBlock(self,0)
}
_remove()
}
// MARK: - Life
deinit {
// let filename = URL(string:"\(#file)")?.lastPathComponent ?? ""
// debugPrint("\(filename) 第 \(#line) 行 ,\(#function)")
}
}
| apache-2.0 | 9afd70b6e5bd9f81a5665997fcc10ca2 | 36.152466 | 220 | 0.557514 | 5.1348 | false | false | false | false |
SuEric/SVU_iOS | SVU/GuardiaViewController.swift | 1 | 6689 | //
// GuardiaViewController.swift
// SVU
//
// Created by Eric García on 25/10/15.
// Copyright © 2015 Eric García. All rights reserved.
//
import UIKit
import EZLoadingActivity
class GuardiaViewController: UIViewController, UITextFieldDelegate, UIScrollViewDelegate {
@IBOutlet weak var numTrabajador: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var scrollView: UIScrollView!
var activeField: UITextField!;
var firstLaunch : Bool!
var logged : Bool!
override func viewDidLoad() {
super.viewDidLoad()
self.numTrabajador.delegate = self
self.password.delegate = self
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "FirstLaunch")
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "Logged")
firstLaunch = NSUserDefaults.standardUserDefaults().boolForKey("FirstLaunch")
logged = NSUserDefaults.standardUserDefaults().boolForKey("Logged")
if firstLaunch == false && logged == true {
self.performSegueWithIdentifier("ingreso_guardia", sender: self)
}
else {
NSUserDefaults.standardUserDefaults().setBool(false, forKey: "FirstLaunch")
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
}
override func viewWillAppear(animated: Bool) {
self.registerForKeyboardNotifications()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func ingresarButtonClicked(sender: AnyObject) {
let str_trabajador = numTrabajador.text
let str_password = password.text
EZLoadingActivity.Settings.SuccessText = "Bienvenido"
EZLoadingActivity.Settings.FailText = "Error"
EZLoadingActivity.show("Ingresando...", disableUI: false)
var error_campos = false
var error_datos = false
let backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)
dispatch_async(backgroundQueue, {
if str_trabajador?.isEmpty == true || str_password?.isEmpty == true {
error_campos = true
}
else {
if str_trabajador != "18F4550" || str_password != "pic" {
error_datos = true
}
}
dispatch_async(dispatch_get_main_queue(), { () -> Void in
if error_campos == false && error_datos == false {
EZLoadingActivity.hide(success: true, animated: true)
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "Logged")
NSNotificationCenter.defaultCenter().removeObserver(self)
self.performSegueWithIdentifier("ingreso_guardia", sender: self)
}
else {
EZLoadingActivity.hide(success: false, animated: true)
if error_campos {
let alert = UIAlertController(title: nil, message: "Favor de ingresar más campos", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: true, completion: nil)
self.dismissViewControllerAnimated(true, completion: nil)
}
else {
let alert = UIAlertController(title: nil, message: "Los datos son incorrectos", preferredStyle: UIAlertControllerStyle.Alert)
self.presentViewController(alert, animated: true, completion: nil)
self.dismissViewControllerAnimated(true, completion: nil)
}
}
})
})
}
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
if identifier == "ingreso_guardia" {
if firstLaunch == false && logged == true {
return true
}
}
return false
}
func textFieldDidBeginEditing(textField: UITextField) {
activeField = textField
}
func textFieldDidEndEditing(textField: UITextField) {
activeField = nil
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
if textField == self.numTrabajador {
self.password.becomeFirstResponder()
}
else {
textField.resignFirstResponder()
}
return true
}
// Call this method somewhere in your view controller setup code.
func registerForKeyboardNotifications() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWasShown:", name: UIKeyboardDidShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillBeHidden:", name: UIKeyboardWillHideNotification, object: nil)
}
// Called when the UIKeyboardDidShowNotification is sent.
func keyboardWasShown(aNotification: NSNotification) {
var info: [NSObject : AnyObject] = aNotification.userInfo!
let kbSize: CGSize = info[UIKeyboardFrameBeginUserInfoKey]!.CGRectValue.size
let contentInsets: UIEdgeInsets = UIEdgeInsetsMake(0.0, 0.0, kbSize.height, 0.0)
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
// If active text field is hidden by keyboard, scroll it so it's visible
// Your app might not need or want this behavior.
var aRect: CGRect = self.view.frame
aRect.size.height -= kbSize.height
if !CGRectContainsPoint(aRect, activeField.frame.origin) {
self.scrollView.scrollRectToVisible(activeField.frame, animated: true)
}
}
// Called when the UIKeyboardWillHideNotification is sent
func keyboardWillBeHidden(aNotification: NSNotification) {
let contentInsets: UIEdgeInsets = UIEdgeInsetsZero
scrollView.contentInset = contentInsets
scrollView.scrollIndicatorInsets = contentInsets
}
/*
// 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.
}
*/
}
| gpl-3.0 | 7a916fa9674d96efc6a82c8f331ccb7c | 37.41954 | 152 | 0.626178 | 5.660457 | false | false | false | false |
rajeejones/SavingPennies | Pods/IBAnimatable/IBAnimatable/ScreenEdgePanInteractiveAnimator.swift | 5 | 2753 | //
// Created by Jake Lin on 4/5/16.
// Copyright © 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ScreenEdgePanInteractiveAnimator: InteractiveAnimator {
override func makeGestureRecognizer() -> UIGestureRecognizer {
let gestureRecognizer = UIScreenEdgePanGestureRecognizer(target: self, action: #selector(handleGesture(for:)))
switch interactiveGestureType {
case let .screenEdgePan(direction):
switch direction {
case .left:
gestureRecognizer.edges = .left
case .right:
gestureRecognizer.edges = .right
case .horizontal:
gestureRecognizer.edges = [.left, .right]
case .top:
gestureRecognizer.edges = .top
case .bottom:
gestureRecognizer.edges = .bottom
case .vertical:
gestureRecognizer.edges = [.top, .bottom]
default:
break
}
default:
break
}
return gestureRecognizer
}
override func calculateProgress(for gestureRecognizer: UIGestureRecognizer) -> (progress: CGFloat, shouldFinishInteractiveTransition: Bool) {
guard let gestureRecognizer = gestureRecognizer as? UIScreenEdgePanGestureRecognizer,
let superview = gestureRecognizer.view?.superview else {
return (0, false)
}
let translation = gestureRecognizer.translation(in: superview)
let velocity = gestureRecognizer.velocity(in: superview)
var progress: CGFloat
let distance: CGFloat
let speed: CGFloat
switch interactiveGestureType {
case let .screenEdgePan(direction):
switch direction {
case .horizontal:
distance = superview.frame.width
progress = abs(translation.x / distance)
speed = abs(velocity.x)
case .left:
distance = superview.frame.width
progress = translation.x / distance
speed = velocity.x
case .right:
distance = superview.frame.width
progress = -(translation.x / distance)
speed = -velocity.x
case .vertical:
distance = superview.frame.height
progress = abs(translation.y / distance)
speed = abs(velocity.y)
case .top:
distance = superview.frame.height
progress = translation.y / distance
speed = velocity.y
case .bottom:
distance = superview.frame.height
progress = -translation.y / distance
speed = -velocity.y
default:
return (0, false)
}
default:
return (0, false)
}
progress = min(max(progress, 0), 0.99)
// Finish the transition when pass the threathold
let shouldFinishInteractiveTransition = progress > 0.5 || speed > 1000
return (progress, shouldFinishInteractiveTransition)
}
}
| gpl-3.0 | 1ff9b671a98a60f2c438e8e16d1f596e | 30.272727 | 143 | 0.65407 | 4.9319 | false | false | false | false |
skedgo/tripkit-ios | Tests/TripKitUITests/vendor/RxBlocking/RunLoopLock.swift | 3 | 2342 | //
// RunLoopLock.swift
// RxBlocking
//
// Created by Krunoslav Zaher on 11/5/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import CoreFoundation
import Foundation
import RxSwift
#if os(Linux)
import Foundation
let runLoopMode: RunLoop.Mode = .default
let runLoopModeRaw: CFString = unsafeBitCast(runLoopMode.rawValue._bridgeToObjectiveC(), to: CFString.self)
#else
let runLoopMode: CFRunLoopMode = CFRunLoopMode.defaultMode
let runLoopModeRaw = runLoopMode.rawValue
#endif
final class RunLoopLock {
let currentRunLoop: CFRunLoop
let calledRun = AtomicInt(0)
let calledStop = AtomicInt(0)
var timeout: TimeInterval?
init(timeout: TimeInterval?) {
self.timeout = timeout
self.currentRunLoop = CFRunLoopGetCurrent()
}
func dispatch(_ action: @escaping () -> Void) {
CFRunLoopPerformBlock(self.currentRunLoop, runLoopModeRaw) {
if CurrentThreadScheduler.isScheduleRequired {
_ = CurrentThreadScheduler.instance.schedule(()) { _ in
action()
return Disposables.create()
}
}
else {
action()
}
}
CFRunLoopWakeUp(self.currentRunLoop)
}
func stop() {
if decrement(self.calledStop) > 1 {
return
}
CFRunLoopPerformBlock(self.currentRunLoop, runLoopModeRaw) {
CFRunLoopStop(self.currentRunLoop)
}
CFRunLoopWakeUp(self.currentRunLoop)
}
func run() throws {
if increment(self.calledRun) != 0 {
fatalError("Run can be only called once")
}
if let timeout = self.timeout {
#if os(Linux)
let runLoopResult = CFRunLoopRunInMode(runLoopModeRaw, timeout, false)
#else
let runLoopResult = CFRunLoopRunInMode(runLoopMode, timeout, false)
#endif
switch runLoopResult {
case .finished:
return
case .handledSource:
return
case .stopped:
return
case .timedOut:
throw RxError.timeout
default:
return
}
}
else {
CFRunLoopRun()
}
}
}
| apache-2.0 | a8850bbf683a7cb86f6c40cf9cbb512f | 25.908046 | 111 | 0.573259 | 5.225446 | false | false | false | false |
rzil/honours | DeepLearning/Tensorflow/Zilisweeper/Zilisweeper/BoardView.swift | 1 | 2414 | //
// BoardView.swift
// Zilisweeper
//
// Created by Ruben Zilibowitz on 6/11/17.
// Copyright © 2017 Ruben Zilibowitz. All rights reserved.
//
import UIKit
class BoardView: UIView {
weak var board: Board!
var dead: Bool = false {
didSet {
backgroundColor = dead ? .red : .lightGray
}
}
var guess: (free: Bool, row: Int, col: Int)?
override func awakeFromNib() {
super.awakeFromNib()
layer.borderWidth = 1
dead = false
}
override func draw(_ rect: CGRect) {
super.draw(rect)
let rowHeight = bounds.height / CGFloat(board.rows)
let colWidth = bounds.width / CGFloat(board.cols)
guard let ctx = UIGraphicsGetCurrentContext() else { return }
// draw guess
if let (free,row,col) = self.guess {
let rect = CGRect(x: colWidth * CGFloat(col), y: rowHeight * CGFloat(row), width: colWidth, height: rowHeight)
if free {
UIColor.blue.setFill()
}
else {
UIColor.magenta.setFill()
}
UIRectFill(rect)
}
// draw cell outlines
for r in 1 ..< board.rows {
ctx.move(to: CGPoint(x: 0, y: rowHeight * CGFloat(r)))
ctx.addLine(to: CGPoint(x: bounds.width, y: rowHeight * CGFloat(r)))
ctx.strokePath()
}
for c in 1 ..< board.cols {
ctx.move(to: CGPoint(x: colWidth * CGFloat(c), y: 0))
ctx.addLine(to: CGPoint(x: colWidth * CGFloat(c), y: bounds.height))
ctx.strokePath()
}
// draw adjacency info
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attrs = [NSAttributedStringKey.font: UIFont.preferredFont(forTextStyle: .callout),
NSAttributedStringKey.paragraphStyle: paragraphStyle]
for (i,a) in board.adjacency.enumerated() {
guard a >= 0 else { continue }
let (r,c) = board.cellFrom(index: i)
let string = "\(a)"
string.draw(with: CGRect(x: colWidth * CGFloat(c), y: rowHeight * CGFloat(r), width: colWidth, height: rowHeight), options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
}
}
}
| mit | ca7d8ea4248b2c37d30e6e5bf61ffa4a | 30.337662 | 193 | 0.542064 | 4.427523 | false | false | false | false |
wangyandong-ningxia/Swift-CoreAnimation | SwiftCoreAnimationFun/CAAnimation+Closures.swift | 1 | 1926 | //
// CAAnimation+Closures.swift
// SwiftCoreAnimationFun
//
// Created by Wang Yandong on 6/13/14.
// Copyright (c) 2014 Wang Yandong. All rights reserved.
//
//import Foundation
//import QuartzCore
//
//class CAAnimationDelagate: NSObject {
//
// var didStar: ((CAAnimation!) -> Void)?
// var didStop: ((CAAnimation!, Bool) -> Void)?
//
// override func animationDidStart(anim: CAAnimation!) {
// if (nil != didStar) {
// didStar!(anim)
// }
// }
//
// override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
// if (nil != didStop) {
// didStop!(anim, flag)
// }
// }
//
//}
//
//extension CAAnimation {
//
// var didStart: ((CAAnimation!) -> Void)? {
// get {
// if let delegate = self.delegate as? CAAnimationDelagate {
// return delegate.didStar
// }
//
// return nil
// }
//
// set {
// if let delegate = self.delegate as? CAAnimationDelagate {
// delegate.didStar = newValue
// } else {
// var delegate = CAAnimationDelagate()
// delegate.didStar = newValue
// self.delegate = delegate
// }
// }
// }
//
// var didStop: ((CAAnimation!, Bool) -> Void)? {
// get {
// if let delegate = self.delegate as? CAAnimationDelagate {
// return delegate.didStop
// }
//
// return nil
// }
//
// set {
// if let delegate = self.delegate as? CAAnimationDelagate {
// delegate.didStop = newValue
// } else {
// var delegate = CAAnimationDelagate()
// delegate.didStop = newValue
// self.delegate = delegate
// }
// }
// }
//
//} | mit | 93c35b70ced0afdf4b24cd183e63de78 | 25.39726 | 79 | 0.475597 | 4.097872 | false | false | false | false |
mikecole20/ReSwiftThunk | Pods/ReSwift/ReSwift/CoreTypes/Store.swift | 3 | 7315 | //
// Store.swift
// ReSwift
//
// Created by Benjamin Encz on 11/11/15.
// Copyright © 2015 DigiTales. All rights reserved.
//
import Foundation
/**
This class is the default implementation of the `Store` protocol. You will use this store in most
of your applications. You shouldn't need to implement your own store.
You initialize the store with a reducer and an initial application state. If your app has multiple
reducers you can combine them by initializng a `MainReducer` with all of your reducers as an
argument.
*/
open class Store<State: StateType>: StoreType {
typealias SubscriptionType = SubscriptionBox<State>
// swiftlint:disable todo
// TODO: Setter should not be public; need way for store enhancers to modify appState anyway
// swiftlint:enable todo
/*private (set)*/ public var state: State! {
didSet {
subscriptions = subscriptions.filter { $0.subscriber != nil }
subscriptions.forEach {
$0.newValues(oldState: oldValue, newState: state)
}
}
}
public var dispatchFunction: DispatchFunction!
private var reducer: Reducer<State>
var subscriptions: [SubscriptionType] = []
private var isDispatching = false
public required init(
reducer: @escaping Reducer<State>,
state: State?,
middleware: [Middleware<State>] = []
) {
self.reducer = reducer
// Wrap the dispatch function with all middlewares
self.dispatchFunction = middleware
.reversed()
.reduce({ [unowned self] action in
return self._defaultDispatch(action: action)
}) { dispatchFunction, middleware in
// If the store get's deinitialized before the middleware is complete; drop
// the action without dispatching.
let dispatch: (Action) -> Void = { [weak self] in self?.dispatch($0) }
let getState = { [weak self] in self?.state }
return middleware(dispatch, getState)(dispatchFunction)
}
if let state = state {
self.state = state
} else {
dispatch(ReSwiftInit())
}
}
fileprivate func _subscribe<SelectedState, S: StoreSubscriber>(
_ subscriber: S, originalSubscription: Subscription<State>,
transformedSubscription: Subscription<SelectedState>?)
where S.StoreSubscriberStateType == SelectedState
{
// If the same subscriber is already registered with the store, replace the existing
// subscription with the new one.
if let index = subscriptions.index(where: { $0.subscriber === subscriber }) {
subscriptions.remove(at: index)
}
let subscriptionBox = self.subscriptionBox(
originalSubscription: originalSubscription,
transformedSubscription: transformedSubscription,
subscriber: subscriber
)
subscriptions.append(subscriptionBox)
if let state = self.state {
originalSubscription.newValues(oldState: nil, newState: state)
}
}
open func subscribe<S: StoreSubscriber>(_ subscriber: S)
where S.StoreSubscriberStateType == State {
_ = subscribe(subscriber, transform: nil)
}
open func subscribe<SelectedState, S: StoreSubscriber>(
_ subscriber: S, transform: ((Subscription<State>) -> Subscription<SelectedState>)?
) where S.StoreSubscriberStateType == SelectedState
{
// Create a subscription for the new subscriber.
let originalSubscription = Subscription<State>()
// Call the optional transformation closure. This allows callers to modify
// the subscription, e.g. in order to subselect parts of the store's state.
let transformedSubscription = transform?(originalSubscription)
_subscribe(subscriber, originalSubscription: originalSubscription,
transformedSubscription: transformedSubscription)
}
internal func subscriptionBox<T>(
originalSubscription: Subscription<State>,
transformedSubscription: Subscription<T>?,
subscriber: AnyStoreSubscriber
) -> SubscriptionBox<State> {
return SubscriptionBox(
originalSubscription: originalSubscription,
transformedSubscription: transformedSubscription,
subscriber: subscriber
)
}
open func unsubscribe(_ subscriber: AnyStoreSubscriber) {
if let index = subscriptions.index(where: { return $0.subscriber === subscriber }) {
subscriptions.remove(at: index)
}
}
// swiftlint:disable:next identifier_name
open func _defaultDispatch(action: Action) {
guard !isDispatching else {
raiseFatalError(
"ReSwift:ConcurrentMutationError- Action has been dispatched while" +
" a previous action is action is being processed. A reducer" +
" is dispatching an action, or ReSwift is used in a concurrent context" +
" (e.g. from multiple threads)."
)
}
isDispatching = true
let newState = reducer(action, state)
isDispatching = false
state = newState
}
open func dispatch(_ action: Action) {
dispatchFunction(action)
}
open func dispatch(_ actionCreatorProvider: @escaping ActionCreator) {
if let action = actionCreatorProvider(state, self) {
dispatch(action)
}
}
open func dispatch(_ asyncActionCreatorProvider: @escaping AsyncActionCreator) {
dispatch(asyncActionCreatorProvider, callback: nil)
}
open func dispatch(_ actionCreatorProvider: @escaping AsyncActionCreator,
callback: DispatchCallback?) {
actionCreatorProvider(state, self) { actionProvider in
let action = actionProvider(self.state, self)
if let action = action {
self.dispatch(action)
callback?(self.state)
}
}
}
public typealias DispatchCallback = (State) -> Void
public typealias ActionCreator = (_ state: State, _ store: Store) -> Action?
public typealias AsyncActionCreator = (
_ state: State,
_ store: Store,
_ actionCreatorCallback: @escaping ((ActionCreator) -> Void)
) -> Void
}
// MARK: Skip Repeats for Equatable States
extension Store where State: Equatable {
open func subscribe<S: StoreSubscriber>(_ subscriber: S)
where S.StoreSubscriberStateType == State {
_ = subscribe(subscriber, transform: { $0.skipRepeats() })
}
open func subscribe<SelectedState: Equatable, S: StoreSubscriber>(
_ subscriber: S, transform: ((Subscription<State>) -> Subscription<SelectedState>)?
) where S.StoreSubscriberStateType == SelectedState
{
let originalSubscription = Subscription<State>()
var transformedSubscription = transform?(originalSubscription)
transformedSubscription = transformedSubscription?.skipRepeats()
_subscribe(subscriber,
originalSubscription: originalSubscription,
transformedSubscription: transformedSubscription)
}
}
| mit | 36037c83a8ad733698ef84100c4307a4 | 34.163462 | 99 | 0.641373 | 5.397786 | false | false | false | false |
OEASLAN/LetsEat | IOS/Let's Eat/Let's Eat/SideBar/SideBarTableViewController.swift | 1 | 2461 | //
// SideBarTableViewController.swift
// Let's Eat
//
// Created by Vidal_HARA on 17.03.2015.
// Copyright (c) 2015 vidal hara S002866. All rights reserved.
//
import UIKit
protocol SideBarTableViewControllerDelegate{
func sideBarControlDidSelectRow(indexPath:NSIndexPath)
}
class SideBarTableViewController: UITableViewController {
var delegate:SideBarTableViewControllerDelegate?
var tableData:Array<String> = []
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return tableData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("Cell") as? UITableViewCell
if cell == nil{
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "Cell")
// Configure the cell...
if indexPath.row == tableData.count-1{
cell!.backgroundColor = UIColor.redColor()
}else{
cell!.backgroundColor = UIColor.clearColor()
}
cell!.textLabel?.textAlignment = NSTextAlignment.Center
cell!.textLabel?.textColor = UIColor.darkTextColor()
let selectedView:UIView = UIView(frame: CGRect(x: 0, y: 0, width: cell!.frame.size.width, height: cell!.frame.size.height))
if indexPath.row == tableData.count-1 {
selectedView.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.3)
}else{
selectedView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.3)
}
cell!.selectedBackgroundView = selectedView
}
cell!.textLabel?.text = tableData[indexPath.row]
return cell!
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 40.0
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.sideBarControlDidSelectRow(indexPath)
}
}
| gpl-2.0 | 781762cf0951f24a7901f56010e5737e | 29.7625 | 135 | 0.635514 | 5.530337 | false | false | false | false |
CrowdShelf/ios | CrowdShelf/CrowdShelf/Utilities.swift | 1 | 1917 | //
// Utilities.swift
// CrowdShelf
//
// Created by Øyvind Grimnes on 25/09/15.
// Copyright © 2015 Øyvind Grimnes. All rights reserved.
//
import Foundation
class Utilities {
class func delayDispatchInQueue(queue: dispatch_queue_t, delay: NSTimeInterval, block: (()->Void)) {
let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue(), { () -> Void in
block()
})
}
class func throttle( delay:NSTimeInterval, queue:dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), action: (()->()) ) -> ()->() {
var wait = false
return {
if !wait {
wait = true
action()
let delayTime = Int64(delay * Double(NSEC_PER_SEC))
dispatch_after( dispatch_time(DISPATCH_TIME_NOW, delayTime) , queue ) {
wait = false
}
}
}
}
class func debounce( delay:NSTimeInterval, queue:dispatch_queue_t = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), action: (()->()) ) -> ()->() {
var lastFireTime:dispatch_time_t = 0
let dispatchDelay = Int64(delay * Double(NSEC_PER_SEC))
return {
lastFireTime = dispatch_time(DISPATCH_TIME_NOW,0)
dispatch_after(
dispatch_time(
DISPATCH_TIME_NOW,
dispatchDelay
),
queue) {
let now = dispatch_time(DISPATCH_TIME_NOW,0)
let when = dispatch_time(lastFireTime, dispatchDelay)
if now >= when {
action()
}
}
}
}
} | mit | ac3a517af0d1817a89b500e6126c33f4 | 29.396825 | 165 | 0.497388 | 4.702703 | false | false | false | false |
ykyouhei/QiitaKit | QiitaKit/Sources/Responses/PageableResponse.swift | 1 | 2226 | //
// PageableResponse.swift
// QiitaKit
//
// Created by kyohei yamaguchi on 2018/03/21.
// Copyright © 2018年 kyo__hei. All rights reserved.
//
import Foundation
/// ページ可能なリクエスト用のレスポンスオブジェクト
public struct PageableResponse<Element: Decodable>: QiitaResponse {
public let totalCount: Int
public let currentPage: Int
public let objects: [Element]
public let nextPage: Int?
public let prevPage: Int?
public var count: Int {
return objects.count
}
public var hasNext: Bool {
return nextPage != nil
}
public var hasPrev: Bool {
return prevPage != nil
}
public init() {
self.totalCount = 0
self.currentPage = 1
self.objects = []
self.nextPage = nil
self.prevPage = nil
}
public init(response: HTTPURLResponse, json: Data) throws {
func pageNum(with target: String) -> Int? {
let link = response.allHeaderFields["Link"] as! String
let range = NSRange(location: 0, length: link.count)
let pattern = "<.+[\\?|&]page=([0-9]+)[^>]*>; rel=\"\(target)\""
guard let matched = try! NSRegularExpression(pattern: pattern).firstMatch(in: link, options: [], range: range) else {
return nil
}
return Int(NSString(string: link).substring(with: matched.range(at: 1)))
}
let jsonDecoder = JSONDecoder()
jsonDecoder.dateDecodingStrategy = .iso8601
self.objects = try jsonDecoder.decode(Array<Element>.self, from: json)
self.totalCount = Int(response.allHeaderFields["total-count"] as! String)!
self.prevPage = pageNum(with: "prev")
self.nextPage = pageNum(with: "next")
switch (self.prevPage, self.nextPage) {
case let (.some(prev), _): self.currentPage = prev + 1
case let (_, .some(next)): self.currentPage = next - 1
default: self.currentPage = 1
}
}
public subscript(index: Int) -> Element {
return objects[index]
}
}
| mit | 87802d794ff50f01b4f5389cb127496d | 27.618421 | 129 | 0.566437 | 4.402834 | false | false | false | false |
xiaotaijun/actor-platform | actor-apps/app-ios/ActorApp/Controllers/Conversation/Cells/AutoCompleteCell.swift | 2 | 4718 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
class AutoCompleteCell: UITableViewCell {
var avatarView = AvatarView(frameSize: 32)
var nickView = TTTAttributedLabel(frame: CGRectZero)
var nameView = TTTAttributedLabel(frame: CGRectZero)
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: UITableViewCellStyle.Default, reuseIdentifier: reuseIdentifier)
avatarView.enableAnimation = false
nickView.font = UIFont.systemFontOfSize(14)
nickView.textColor = MainAppTheme.list.textColor
nameView.font = UIFont.systemFontOfSize(14)
nameView.textColor = MainAppTheme.list.hintColor
self.contentView.addSubview(avatarView)
self.contentView.addSubview(nickView)
self.contentView.addSubview(nameView)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func bindData(user: ACUserVM, highlightWord: String) {
avatarView.bind(user.getNameModel().get(), id: user.getId(), avatar: user.getAvatarModel().get(), clearPrev: true)
var nickText: String
var nameText: String
if user.getNickModel().get() == nil {
if user.getLocalNameModel().get() == nil {
nickText = user.getNameModel().get()
nameText = ""
} else {
nickText = user.getServerNameModel().get()
nameText = " \u{2022} \(user.getLocalNameModel().get())"
}
} else {
nickText = "@\(user.getNickModel().get())"
nameText = " \u{2022} \(user.getNameModel().get())"
}
var nickAttrs = NSMutableAttributedString(string: nickText)
var nameAttrs = NSMutableAttributedString(string: nameText)
nickAttrs.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: NSMakeRange(0, nickText.size))
nameAttrs.addAttribute(NSFontAttributeName, value: UIFont.systemFontOfSize(14), range: NSMakeRange(0, nameText.size))
for range in nickText.rangesOfString(highlightWord) {
let start = distance(nickText.startIndex, range.startIndex)
let length = distance(range.startIndex, range.endIndex)
let nsRange = NSMakeRange(start, length)
nickAttrs.addAttribute(NSForegroundColorAttributeName, value: MainAppTheme.chat.autocompleteHighlight, range: nsRange)
}
for range in nameText.rangesOfString(highlightWord) {
let start = distance(nameText.startIndex, range.startIndex)
let length = distance(range.startIndex, range.endIndex)
let nsRange = NSMakeRange(start, length)
nameAttrs.addAttribute(NSForegroundColorAttributeName, value: MainAppTheme.chat.autocompleteHighlight, range: nsRange)
}
nickView.setText(nickAttrs)
nameView.setText(nameText)
// [label setText:text afterInheritingLabelAttributesAndConfiguringWithBlock:^ NSMutableAttributedString *(NSMutableAttributedString *mutableAttributedString) {
// NSRange boldRange = [[mutableAttributedString string] rangeOfString:@"ipsum dolor" options:NSCaseInsensitiveSearch];
// NSRange strikeRange = [[mutableAttributedString string] rangeOfString:@"sit amet" options:NSCaseInsensitiveSearch];
//
// // Core Text APIs use C functions without a direct bridge to UIFont. See Apple's "Core Text Programming Guide" to learn how to configure string attributes.
// UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:14];
// CTFontRef font = CTFontCreateWithName((__bridge CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
// if (font) {
// [mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(__bridge id)font range:boldRange];
// [mutableAttributedString addAttribute:kTTTStrikeOutAttributeName value:@YES range:strikeRange];
// CFRelease(font);
// }
//
// return mutableAttributedString;
// }];
}
override func layoutSubviews() {
super.layoutSubviews()
avatarView.frame = CGRectMake(6, 6, 32, 32)
nickView.frame = CGRectMake(44, 6, 100, 32)
nickView.sizeToFit()
nickView.frame = CGRectMake(44, 6, nickView.frame.width, 32)
var left = 44 + nickView.frame.width
nameView.frame = CGRectMake(left, 6, self.contentView.frame.width - left, 32)
}
} | mit | 709b63953942cb33247ac395014cd160 | 45.264706 | 169 | 0.651335 | 5.111593 | false | false | false | false |
apple/swift-format | Sources/SwiftFormatRules/NoEmptyTrailingClosureParentheses.swift | 1 | 2283 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
import SwiftFormatCore
import SwiftSyntax
/// Function calls with no arguments and a trailing closure should not have empty parentheses.
///
/// Lint: If a function call with a trailing closure has an empty argument list with parentheses,
/// a lint error is raised.
///
/// Format: Empty parentheses in function calls with trailing closures will be removed.
public final class NoEmptyTrailingClosureParentheses: SyntaxFormatRule {
public override func visit(_ node: FunctionCallExprSyntax) -> ExprSyntax {
guard node.argumentList.count == 0 else { return super.visit(node) }
guard let trailingClosure = node.trailingClosure,
node.argumentList.isEmpty && node.leftParen != nil else
{
return super.visit(node)
}
guard let name = node.calledExpression.lastToken?.withoutTrivia() else {
return super.visit(node)
}
diagnose(.removeEmptyTrailingParentheses(name: "\(name)"), on: node)
// Need to visit `calledExpression` before creating a new node so that the location data (column
// and line numbers) is available.
guard let rewrittenCalledExpr = ExprSyntax(visit(Syntax(node.calledExpression))) else {
return super.visit(node)
}
let formattedExp = replaceTrivia(
on: rewrittenCalledExpr,
token: rewrittenCalledExpr.lastToken,
trailingTrivia: .spaces(1))
let formattedClosure = visit(trailingClosure).as(ClosureExprSyntax.self)
let result = node.withLeftParen(nil).withRightParen(nil).withCalledExpression(formattedExp)
.withTrailingClosure(formattedClosure)
return ExprSyntax(result)
}
}
extension Finding.Message {
public static func removeEmptyTrailingParentheses(name: String) -> Finding.Message {
"remove '()' after \(name)"
}
}
| apache-2.0 | 97ae6d3c817b7e9902c1b57348284fea | 38.362069 | 100 | 0.681121 | 4.76618 | false | false | false | false |
apple/swift-driver | Sources/SwiftDriver/Jobs/Planning.swift | 1 | 45499 | //===--------------- Planning.swift - Swift Compilation Planning ----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 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
//
//===----------------------------------------------------------------------===//
import SwiftOptions
import class Foundation.JSONDecoder
import TSCBasic // <<<
import protocol TSCBasic.DiagnosticData
import struct TSCBasic.AbsolutePath
import struct TSCBasic.Diagnostic
import var TSCBasic.localFileSystem
import var TSCBasic.stdoutStream
public enum PlanningError: Error, DiagnosticData {
case replReceivedInput
case emitPCMWrongInputFiles
case dumpPCMWrongInputFiles
public var description: String {
switch self {
case .replReceivedInput:
return "REPL mode requires no input files"
case .emitPCMWrongInputFiles:
return "Clang module emission requires exactly one input file (the module map)"
case .dumpPCMWrongInputFiles:
return "Emitting information about Clang module requires exactly one input file (pre-compiled module)"
}
}
}
/// When emitting bitcode, if the first compile job is scheduled, the second must be.
/// So, group them together for incremental build purposes.
struct CompileJobGroup {
let compileJob: Job
let backendJob: Job?
init(compileJob: Job, backendJob: Job?) {
assert(compileJob.kind == .compile)
assert(compileJob.primaryInputs.count == 1, "must be unbatched")
assert(backendJob?.kind ?? .backend == .backend)
self.compileJob = compileJob
self.backendJob = backendJob
}
func allJobs() -> [Job] {
backendJob.map {[compileJob, $0]} ?? [compileJob]
}
/// Any type of file that is `partOfSwiftCompilation`
var primaryInput: TypedVirtualPath {
compileJob.primaryInputs[0]
}
var primarySwiftSourceInput: SwiftSourceFile? {
SwiftSourceFile(ifSource: primaryInput)
}
var outputs: [TypedVirtualPath] {
allJobs().flatMap {$0.outputs}
}
}
@_spi(Testing) public struct JobsInPhases {
/// In WMO mode, also includes the multi-compile & its backends, since there are >1 backend jobs
let beforeCompiles: [Job]
let compileGroups: [CompileJobGroup]
let afterCompiles: [Job]
var allJobs: [Job] {
var r = beforeCompiles
compileGroups.forEach { r.append(contentsOf: $0.allJobs()) }
r.append(contentsOf: afterCompiles)
return r
}
@_spi(Testing) public static var none = JobsInPhases(beforeCompiles: [],
compileGroups: [],
afterCompiles: [])
}
// MARK: Standard build planning
extension Driver {
/// Plan a standard compilation, which produces jobs for compiling separate
/// primary files.
private mutating func planStandardCompile() throws
-> ([Job], IncrementalCompilationState?) {
precondition(compilerMode.isStandardCompilationForPlanning,
"compiler mode \(compilerMode) is handled elsewhere")
// Determine the initial state for incremental compilation that is required during
// the planning process. This state contains the module dependency graph and
// cross-module dependency information.
let initialIncrementalState =
try IncrementalCompilationState.computeIncrementalStateForPlanning(driver: &self)
// Compute the set of all jobs required to build this module
let jobsInPhases = try computeJobsForPhasedStandardBuild()
// Determine the state for incremental compilation
let incrementalCompilationState: IncrementalCompilationState?
// If no initial state was computed, we will not be performing an incremental build
if let initialState = initialIncrementalState {
incrementalCompilationState =
try IncrementalCompilationState(driver: &self, jobsInPhases: jobsInPhases,
initialState: initialState)
} else {
incrementalCompilationState = nil
}
return try (
// For compatibility with swiftpm, the driver produces batched jobs
// for every job, even when run in incremental mode, so that all jobs
// can be returned from `planBuild`.
// But in that case, don't emit lifecycle messages.
formBatchedJobs(jobsInPhases.allJobs,
showJobLifecycle: showJobLifecycle && incrementalCompilationState == nil),
incrementalCompilationState
)
}
/// Construct a build plan consisting of *all* jobs required for building the current module (non-incrementally).
/// At build time, incremental state will be used to distinguish which of these jobs must run.
mutating private func computeJobsForPhasedStandardBuild() throws -> JobsInPhases {
// Centralize job accumulation here.
// For incremental compilation, must separate jobs happening before,
// during, and after compilation.
var jobsBeforeCompiles = [Job]()
func addJobBeforeCompiles(_ job: Job) {
assert(job.kind != .compile || job.primaryInputs.isEmpty)
jobsBeforeCompiles.append(job)
}
var compileJobGroups = [CompileJobGroup]()
func addCompileJobGroup(_ group: CompileJobGroup) {
compileJobGroups.append(group)
}
// need to buffer these to dodge shared ownership
var jobsAfterCompiles = [Job]()
func addJobAfterCompiles(_ j: Job) {
jobsAfterCompiles.append(j)
}
try addPrecompileModuleDependenciesJobs(addJob: addJobBeforeCompiles)
try addPrecompileBridgingHeaderJob(addJob: addJobBeforeCompiles)
let linkerInputs = try addJobsFeedingLinker(
addJobBeforeCompiles: addJobBeforeCompiles,
addCompileJobGroup: addCompileJobGroup,
addJobAfterCompiles: addJobAfterCompiles)
try addAPIDigesterJobs(addJob: addJobAfterCompiles)
try addLinkAndPostLinkJobs(linkerInputs: linkerInputs,
debugInfo: debugInfo,
addJob: addJobAfterCompiles)
return JobsInPhases(beforeCompiles: jobsBeforeCompiles,
compileGroups: compileJobGroups,
afterCompiles: jobsAfterCompiles)
}
private mutating func addPrecompileModuleDependenciesJobs(addJob: (Job) -> Void) throws {
// If asked, add jobs to precompile module dependencies
guard parsedOptions.contains(.driverExplicitModuleBuild) else { return }
let modulePrebuildJobs = try generateExplicitModuleDependenciesJobs()
modulePrebuildJobs.forEach(addJob)
}
private mutating func addPrecompileBridgingHeaderJob(addJob: (Job) -> Void) throws {
guard
let importedObjCHeader = importedObjCHeader,
let bridgingPrecompiledHeader = bridgingPrecompiledHeader
else { return }
addJob(
try generatePCHJob(input: .init(file: importedObjCHeader,
type: .objcHeader),
output: .init(file: bridgingPrecompiledHeader,
type: .pch))
)
}
private mutating func addEmitModuleJob(addJobBeforeCompiles: (Job) -> Void) throws -> Job? {
if emitModuleSeparately {
let emitJob = try emitModuleJob()
addJobBeforeCompiles(emitJob)
return emitJob
}
return nil
}
private mutating func addJobsFeedingLinker(
addJobBeforeCompiles: (Job) -> Void,
addCompileJobGroup: (CompileJobGroup) -> Void,
addJobAfterCompiles: (Job) -> Void
) throws -> [TypedVirtualPath] {
var linkerInputs = [TypedVirtualPath]()
func addLinkerInput(_ li: TypedVirtualPath) { linkerInputs.append(li) }
var moduleInputs = [TypedVirtualPath]()
let acceptBitcodeAsLinkerInput = lto == .llvmThin || lto == .llvmFull
func addModuleInput(_ mi: TypedVirtualPath) { moduleInputs.append(mi) }
var moduleInputsFromJobOutputs = [TypedVirtualPath]()
func addModuleInputFromJobOutputs(_ mis: TypedVirtualPath) {
moduleInputsFromJobOutputs.append(mis) }
func addJobOutputs(_ jobOutputs: [TypedVirtualPath]) {
for jobOutput in jobOutputs {
switch jobOutput.type {
case .object, .autolink:
addLinkerInput(jobOutput)
case .llvmBitcode where acceptBitcodeAsLinkerInput:
addLinkerInput(jobOutput)
case .swiftModule:
addModuleInputFromJobOutputs(jobOutput)
default:
break
}
}
}
// Ensure that only one job emits the module files and insert a verify swiftinterface job
var jobCreatingSwiftModule: Job? = nil
func addPostModuleFilesJobs(_ emitModuleJob: Job) throws {
let emitsSwiftInterface =
emitModuleJob.outputs.contains(where: { out in out.type == .swiftInterface })
guard emitsSwiftInterface else {
return
}
// We should only emit module files from one job
assert(jobCreatingSwiftModule == nil)
jobCreatingSwiftModule = emitModuleJob
try addVerifyJobs(emitModuleJob: emitModuleJob, addJob: addJobAfterCompiles)
}
// Whole-module
if let compileJob = try addSingleCompileJobs(addJob: addJobBeforeCompiles,
addJobOutputs: addJobOutputs,
emitModuleTrace: loadedModuleTracePath != nil) {
try addPostModuleFilesJobs(compileJob)
}
// Emit-module-separately
if let emitModuleJob = try addEmitModuleJob(addJobBeforeCompiles: addJobBeforeCompiles) {
try addPostModuleFilesJobs(emitModuleJob)
try addWrapJobOrMergeOutputs(
mergeJob: emitModuleJob,
debugInfo: debugInfo,
addJob: addJobAfterCompiles,
addLinkerInput: addLinkerInput)
}
try addJobsForPrimaryInputs(
addCompileJobGroup: addCompileJobGroup,
addModuleInput: addModuleInput,
addLinkerInput: addLinkerInput,
addJobOutputs: addJobOutputs)
try addAutolinkExtractJob(linkerInputs: linkerInputs,
addLinkerInput: addLinkerInput,
addJob: addJobAfterCompiles)
// Merge-module
if let mergeJob = try mergeModuleJob(
moduleInputs: moduleInputs,
moduleInputsFromJobOutputs: moduleInputsFromJobOutputs) {
addJobAfterCompiles(mergeJob)
try addPostModuleFilesJobs(mergeJob)
try addWrapJobOrMergeOutputs(
mergeJob: mergeJob,
debugInfo: debugInfo,
addJob: addJobAfterCompiles,
addLinkerInput: addLinkerInput)
}
return linkerInputs
}
/// When in single compile, add one compile job and possibility multiple backend jobs.
/// Return the compile job if one was created.
private mutating func addSingleCompileJobs(
addJob: (Job) -> Void,
addJobOutputs: ([TypedVirtualPath]) -> Void,
emitModuleTrace: Bool
) throws -> Job? {
guard case .singleCompile = compilerMode
else { return nil }
if parsedOptions.hasArgument(.embedBitcode),
inputFiles.allSatisfy({ $0.type.isPartOfSwiftCompilation }) {
let compile = try compileJob(primaryInputs: [],
outputType: .llvmBitcode,
addJobOutputs: addJobOutputs,
emitModuleTrace: emitModuleTrace)
addJob(compile)
let backendJobs = try compile.outputs.compactMap { output in
output.type == .llvmBitcode
? try backendJob(input: output, baseInput: nil, addJobOutputs: addJobOutputs)
: nil
}
backendJobs.forEach(addJob)
return compile
} else {
// We can skip the compile jobs if all we want is a module when it's
// built separately.
let compile = try compileJob(primaryInputs: [],
outputType: compilerOutputType,
addJobOutputs: addJobOutputs,
emitModuleTrace: emitModuleTrace)
addJob(compile)
return compile
}
}
private mutating func addJobsForPrimaryInputs(
addCompileJobGroup: (CompileJobGroup) -> Void,
addModuleInput: (TypedVirtualPath) -> Void,
addLinkerInput: (TypedVirtualPath) -> Void,
addJobOutputs: ([TypedVirtualPath]) -> Void)
throws {
let loadedModuleTraceInputIndex = inputFiles.firstIndex(where: {
$0.type.isPartOfSwiftCompilation && loadedModuleTracePath != nil
})
for (index, input) in inputFiles.enumerated() {
// Only emit a loaded module trace from the first frontend job.
try addJobForPrimaryInput(
input: input,
addCompileJobGroup: addCompileJobGroup,
addModuleInput: addModuleInput,
addLinkerInput: addLinkerInput,
addJobOutputs: addJobOutputs,
emitModuleTrace: index == loadedModuleTraceInputIndex)
}
}
private mutating func addJobForPrimaryInput(
input: TypedVirtualPath,
addCompileJobGroup: (CompileJobGroup) -> Void,
addModuleInput: (TypedVirtualPath) -> Void,
addLinkerInput: (TypedVirtualPath) -> Void,
addJobOutputs: ([TypedVirtualPath]) -> Void,
emitModuleTrace: Bool
) throws
{
switch input.type {
case .swift, .sil, .sib:
// Generate a compile job for primary inputs here.
guard compilerMode.usesPrimaryFileInputs else { break }
assert(input.type.isPartOfSwiftCompilation)
// We can skip the compile jobs if all we want is a module when it's
// built separately.
let canSkipIfOnlyModule = compilerOutputType == .swiftModule && emitModuleSeparately
try createAndAddCompileJobGroup(primaryInput: input,
emitModuleTrace: emitModuleTrace,
canSkipIfOnlyModule: canSkipIfOnlyModule,
addCompileJobGroup: addCompileJobGroup,
addJobOutputs: addJobOutputs)
case .object, .autolink, .llvmBitcode, .tbd:
if linkerOutputType != nil {
addLinkerInput(input)
} else {
diagnosticEngine.emit(.error_unexpected_input_file(input.file))
}
case .swiftModule:
if moduleOutputInfo.output != nil && linkerOutputType == nil {
// When generating a .swiftmodule as a top-level output (as opposed
// to, for example, linking an image), treat .swiftmodule files as
// inputs to a MergeModule action.
addModuleInput(input)
} else if linkerOutputType != nil {
// Otherwise, if linking, pass .swiftmodule files as inputs to the
// linker, so that their debug info is available.
addLinkerInput(input)
} else {
diagnosticEngine.emit(.error_unexpected_input_file(input.file))
}
default:
diagnosticEngine.emit(.error_unexpected_input_file(input.file))
}
}
private mutating func createAndAddCompileJobGroup(
primaryInput: TypedVirtualPath,
emitModuleTrace: Bool,
canSkipIfOnlyModule: Bool,
addCompileJobGroup: (CompileJobGroup) -> Void,
addJobOutputs: ([TypedVirtualPath]) -> Void
) throws {
if parsedOptions.hasArgument(.embedBitcode),
inputFiles.allSatisfy({ $0.type.isPartOfSwiftCompilation }) {
let compile = try compileJob(primaryInputs: [primaryInput],
outputType: .llvmBitcode,
addJobOutputs: addJobOutputs,
emitModuleTrace: emitModuleTrace)
let backendJobs = try compile.outputs.compactMap { output in
output.type == .llvmBitcode
? try backendJob(input: output, baseInput: primaryInput, addJobOutputs: addJobOutputs)
: nil
}
assert(backendJobs.count <= 1)
addCompileJobGroup(CompileJobGroup(compileJob: compile, backendJob: backendJobs.first))
} else {
// TODO: if !canSkipIfOnlyModule {
// Some other tools still expect the partial jobs. Bring this check
// back once they are updated. rdar://84979778
// We can skip the compile jobs if all we want is a module when it's
// built separately.
let compile = try compileJob(primaryInputs: [primaryInput],
outputType: compilerOutputType,
addJobOutputs: addJobOutputs,
emitModuleTrace: emitModuleTrace)
addCompileJobGroup(CompileJobGroup(compileJob: compile, backendJob: nil))
}
}
/// Need a merge module job if there are module inputs
private mutating func mergeModuleJob(
moduleInputs: [TypedVirtualPath],
moduleInputsFromJobOutputs: [TypedVirtualPath]
) throws -> Job? {
guard moduleOutputInfo.output != nil,
!(moduleInputs.isEmpty && moduleInputsFromJobOutputs.isEmpty),
compilerMode.usesPrimaryFileInputs,
!emitModuleSeparately
else { return nil }
return try mergeModuleJob(inputs: moduleInputs, inputsFromOutputs: moduleInputsFromJobOutputs)
}
func getAdopterConfigPathFromXcodeDefaultToolchain() -> AbsolutePath? {
let swiftPath = try? toolchain.resolvedTool(.swiftCompiler).path
guard var swiftPath = swiftPath else {
return nil
}
let toolchains = "Toolchains"
guard swiftPath.components.contains(toolchains) else {
return nil
}
while swiftPath.basename != toolchains {
swiftPath = swiftPath.parentDirectory
}
assert(swiftPath.basename == toolchains)
return swiftPath.appending(component: "XcodeDefault.xctoolchain")
.appending(component: "usr")
.appending(component: "local")
.appending(component: "lib")
.appending(component: "swift")
.appending(component: "adopter_configs.json")
}
@_spi(Testing) public struct AdopterConfig: Decodable {
public let key: String
public let moduleNames: [String]
}
@_spi(Testing) public static func parseAdopterConfigs(_ config: AbsolutePath) -> [AdopterConfig] {
let results = try? localFileSystem.readFileContents(config).withData {
try JSONDecoder().decode([AdopterConfig].self, from: $0)
}
return results ?? []
}
func getAdopterConfigsFromXcodeDefaultToolchain() -> [AdopterConfig] {
if let config = getAdopterConfigPathFromXcodeDefaultToolchain() {
return Driver.parseAdopterConfigs(config)
}
return []
}
@_spi(Testing) public static func getAllConfiguredModules(withKey: String, _ configs: [AdopterConfig]) -> Set<String> {
let allModules = configs.flatMap {
return $0.key == withKey ? $0.moduleNames : []
}
return Set<String>(allModules)
}
private mutating func addVerifyJobs(emitModuleJob: Job, addJob: (Job) -> Void )
throws {
// Turn this flag on by default with the env var or for public frameworks.
let onByDefault = env["ENABLE_DEFAULT_INTERFACE_VERIFIER"] != nil ||
parsedOptions.getLastArgument(.libraryLevel)?.asSingle == "api"
guard
// Only verify modules with library evolution.
parsedOptions.hasArgument(.enableLibraryEvolution),
// Only verify when requested, on by default and not disabled.
parsedOptions.hasFlag(positive: .verifyEmittedModuleInterface,
negative: .noVerifyEmittedModuleInterface,
default: onByDefault),
// Don't verify by default modules emitted from a merge-module job
// as it's more likely to be invalid.
emitModuleSeparately || compilerMode == .singleCompile ||
parsedOptions.hasFlag(positive: .verifyEmittedModuleInterface,
negative: .noVerifyEmittedModuleInterface,
default: false)
else { return }
let optIn = env["ENABLE_DEFAULT_INTERFACE_VERIFIER"] != nil ||
parsedOptions.hasArgument(.verifyEmittedModuleInterface)
func addVerifyJob(forPrivate: Bool) throws {
let isNeeded =
forPrivate
? parsedOptions.hasArgument(.emitPrivateModuleInterfacePath)
: parsedOptions.hasArgument(.emitModuleInterface, .emitModuleInterfacePath)
guard isNeeded else { return }
let outputType: FileType =
forPrivate ? .privateSwiftInterface : .swiftInterface
let mergeInterfaceOutputs = emitModuleJob.outputs.filter { $0.type == outputType }
assert(mergeInterfaceOutputs.count == 1,
"Merge module job should only have one swiftinterface output")
let job = try verifyModuleInterfaceJob(interfaceInput: mergeInterfaceOutputs[0], optIn: optIn)
addJob(job)
}
try addVerifyJob(forPrivate: false)
try addVerifyJob(forPrivate: true)
}
private mutating func addAutolinkExtractJob(
linkerInputs: [TypedVirtualPath],
addLinkerInput: (TypedVirtualPath) -> Void,
addJob: (Job) -> Void)
throws
{
let autolinkInputs = linkerInputs.filter { $0.type == .object }
if let autolinkExtractJob = try autolinkExtractJob(inputs: autolinkInputs) {
addJob(autolinkExtractJob)
autolinkExtractJob.outputs.forEach(addLinkerInput)
}
}
private mutating func addWrapJobOrMergeOutputs(mergeJob: Job,
debugInfo: DebugInfo,
addJob: (Job) -> Void,
addLinkerInput: (TypedVirtualPath) -> Void)
throws {
guard case .astTypes = debugInfo.level
else { return }
if targetTriple.objectFormat != .macho {
// Module wrapping is required.
let mergeModuleOutputs = mergeJob.outputs.filter { $0.type == .swiftModule }
assert(mergeModuleOutputs.count == 1,
"Merge module job should only have one swiftmodule output")
let wrapJob = try moduleWrapJob(moduleInput: mergeModuleOutputs[0])
addJob(wrapJob)
wrapJob.outputs.forEach(addLinkerInput)
} else {
let mergeModuleOutputs = mergeJob.outputs.filter { $0.type == .swiftModule }
assert(mergeModuleOutputs.count == 1,
"Merge module job should only have one swiftmodule output")
addLinkerInput(mergeModuleOutputs[0])
}
}
private mutating func addAPIDigesterJobs(addJob: (Job) -> Void) throws {
guard let moduleOutputPath = moduleOutputInfo.output?.outputPath else { return }
if let apiBaselinePath = self.digesterBaselinePath {
try addJob(digesterBaselineGenerationJob(modulePath: moduleOutputPath, outputPath: apiBaselinePath, mode: digesterMode))
}
if let baselineArg = parsedOptions.getLastArgument(.compareToBaselinePath)?.asSingle,
let baselinePath = try? VirtualPath.intern(path: baselineArg) {
addJob(try digesterDiagnosticsJob(modulePath: moduleOutputPath, baselinePath: baselinePath, mode: digesterMode))
}
}
private mutating func addLinkAndPostLinkJobs(
linkerInputs: [TypedVirtualPath],
debugInfo: DebugInfo,
addJob: (Job) -> Void
) throws {
guard linkerOutputType != nil && !linkerInputs.isEmpty
else { return }
let linkJ = try linkJob(inputs: linkerInputs)
addJob(linkJ)
guard targetTriple.isDarwin
else { return }
switch linkerOutputType {
case .none, .some(.staticLibrary):
// Cannot generate a dSYM bundle for a non-image target.
return
case .some(.dynamicLibrary), .some(.executable):
guard debugInfo.level != nil
else { return }
}
let dsymJob = try generateDSYMJob(inputs: linkJ.outputs)
addJob(dsymJob)
if debugInfo.shouldVerify {
addJob(try verifyDebugInfoJob(inputs: dsymJob.outputs))
}
}
/// Prescan the source files to produce a module dependency graph and turn it into a set
/// of jobs required to build all dependencies.
/// Preprocess the graph by resolving placeholder dependencies, if any are present and
/// by re-scanning all Clang modules against all possible targets they will be built against.
public mutating func generateExplicitModuleDependenciesJobs() throws -> [Job] {
// Run the dependency scanner and update the dependency oracle with the results
let dependencyGraph = try gatherModuleDependencies()
// Plan build jobs for all direct and transitive module dependencies of the current target
explicitDependencyBuildPlanner =
try ExplicitDependencyBuildPlanner(dependencyGraph: dependencyGraph,
toolchain: toolchain,
integratedDriver: integratedDriver,
supportsExplicitInterfaceBuild:
isFrontendArgSupported(.explicitInterfaceModuleBuild))
return try explicitDependencyBuildPlanner!.generateExplicitModuleDependenciesBuildJobs()
}
@_spi(Testing) public mutating func gatherModuleDependencies()
throws -> InterModuleDependencyGraph {
var dependencyGraph = try performDependencyScan()
if parsedOptions.hasArgument(.printPreprocessedExplicitDependencyGraph) {
try stdoutStream <<< dependencyGraph.toJSONString()
stdoutStream.flush()
}
if let externalTargetDetails = externalTargetModuleDetailsMap {
// Resolve external dependencies in the dependency graph, if any.
try dependencyGraph.resolveExternalDependencies(for: externalTargetDetails)
}
// Re-scan Clang modules at all the targets they will be built against.
// This is currently disabled because we are investigating it being unnecessary
// try resolveVersionedClangDependencies(dependencyGraph: &dependencyGraph)
// Set dependency modules' paths to be saved in the module cache.
try resolveDependencyModulePaths(dependencyGraph: &dependencyGraph)
if parsedOptions.hasArgument(.printExplicitDependencyGraph) {
let outputFormat = parsedOptions.getLastArgument(.explicitDependencyGraphFormat)?.asSingle
if outputFormat == nil || outputFormat == "json" {
try stdoutStream <<< dependencyGraph.toJSONString()
} else if outputFormat == "dot" {
DOTModuleDependencyGraphSerializer(dependencyGraph).writeDOT(to: &stdoutStream)
}
stdoutStream.flush()
}
return dependencyGraph
}
/// Update the given inter-module dependency graph to set module paths to be within the module cache,
/// if one is present, and for Swift modules to use the context hash in the file name.
private mutating func resolveDependencyModulePaths(dependencyGraph: inout InterModuleDependencyGraph)
throws {
// If a module cache path is specified, update all module dependencies
// to be output into it.
if let moduleCachePath = parsedOptions.getLastArgument(.moduleCachePath)?.asSingle {
try resolveDependencyModulePathsRelativeToModuleCache(dependencyGraph: &dependencyGraph,
moduleCachePath: moduleCachePath)
}
// Set the output path to include the module's context hash
try resolveDependencyModuleFileNamesWithContextHash(dependencyGraph: &dependencyGraph)
}
/// For Swift module dependencies, set the output path to include the module's context hash
private mutating func resolveDependencyModuleFileNamesWithContextHash(dependencyGraph: inout InterModuleDependencyGraph)
throws {
for (moduleId, moduleInfo) in dependencyGraph.modules {
// Output path on the main module is determined by the invocation arguments.
guard moduleId.moduleName != dependencyGraph.mainModuleName else {
continue
}
let plainPath = VirtualPath.lookup(dependencyGraph.modules[moduleId]!.modulePath.path)
if case .swift(let swiftDetails) = moduleInfo.details {
guard let contextHash = swiftDetails.contextHash else {
throw Driver.Error.missingContextHashOnSwiftDependency(moduleId.moduleName)
}
let updatedPath = plainPath.parentDirectory.appending(component: "\(plainPath.basenameWithoutExt)-\(contextHash).\(plainPath.extension!)")
dependencyGraph.modules[moduleId]!.modulePath = TextualVirtualPath(path: updatedPath.intern())
}
// TODO: Remove this once toolchain is updated
else if case .clang(let clangDetails) = moduleInfo.details {
if !moduleInfo.modulePath.path.description.contains(clangDetails.contextHash) {
let contextHash = clangDetails.contextHash
let updatedPath = plainPath.parentDirectory.appending(component: "\(plainPath.basenameWithoutExt)-\(contextHash).\(plainPath.extension!)")
dependencyGraph.modules[moduleId]!.modulePath = TextualVirtualPath(path: updatedPath.intern())
}
}
}
}
/// Resolve all paths to dependency binary module files to be relative to the module cache path.
private mutating func resolveDependencyModulePathsRelativeToModuleCache(dependencyGraph: inout InterModuleDependencyGraph,
moduleCachePath: String)
throws {
for (moduleId, moduleInfo) in dependencyGraph.modules {
// Output path on the main module is determined by the invocation arguments.
if case .swift(let name) = moduleId {
if name == dependencyGraph.mainModuleName {
continue
}
let modulePath = VirtualPath.lookup(moduleInfo.modulePath.path)
// Use VirtualPath to get the OS-specific path separators right.
let modulePathInCache =
try VirtualPath(path: moduleCachePath)
.appending(component: modulePath.basename)
dependencyGraph.modules[moduleId]!.modulePath =
TextualVirtualPath(path: modulePathInCache.intern())
}
// TODO: Remove this once toolchain is updated
else if case .clang(_) = moduleId {
let modulePath = VirtualPath.lookup(moduleInfo.modulePath.path)
// Use VirtualPath to get the OS-specific path separators right.
let modulePathInCache =
try VirtualPath(path: moduleCachePath)
.appending(component: modulePath.basename)
dependencyGraph.modules[moduleId]!.modulePath =
TextualVirtualPath(path: modulePathInCache.intern())
}
}
}
}
/// MARK: Planning
extension Driver {
/// Create a job if needed for simple requests that can be immediately
/// forwarded to the frontend.
public mutating func immediateForwardingJob() throws -> Job? {
if parsedOptions.hasArgument(.printTargetInfo) {
let sdkPath = try parsedOptions.getLastArgument(.sdk).map { try VirtualPath(path: $0.asSingle) }
let resourceDirPath = try parsedOptions.getLastArgument(.resourceDir).map { try VirtualPath(path: $0.asSingle) }
return try toolchain.printTargetInfoJob(target: targetTriple,
targetVariant: targetVariantTriple,
sdkPath: sdkPath,
resourceDirPath: resourceDirPath,
requiresInPlaceExecution: true,
useStaticResourceDir: useStaticResourceDir,
swiftCompilerPrefixArgs: swiftCompilerPrefixArgs)
}
if parsedOptions.hasArgument(.version) || parsedOptions.hasArgument(.version_) {
return Job(
moduleName: moduleOutputInfo.name,
kind: .versionRequest,
tool: try toolchain.resolvedTool(.swiftCompiler),
commandLine: [.flag("--version")],
inputs: [],
primaryInputs: [],
outputs: [],
requiresInPlaceExecution: true)
}
if parsedOptions.contains(.help) || parsedOptions.contains(.helpHidden) {
var commandLine: [Job.ArgTemplate] = [.flag(driverKind.rawValue)]
if parsedOptions.contains(.helpHidden) {
commandLine.append(.flag("-show-hidden"))
}
return Job(
moduleName: moduleOutputInfo.name,
kind: .help,
tool: try toolchain.resolvedTool(.swiftHelp),
commandLine: commandLine,
inputs: [],
primaryInputs: [],
outputs: [],
requiresInPlaceExecution: true)
}
return nil
}
/// Plan a build by producing a set of jobs to complete the build.
/// Should be private, but compiler bug
/*private*/ mutating func planPossiblyIncrementalBuild() throws
-> ([Job], IncrementalCompilationState?) {
if let job = try immediateForwardingJob() {
return ([job], nil)
}
// The REPL doesn't require input files, but all other modes do.
guard !inputFiles.isEmpty || compilerMode == .repl || compilerMode == .intro else {
if parsedOptions.hasArgument(.v) {
// `swiftc -v` is allowed and prints version information.
return ([], nil)
}
throw Error.noInputFiles
}
// Plan the build.
switch compilerMode {
case .repl:
if !inputFiles.isEmpty {
throw PlanningError.replReceivedInput
}
return ([try replJob()], nil)
case .immediate:
var jobs: [Job] = []
try addPrecompileModuleDependenciesJobs(addJob: { jobs.append($0) })
jobs.append(try interpretJob(inputs: inputFiles))
return (jobs, nil)
case .standardCompile, .batchCompile, .singleCompile:
return try planStandardCompile()
case .compilePCM:
if inputFiles.count != 1 {
throw PlanningError.emitPCMWrongInputFiles
}
return ([try generateEmitPCMJob(input: inputFiles.first!)], nil)
case .dumpPCM:
if inputFiles.count != 1 {
throw PlanningError.dumpPCMWrongInputFiles
}
return ([try generateDumpPCMJob(input: inputFiles.first!)], nil)
case .intro:
return (try helpIntroJobs(), nil)
}
}
}
extension Diagnostic.Message {
static func error_unexpected_input_file(_ file: VirtualPath) -> Diagnostic.Message {
.error("unexpected input file: \(file.name)")
}
}
// MARK: Batch mode
extension Driver {
/// Given some jobs, merge the compile jobs into batched jobs, as appropriate
/// While it may seem odd to create unbatched jobs, then later dissect and rebatch them,
/// there are reasons for doing it this way:
/// 1. For incremental builds, the inputs compiled in the 2nd wave cannot be known in advance, and
/// 2. The code that creates a compile job intermixes command line formation, output gathering, etc.
/// It does this for good reason: these things are connected by consistency requirements, and
/// 3. The outputs of all compilations are needed, not just 1st wave ones, to feed as inputs to the link job.
///
/// So, in order to avoid making jobs and rebatching, the code would have to just get outputs for each
/// compilation. But `compileJob` intermixes the output computation with other stuff.
mutating func formBatchedJobs(_ jobs: [Job], showJobLifecycle: Bool) throws -> [Job] {
guard compilerMode.isBatchCompile else {
// Don't even go through the logic so as to not print out confusing
// "batched foobar" messages.
return jobs
}
let noncompileJobs = jobs.filter {$0.kind != .compile}
let compileJobs = jobs.filter {$0.kind == .compile}
let inputsAndJobs = compileJobs.flatMap { job in
job.primaryInputs.map {($0, job)}
}
let jobsByInput = Dictionary(uniqueKeysWithValues: inputsAndJobs)
// Try to preserve input order for easier testing
let inputsInOrder = inputFiles.filter {jobsByInput[$0] != nil}
let partitions = batchPartitions(
inputs: inputsInOrder,
showJobLifecycle: showJobLifecycle)
let outputType = parsedOptions.hasArgument(.embedBitcode)
? .llvmBitcode
: compilerOutputType
let inputsRequiringModuleTrace = Set(
compileJobs.filter { $0.outputs.contains {$0.type == .moduleTrace} }
.flatMap {$0.primaryInputs}
)
let batchedCompileJobs = try inputsInOrder.compactMap { anInput -> Job? in
let idx = partitions.assignment[anInput]!
let primaryInputs = partitions.partitions[idx]
guard primaryInputs[0] == anInput
else {
// This input file isn't the first
// file in the partition, skip it: it's been accounted for already.
return nil
}
if showJobLifecycle {
// Log life cycle for added batch job
primaryInputs.forEach {
diagnosticEngine
.emit(
.remark(
"Adding {compile: \($0.file.basename)} to batch \(idx)"))
}
let constituents = primaryInputs.map {$0.file.basename}.joined(separator: ", ")
diagnosticEngine
.emit(
.remark(
"Forming batch job from \(primaryInputs.count) constituents: \(constituents)"))
}
let constituentsEmittedModuleTrace = !inputsRequiringModuleTrace.intersection(primaryInputs).isEmpty
// no need to add job outputs again
return try compileJob(primaryInputs: primaryInputs,
outputType: outputType,
addJobOutputs: {_ in },
emitModuleTrace: constituentsEmittedModuleTrace)
}
return batchedCompileJobs + noncompileJobs
}
/// Determine the number of partitions we'll use for batch mode.
private func numberOfBatchPartitions(
_ info: BatchModeInfo?,
numInputFiles: Int
) -> Int {
guard numInputFiles > 0 else {
return 0
}
guard let info = info else {
return 1 // not batch mode
}
// If the number of partitions was specified by the user, use it
if let fixedCount = info.count {
return fixedCount
}
// This is a long comment to justify a simple calculation.
//
// Because there is a secondary "outer" build system potentially also
// scheduling multiple drivers in parallel on separate build targets
// -- while we, the driver, schedule our own subprocesses -- we might
// be creating up to $NCPU^2 worth of _memory pressure_.
//
// Oversubscribing CPU is typically no problem these days, but
// oversubscribing memory can lead to paging, which on modern systems
// is quite bad.
//
// In practice, $NCPU^2 processes doesn't _quite_ happen: as core
// count rises, it usually exceeds the number of large targets
// without any dependencies between them (which are the only thing we
// have to worry about): you might have (say) 2 large independent
// modules * 2 architectures, but that's only an $NTARGET value of 4,
// which is much less than $NCPU if you're on a 24 or 36-way machine.
//
// So the actual number of concurrent processes is:
//
// NCONCUR := $NCPU * min($NCPU, $NTARGET)
//
// Empirically, a frontend uses about 512kb RAM per non-primary file
// and about 10mb per primary. The number of non-primaries per
// process is a constant in a given module, but the number of
// primaries -- the "batch size" -- is inversely proportional to the
// batch count (default: $NCPU). As a result, the memory pressure
// we can expect is:
//
// $NCONCUR * (($NONPRIMARYMEM * $NFILE) +
// ($PRIMARYMEM * ($NFILE/$NCPU)))
//
// If we tabulate this across some plausible values, we see
// unfortunate memory-pressure results:
//
// $NFILE
// +---------------------
// $NTARGET $NCPU | 100 500 1000
// ----------------+---------------------
// 2 2 | 2gb 11gb 22gb
// 4 4 | 4gb 24gb 48gb
// 4 8 | 5gb 28gb 56gb
// 4 16 | 7gb 36gb 72gb
// 4 36 | 11gb 56gb 112gb
//
// As it happens, the lower parts of the table are dominated by
// number of processes rather than the files-per-batch (the batches
// are already quite small due to the high core count) and the left
// side of the table is dealing with modules too small to worry
// about. But the middle and upper-right quadrant is problematic: 4
// and 8 core machines do not typically have 24-48gb of RAM, it'd be
// nice not to page on them when building a 4-target project with
// 500-file modules.
//
// Turns we can do that if we just cap the batch size statically at,
// say, 25 files per batch, we get a better formula:
//
// $NCONCUR * (($NONPRIMARYMEM * $NFILE) +
// ($PRIMARYMEM * min(25, ($NFILE/$NCPU))))
//
// $NFILE
// +---------------------
// $NTARGET $NCPU | 100 500 1000
// ----------------+---------------------
// 2 2 | 1gb 2gb 3gb
// 4 4 | 4gb 8gb 12gb
// 4 8 | 5gb 16gb 24gb
// 4 16 | 7gb 32gb 48gb
// 4 36 | 11gb 56gb 108gb
//
// This means that the "performance win" of batch mode diminishes
// slightly: the batching factor in the equation drops from
// ($NFILE/$NCPU) to min(25, $NFILE/$NCPU). In practice this seems to
// not cost too much: the additional factor in number of subprocesses
// run is the following:
//
// $NFILE
// +---------------------
// $NTARGET $NCPU | 100 500 1000
// ----------------+---------------------
// 2 2 | 2x 10x 20x
// 4 4 | - 5x 10x
// 4 8 | - 2.5x 5x
// 4 16 | - 1.25x 2.5x
// 4 36 | - - 1.1x
//
// Where - means "no difference" because the batches were already
// smaller than 25.
//
// Even in the worst case here, the 1000-file module on 2-core
// machine is being built with only 40 subprocesses, rather than the
// pre-batch-mode 1000. I.e. it's still running 96% fewer
// subprocesses than before. And significantly: it's doing so while
// not exceeding the RAM of a typical 2-core laptop.
// An explanation of why the partition calculation isn't integer
// division. Using an example, a module of 26 files exceeds the
// limit of 25 and must be compiled in 2 batches. Integer division
// yields 26/25 = 1 batch, but a single batch of 26 exceeds the
// limit. The calculation must round up, which can be calculated
// using: `(x + y - 1) / y`
let divideRoundingUp = { num, div in
return (num + div - 1) / div
}
let defaultSizeLimit = 25
let sizeLimit = info.sizeLimit ?? defaultSizeLimit
let numTasks = numParallelJobs ?? 1
return max(numTasks, divideRoundingUp(numInputFiles, sizeLimit))
}
/// Describes the partitions used when batching.
private struct BatchPartitions {
/// Assignment of each Swift input file to a particular partition.
/// The values are indices into `partitions`.
let assignment: [TypedVirtualPath : Int]
/// The contents of each partition.
let partitions: [[TypedVirtualPath]]
}
private func batchPartitions(
inputs: [TypedVirtualPath],
showJobLifecycle: Bool
) -> BatchPartitions {
let numScheduledPartitions = numberOfBatchPartitions(
compilerMode.batchModeInfo,
numInputFiles: inputs.count)
if showJobLifecycle && inputs.count > 0 {
diagnosticEngine
.emit(
.remark(
"Found \(inputs.count) batchable job\(inputs.count != 1 ? "s" : "")"
))
diagnosticEngine
.emit(
.remark(
"Forming into \(numScheduledPartitions) batch\(numScheduledPartitions != 1 ? "es" : "")"
))
}
// If there is at most one partition, fast path.
if numScheduledPartitions <= 1 {
var assignment = [TypedVirtualPath: Int]()
for input in inputs {
assignment[input] = 0
}
let partitions = inputs.isEmpty ? [] : [inputs]
return BatchPartitions(assignment: assignment,
partitions: partitions)
}
// Map each input file to a partition index. Ensure that we evenly
// distribute the remainder.
let numScheduledInputFiles = inputs.count
let remainder = numScheduledInputFiles % numScheduledPartitions
let targetSize = numScheduledInputFiles / numScheduledPartitions
var partitionIndices: [Int] = []
for partitionIdx in 0..<numScheduledPartitions {
let fillCount = targetSize + (partitionIdx < remainder ? 1 : 0)
partitionIndices.append(contentsOf: Array(repeating: partitionIdx, count: fillCount))
}
assert(partitionIndices.count == numScheduledInputFiles)
guard let info = compilerMode.batchModeInfo else {
fatalError("should be at most 1 partition if not in batch mode")
}
if let seed = info.seed {
var generator = PredictableRandomNumberGenerator(seed: UInt64(seed))
partitionIndices.shuffle(using: &generator)
}
// Form the actual partitions.
var assignment: [TypedVirtualPath : Int] = [:]
var partitions = Array<[TypedVirtualPath]>(repeating: [], count: numScheduledPartitions)
for (fileIndex, file) in inputs.enumerated() {
let partitionIdx = partitionIndices[fileIndex]
assignment[file] = partitionIdx
partitions[partitionIdx].append(file)
}
return BatchPartitions(assignment: assignment,
partitions: partitions)
}
}
| apache-2.0 | 893289b46d7c11e180ed777415a944ed | 39.229001 | 148 | 0.657795 | 5.010903 | false | false | false | false |
gxf2015/DYZB | DYZB/DYZB/Classes/Tools/Extension/UIBarButtonItem-Extension.swift | 1 | 741 | //
// UIBarButtonItem-Extension.swift
// DYZB
//
// Created by guo xiaofei on 2017/8/10.
// Copyright © 2017年 guo xiaofei. All rights reserved.
//
import UIKit
extension UIBarButtonItem{
convenience init(imageName : String, highImageName : String = "", size : CGSize = CGSize.zero) {
let btn = UIButton()
btn.setImage(UIImage(named : imageName), for: .normal)
if highImageName != ""{
btn.setImage(UIImage(named : highImageName), for: .highlighted)
}
if size == CGSize.zero{
btn.sizeToFit()
}else{
btn.frame = CGRect(origin: CGPoint.zero, size: size)
}
self.init(customView : btn)
}
}
| mit | a25955ecd74a6b0fc8e47b15b5e20b9e | 22.0625 | 101 | 0.566396 | 4.265896 | false | false | false | false |
phillippbertram/JsonDiffPatchSwift | Sources/JsonDiffPatch.swift | 1 | 2454 | //
// Created by Phillipp Bertram on 2/6/17.
// Copyright (c) 2017 Phillipp Bertram. All rights reserved.
//
import Foundation
import JavaScriptCore
public final class JsonDiffPatch {
/// JsonDiffPatchError
///
/// - CouldNotCreateJSContext: Thrown, if JSConext() could not created
/// - FailedLoadingJavaScript: Thrown, if the javascrip file coul not be loaded
public enum JsonDiffPatchError: Error {
case CouldNotCreateJSContext
case FailedLoadingJavaScript
}
/// Creates a delta dependent on given json parameters
///
/// - Parameters:
/// - source: source JSON
/// - target: target JSON
/// - Returns: json diff as dictionary
public static func deltaOrFail(source: String, target: String) throws -> [String: Any] {
guard let context = JSContext() else {
throw JsonDiffPatchError.CouldNotCreateJSContext
}
guard let path = Bundle(for: JsonDiffPatch.self).path(forResource: "jsondiff", ofType: "js") else {
throw JsonDiffPatchError.FailedLoadingJavaScript
}
var output: [String: Any] = [:]
do {
// load jsondiff.js
var jsSource: String = try String(contentsOfFile: path)
jsSource = "var window = this; \(jsSource)"
context.evaluateScript(jsSource)
let diff = context.objectForKeyedSubscript("diff")!
if let result = diff.call(withArguments: [source, target]).toDictionary() as? [String: Any] {
output = result
}
} catch {
throw JsonDiffPatchError.FailedLoadingJavaScript
}
return output
}
/// Creates delta for given json string.
///
/// - Parameters:
/// - source: source json
/// - target: target json
/// - Returns: json dictionary
public static func delta(source: String, target: String) -> [String: Any] {
do {
return try JsonDiffPatch.deltaOrFail(source: source, target: target)
} catch {
return [:]
}
}
}
public extension Sequence where Iterator.Element == (key: String, value: Any) {
var jsonString: String {
do {
let data = try JSONSerialization.data(withJSONObject: self, options: .prettyPrinted)
return String(data: data, encoding: .utf8) ?? ""
} catch {
return ""
}
}
}
| mit | 77178a3ceb04a4a367640101fe8bef64 | 27.870588 | 107 | 0.595762 | 4.674286 | false | false | false | false |
mrArkwright/MyLittleEngine | My Little Engine Demo/AppDelegate.swift | 1 | 1397 | //
// AppDelegate.swift
// My Little Engine
//
// Created by Jannik Theiß on 25.12.16.
//
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var openGLView: ExampleSceneView!
func applicationDidFinishLaunching(_ aNotification: Notification) {
window.backgroundColor = NSColor.clear
}
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
return true
}
@IBAction func toggleShowDebug(_ sender: NSMenuItem) {
sender.state = 1 - sender.state
let showDebug = sender.state == 0 ? false : true
openGLView.showDebug = showDebug
}
@IBAction func toggleBackgroundTransparency(_ sender: NSMenuItem) {
sender.state = 1 - sender.state
let isTransparent = sender.state == 0 ? false : true
window.isOpaque = !isTransparent
window.hasShadow = !isTransparent
openGLView.setBackgroundTransparency(isTransparent)
}
@IBAction func screenshot(_ sender: NSMenuItem) {
let image = openGLView.screenshot()
let imageTiff = image.tiffRepresentation!
let savePanel = NSSavePanel()
savePanel.nameFieldStringValue = "screenshot.tiff"
savePanel.beginSheetModal(for: window) { result in
if (result == NSFileHandlingPanelOKButton) {
if let url = savePanel.url {
try! imageTiff.write(to: url)
}
}
}
}
}
| mit | 16b3ee95184e0326419bb56bd59b2457 | 21.885246 | 88 | 0.721347 | 4.046377 | false | false | false | false |
coach-plus/ios | CoachPlus/models/ParticipationItem.swift | 1 | 1142 | //
// ParticipationItem.swift
// CoachPlus
//
// Created by Maurice Breit on 04.08.17.
// Copyright © 2017 Mathandoro GbR. All rights reserved.
//
import Foundation
import SwiftyJSON
class ParticipationItem: JSONable, BackJSONable {
enum Fields:String {
case user = "user"
case participation = "participation"
}
var user: User?
var participation: Participation?
init(user:User, participation:Participation) {
self.user = user
self.participation = participation
}
required init(json:JSON) {
let user = json[Fields.user.rawValue]
if (user.type != .string) {
self.user = User(json: user)
}
let participation = json[Fields.participation.rawValue]
if (participation.type != .string) {
self.participation = Participation(json: participation)
}
}
func toJson() -> JSON {
let json: JSON = [
Fields.user.rawValue: self.user?.toJson(),
Fields.participation.rawValue: self.participation?.toJson()]
return json
}
}
| mit | bef41f047f5be99ec86cd74167e328a9 | 23.276596 | 72 | 0.592463 | 4.422481 | false | false | false | false |
coach-plus/ios | Pods/RxSwift/RxSwift/Observables/Materialize.swift | 6 | 1569 | //
// Materialize.swift
// RxSwift
//
// Created by sergdort on 08/03/2017.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Convert any Observable into an Observable of its events.
- seealso: [materialize operator on reactivex.io](http://reactivex.io/documentation/operators/materialize-dematerialize.html)
- returns: An observable sequence that wraps events in an Event<E>. The returned Observable never errors, but it does complete after observing all of the events of the underlying Observable.
*/
public func materialize() -> Observable<Event<Element>> {
return Materialize(source: self.asObservable())
}
}
private final class MaterializeSink<Element, Observer: ObserverType>: Sink<Observer>, ObserverType where Observer.Element == Event<Element> {
func on(_ event: Event<Element>) {
self.forwardOn(.next(event))
if event.isStopEvent {
self.forwardOn(.completed)
self.dispose()
}
}
}
final private class Materialize<T>: Producer<Event<T>> {
private let _source: Observable<T>
init(source: Observable<T>) {
self._source = source
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element {
let sink = MaterializeSink(observer: observer, cancel: cancel)
let subscription = self._source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
| mit | 7d77633f94b25b9b5788fef0cb8b3295 | 34.636364 | 195 | 0.6875 | 4.518732 | false | false | false | false |
akirark/MTCCore | MTCCore/MarkupTag.swift | 1 | 1372 | //
// MarkupTag.swift
//
// Created by Akira Hayashi on 2016/12/30.
//
// -----------------------------------------------------------------
//
// Copyright (c) 2016 Akira Hayashi
// This software is released under the Apache 2.0 License,
// see LICENSE.txt for license information
//
// -----------------------------------------------------------------
//
import Foundation
public class MarkupTag {
public var name = String()
public var attributes = [String: String]()
public var attributesOrder = [String]()
public var isCloseFormat = false
public var suffix: String = String()
public var tagString: String {
if name.isEmpty {
return ""
}
var tagString = String()
tagString.append("<")
tagString.append(self.name)
if self.attributes.count > 0 && self.attributes.count == self.attributesOrder.count {
// Append attributes
for attr in self.attributesOrder {
if let attrValue = self.attributes[attr] {
tagString.append(" \(attr)=\"\(attrValue)\"")
}
}
}
if self.isCloseFormat {
tagString.append(" /")
}
if !self.suffix.isEmpty {
tagString.append(self.suffix)
}
tagString.append(">")
return tagString
}
}
| apache-2.0 | 51bda3bfac8f0903cefeec6e1a06a897 | 24.407407 | 93 | 0.507289 | 4.865248 | false | false | false | false |
GraphKit/MaterialKit | Sources/iOS/TableViewCell.swift | 1 | 6413 | /*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
open class TableViewCell: UITableViewCell, Pulseable {
/**
A CAShapeLayer used to manage elements that would be affected by
the clipToBounds property of the backing layer. For example, this
allows the dropshadow effect on the backing layer, while clipping
the image to a desired shape within the visualLayer.
*/
open let visualLayer = CAShapeLayer()
/// A Pulse reference.
fileprivate var pulse: Pulse!
/// PulseAnimation value.
open var pulseAnimation: PulseAnimation {
get {
return pulse.animation
}
set(value) {
pulse.animation = value
}
}
/// PulseAnimation color.
@IBInspectable
open var pulseColor: UIColor {
get {
return pulse.color
}
set(value) {
pulse.color = value
}
}
/// Pulse opacity.
@IBInspectable
open var pulseOpacity: CGFloat {
get {
return pulse.opacity
}
set(value) {
pulse.opacity = value
}
}
/// A property that accesses the backing layer's background
@IBInspectable
open override var backgroundColor: UIColor? {
didSet {
layer.backgroundColor = backgroundColor?.cgColor
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
prepare()
}
/**
An initializer that initializes the object.
- Parameter style: A UITableViewCellStyle enum.
- Parameter reuseIdentifier: A String identifier.
*/
public override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
prepare()
}
open override func layoutSubviews() {
super.layoutSubviews()
layoutShape()
layoutVisualLayer()
layoutShadowPath()
}
/**
Triggers the pulse animation.
- Parameter point: A Optional point to pulse from, otherwise pulses
from the center.
*/
open func pulse(point: CGPoint? = nil) {
let p = point ?? center
pulse.expandAnimation(point: p)
Animation.delay(time: 0.35) { [weak self] in
self?.pulse.contractAnimation()
}
}
/**
A delegation method that is executed when the view has began a
touch event.
- Parameter touches: A set of UITouch objects.
- Parameter event: A UIEvent object.
*/
open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
pulse.expandAnimation(point: layer.convert(touches.first!.location(in: self), from: layer))
}
/**
A delegation method that is executed when the view touch event has
ended.
- Parameter touches: A set of UITouch objects.
- Parameter event: A UIEvent object.
*/
open override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
pulse.contractAnimation()
}
/**
A delegation method that is executed when the view touch event has
been cancelled.
- Parameter touches: A set of UITouch objects.
- Parameter event: A UIEvent object.
*/
open override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
pulse.contractAnimation()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open func prepare() {
selectionStyle = .none
separatorInset = .zero
contentScaleFactor = Screen.scale
imageView?.isUserInteractionEnabled = false
textLabel?.isUserInteractionEnabled = false
detailTextLabel?.isUserInteractionEnabled = false
prepareVisualLayer()
preparePulse()
}
}
extension TableViewCell {
/// Prepares the pulse motion.
fileprivate func preparePulse() {
pulse = Pulse(pulseView: self, pulseLayer: visualLayer)
}
/// Prepares the visualLayer property.
fileprivate func prepareVisualLayer() {
visualLayer.zPosition = 0
visualLayer.masksToBounds = true
contentView.layer.addSublayer(visualLayer)
}
}
extension TableViewCell {
/// Manages the layout for the visualLayer property.
fileprivate func layoutVisualLayer() {
visualLayer.frame = bounds
visualLayer.cornerRadius = cornerRadius
}
}
| agpl-3.0 | 4f6f53c6333d2be1a4d2906c896ceea6 | 31.553299 | 99 | 0.679869 | 4.921719 | false | false | false | false |
mleiv/MEGameTracker | MEGameTrackerTests/CoreData/BaseDataImportTest.swift | 1 | 5665 | //
// BaseDataImportTest.swift
// MEGameTracker
//
// Created by Emily Ivie on 2/17/17.
// Copyright © 2017 Emily Ivie. All rights reserved.
//
import XCTest
import Nuke
@testable import MEGameTracker
final class BaseDataImportTest: MEGameTrackerTests {
struct TestImport: CoreDataMigrationType {
func run() {}
}
let isRun = true // this takes a long time, only run it when you want to
override func setUp() {
super.setUp()
initializeSandboxedStore()
}
override func tearDown() {
super.tearDown()
}
/// Verify that all json import files are valid
func testValidJson() {
let files = BaseDataImport().progressFilesEvents + BaseDataImport().progressFilesOther
for row in files {
var didParse = false
let filename = row.filename
// print("\(filename)") // uncomment to debug
do {
if let file = Bundle.main.path(forResource: filename, ofType: "json") {
let data = try Data(contentsOf: URL(fileURLWithPath: file))
_ = try JSONSerialization.jsonObject(with: data, options: [])
_ = TestImport().importData(data, with: nil)
// print("\(ids)") // uncomment to debug
didParse = true
}
} catch {
print("Failed to parse file \(filename): \(error)")
}
XCTAssert(didParse, "Failed to parse file \(filename)")
}
}
func testOneImport() {
let filename = "DataDecisions_2"
do {
if let file = Bundle.main.path(forResource: filename, ofType: "json") {
let data = try Data(contentsOf: URL(fileURLWithPath: file))
let ids = TestImport().importData(data, with: nil)
// print id in Codable init to find failure row
print(ids)
}
} catch {
// failure
print("Failed to load file \(filename)")
}
}
/// Clock the full import.
func testBaseDataImportPerformance() {
guard isRun else { return }
let start = Date()
BaseDataImport().run()
let time = Int(Date().timeIntervalSince(start))
print("Performance: testBaseDataImportTime ran in \(time) seconds")
XCTAssert(time < 300) // my ancient computer is slow
let decisionsCount = DataDecision.getCount()
XCTAssert(decisionsCount > 100)
let eventsCount = DataEvent.getCount()
XCTAssert(eventsCount > 150)
let itemsCount = DataItem.getCount()
XCTAssert(itemsCount > 1100)
let mapsCount = DataMap.getCount()
XCTAssert(mapsCount > 1500)
let missionsCount = DataMission.getCount()
XCTAssert(missionsCount > 1500)
let personsCount = DataPerson.getCount()
XCTAssert(personsCount > 290)
}
// /// Clock the full import.
// func testBaseDataImportPerformance() {
// guard isRun else { return }
// measureMetrics([XCTPerformanceMetric_WallClockTime], automaticallyStartMeasuring: false) {
// let manager = self.getSandboxedManager()
// self.startMeasuring()
// BaseDataImport(manager: manager).run()
// self.stopMeasuring()
//// let mapsCount = DataMap.getCount(with: manager)
//// XCTAssert(mapsCount > 1500, "Failed to import all maps")
// }
// }
// The downsides of manually editing JSON files instead of maintaining a relational database
func testConversationIdsUnique() {
let files = BaseDataImport().progressFilesOther
var convoIds: [String: Bool] = [:]
var noFailuresFound = true
for row in files where row.type == .mission {
let filename = row.filename
if let file = Bundle.main.path(forResource: filename, ofType: "json"),
let data = try? Data(contentsOf: URL(fileURLWithPath: file)),
let extractedData = try? JSONSerialization.jsonObject(with: data, options: []),
let missions = (extractedData as? [String: Any])?["missions"] as? [[String: Any]] {
for mission in missions {
if let conversations = mission["conversationRewards"] as? [[String: Any]] {
for conversation in conversations {
for id in recursedConversationIds(conversation) {
if (convoIds[id] == true) {
print("Duplicate conversation id: \(id)")
noFailuresFound = false
} else {
convoIds[id] = true
}
}
}
}
}
}
}
XCTAssert(noFailuresFound, "Found duplicate ids")
}
private func recursedConversationIds(_ data: [String: Any]) -> [String] {
var ids: [String] = [];
for (key, value) in data {
if key == "id", let id = value as? String {
ids.append( id)
continue
} else if let subDataList = value as? [[String: Any]] {
for subData in subDataList {
ids.append(contentsOf: recursedConversationIds(subData))
}
} else if let subData = value as? [String: Any] {
ids.append(contentsOf: recursedConversationIds(subData))
}
}
return ids;
}
}
| mit | d62c58686808e61cd96374b086e23862 | 36.76 | 100 | 0.544845 | 5.025732 | false | true | false | false |
tkester/swift-algorithm-club | Monty Hall Problem/MontyHall.playground/Contents.swift | 1 | 1417 | //: Playground - noun: a place where people can play
// last checked with Xcode 9.0b4
#if swift(>=4.0)
print("Hello, Swift 4!")
#endif
import Foundation
func random(_ n: Int) -> Int {
return Int(arc4random_uniform(UInt32(n)))
}
let numberOfDoors = 3
var rounds = 0
var winOriginalChoice = 0
var winChangedMind = 0
func playRound() {
// The door with the prize.
let prizeDoor = random(numberOfDoors)
// The door the player chooses.
let chooseDoor = random(numberOfDoors)
// The door that Monty opens. This must be empty and not the one the player chose.
var openDoor = -1
repeat {
openDoor = random(numberOfDoors)
} while openDoor == prizeDoor || openDoor == chooseDoor
// What happens when the player changes his mind and picks the other door.
var changeMind = -1
repeat {
changeMind = random(numberOfDoors)
} while changeMind == openDoor || changeMind == chooseDoor
// Figure out which choice was the winner.
if chooseDoor == prizeDoor {
winOriginalChoice += 1
}
if changeMind == prizeDoor {
winChangedMind += 1
}
rounds += 1
}
// Run the simulation a large number of times.
for _ in 1...5000 {
playRound()
}
let stubbornPct = Double(winOriginalChoice)/Double(rounds)
let changedMindPct = Double(winChangedMind)/Double(rounds)
print(String(format: "Played %d rounds, stubborn: %g%% vs changed mind: %g%%", rounds, stubbornPct, changedMindPct))
| mit | b34785b12ff233dcbde9b435783f1dc7 | 23.431034 | 116 | 0.697953 | 3.925208 | false | false | false | false |
mikelikespie/swiftled | src/main/swift/Visualizations/VisualizationClient.swift | 1 | 6113 | //
// VisualizationClient.swift
// SwiftledMobile
//
// Created by Michael Lewis on 2/5/16.
// Copyright © 2016 Lolrus Industries. All rights reserved.
//
import Foundation
import OPC
import RxSwift
import Cleanse
import Dispatch
private final class VisualizationClient : Component {
fileprivate typealias Root = VisualizationClient
fileprivate typealias Seed = ClientConnection
let connection: ClientConnection
let gamma: TaggedProvider<Gamma>
let brightness: TaggedProvider<Brightness>
var buffer: [RGBFloat]
init(
connection: ClientConnection,
gamma: TaggedProvider<Gamma>,
brightness: TaggedProvider<Brightness>) {
self.brightness = brightness
self.gamma = gamma
self.connection = connection
self.buffer = [RGBFloat](repeating: RGBFloat(r: 0, g: 0, b: 0), count: connection.count)
}
fileprivate static func configureRoot(binder bind: Cleanse.ReceiptBinder<Root>) -> Cleanse.BindingReceipt<Root> {
return bind.to(factory: Root.init)
}
fileprivate static func configure(binder: Binder<Unscoped>) {
}
func start(_ fps: Double, visualization: BaseVisualization) -> Disposable {
let serialQueue = DispatchQueue(label: "MyQueue", attributes: [], target: nil)
let defaultScheduler = SerialDispatchQueueScheduler(queue: serialQueue, internalSerialQueueName: "MyQueue")
let ticker: Observable<Int> = Observable.interval(1.0 / TimeInterval(fps), scheduler: defaultScheduler)
let compositeDisposable = CompositeDisposable()
let publishSubject = PublishSubject<WriteContext>()
let visualizationDisposable = visualization.bind(publishSubject)
_ = compositeDisposable.insert(visualizationDisposable)
let tickerDisposable = ticker
.map { idx -> (Int, TimeInterval) in
let now = Date.timeIntervalSinceReferenceDate
return (index: idx, now: now)
}
.scan(nil as (startTime: TimeInterval, context: TickContext)?) { startOffsetLastContext, indexNow in
let now = indexNow.1
let start = startOffsetLastContext?.startTime ?? now
let offset = now - start
let delta = offset - (startOffsetLastContext?.context.timeOffset ?? offset)
return (start, TickContext(tickIndex: indexNow.0, timeOffset: offset, timeDelta: delta))
}
.map { startOffsetContext -> TickContext in
return startOffsetContext!.1
}
.subscribe(onNext: { tickContext in
self.buffer.withUnsafeMutableBufferPointer { ptr in
let writeContext = WriteContext(tickContext: tickContext, writeBuffer: ptr)
publishSubject.onNext(writeContext)
}
// Divide the tasks up into 8
let fullBounds = self.buffer.startIndex..<self.buffer.endIndex
let brightness = self.brightness.get()
applyOverRange(fullBounds) { bounds in
for idx in bounds {
let bufferValue = self.buffer[idx]
self.connection[idx] =
(bufferValue * brightness)
// .toLinear()
}
}
_ = self.connection.flush()
})
_ = compositeDisposable.insert(tickerDisposable)
return compositeDisposable
}
}
public struct VisualizationRunner {
private let ledCount: Int
private let visualizationClientFactory: ComponentFactory<VisualizationClient>
private init(
ledCount: TaggedProvider<LedCount>,
visualizationClientFactory: ComponentFactory<VisualizationClient>
) {
self.ledCount = ledCount.get()
self.visualizationClientFactory = visualizationClientFactory
}
public func startVisualization(_ visualization: BaseVisualization, fps: Double) -> Disposable {
let compositeDisposable = CompositeDisposable()
let visualizationClientFactory = self.visualizationClientFactory
let addrInfoDisposable = getaddrinfoSockAddrsAsync("pi0.local", servname: "7890")
.debug()
.flatMap { sa in
return sa.connect().catchError { _ in Observable.empty() }
}
.take(1)
.subscribe(
onNext: { sock in
let connection = ClientConnection(
fd: sock,
ledCount: self.ledCount,
mode: .rgbaRaw
)
let client = visualizationClientFactory.build(connection)
let clientDisposable = client.start(fps, visualization: visualization)
_ = compositeDisposable.insert(clientDisposable)
NSLog("Connected!")
},
onError: { error in
NSLog("failed \(error) \((error as? POSIXErrorCode)?.rawValue ?? -999)")
// page.finishExecution()
},
onCompleted: {
NSLog("completed?")
// page.finishExecution()
}
)
_ = compositeDisposable.insert(addrInfoDisposable)
return compositeDisposable
}
struct Module : Cleanse.Module {
static func configure(binder: Binder<Unscoped>) {
binder.install(dependency: VisualizationClient.self)
binder
.bind()
.to(factory: VisualizationRunner.init)
}
}
}
| mit | 4ce743094a08a19e1839617bb922b7a6 | 34.534884 | 117 | 0.557101 | 5.787879 | false | false | false | false |
jsslai/Action | Carthage/Checkouts/RxSwift/Tests/RxCocoaTests/RxTest+Controls.swift | 1 | 3410 | //
// RxTest+Controls.swift
// Rx
//
// Created by Krunoslav Zaher on 3/12/16.
// Copyright © 2016 Krunoslav Zaher. All rights reserved.
//
import Foundation
import RxCocoa
import RxSwift
import XCTest
extension RxTest {
func ensurePropertyDeallocated<C, T: Equatable>(_ createControl: () -> C, _ initialValue: T, _ propertySelector: (C) -> ControlProperty<T>) where C: NSObject {
let variable = Variable(initialValue)
var completed = false
var deallocated = false
var lastReturnedPropertyValue: T!
autoreleasepool {
var control: C! = createControl()
let property = propertySelector(control)
let disposable = variable.asObservable().bindTo(property)
_ = property.subscribe(onNext: { n in
lastReturnedPropertyValue = n
}, onCompleted: {
completed = true
disposable.dispose()
})
_ = (control as NSObject).rx.deallocated.subscribe(onNext: { _ in
deallocated = true
})
control = nil
}
// this code is here to flush any events that were scheduled to
// run on main loop
DispatchQueue.main.async {
let runLoop = CFRunLoopGetCurrent()
CFRunLoopStop(runLoop)
}
let runLoop = CFRunLoopGetCurrent()
CFRunLoopWakeUp(runLoop)
CFRunLoopRun()
XCTAssertTrue(deallocated)
XCTAssertTrue(completed)
XCTAssertEqual(initialValue, lastReturnedPropertyValue)
}
func ensureEventDeallocated<C, T>(_ createControl: @escaping () -> C, _ eventSelector: (C) -> ControlEvent<T>) where C: NSObject {
return ensureEventDeallocated({ () -> (C, Disposable) in (createControl(), Disposables.create()) }, eventSelector)
}
func ensureEventDeallocated<C, T>(_ createControl: () -> (C, Disposable), _ eventSelector: (C) -> ControlEvent<T>) where C: NSObject {
var completed = false
var deallocated = false
let outerDisposable = SingleAssignmentDisposable()
autoreleasepool {
let (control, disposable) = createControl()
let eventObservable = eventSelector(control)
_ = eventObservable.subscribe(onNext: { n in
}, onCompleted: {
completed = true
})
_ = (control as NSObject).rx.deallocated.subscribe(onNext: { _ in
deallocated = true
})
outerDisposable.setDisposable(disposable)
}
outerDisposable.dispose()
XCTAssertTrue(deallocated)
XCTAssertTrue(completed)
}
func ensureControlObserverHasWeakReference<C, T>( _ createControl: @autoclosure() -> (C), _ observerSelector: (C) -> AnyObserver<T>, _ observableSelector: () -> (Observable<T>)) where C: NSObject {
var deallocated = false
let disposeBag = DisposeBag()
autoreleasepool {
let control = createControl()
let propertyObserver = observerSelector(control)
let observable = observableSelector()
observable.bindTo(propertyObserver).addDisposableTo(disposeBag)
_ = (control as NSObject).rx.deallocated.subscribe(onNext: { _ in
deallocated = true
})
}
XCTAssertTrue(deallocated)
}
}
| mit | 5cdfaee5cba6d946dec9d07243ddc463 | 29.711712 | 201 | 0.600469 | 5.309969 | false | false | false | false |
brentdax/swift | test/Parse/try.swift | 4 | 11546 | // RUN: %target-typecheck-verify-swift
// Intentionally has lower precedence than assignments and ?:
infix operator %%%% : LowPrecedence
precedencegroup LowPrecedence {
associativity: none
lowerThan: AssignmentPrecedence
}
func %%%%<T, U>(x: T, y: U) -> Int { return 0 }
// Intentionally has lower precedence between assignments and ?:
infix operator %%% : MiddlingPrecedence
precedencegroup MiddlingPrecedence {
associativity: none
higherThan: AssignmentPrecedence
lowerThan: TernaryPrecedence
}
func %%%<T, U>(x: T, y: U) -> Int { return 1 }
func foo() throws -> Int { return 0 }
func bar() throws -> Int { return 0 }
var x = try foo() + bar()
x = try foo() + bar()
x += try foo() + bar()
x += try foo() %%%% bar() // expected-error {{'try' following assignment operator does not cover everything to its right}} // expected-error {{call can throw but is not marked with 'try'}} // expected-warning {{result of operator '%%%%' is unused}}
// expected-note@-1 {{did you mean to use 'try'?}} {{21-21=try }}
// expected-note@-2 {{did you mean to handle error as optional value?}} {{21-21=try? }}
// expected-note@-3 {{did you mean to disable error propagation?}} {{21-21=try! }}
x += try foo() %%% bar()
x = foo() + try bar() // expected-error {{'try' cannot appear to the right of a non-assignment operator}} // expected-error {{call can throw but is not marked with 'try'}}
// expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }}
// expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }}
// expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }}
var y = true ? try foo() : try bar() + 0
var z = true ? try foo() : try bar() %%% 0 // expected-error {{'try' following conditional operator does not cover everything to its right}}
var a = try! foo() + bar()
a = try! foo() + bar()
a += try! foo() + bar()
a += try! foo() %%%% bar() // expected-error {{'try!' following assignment operator does not cover everything to its right}} // expected-error {{call can throw but is not marked with 'try'}} // expected-warning {{result of operator '%%%%' is unused}}
// expected-note@-1 {{did you mean to use 'try'?}} {{22-22=try }}
// expected-note@-2 {{did you mean to handle error as optional value?}} {{22-22=try? }}
// expected-note@-3 {{did you mean to disable error propagation?}} {{22-22=try! }}
a += try! foo() %%% bar()
a = foo() + try! bar() // expected-error {{'try!' cannot appear to the right of a non-assignment operator}} // expected-error {{call can throw but is not marked with 'try'}}
// expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }}
// expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }}
// expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }}
var b = true ? try! foo() : try! bar() + 0
var c = true ? try! foo() : try! bar() %%% 0 // expected-error {{'try!' following conditional operator does not cover everything to its right}}
infix operator ?+= : AssignmentPrecedence
func ?+=(lhs: inout Int?, rhs: Int?) {
lhs = lhs! + rhs!
}
var i = try? foo() + bar()
let _: Double = i // expected-error {{cannot convert value of type 'Int?' to specified type 'Double'}}
i = try? foo() + bar()
i ?+= try? foo() + bar()
i ?+= try? foo() %%%% bar() // expected-error {{'try?' following assignment operator does not cover everything to its right}} // expected-error {{call can throw but is not marked with 'try'}} // expected-warning {{result of operator '%%%%' is unused}}
// expected-note@-1 {{did you mean to use 'try'?}} {{23-23=try }}
// expected-note@-2 {{did you mean to handle error as optional value?}} {{23-23=try? }}
// expected-note@-3 {{did you mean to disable error propagation?}} {{23-23=try! }}
i ?+= try? foo() %%% bar()
_ = foo() == try? bar() // expected-error {{'try?' cannot appear to the right of a non-assignment operator}} // expected-error {{call can throw but is not marked with 'try'}}
// expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }}
// expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }}
// expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }}
_ = (try? foo()) == bar() // expected-error {{call can throw but is not marked with 'try'}}
// expected-note@-1 {{did you mean to use 'try'?}} {{21-21=try }}
// expected-note@-2 {{did you mean to handle error as optional value?}} {{21-21=try? }}
// expected-note@-3 {{did you mean to disable error propagation?}} {{21-21=try! }}
_ = foo() == (try? bar()) // expected-error {{call can throw but is not marked with 'try'}}
// expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }}
// expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }}
// expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }}
_ = (try? foo()) == (try? bar())
let j = true ? try? foo() : try? bar() + 0
let k = true ? try? foo() : try? bar() %%% 0 // expected-error {{'try?' following conditional operator does not cover everything to its right}}
try let singleLet = foo() // expected-error {{'try' must be placed on the initial value expression}} {{1-5=}} {{21-21=try }}
try var singleVar = foo() // expected-error {{'try' must be placed on the initial value expression}} {{1-5=}} {{21-21=try }}
try let uninit: Int // expected-error {{'try' must be placed on the initial value expression}}
try let (destructure1, destructure2) = (foo(), bar()) // expected-error {{'try' must be placed on the initial value expression}} {{1-5=}} {{40-40=try }}
try let multi1 = foo(), multi2 = bar() // expected-error {{'try' must be placed on the initial value expression}} expected-error 2 {{call can throw but is not marked with 'try'}}
// expected-note@-1 {{did you mean to use 'try'?}} {{18-18=try }} expected-note@-1 {{did you mean to use 'try'?}} {{34-34=try }}
// expected-note@-2 {{did you mean to handle error as optional value?}} {{18-18=try? }} expected-note@-2 {{did you mean to handle error as optional value?}} {{34-34=try? }}
// expected-note@-3 {{did you mean to disable error propagation?}} {{18-18=try! }} expected-note@-3 {{did you mean to disable error propagation?}} {{34-34=try! }}
class TryDecl { // expected-note {{in declaration of 'TryDecl'}}
try let singleLet = foo() // expected-error {{'try' must be placed on the initial value expression}} {{3-7=}} {{23-23=try }}
// expected-error @-1 {{call can throw, but errors cannot be thrown out of a property initializer}}
try var singleVar = foo() // expected-error {{'try' must be placed on the initial value expression}} {{3-7=}} {{23-23=try }}
// expected-error @-1 {{call can throw, but errors cannot be thrown out of a property initializer}}
try // expected-error {{expected declaration}}
func method() {}
}
func test() throws -> Int {
try while true { // expected-error {{'try' cannot be used with 'while'}}
try break // expected-error {{'try' cannot be used with 'break'}}
}
try throw // expected-error {{'try' must be placed on the thrown expression}} {{3-7=}} {{3-3=try }} expected-error {{expected expression in 'throw' statement}}
; // Reset parser.
try return // expected-error {{'try' cannot be used with 'return'}} expected-error {{non-void function should return a value}}
; // Reset parser.
try throw foo() // expected-error {{'try' must be placed on the thrown expression}} {{3-7=}} {{13-13=try }}
// expected-error@-1 {{thrown expression type 'Int' does not conform to 'Error'}}
try return foo() // expected-error {{'try' must be placed on the returned expression}} {{3-7=}} {{14-14=try }}
}
// Test operators.
func *(a : String, b : String) throws -> Int { return 42 }
let _ = "foo"
* // expected-error {{operator can throw but expression is not marked with 'try'}}
// expected-note@-1 {{did you mean to use 'try'?}} {{9-9=try }}
// expected-note@-2 {{did you mean to handle error as optional value?}} {{9-9=try? }}
// expected-note@-3 {{did you mean to disable error propagation?}} {{9-9=try! }}
"bar"
let _ = try! "foo"*"bar"
let _ = try? "foo"*"bar"
let _ = (try? "foo"*"bar") ?? 0
// <rdar://problem/21414023> Assertion failure when compiling function that takes throwing functions and rethrows
func rethrowsDispatchError(handleError: ((Error) throws -> ()), body: () throws -> ()) rethrows {
do {
body() // expected-error {{call can throw but is not marked with 'try'}}
// expected-note@-1 {{did you mean to use 'try'?}} {{5-5=try }}
// expected-note@-2 {{did you mean to handle error as optional value?}} {{5-5=try? }}
// expected-note@-3 {{did you mean to disable error propagation?}} {{5-5=try! }}
} catch {
}
}
// <rdar://problem/21432429> Calling rethrows from rethrows crashes Swift compiler
struct r21432429 {
func x(_ f: () throws -> ()) rethrows {}
func y(_ f: () throws -> ()) rethrows {
x(f) // expected-error {{call can throw but is not marked with 'try'}} expected-note {{call is to 'rethrows' function, but argument function can throw}}
}
}
// <rdar://problem/21427855> Swift 2: Omitting try from call to throwing closure in rethrowing function crashes compiler
func callThrowingClosureWithoutTry(closure: (Int) throws -> Int) rethrows {
closure(0) // expected-error {{call can throw but is not marked with 'try'}} expected-warning {{result of call to function returning 'Int' is unused}}
// expected-note@-1 {{did you mean to use 'try'?}} {{3-3=try }}
// expected-note@-2 {{did you mean to handle error as optional value?}} {{3-3=try? }}
// expected-note@-3 {{did you mean to disable error propagation?}} {{3-3=try! }}
}
func producesOptional() throws -> Int? { return nil }
let doubleOptional = try? producesOptional()
let _: String = doubleOptional // expected-error {{cannot convert value of type 'Int??' to specified type 'String'}}
func maybeThrow() throws {}
try maybeThrow() // okay
try! maybeThrow() // okay
try? maybeThrow() // okay since return type of maybeThrow is Void
_ = try? maybeThrow() // okay
let _: () -> Void = { try! maybeThrow() } // okay
let _: () -> Void = { try? maybeThrow() } // okay since return type of maybeThrow is Void
if try? maybeThrow() { // expected-error {{cannot be used as a boolean}} {{4-4=((}} {{21-21=) != nil)}}
}
let _: Int = try? foo() // expected-error {{value of optional type 'Int?' not unwrapped; did you mean to use 'try!' or chain with '?'?}} {{14-18=try!}}
class X {}
func test(_: X) {}
func producesObject() throws -> AnyObject { return X() }
test(try producesObject()) // expected-error {{'AnyObject' is not convertible to 'X'; did you mean to use 'as!' to force downcast?}} {{26-26= as! X}}
| apache-2.0 | a3f40a36d23a8110c937dc29c8051bab | 62.43956 | 251 | 0.598735 | 3.896726 | false | false | false | false |
nRewik/swift-corelibs-foundation | Foundation/NSThread.swift | 1 | 5791 | // 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
//
#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc
#endif
import CoreFoundation
private func disposeTLS(ctx: UnsafeMutablePointer<Void>) -> Void {
Unmanaged<AnyObject>.fromOpaque(COpaquePointer(ctx)).release()
}
private var NSThreadSpecificKeySet = false
private var NSThreadSpecificKeyLock = NSLock()
private var NSThreadSpecificKey = pthread_key_t()
internal class NSThreadSpecific<T: AnyObject> {
private static var key: pthread_key_t {
get {
NSThreadSpecificKeyLock.lock()
if !NSThreadSpecificKeySet {
withUnsafeMutablePointer(&NSThreadSpecificKey) { key in
NSThreadSpecificKeySet = pthread_key_create(key, disposeTLS) == 0
}
}
NSThreadSpecificKeyLock.unlock()
return NSThreadSpecificKey
}
}
internal func get(generator: (Void) -> T) -> T {
let specific = pthread_getspecific(NSThreadSpecific.key)
if specific != UnsafeMutablePointer<Void>() {
return Unmanaged<T>.fromOpaque(COpaquePointer(specific)).takeUnretainedValue()
} else {
let value = generator()
pthread_setspecific(NSThreadSpecific.key, UnsafePointer<Void>(Unmanaged<AnyObject>.passRetained(value).toOpaque()))
return value
}
}
internal func set(value: T) {
let specific = pthread_getspecific(NSThreadSpecific.key)
var previous: Unmanaged<T>?
if specific != UnsafeMutablePointer<Void>() {
previous = Unmanaged<T>.fromOpaque(COpaquePointer(specific))
}
if let prev = previous {
if prev.takeUnretainedValue() === value {
return
}
}
pthread_setspecific(NSThreadSpecific.key, UnsafePointer<Void>(Unmanaged<AnyObject>.passRetained(value).toOpaque()))
if let prev = previous {
prev.release()
}
}
}
private func NSThreadStart(context: UnsafeMutablePointer<Void>) -> UnsafeMutablePointer<Void> {
let unmanaged: Unmanaged<NSThread> = Unmanaged.fromOpaque(COpaquePointer(context))
unmanaged.takeUnretainedValue().main()
unmanaged.release()
return nil
}
public class NSThread : NSObject {
static internal var _currentThread = NSThreadSpecific<NSThread>()
public static func currentThread() -> NSThread {
return NSThread._currentThread.get() {
return NSThread(thread: pthread_self())
}
}
/// Alternative API for detached thread creation
/// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative to creation via selector
/// - Note: Since this API is under consideration it may be either removed or revised in the near future
public class func detachNewThread(main: (Void) -> Void) {
let t = NSThread(main)
t.start()
}
public class func isMultiThreaded() -> Bool {
return true
}
public class func sleepUntilDate(date: NSDate) {
let start_ut = CFGetSystemUptime()
let start_at = CFAbsoluteTimeGetCurrent()
let end_at = date.timeIntervalSinceReferenceDate
var ti = end_at - start_at
let end_ut = start_ut + ti
while (0.0 < ti) {
var __ts__ = timespec(tv_sec: LONG_MAX, tv_nsec: 0)
if ti < Double(LONG_MAX) {
var integ = 0.0
let frac: Double = withUnsafeMutablePointer(&integ) { integp in
return modf(ti, integp)
}
__ts__.tv_sec = Int(integ)
__ts__.tv_nsec = Int(frac * 1000000000.0)
}
withUnsafePointer(&__ts__) { ts in
nanosleep(ts, nil)
}
ti = end_ut - CFGetSystemUptime()
}
}
public class func sleepForTimeInterval(interval: NSTimeInterval) {
var ti = interval
let start_ut = CFGetSystemUptime()
let end_ut = start_ut + ti
while 0.0 < ti {
var __ts__ = timespec(tv_sec: LONG_MAX, tv_nsec: 0)
if ti < Double(LONG_MAX) {
var integ = 0.0
let frac: Double = withUnsafeMutablePointer(&integ) { integp in
return modf(ti, integp)
}
__ts__.tv_sec = Int(integ)
__ts__.tv_nsec = Int(frac * 1000000000.0)
}
withUnsafePointer(&__ts__) { ts in
nanosleep(ts, nil)
}
ti = end_ut - CFGetSystemUptime()
}
}
public class func exit() {
pthread_exit(nil)
}
internal var _main: (Void) -> Void = {}
internal var _thread = pthread_t()
/// - Note: this differs from the Darwin implementation in that the keys must be Strings
public var threadDictionary = [String:AnyObject]()
internal init(thread: pthread_t) {
_thread = thread
}
public init(_ main: (Void) -> Void) {
_main = main
}
public func start() {
withUnsafeMutablePointer(&_thread) { thread in
let ptr = Unmanaged.passRetained(self)
pthread_create(thread, nil, NSThreadStart, UnsafeMutablePointer(ptr.toOpaque()))
}
}
public func main() {
NSThread._currentThread.set(self)
_main()
}
}
| apache-2.0 | 126c6396c781754b7fd633d448465de3 | 32.865497 | 158 | 0.595752 | 4.700487 | false | false | false | false |
meetkei/KxUI | KxUI/Color/UIColor+RGB.swift | 1 | 6080 | //
// Copyright (c) 2016 Keun young Kim <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension UIColor {
/**
Initializes and returns a color object using the elements of the Array
- Parameter list: RGBA component values
*/
convenience init?(normalizedRgbaComponents list: [Double]) {
guard list.count == 4 else {
return nil
}
for value in list {
if value < 0.0 || value > 1.0 {
return nil
}
}
let red = CGFloat(list[0])
let green = CGFloat(list[1])
let blue = CGFloat(list[2])
let alpha = CGFloat(list[3])
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
/**
- Parameter list:
*/
convenience init?(normalizedRgbComponents list: [Double]) {
guard list.count == 3 else {
return nil
}
var rgbaList = list
rgbaList.append(1.0)
self.init(normalizedRgbaComponents: rgbaList)
}
/**
- Parameter list:
*/
convenience init?(rgbaComponents list: [Int]) {
guard list.count == 4 else {
return nil
}
let list = list.map { Double($0) / 255.0 }
self.init(normalizedRgbaComponents: list)
}
/**
- Parameter list:
*/
convenience init?(rgbComponents list: [Int]) {
guard list.count == 3 else {
return nil
}
let list = list.map { Double($0) / 255.0 }
self.init(normalizedRgbComponents: list)
}
convenience init?(whiteComponent: Int) {
self.init(rgbComponents: [whiteComponent, whiteComponent, whiteComponent])
}
///
var normalizedRGBAComponent: (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)? {
var normalizedR: CGFloat = 0
var normalizedG: CGFloat = 0
var normalizedB: CGFloat = 0
var normalizedA: CGFloat = 0
if getRed(&normalizedR, green: &normalizedG, blue: &normalizedB, alpha: &normalizedA) {
return (normalizedR, normalizedG, normalizedB, normalizedA)
}
return nil
}
var rgbaComponent: (r: Int, g: Int, b: Int, a: Int)? {
var normalizedR: CGFloat = 0
var normalizedG: CGFloat = 0
var normalizedB: CGFloat = 0
var normalizedA: CGFloat = 0
if getRed(&normalizedR, green: &normalizedG, blue: &normalizedB, alpha: &normalizedA) {
return (Int(normalizedR * 255.0), Int(normalizedG * 255.0), Int(normalizedB * 255.0), Int(normalizedA * 255.0))
}
return nil
}
/// The red component of the hexadecimal color string
var normalizedRedComponent: CGFloat? {
return normalizedRGBAComponent?.r
}
///
var redComponent: CGFloat? {
if let value = normalizedRGBAComponent?.r {
return value * 255
}
return nil
}
/// The green component of the hexadecimal color string
var normalizedGreenComponent: CGFloat? {
return normalizedRGBAComponent?.g
}
///
var greenComponent: CGFloat? {
if let value = normalizedRGBAComponent?.g {
return value * 255
}
return nil
}
/// The blue component of the hexadecimal color string
var normalizedBlueComponent: CGFloat? {
return normalizedRGBAComponent?.b
}
///
var blueComponent: CGFloat? {
if let value = normalizedRGBAComponent?.b {
return value * 255
}
return nil
}
/// The alpha component of the hexadecimal color string
var normalizedAlphaComponent: CGFloat? {
return normalizedRGBAComponent?.a
}
///
var alphaComponent: CGFloat? {
if let value = normalizedRGBAComponent?.a {
return value * 255
}
return nil
}
///
var rgbString: String {
return toRGBString(includeAlpha: false)
}
///
var rgbaString: String {
return toRGBString(includeAlpha: true)
}
/**
- Parameter includeAlpha:
- Returns: 문자열
*/
func toRGBString(includeAlpha: Bool) -> String {
var normalizedR: CGFloat = 0
var normalizedG: CGFloat = 0
var normalizedB: CGFloat = 0
var normalizedA: CGFloat = 0
getRed(&normalizedR, green: &normalizedG, blue: &normalizedB, alpha: &normalizedA)
let r = Int(normalizedR * 255)
let g = Int(normalizedG * 255)
let b = Int(normalizedB * 255)
let a = Int(normalizedA * 255)
if includeAlpha {
return "R\(r) G\(g) B\(b) A\(a)"
}
return "R\(r) G\(g) B\(b)"
}
}
| mit | 25909ce5198ff7a0c7cf8aad8516f74d | 26.609091 | 123 | 0.575733 | 4.626047 | false | false | false | false |
AlvinL33/TownHunt | TownHunt-1.9/TownHunt/MainGamePackSelectorViewController.swift | 1 | 5644 | //
// MainGamePackSelectorViewController.swift
// TownHunt
//
// Created by Alvin Lee on 07/04/2017.
// Copyright © 2017 LeeTech. All rights reserved.
//
import UIKit
class MainGamePackSelectorViewController: FormTemplateExtensionOfViewController, UIPickerViewDelegate, UIPickerViewDataSource {
var delegate: MainGameModalDelegate?
@IBOutlet weak var packPicker: UIPickerView!
@IBOutlet weak var gameTypeSegCon: UISegmentedControl!
@IBOutlet weak var selectMapButton: UIButton!
@IBOutlet weak var viewLeaderboardButton: UIButton!
private var allPacksDict = [String: String]()
private var pickerData = [String]()
private var selectedPickerData: String = ""
private var gameType = "competitive"
override func viewDidLoad() {
super.viewDidLoad()
self.packPicker.delegate = self
self.packPicker.dataSource = self
setUpPicker()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func cancelButtonTapped(_ sender: Any) {
self.dismiss(animated: true, completion: nil)
}
// Populates the picker with the names of local packs
private func setUpPicker(){
let defaults = UserDefaults.standard
// Retrieves the list of user ids whose packs are found in local storage
if let listOfUsersOnPhone = defaults.array(forKey: "listOfLocalUserIDs"){
// Iterates over every id and retrieves all packs on the phone
for userID in listOfUsersOnPhone as! [String]{
let userPackDictName = "UserID-\(userID)-LocalPacks"
if let dictOfPacksOnPhone = defaults.dictionary(forKey: userPackDictName) {
// Appends all pack names and their creator user id to the allPacksDict
for pack in Array(dictOfPacksOnPhone.keys){
self.allPacksDict[pack] = userID
}
}
// Sorts the picker data in ascending order
self.pickerData = Array(allPacksDict.keys).sorted(by: <)
self.selectedPickerData = pickerData[0]
}
// If there are no local packs, pack interaction buttons are hidden and a message is shown to the user
} else if pickerData.isEmpty {
self.pickerData = ["No Packs Found"]
self.selectMapButton.isHidden = true
self.viewLeaderboardButton.isHidden = true
}
}
// Number of columns of data
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
// Numbers of rows of data
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.pickerData.count
}
// The picker data to return for a certain row and column
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.pickerData[row]
}
// Setting up the attributes of the text displayed in the picker
func pickerView(_ pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString? {
let textString = self.pickerData[row]
// Sets up the font and the colour of the text
return NSAttributedString(string: textString, attributes: [NSFontAttributeName:UIFont(name: "Futura"
, size: 17.0)!, NSForegroundColorAttributeName: UIColor.white])
}
// Retrieves which item is currently selected by the user
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
self.selectedPickerData = pickerData[row]
}
@IBAction func indexChanged(_ sender: UISegmentedControl) {
switch gameTypeSegCon.selectedSegmentIndex
{
case 0:
gameType = "competitive"
case 1:
gameType = "casual"
default:
break
}
}
@IBAction func tapForInfoButtonTapped(_ sender: Any) {
let displayMessage = "Competitive mode: 5 Pins will be initially appear with more and more pins being added as the game progresses. You will have to hunt for the pins under a time limit. \n\nCasual mode: All of the pins in the pack will appear. Hunt them all in your own time with no time limit. \n\nYour first competitive playthrough score will be added to the leaderboard. If your first playthrough was casual, no future scores for that pack will count in the leaderboard"
displayAlertMessage(alertTitle: "Competitive or Casual?", alertMessage: displayMessage)
}
@IBAction func selectPackButtonTapped(_ sender: Any) {
if let delegate = self.delegate {
delegate.packSelectedHandler(selectedPackKey: self.selectedPickerData, packCreatorID: self.allPacksDict[self.selectedPickerData]!, gameType: gameType)
}
NotificationCenter.default.post(name: Notification.Name(rawValue: "load"), object: nil)
self.dismiss(animated: true, completion: nil)
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "PackSelectorToLeaderboard" {
let destNavCon = segue.destination as! UINavigationController
if let targetController = destNavCon.topViewController as? LeaderboardViewController{
targetController.selectedPackKey = self.selectedPickerData
targetController.packCreatorID = self.allPacksDict[self.selectedPickerData]!
}
}
}
}
| apache-2.0 | 350b06b82426fca66529be6ba60742a6 | 42.407692 | 482 | 0.668439 | 5.12069 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Conversation/Content/Cells/CallCellViewModel.swift | 1 | 2684 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireCommonComponents
import UIKit
import WireDataModel
struct CallCellViewModel {
let icon: StyleKitIcon
let iconColor: UIColor?
let systemMessageType: ZMSystemMessageType
let font: UIFont?
let textColor: UIColor?
let message: ZMConversationMessage
func image() -> UIImage? {
return iconColor.map { icon.makeImage(size: .tiny, color: $0) }
}
func attributedTitle() -> NSAttributedString? {
guard let systemMessageData = message.systemMessageData,
let sender = message.senderUser,
let labelFont = font,
let labelTextColor = textColor,
systemMessageData.systemMessageType == systemMessageType
else { return nil }
let senderString: String
var called = NSAttributedString()
let childs = systemMessageData.childMessages.count
if systemMessageType == .missedCall {
var detailKey = "missed-call"
if message.conversationLike?.conversationType == .group {
detailKey.append(".groups")
}
senderString = sender.isSelfUser ? selfKey(with: detailKey).localized : (sender.name ?? "")
called = key(with: detailKey).localized(pov: sender.pov, args: childs + 1, senderString) && labelFont
} else {
let detailKey = "called"
senderString = sender.isSelfUser ? selfKey(with: detailKey).localized : (sender.name ?? "")
called = key(with: detailKey).localized(pov: sender.pov, args: senderString) && labelFont
}
var title = called
if childs > 0 {
title += " (\(childs + 1))" && labelFont
}
return title && labelTextColor
}
private func key(with component: String) -> String {
return "content.system.call.\(component)"
}
private func selfKey(with component: String) -> String {
return "\(key(with: component)).you"
}
}
| gpl-3.0 | 97e71d68fe89ec75f86b526b5eda4dd4 | 32.135802 | 113 | 0.651267 | 4.801431 | false | false | false | false |
PJayRushton/TeacherTools | TeacherTools/Platform.swift | 1 | 476 | //
// Platform.swift
// TeacherTools
//
// Created by Parker Rushton on 5/6/17.
// Copyright © 2017 AppsByPJ. All rights reserved.
//
import UIKit
struct Platform {
@nonobjc static var isSimulator: Bool {
return TARGET_OS_SIMULATOR != 0
}
static var isPad: Bool {
return UIDevice.current.userInterfaceIdiom == .pad
}
static var isPhone: Bool {
return UIDevice.current.userInterfaceIdiom == .phone
}
}
| mit | c24513a366bcc3dde2f520097985a042 | 18 | 60 | 0.621053 | 4.20354 | false | false | false | false |
Mattmlm/codepath-twitter-redux | Codepath Twitter/Codepath Twitter/User.swift | 1 | 2308 | //
// User.swift
// Codepath Twitter
//
// Created by admin on 10/2/15.
// Copyright © 2015 mattmo. All rights reserved.
//
import UIKit
var _currentUser: User?
let currentUserKey = "kCurrentUserKey"
let userDidLoginNotification = "userDidLoginNotification"
let userDidLogoutNotification = "userDidLogoutNotification"
class User: NSObject {
var name: String?
var screenname: String?
var profileImageUrl: String?
var profileBackgroundImageUrl: String?
var tagline: String?
var tweetsCount: Int?
var followingCount: Int?
var followersCount: Int?
var dictionary: NSDictionary
init(dictionary: NSDictionary) {
self.dictionary = dictionary
name = dictionary["name"] as? String
screenname = dictionary["screen_name"] as? String
profileImageUrl = dictionary["profile_image_url"] as? String
profileBackgroundImageUrl = dictionary["profile_background_image_url"] as? String
tweetsCount = dictionary["statuses_count"] as? Int
followingCount = dictionary["friends_count"] as? Int
followersCount = dictionary["followers_count"] as? Int
tagline = dictionary["description"] as? String
}
func logout() {
// User.currentUser = nil
// TwitterClient.sharedInstance.requestSerializer.removeAccessToken()
//
// NSNotificationCenter.defaultCenter().postNotificationName(userDidLogoutNotification, object:nil)
}
class var currentUser: User? {
get {
if _currentUser == nil {
if let data = UserDefaults.standard.object(forKey: currentUserKey) as? Data {
do {
let dictionary = try JSONSerialization.jsonObject(with: data, options: [])
_currentUser = User(dictionary: dictionary as! NSDictionary);
} catch {
print("Error: \(error)")
}
}
}
return _currentUser
}
set(user) {
_currentUser = user
if _currentUser != nil {
do {
let data = try JSONSerialization.data(withJSONObject: user!.dictionary, options: [])
UserDefaults.standard.set(data, forKey: currentUserKey)
} catch {
print("Error: \(error)")
}
} else {
UserDefaults.standard.set(nil, forKey: currentUserKey)
}
UserDefaults.standard.synchronize()
}
}
}
| mit | c3eebd8ad81d058860a2e7626dbbea79 | 29.355263 | 106 | 0.658431 | 4.660606 | false | false | false | false |
wuaschtikus/NanoScanner | NanoScanner/Core/NanoScannerCreater.swift | 1 | 3873 | //
// MiniBarcodeCreator.swift
// MiniBarcodeScanner
//
// Created by Grüner Martin on 28/03/16.
// Copyright © 2016 Grüner Martin. All rights reserved.
//
import Foundation
public enum BarcodeCreatorType : String {
case CICode128BarcodeGenerator = "CICode128BarcodeGenerator"
case CIQRCodeGenerator = "CIQRCodeGenerator"
case CIPDF417BarcodeGenerator = "CIPDF417BarcodeGenerator"
case CIAztecCodeGenerator = "CIAztecCodeGenerator"
}
public protocol NanoScannerCreaterProtocol {
func createBarcodeImage(_ value:String, barcodeType:BarcodeCreatorType, size:CGSize) throws -> UIImage
func createBarcodeImageData(_ value:String, barcodeType:BarcodeCreatorType, size:CGSize) throws -> Data
}
public extension NanoScannerCreaterProtocol {
// MARK: - Public
public func createBarcodeImage(_ value:String, barcodeType:BarcodeCreatorType, size:CGSize) throws -> UIImage {
guard let data:Data = value.data(using: String.Encoding.ascii) else { throw NanoError.cannotAddInput }
let resizedImage:CIImage = try createBarcodeAccordingToType(barcodeType: barcodeType, data: data, size: size)
let resizedUIImage:UIImage = UIImage(ciImage: resizedImage)
return resizedUIImage
}
public func createBarcodeImageData(_ value:String, barcodeType:BarcodeCreatorType, size:CGSize) throws -> Data {
guard let data:Data = value.data(using: String.Encoding.ascii) else { throw NanoError.cannotAddInput }
let context:CIContext = CIContext(options: nil)
let resizedImage:CIImage = try createBarcodeAccordingToType(barcodeType: barcodeType, data: data, size: size)
let outputCgImage:CGImage = context.createCGImage(resizedImage, from: resizedImage.extent)!
let outputImage:UIImage = UIImage(cgImage: outputCgImage)
let outputCgImageData:Data = UIImagePNGRepresentation(outputImage)!
return outputCgImageData
}
// MARK: - Private
fileprivate func createBarcodeAccordingToType(barcodeType:BarcodeCreatorType, data:Data, size:CGSize) throws -> CIImage {
let filter:CIFilter = try self.createFilter(barcodeType, imageData: data)
let outputImage:CIImage = try self.createOutputImage(filter)
var resizedImage:CIImage!
if barcodeType == BarcodeCreatorType.CIQRCodeGenerator {
resizedImage = resizeImage(outputImage, desiredSize: CGSize(width: size.height, height: size.height))
} else {
resizedImage = resizeImage(outputImage, desiredSize: size)
}
return resizedImage
}
fileprivate func resizeImage(_ barcodeImage:CIImage, desiredSize:CGSize) -> CIImage {
let scaleX = desiredSize.width / barcodeImage.extent.size.width
let scaleY = desiredSize.height / barcodeImage.extent.size.height
let transformedImage = barcodeImage.applying(CGAffineTransform(scaleX: scaleX, y: scaleY))
return transformedImage
}
// MARK: - Private
fileprivate func createFilter(_ barcodeType:BarcodeCreatorType, imageData:Data) throws -> CIFilter {
guard let actualFilter = CIFilter(name: barcodeType.rawValue)
else {
throw NanoError.couldNotCreateFilterWithValue(filterValue: barcodeType.rawValue)
}
actualFilter.setValue(imageData, forKey: "inputMessage")
return actualFilter
}
fileprivate func createOutputImage(_ filter:CIFilter) throws -> CIImage {
guard let actualOutputImage = filter.outputImage
else {
throw NanoError.outputImageMustNotBeNil
}
return actualOutputImage
}
}
| apache-2.0 | 662e83af071b2be983cb3d09f3a52cac | 35.509434 | 125 | 0.678553 | 5.27248 | false | false | false | false |
Mindera/Alicerce | Sources/Logging/Log.swift | 1 | 3827 | import Foundation
/// A type representing the Log namespace (case-less enum).
public enum Log {
/// A log item value that represents a log message and its context.
public struct Item: Equatable, Codable {
/// The timestamp when the log item was created.
public let timestamp: Date
/// The module of the log item.
public let module: String?
/// The severity level of the log item.
public let level: Level
/// The message of the log item.
public let message: String
/// The current thread's name when the log item was created.
public let thread: String
/// The current queue's label when the log item was created.
public let queue: String
/// The file from where the log originated.
public let file: String
/// The file line from where the log originated.
public let line: Int
/// The function from where the log originated.
public let function: String
}
/// A logging level defining message severity levels, as well as enabling filtering on a per log destination basis.
public enum Level: Int, Codable {
case verbose
case debug
case info
case warning
case error
/// Checks if `self` meets the specified (minimum) log level. A message can be logged if its level is
/// *greater than or equal* to another level defined as minimum.
///
/// The relationship between levels is as follows:
/// `.verbose` < `.debug` < `.info` < `.warning` < `.error`
///
/// - Parameter minLevel: The level to compare against `self`.
/// - Returns: `true` if `self` meets the minimum level, `false` otherwise.
func meets(minLevel: Level) -> Bool { rawValue >= minLevel.rawValue }
}
/// A queue object used to specify `DispatchQueue`'s used in log destinations, ensuring they are serial with the
/// specified QoS, targeting an optional queue.
public final class Queue {
/// The inner GCD queue.
public let dispatchQueue: DispatchQueue
/// Creates an instance with the specified label, QoS and target queue.
///
/// - Parameters:
/// - label: The inner dispatch queue's label.
/// - qos: The inner dispatch queue's quality of service.
/// - target: The inner dispatch queue's target queue.
public init(label: String, qos: DispatchQoS = .utility, target: DispatchQueue? = nil) {
dispatchQueue = DispatchQueue(label: label, qos: qos, target: target)
}
}
}
extension Log {
/// The framework's (configurable) internal logger, mostly used as a default error logger, or to log errors which
/// don't impact normal functioning and are not exposed/propagated via the current API's.
///
/// The default value is set to a `Log.ConsoleLogDestination` instance configured with a `StringLogItemFormatter`
/// with the format string: `"$DHH:mm:ss.SSS$d $C$L$c $N.$F:$l - [Alicerce 🏗] $M"`.
///
/// Set to a `Log.DummyLogger` instance to disable logging from the framework, or to the `Logger` of your choice to
/// easily include Alicerce's logs into to your own logs.
///
/// - Warning: This variable is **not** thread safe (for performance reasons). If you wish to customize its value
/// please do so just once on app launch, or before using any of Alicerce's components.
public static var internalLogger: Logger = {
let format = "$DHH:mm:ss.SSS$d $C$L$c $N.$F:$l - [Alicerce 🏗] $M"
let formatter = Log.StringLogItemFormatter()
let destination = Log.ConsoleLogDestination<StringLogItemFormatter, NoMetadataKey>(formatter: formatter)
return destination
}()
}
| mit | 64f011a5b26b4401740451e5b08b3831 | 37.989796 | 119 | 0.636744 | 4.598075 | false | false | false | false |
weareyipyip/SwiftStylable | Sources/SwiftStylable/Classes/Style/StylableComponents/STLabel.swift | 1 | 4043 | //
// STLabel.swift
// SwiftStylable
//
// Created by Marcel Bloemendaal on 10/08/16.
// Copyright © 2016 YipYip. All rights reserved.
//
import UIKit
@IBDesignable open class STLabel : UILabel, Stylable, BackgroundAndBorderStylable, ForegroundStylable, TextStylable, StyledTextStylable {
private var _stComponentHelper: STComponentHelper!
private var _text:String?
private var _styledText:String?
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Initializers & deinit
//
// -----------------------------------------------------------------------------------------------------------------------
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self._text = super.text
self.setUpSTComponentHelper()
}
override public init(frame: CGRect) {
super.init(frame: frame)
self._text = super.text
self.setUpSTComponentHelper()
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Computed properties
//
// -----------------------------------------------------------------------------------------------------------------------
@IBInspectable open var styleName:String? {
set {
self._stComponentHelper.styleName = newValue
}
get {
return self._stComponentHelper.styleName
}
}
@IBInspectable open var substyleName:String? {
set {
self._stComponentHelper.substyleName = newValue
}
get {
return self._stComponentHelper.substyleName
}
}
open override var text: String? {
set {
self._text = newValue
super.text = self.fullUppercaseText ? newValue?.uppercased() : newValue
self._styledText = nil
}
get {
return self._text
}
}
open override var attributedText: NSAttributedString? {
didSet {
self._styledText = nil
}
}
open var fullUppercaseText = false {
didSet {
self.text = self._text
}
}
var foregroundColor: UIColor? {
set {
self.textColor = newValue ?? UIColor.black
}
get {
return self.textColor
}
}
var textFont: UIFont? {
set {
if let font = newValue {
self.font = font
}
}
get {
return self.font
}
}
var styledTextAttributes:[NSAttributedString.Key:Any]? {
didSet {
if self._styledText != nil {
self.styledText = self._styledText
}
}
}
@IBInspectable open var styledText:String? {
set {
self._styledText = newValue
self._text = newValue
if let text = newValue {
super.attributedText = NSAttributedString(string: text, attributes: self.styledTextAttributes ?? [NSAttributedString.Key:Any]())
}
}
get {
return self._styledText
}
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: - Public properties
//
// -----------------------------------------------------------------------------------------------------------------------
open func applyStyle(_ style:Style) {
self._stComponentHelper.applyStyle(style)
}
// -----------------------------------------------------------------------------------------------------------------------
//
// MARK: Private methods
//
// -----------------------------------------------------------------------------------------------------------------------
private func setUpSTComponentHelper() {
self._stComponentHelper = STComponentHelper(stylable: self, stylePropertySets: [
BackgroundAndBorderStyler(self),
ForegroundStyler(self),
TextStyler(self),
StyledTextStyler(self)
])
}
}
| mit | 6653185ea7ca1ea10aceda58818db7c2 | 25.768212 | 144 | 0.445819 | 5.469553 | false | false | false | false |
tutsplus/iOS-MagnetMessage | MessageMe/SignInViewController.swift | 1 | 4645 | //
// SignInViewController.swift
// MessageMe
//
// Created by Bart Jacobs on 26/11/15.
// Copyright © 2015 Magnet. All rights reserved.
//
import UIKit
import MagnetMax
protocol SignInViewControllerDelegate {
func controller(controller: SignInViewController, didSignInWithUser user: MMUser)
}
class SignInViewController: UIViewController {
@IBOutlet weak var signInButton: UIButton!
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
var delegate: SignInViewControllerDelegate?
var hasAccount = true
// MARK: -
// MARK: View Life Cycle
override func viewDidLoad() {
if hasAccount {
signInButton.setTitle("Sign In", forState: UIControlState.Normal)
} else {
signInButton.setTitle("Create Account", forState: UIControlState.Normal)
}
}
// MARK: -
// MARK: Actions
@IBAction func signIn(sender: UIButton) {
guard let username = usernameTextField.text else {
showAlertWithTitle("Username Required", message: "Enter a valid username.")
return
}
guard let password = passwordTextField.text else {
showAlertWithTitle("Password Required", message: "Enter a valid password.")
return
}
guard !username.isEmpty && !password.isEmpty else {
showAlertWithTitle("Error", message: "Enter a valid username and password.")
return;
}
// Create Credential
let credential = NSURLCredential(user: username, password: password, persistence: .None)
if hasAccount {
signInWithCredential(credential)
} else {
createAccountWithCredential(credential)
}
}
@IBAction func cancel(sender: UIBarButtonItem) {
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: -
// MARK: Helper Methods
private func showAlertWithTitle(title: String, message: String) {
// Initialize Alert Controller
let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
// Configure Alert Controller
alertController.addAction(UIAlertAction(title: "OK", style: .Cancel, handler: nil))
// Present Alert Controller
presentViewController(alertController, animated: true, completion: nil)
}
private func createAccountWithCredential(credential: NSURLCredential) {
// Create User
let user = MMUser()
// Configure User
user.userName = credential.user
user.password = credential.password
// Register User
user.register({ (user) -> Void in
// Sign User In
self.signInWithCredential(credential)
}) { (error) -> Void in
print(error)
if error.code == 409 {
// Account Already Exists
self.signInWithCredential(credential)
} else {
// Notify User
self.showAlertWithTitle("Error", message: "We were unable to create an account. Please try again.")
}
}
}
private func signInWithCredential(credential: NSURLCredential) {
MMUser.login(credential, success: { () -> Void in
MagnetMax.initModule(MMX.sharedInstance(), success: { () -> Void in
// Store Username in User Defaults
NSUserDefaults.standardUserDefaults().setObject(credential.user, forKey: "username")
// Notify Delegate
self.delegate?.controller(self, didSignInWithUser: MMUser.currentUser()!)
// Pop View Controller
self.dismissViewControllerAnimated(true, completion: nil)
}, failure: { (error) -> Void in
print(error)
// Notify User
self.showAlertWithTitle("Error", message: "We were unable to sign you in. Please make sure that the credentials you entered are correct.")
})
}) { (error) -> Void in
print(error)
// Notify User
self.showAlertWithTitle("Error", message: "We were unable to sign you in. Please make sure that the credentials you entered are correct.")
}
}
}
| bsd-2-clause | 1837998a7109d5067c513e676e4cb089 | 32.89781 | 158 | 0.575151 | 5.797753 | false | false | false | false |
coderQuanjun/PigTV | GYJTV/GYJTV/Classes/Live/View/GiftAnimation/GiftContentView.swift | 1 | 3593 | //
// GiftContentView.swift
// GiftAnimation
//
// Created by zcm_iOS on 2017/6/7.
// Copyright © 2017年 com.zcmlc.zcmlc. All rights reserved.
//
import UIKit
private let kChannelCount = 2
private let kChannelViewH : CGFloat = 40
private let kChannelMargin : CGFloat = 10
class GiftContentView: UIView {
//MARK: 私有属性
fileprivate lazy var giftChannelArr : [GiftChannelView] = [GiftChannelView]()
fileprivate lazy var cacheGiftModels : [GiftAnimationModel] = [GiftAnimationModel]()
override init(frame: CGRect) {
super.init(frame: frame)
setupViews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK: 界面处理
extension GiftContentView{
fileprivate func setupViews(){
// 根据当前的渠道数,创建HYGiftChannelView
for i in 0..<kChannelCount {
let channelView = GiftChannelView.loadFromNib()
channelView.frame = CGRect(x: 0, y: (kChannelViewH + kChannelMargin) * CGFloat(i), width: frame.width, height: kChannelViewH)
channelView.alpha = 0
addSubview(channelView)
giftChannelArr.append(channelView)
channelView.complectionCallback = {channelView in
//1.取出缓存中的模型
guard self.cacheGiftModels.count != 0 else {
return
}
//2.取出缓存中的第一个模型
let firstmodel = self.cacheGiftModels.first
//3.清除第一个模型
self.cacheGiftModels.removeFirst()
//4.让闲置的channelView执行动画
channelView.giftModel = firstmodel
//5.将数组中剩余有和firstGiftModel相同的模型放入到ChanelView缓存中
for i in (0..<self.cacheGiftModels.count).reversed() {
let giftModel = self.cacheGiftModels[i]
if giftModel.isEqual(firstmodel) {
channelView.addOnceToCache()
self.cacheGiftModels.remove(at: i)
}
}
}
}
}
}
//MARK:
extension GiftContentView{
func showGiftModel(_ giftModel : GiftAnimationModel) {
// 1.判断正在忙的ChanelView和赠送的新礼物的(username/giftname)
if let channelView = chackUsingChannelView(giftModel){
channelView.addOnceToCache()
return
}
// 2.判断有没有闲置的ChanelView
if let channelView = chackIdelChannelView(){
channelView.giftModel = giftModel
return
}
// 3.将数据放入缓存中
cacheGiftModels.append(giftModel)
}
//判断有没有正在使用的,并且和赠送礼物相同的
private func chackUsingChannelView(_ giftModel : GiftAnimationModel) -> GiftChannelView?{
for channelView in giftChannelArr {
if giftModel.isEqual(channelView.giftModel) && channelView.giftState != .endAnimating {
return channelView
}
}
return nil
}
//判断有没有闲置的channelView
private func chackIdelChannelView() -> GiftChannelView? {
for channelView in giftChannelArr {
if channelView.giftState == .idle {
return channelView
}
}
return nil
}
}
| mit | 7b08a0862943f57c452453c8c6a7b918 | 29.272727 | 137 | 0.572673 | 4.826087 | false | false | false | false |
karavakis/simply_counted | simply_counted/ClientCollection.swift | 1 | 2255 | //
// ClientCollection.swift
// simply_counted
//
// Created by Jennifer Karavakis on 8/19/16.
// Copyright © 2017 Jennifer Karavakis. All rights reserved.
//
import UIKit
import CloudKit
open class ClientCollection: CloudKitContainer {
var clients = [CKRecord.ID: Client]()
override init() {
super.init()
}
subscript(id:CKRecord.ID) -> Client? {
return self.clients[id]
}
open func count() -> Int {
return self.clients.count
}
open func append(_ client:Client) {
clients[client.record!.recordID] = client
}
open func removeValue(forId: CKRecord.ID) {
clients.removeValue(forKey: forId)
}
func getIndexedList() -> [String:[Client]] {
var indexedList = [String:[Client]]()
for client in clients.values
{
let firstLetter = String(client.name[client.name.startIndex]).uppercased()
if (indexedList[firstLetter] != nil) {
indexedList[firstLetter]!.append(client)
}
else {
indexedList[firstLetter] = [Client]()
indexedList[firstLetter]!.append(client)
}
}
var indexedListSorted = [String:[Client]]()
for list in indexedList {
indexedListSorted[list.key] = list.value.sorted(by: { $0.name < $1.name })
}
return indexedListSorted
}
func load(successHandler:@escaping (()->Void), errorHandler: @escaping (()->Void)) {
let predicate = NSPredicate(format: "TRUEPREDICATE")
let query = CKQuery(recordType: "Client", predicate: predicate)
let sort = NSSortDescriptor(key: "name", ascending: true)
func createClientList(_ records: [CKRecord]) {
self.clients.removeAll()
for record in records {
let newClient = Client(clientRecord : record)
self.clients[newClient.record!.recordID] = newClient
}
successHandler()
}
func handleError(_ error: NSError) {
print("Error: \(error) \(error.userInfo)")
errorHandler()
}
performQuery(query, successHandler: createClientList, errorHandler: handleError)
}
}
| apache-2.0 | 36c4ec156428f2463135d23b2ec8dc50 | 27.175 | 88 | 0.586513 | 4.63786 | false | false | false | false |
xwu/swift | test/SILGen/enum_resilience.swift | 13 | 10209 |
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-emit-silgen -module-name enum_resilience -I %t -enable-library-evolution %s | %FileCheck %s
import resilient_enum
// Resilient enums are always address-only, and switches must include
// a default case
// CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience15resilientSwitchyy0c1_A06MediumOF : $@convention(thin) (@in_guaranteed Medium) -> ()
// CHECK: [[BOX:%.*]] = alloc_stack $Medium
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]]
// CHECK-NEXT: [[METATYPE:%.+]] = value_metatype $@thick Medium.Type, [[BOX]] : $*Medium
// CHECK-NEXT: switch_enum_addr [[BOX]] : $*Medium, case #Medium.Paper!enumelt: bb1, case #Medium.Canvas!enumelt: bb2, case #Medium.Pamphlet!enumelt: bb3, case #Medium.Postcard!enumelt: bb4, default bb5
// CHECK: bb1:
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb3:
// CHECK-NEXT: [[INDIRECT_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]]
// CHECK-NEXT: [[INDIRECT:%.*]] = load [take] [[INDIRECT_ADDR]]
// CHECK-NEXT: [[PAYLOAD:%.*]] = project_box [[INDIRECT]]
// CHECK-NEXT: destroy_value [[INDIRECT]]
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb4:
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]]
// CHECK-NEXT: destroy_addr [[PAYLOAD_ADDR]]
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb5:
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[DIAGNOSE:%.+]] = function_ref @$ss27_diagnoseUnexpectedEnumCase
// CHECK-NEXT: = apply [[DIAGNOSE]]<Medium>([[METATYPE]]) : $@convention(thin) <τ_0_0> (@thick τ_0_0.Type) -> Never
// CHECK-NEXT: unreachable
// CHECK: bb6:
// CHECK-NOT: destroy_addr %0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]]
func resilientSwitch(_ m: Medium) {
switch m {
case .Paper: ()
case .Canvas: ()
case .Pamphlet: ()
case .Postcard: ()
}
}
// CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience22resilientSwitchDefaultys5Int32V0c1_A06MediumOF : $@convention(thin) (@in_guaranteed Medium) -> Int32 {
func resilientSwitchDefault(_ m: Medium) -> Int32 {
// CHECK: switch_enum_addr %2 : $*Medium, case #Medium.Paper!enumelt: [[PAPER:[^ ]+]], case #Medium.Canvas!enumelt: [[CANVAS:[^ ]+]], default [[DEFAULT:[^ ]+]]
switch m {
// CHECK: [[PAPER]]:
// CHECK: integer_literal $Builtin.IntLiteral, 0
case .Paper: return 0
// CHECK: [[CANVAS]]:
// CHECK: integer_literal $Builtin.IntLiteral, 1
case .Canvas: return 1
// CHECK: [[DEFAULT]]:
// CHECK: integer_literal $Builtin.IntLiteral, -1
default: return -1
}
} // CHECK: end sil function '$s15enum_resilience22resilientSwitchDefaultys5Int32V0c1_A06MediumOF'
// CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience26resilientSwitchUnknownCaseys5Int32V0c1_A06MediumOF : $@convention(thin) (@in_guaranteed Medium) -> Int32 {
func resilientSwitchUnknownCase(_ m: Medium) -> Int32 {
// CHECK: switch_enum_addr %2 : $*Medium, case #Medium.Paper!enumelt: [[PAPER:[^ ]+]], case #Medium.Canvas!enumelt: [[CANVAS:[^ ]+]], default [[DEFAULT:[^ ]+]]
switch m {
// CHECK: [[PAPER]]:
// CHECK: integer_literal $Builtin.IntLiteral, 0
case .Paper: return 0
// CHECK: [[CANVAS]]:
// CHECK: integer_literal $Builtin.IntLiteral, 1
case .Canvas: return 1
// CHECK: [[DEFAULT]]:
// CHECK: integer_literal $Builtin.IntLiteral, -1
@unknown case _: return -1
}
} // CHECK: end sil function '$s15enum_resilience26resilientSwitchUnknownCaseys5Int32V0c1_A06MediumOF'
// CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience36resilientSwitchUnknownCaseExhaustiveys5Int32V0c1_A06MediumOF : $@convention(thin) (@in_guaranteed Medium) -> Int32 {
func resilientSwitchUnknownCaseExhaustive(_ m: Medium) -> Int32 {
// CHECK: switch_enum_addr %2 : $*Medium, case #Medium.Paper!enumelt: [[PAPER:[^ ]+]], case #Medium.Canvas!enumelt: [[CANVAS:[^ ]+]], case #Medium.Pamphlet!enumelt: [[PAMPHLET:[^ ]+]], case #Medium.Postcard!enumelt: [[POSTCARD:[^ ]+]], default [[DEFAULT:[^ ]+]]
switch m {
// CHECK: [[PAPER]]:
// CHECK: integer_literal $Builtin.IntLiteral, 0
case .Paper: return 0
// CHECK: [[CANVAS]]:
// CHECK: integer_literal $Builtin.IntLiteral, 1
case .Canvas: return 1
// CHECK: [[PAMPHLET]]:
// CHECK: integer_literal $Builtin.IntLiteral, 2
case .Pamphlet: return 2
// CHECK: [[POSTCARD]]:
// CHECK: integer_literal $Builtin.IntLiteral, 3
case .Postcard: return 3
// CHECK: [[DEFAULT]]:
// CHECK: integer_literal $Builtin.IntLiteral, -1
@unknown case _: return -1
}
}
// Indirect enums are still address-only, because the discriminator is stored
// as part of the value, so we cannot resiliently make assumptions about the
// enum's size
// CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience21indirectResilientEnumyy010resilient_A016IndirectApproachOF : $@convention(thin) (@in_guaranteed IndirectApproach) -> ()
func indirectResilientEnum(_ ia: IndirectApproach) {}
public enum MyResilientEnum {
case kevin
case loki
// CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience15MyResilientEnumOACycfC : $@convention(method) (@thin MyResilientEnum.Type) -> @out MyResilientEnum
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var MyResilientEnum }, var, name "self"
// CHECK: [[SELF_TMP:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var MyResilientEnum }
// CHECK: [[SELF_ADDR:%.*]] = project_box [[SELF_TMP]] : ${ var MyResilientEnum }, 0
// CHECK: [[NEW_SELF:%.*]] = enum $MyResilientEnum, #MyResilientEnum.loki!enumelt
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*MyResilientEnum
// CHECK: assign [[NEW_SELF]] to [[ACCESS]] : $*MyResilientEnum
// CHECK: end_access [[ACCESS]] : $*MyResilientEnum
// CHECK: copy_addr [[SELF_ADDR]] to [initialization] %0 : $*MyResilientEnum
// CHECK: destroy_value [[SELF_TMP]] : ${ var MyResilientEnum }
// CHECK: return
init() {
self = .loki
}
// CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience15MyResilientEnumO9getAHorseACyFZ : $@convention(method) (@thin MyResilientEnum.Type) -> @out MyResilientEnum
// CHECK: [[NEW_SELF:%.*]] = enum $MyResilientEnum, #MyResilientEnum.loki!enumelt
// CHECK: store [[NEW_SELF]] to [trivial] %0 : $*MyResilientEnum
// CHECK: return
static func getAHorse() -> MyResilientEnum {
return .loki
}
}
public enum MoreHorses {
case marshall(Int)
case seuss(AnyObject)
// CHECK-LABEL: sil hidden [ossa] @$s15enum_resilience10MoreHorsesOACycfC : $@convention(method) (@thin MoreHorses.Type) -> @out MoreHorses
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var MoreHorses }, var, name "self"
// CHECK: [[SELF_TMP:%.*]] = mark_uninitialized [delegatingself] [[SELF_BOX]] : ${ var MoreHorses }
// CHECK: [[SELF_ADDR:%.*]] = project_box [[SELF_TMP]] : ${ var MoreHorses }, 0
// CHECK: [[BUILTIN_INT:%.*]] = integer_literal $Builtin.IntLiteral, 0
// CHECK: [[INT_METATYPE:%.*]] = metatype $@thin Int.Type
// CHECK: [[INT_CTOR:%.*]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [[PAYLOAD:%.*]] = apply [[INT_CTOR]]([[BUILTIN_INT]], [[INT_METATYPE]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK: [[NEW_SELF:%.*]] = enum $MoreHorses, #MoreHorses.marshall!enumelt, [[PAYLOAD]] : $Int
// CHECK: [[ACCESS:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*MoreHorses
// CHECK: assign [[NEW_SELF]] to [[ACCESS]] : $*MoreHorses
// CHECK: end_access [[ACCESS]] : $*MoreHorses
// CHECK: copy_addr [[SELF_ADDR]] to [initialization] %0 : $*MoreHorses
// CHECK: destroy_value [[SELF_TMP]] : ${ var MoreHorses }
// CHECK: return
init() {
self = .marshall(0)
}
}
public func referenceCaseConstructors() {
_ = MoreHorses.marshall
_ = MoreHorses.seuss
}
// CHECK-LABEL: sil [ossa] @$s15enum_resilience15resilientSwitchyyAA15MyResilientEnumOF : $@convention(thin) (@in_guaranteed MyResilientEnum) -> ()
// CHECK: [[ENUM:%.*]] = load [trivial] %0
// CHECK: switch_enum [[ENUM]] : $MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2
// CHECK: return
public func resilientSwitch(_ e: MyResilientEnum) {
switch e {
case .kevin: ()
case .loki: ()
}
}
// CHECK-LABEL: sil [ossa] @$s15enum_resilience15resilientIfCaseySbAA15MyResilientEnumOF : $@convention(thin) (@in_guaranteed MyResilientEnum) -> Bool
// CHECK: [[ENUM:%.*]] = load [trivial] %0 : $*MyResilientEnum
// CHECK: switch_enum [[ENUM]] : $MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2
// CHECK: return
public func resilientIfCase(_ e: MyResilientEnum) -> Bool {
if case .kevin = e {
return true
} else {
return false
}
}
// Inlinable functions must lower the switch as if it came from outside the module
// CHECK-LABEL: sil [serialized] [ossa] @$s15enum_resilience15inlinableSwitchyyAA15MyResilientEnumOF : $@convention(thin) (@in_guaranteed MyResilientEnum) -> ()
// CHECK: [[ENUM:%.*]] = alloc_stack $MyResilientEnum
// CHECK: copy_addr %0 to [initialization] [[ENUM]] : $*MyResilientEnum
// CHECK: switch_enum_addr [[ENUM]] : $*MyResilientEnum, case #MyResilientEnum.kevin!enumelt: bb1, case #MyResilientEnum.loki!enumelt: bb2, default bb3
// CHECK: return
@inlinable public func inlinableSwitch(_ e: MyResilientEnum) {
switch e {
case .kevin: ()
case .loki: ()
}
}
| apache-2.0 | d27b8633ceb0ad68d1d48a18a5225805 | 48.309179 | 263 | 0.655433 | 3.61822 | false | false | false | false |
XeresRazor/SMGOLFramework | Sources/XMLNode.swift | 2 | 3733 | //
// XMLNode.swift
// SMGOLFramework
//
// Created by David Green on 2/22/16.
// Copyright © 2016 David Green. All rights reserved.
//
/// Description: XML Node object
import Foundation
public typealias AttributeType = (String, String)
public class Node {
public typealias NodeList = [Node]
public typealias AttributeList = [String: String]
public var text: String?
public var parent: Node?
public var isTag: Bool = false
private(set) public var children: NodeList = NodeList()
private(set) public var attributes: AttributeList = AttributeList()
public var innerText: String? {
if children.count != 1 {
return nil
}
return children.first!.text
}
public convenience init(text: String, isTag: Bool) {
self.init()
self.text = text
self.isTag = isTag
}
public func insertNode(node: Node) -> Node {
assert(node.parent == nil)
node.parent = self
children.append(node)
return node
}
public func insertTextNode(text: String) -> Node {
return insertNode(Node(text: text, isTag: false))
}
public func insertTagNode(name: String) -> Node {
return insertNode(Node(text: name, isTag: true))
}
public func insertNode(node: Node, atIndex index: Int) {
assert( node.parent == nil)
node.parent = self
children.insert(node, atIndex: index)
}
public func insertAttribute(attribute: AttributeType) -> Node {
attributes[attribute.0] = attribute.1
return self
}
public func insertAttribute(name: String, value: String) -> Node {
return insertAttribute((name, value))
}
public func childCount() -> Int {
return children.count
}
public func firstChild() -> Node {
assert(!children.isEmpty)
return children.first!
}
public func removeChildAt(index: Int) {
children.removeAtIndex(index)
}
public func attribute(name: String) -> String? {
return attributes[name]
}
public func attributeCount() -> Int {
return attributes.count
}
public func searchForNode(named name: String) -> Node? {
for node in children {
if !node.isTag {
continue
}
if node.text == name {
return node
}
}
return nil
}
private func selectNodesImplementation(path: String, single: Bool) -> NodeList {
var node: Node? = self
var curr = path
while true {
// check if we're at the end of an expression
let range = curr.rangeOfString("/")
guard range != nil else { break /* We are */ }
let position = range!.startIndex
let next = curr[curr.startIndex ..< position]
node = node?.searchForNode(named: next)
if node == nil {
return NodeList()
}
curr = curr[position.successor() ..< curr.endIndex]
}
var tempList = NodeList()
let filter = NodeFilter(node: node!, filter: curr)
while let filteredNode = filter.next() {
tempList.append(filteredNode)
if single { break }
}
return tempList
}
public func select(path: String) -> Node? {
return selectNodesImplementation(path, single: true).first
}
public func selectNodes(path: String) -> NodeList {
return selectNodesImplementation(path, single: false)
}
}
| mit | 6998193730f7376156064f575fdce4e2 | 25.657143 | 84 | 0.560825 | 4.700252 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/YBSlantedCollectionViewLayout-master/Example/YBSlantedCollectionViewLayoutSample/CustomCollectionCell.swift | 1 | 860 | //
// CustomCollectionCell.swift
// YBSlantedCollectionViewLayout
//
// Created by Yassir Barchi on 28/02/2016.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
import YBSlantedCollectionViewLayout
let yOffsetSpeed: CGFloat = 150.0
let xOffsetSpeed: CGFloat = 100.0
class CustomCollectionCell: YBSlantedCollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
var image: UIImage = UIImage() {
didSet {
imageView.image = image
}
}
var imageHeight: CGFloat {
return (imageView?.image?.size.height) ?? 0.0
}
var imageWidth: CGFloat {
return (imageView?.image?.size.width) ?? 0.0
}
func offset(_ offset: CGPoint) {
imageView.frame = self.imageView.bounds.offsetBy(dx: offset.x, dy: offset.y)
}
}
| mit | c9ba7765a4f457f0edf95582f4a6cc01 | 20.475 | 84 | 0.649593 | 4.051887 | false | false | false | false |
kkolli/MathGame | client/Speedy/RandomNumbers.swift | 1 | 3004 | //
// RandomNumbers.swift
// Speedy
//
// Created by Edward Chiou on 1/31/15.
// Copyright (c) 2015 Krishna Kolli. All rights reserved.
//
import Foundation
class RandomNumbers {
var target: Int?
var weights: [Double]
var weightedList: [Int]
//Bounds that determine how low/high the target value can be
let minTarget = 10
let targetRange = 10
let maxRange = 95
init(){
self.weights = []
self.weightedList = []
self.weights = generateWeights()
self.weightedList = generateWeightedList(weights)
}
/*
* We want 1-10 to appear more than 11-100, so 1-10 is assigned a
* higher probability.
*/
func generateGeometricDist() -> Int{
let p = 0.25
var random = Double(arc4random() / UInt32.max)
var denom = log(1.0 - p)
var exponentialDist = log(random) / denom
return Int(floor(exponentialDist))
}
func generateWeights() -> [Double]{
let primaryProbability = 0.055
let secondaryProbability = 0.005
var weights: [Double] = []
var remainingProb = 1.0
for(var i = 0; i < 100; ++i){
if(i < 10){
weights.append(primaryProbability)
remainingProb -= primaryProbability
}else{
weights.append(secondaryProbability)
remainingProb -= secondaryProbability
}
}
return weights
}
/*
* Generates weighted number list to provide the RNG that we want.
* List contains 1000 numbers. If probability of a number is x, then
* it will appear x * 1000 times.
*/
func generateWeightedList(weights: [Double]) -> [Int]{
var weightedList: [Int] = []
for (index, weight) in enumerate(weights) {
var multiples = Int(weight * 1000)
for(var j = 0; j < multiples; ++j){
weightedList.append(index + 1)
}
}
return weightedList
}
/*
* Call this to generate a random number.
*/
func generateNumber() -> Int{
var randomNumber = Int(arc4random_uniform(UInt32(1000)))
while weightedList[randomNumber] == target{
randomNumber = Int(arc4random_uniform(UInt32(1000)))
}
return weightedList[randomNumber]
}
func generateTarget() -> Int{
return Int(arc4random_uniform(UInt32(maxRange))) + minTarget
}
func generateTarget(numbers: [Int]) -> Int{
var generatedTarget = generateTarget()
var filteredNumbers = numbers.filter{$0 == generatedTarget}
while filteredNumbers.count > 0{
generatedTarget = generateTarget()
filteredNumbers = numbers.filter{$0 == generatedTarget}
}
target = generatedTarget
return generatedTarget
}
}
| gpl-2.0 | f51cd8f2c892527c1025a23e46f40304 | 26.309091 | 72 | 0.556924 | 4.635802 | false | false | false | false |
thedistance/TheDistanceForms | FormsDemo/ViewController.swift | 1 | 3256 | //
// ViewController.swift
// FormsDemo
//
// Created by Josh Campion on 21/04/2016.
// Copyright © 2016 The Distance. All rights reserved.
//
import UIKit
import SwiftyJSON
import TheDistanceForms
import TheDistanceCore
import KeyboardResponder
class ViewController: UIViewController, FormContainer {
var form:Form?
var buttonTargets: [ObjectTarget<UIButton>] = []
var keyboardResponder:KeyboardResponder?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let scroll = UIScrollView()
scroll.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scroll)
view.addConstraints(NSLayoutConstraint.constraintsToAlign(view: scroll, to: view))
guard let jsonURL = Bundle.main.url(forResource: "Form", withExtension: "json"),
let form = addFormFromURL(jsonURL, toContainerView: scroll, withInsets: UIEdgeInsetsMake(16.0, 16.0, 16.0, 8.0))
else { return }
self.form = form
keyboardResponder = setUpKeyboardResponder(onForm: form, withScrollView: scroll)
}
func buttonTappedForQuestion(_ question: FormQuestion) {
print("Tapped button: \(question.key)")
if question.key == "Submit" {
submitTapped()
}
}
func submitTapped() {
guard let form = self.form else { return }
let validation = form.validateForm()
if validation.0 == .valid {
let results = form.answersJSON()
print(results)
} else {
let errors = validation.1.flatMap({ (question, result) -> String? in
switch result {
case .valid:
return nil
case .invalid(let reason):
return "\(question.key): \(reason)"
}
})
let errorString = errors.joined(separator: "\n")
print("errors still in form:\n\(errorString)")
}
}
}
class RegisterViewController: UIViewController, FormContainer {
var form:Form?
var buttonTargets: [ObjectTarget<UIButton>] = []
var keyboardResponder:KeyboardResponder?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let scroll = UIScrollView()
scroll.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(scroll)
view.addConstraints(NSLayoutConstraint.constraintsToAlign(view: scroll, to: view))
guard let jsonURL = Bundle.main.url(forResource: "RegisterForm", withExtension: "json"),
let form = addFormFromURL(jsonURL, ofType: RegisterForm.self, toContainerView: scroll, withInsets: UIEdgeInsetsMake(16.0, 16.0, 16.0, 8.0))
else { return }
self.form = form
keyboardResponder = setUpKeyboardResponder(onForm: form, withScrollView: scroll)
}
func buttonTappedForQuestion(_ question: FormQuestion) { }
}
| mit | 57fdf2a29959edbb0912c11f99297876 | 30.601942 | 151 | 0.603072 | 5.062208 | false | false | false | false |
jwalsh/mal | swift3/Sources/stepA_mal/main.swift | 3 | 9665 | import Foundation
// read
func READ(str: String) throws -> MalVal {
return try read_str(str)
}
// eval
func is_pair(ast: MalVal) -> Bool {
switch ast {
case MalVal.MalList(let lst, _): return lst.count > 0
case MalVal.MalVector(let lst, _): return lst.count > 0
default: return false
}
}
func quasiquote(ast: MalVal) -> MalVal {
if !is_pair(ast) {
return list([MalVal.MalSymbol("quote"), ast])
}
let a0 = try! _nth(ast, 0)
switch a0 {
case MalVal.MalSymbol("unquote"):
return try! _nth(ast, 1)
default: true // fallthrough
}
if is_pair(a0) {
let a00 = try! _nth(a0, 0)
switch a00 {
case MalVal.MalSymbol("splice-unquote"):
return list([MalVal.MalSymbol("concat"),
try! _nth(a0, 1),
quasiquote(try! rest(ast))])
default: true // fallthrough
}
}
return list([MalVal.MalSymbol("cons"),
quasiquote(a0),
quasiquote(try! rest(ast))])
}
func is_macro(ast: MalVal, _ env: Env) -> Bool {
switch ast {
case MalVal.MalList(let lst, _) where lst.count > 0:
let a0 = lst[lst.startIndex]
switch a0 {
case MalVal.MalSymbol:
let e = try! env.find(a0)
if e != nil {
let mac = try! e!.get(a0)
switch mac {
case MalVal.MalFunc(_,_,_,_,let macro,_): return macro
default: return false
}
} else {
return false
}
default: return false
}
default: return false
}
}
func macroexpand(orig_ast: MalVal, _ env: Env) throws -> MalVal {
var ast: MalVal = orig_ast
while is_macro(ast, env) {
switch try! env.get(try! _nth(ast, 0)) {
case MalVal.MalFunc(let mac,_,_,_,_,_):
ast = try mac(_rest(ast))
default: throw MalError.General(msg: "impossible state in macroexpand")
}
}
return ast
}
func eval_ast(ast: MalVal, _ env: Env) throws -> MalVal {
switch ast {
case MalVal.MalSymbol:
return try env.get(ast)
case MalVal.MalList(let lst, _):
return list(try lst.map { try EVAL($0, env) })
case MalVal.MalVector(let lst, _):
return vector(try lst.map { try EVAL($0, env) })
case MalVal.MalHashMap(let dict, _):
var new_dict = Dictionary<String,MalVal>()
for (k,v) in dict { new_dict[k] = try EVAL(v, env) }
return hash_map(new_dict)
default:
return ast
}
}
func EVAL(orig_ast: MalVal, _ orig_env: Env) throws -> MalVal {
var ast = orig_ast, env = orig_env
while true {
switch ast {
case MalVal.MalList(let lst, _): if lst.count == 0 { return ast }
default: return try eval_ast(ast, env)
}
ast = try macroexpand(ast, env)
switch ast {
case MalVal.MalList: true
default: return try eval_ast(ast, env)
}
switch ast {
case MalVal.MalList(let lst, _):
switch lst[0] {
case MalVal.MalSymbol("def!"):
return try env.set(lst[1], try EVAL(lst[2], env))
case MalVal.MalSymbol("let*"):
let let_env = try Env(env)
var binds = Array<MalVal>()
switch lst[1] {
case MalVal.MalList(let l, _): binds = l
case MalVal.MalVector(let l, _): binds = l
default:
throw MalError.General(msg: "Invalid let* bindings")
}
var idx = binds.startIndex
while idx < binds.endIndex {
let v = try EVAL(binds[idx.successor()], let_env)
try let_env.set(binds[idx], v)
idx = idx.successor().successor()
}
env = let_env
ast = lst[2] // TCO
case MalVal.MalSymbol("quote"):
return lst[1]
case MalVal.MalSymbol("quasiquote"):
ast = quasiquote(lst[1]) // TCO
case MalVal.MalSymbol("defmacro!"):
var mac = try EVAL(lst[2], env)
switch mac {
case MalVal.MalFunc(let fn, let a, let e, let p, _, let m):
mac = malfunc(fn,ast:a,env:e,params:p,macro:true,meta:m)
default: throw MalError.General(msg: "invalid defmacro! form")
}
return try env.set(lst[1], mac)
case MalVal.MalSymbol("macroexpand"):
return try macroexpand(lst[1], env)
case MalVal.MalSymbol("try*"):
do {
return try EVAL(_nth(ast, 1), env)
} catch (let exc) {
if lst.count > 2 {
let a2 = lst[2]
switch a2 {
case MalVal.MalList(let a2lst, _):
let a20 = a2lst[0]
switch a20 {
case MalVal.MalSymbol("catch*"):
if a2lst.count < 3 { return MalVal.MalNil }
let a21 = a2lst[1], a22 = a2lst[2]
var err: MalVal
switch exc {
case MalError.Reader(let msg):
err = MalVal.MalString(msg)
case MalError.General(let msg):
err = MalVal.MalString(msg)
case MalError.MalException(let obj):
err = obj
default:
err = MalVal.MalString(String(exc))
}
return try EVAL(a22, Env(env, binds: list([a21]),
exprs: list([err])))
default: true // fall through
}
default: true // fall through
}
}
throw exc
}
case MalVal.MalSymbol("do"):
let slc = lst[1..<lst.endIndex.predecessor()]
try eval_ast(list(Array(slc)), env)
ast = lst[lst.endIndex.predecessor()] // TCO
case MalVal.MalSymbol("if"):
switch try EVAL(lst[1], env) {
case MalVal.MalFalse, MalVal.MalNil:
if lst.count > 3 {
ast = lst[3] // TCO
} else {
return MalVal.MalNil
}
default:
ast = lst[2] // TCO
}
case MalVal.MalSymbol("fn*"):
return malfunc( {
return try EVAL(lst[2], Env(env, binds: lst[1],
exprs: list($0)))
}, ast:[lst[2]], env:env, params:[lst[1]])
default:
switch try eval_ast(ast, env) {
case MalVal.MalList(let elst, _):
switch elst[0] {
case MalVal.MalFunc(let fn, nil, _, _, _, _):
let args = Array(elst[1..<elst.count])
return try fn(args)
case MalVal.MalFunc(_, let a, let e, let p, _, _):
let args = Array(elst[1..<elst.count])
env = try Env(e, binds: p![0],
exprs: list(args)) // TCO
ast = a![0] // TCO
default:
throw MalError.General(msg: "Cannot apply on '\(elst[0])'")
}
default: throw MalError.General(msg: "Invalid apply")
}
}
default:
throw MalError.General(msg: "Invalid apply")
}
}
}
// print
func PRINT(exp: MalVal) -> String {
return pr_str(exp, true)
}
// repl
func rep(str:String) throws -> String {
return PRINT(try EVAL(try READ(str), repl_env))
}
var repl_env: Env = try Env()
// core.swift: defined using Swift
for (k, fn) in core_ns {
try repl_env.set(MalVal.MalSymbol(k), malfunc(fn))
}
try repl_env.set(MalVal.MalSymbol("eval"),
malfunc({ try EVAL($0[0], repl_env) }))
let pargs = Process.arguments.map { MalVal.MalString($0) }
// TODO: weird way to get empty list, fix this
var args = pargs[pargs.startIndex..<pargs.startIndex]
if pargs.startIndex.advancedBy(2) < pargs.endIndex {
args = pargs[pargs.startIndex.advancedBy(2)..<pargs.endIndex]
}
try repl_env.set(MalVal.MalSymbol("*ARGV*"), list(Array(args)))
// core.mal: defined using the language itself
try rep("(def! *host-language* \"swift\")")
try rep("(def! not (fn* (a) (if a false true)))")
try rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))")
try rep("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))")
try rep("(def! *gensym-counter* (atom 0))")
try rep("(def! gensym (fn* [] (symbol (str \"G__\" (swap! *gensym-counter* (fn* [x] (+ 1 x)))))))")
try rep("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) (let* (condvar (gensym)) `(let* (~condvar ~(first xs)) (if ~condvar ~condvar (or ~@(rest xs)))))))))")
if Process.arguments.count > 1 {
try rep("(load-file \"" + Process.arguments[1] + "\")")
exit(0)
}
while true {
print("user> ", terminator: "")
let line = readLine(stripNewline: true)
if line == nil { break }
if line == "" { continue }
do {
print(try rep(line!))
} catch (MalError.Reader(let msg)) {
print("Error: \(msg)")
} catch (MalError.General(let msg)) {
print("Error: \(msg)")
}
}
| mpl-2.0 | fa9465d8f4f97f869b797b49b9c6ff54 | 34.018116 | 189 | 0.490119 | 3.944898 | false | false | false | false |
kamawshuang/iOS9--Study | iOS9-CoreSpotlight(一)/iOS9-CoreSpotlight/iOS9-CoreSpotlight/ListTableViewController.swift | 1 | 1968 | //
// ListTableViewController.swift
// iOS9-CoreSpotlight
//
// Created by 51Testing on 15/11/11.
// Copyright © 2015年 HHW. All rights reserved.
//
import UIKit
class ListTableViewController: UITableViewController {
let dataSource = DataSource()
var lastSelectPeople: PersonModel?
override func viewDidLoad() {
super.viewDidLoad()
//测试保存一些数据
dataSource.savePeopleToIndex()
tableView.rowHeight = 80
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let destination = segue.destinationViewController as! ViewController
destination.showPerson = lastSelectPeople!
}
func showPerson(id: String) {
lastSelectPeople = dataSource.friendFromID(id)
performSegueWithIdentifier("showInfo", sender: self)
}
}
extension ListTableViewController {
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.peopleArray.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let people = dataSource.peopleArray[indexPath.row]
cell.textLabel!.text = people.name
cell.imageView?.image = people.image
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectIndex = tableView.indexPathForSelectedRow?.row
lastSelectPeople = dataSource.peopleArray[selectIndex!]
//在StoryBoard 中设置过跳转但是无效,再次设置跳转的Indentifier;
performSegueWithIdentifier("showInfo", sender: self)
}
}
| apache-2.0 | 30848cb7f6ef935c8e76e1af0f957036 | 27.954545 | 118 | 0.694924 | 5.308333 | false | false | false | false |
radu-costea/ATests | ATests/ATests/UI/ValidationFormViewController.swift | 1 | 1652 | //
// ValidationFormViewController.swift
// ATests
//
// Created by Radu Costea on 12/04/16.
// Copyright © 2016 Radu Costea. All rights reserved.
//
import UIKit
import Parse
class ValidationFormViewController: BaseViewController, ValidationTextFieldDelegate {
lazy var bindings: [ValidationTextField: FieldValidationViewModel] = self.createBindings()
lazy var viewModels: [FieldValidationViewModel] = self.createViewModels()
var formIsValid: Bool { return viewModels.reduce(true){ $0 && $1.isValid } }
// MARK: - Validation text field delegate
func validationFieldTextDidChanged(validationField: ValidationTextField) {
if var vm = bindings[validationField] {
vm.textTouched = true
vm.text = validationField.text
syncField(validationField, withViewModel: vm)
}
}
func validationFieldTextDidEndEditing(validationField: ValidationTextField) {
if var vm = bindings[validationField] {
vm.textTouched = true
syncField(validationField, withViewModel: vm)
}
}
func validationFieldTextDidBeginEditing(validationField: ValidationTextField) { }
// MARK: - TO Override
func createBindings() -> [ValidationTextField: FieldValidationViewModel] { return [:] }
func createViewModels() -> [FieldValidationViewModel] { return [] }
// MARK: - Helper methods
private func syncField(field: ValidationTextField, withViewModel model: FieldValidationViewModel) -> Void {
field.setValidationIconVisible(model.textTouched)
field.setTextIsValid(model.isValid)
}
} | mit | 4b6da2365efd047cefb49f166d4a2271 | 34.913043 | 111 | 0.69473 | 5.224684 | false | false | false | false |
paul8263/ImageBoardBrowser | ImageBoardBrowser/AppDelegate.swift | 1 | 2835 | //
// AppDelegate.swift
// ImageBoardBrowser
//
// Created by Paul Zhang on 4/12/2016.
// Copyright © 2016 Paul Zhang. All rights reserved.
//
import UIKit
import AFNetworking
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
private func blurWindow() {
let blurEffect = UIBlurEffect(style: .light)
let visualEffectView = UIVisualEffectView(effect: blurEffect)
visualEffectView.frame = window!.frame
visualEffectView.tag = 10000
window?.addSubview(visualEffectView)
}
private func restoreWindow() {
window?.viewWithTag(10000)?.removeFromSuperview()
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
AFNetworkActivityIndicatorManager.shared().isEnabled = true
AFNetworkReachabilityManager.shared().startMonitoring()
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.
blurWindow()
}
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.
restoreWindow()
}
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.
restoreWindow()
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | d6e478b40f6c333d66ab8162f4843322 | 41.939394 | 285 | 0.726535 | 5.807377 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.