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
JerrySir/YCOA
YCOA/Main/Notice/Controller/NoticeDetailTableViewController.swift
1
6995
// // NoticeDetailTableViewController.swift // YCOA // // Created by Jerry on 2017/1/24. // Copyright © 2017年 com.baochunsteel. All rights reserved. // import UIKit class NoticeDetailVC_TableViewCell: UITableViewCell { private var titleLabel: UILabel! private var timeLabel: UILabel! private var authorLabel: UILabel! private var contentLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) self.selectionStyle = .none self.titleLabel = UILabel() self.titleLabel.font = UIFont.systemFont(ofSize: 22) self.titleLabel.textColor = UIColor.darkText self.titleLabel.numberOfLines = 0 self.contentView.addSubview(self.titleLabel) self.timeLabel = UILabel() self.timeLabel.font = UIFont.systemFont(ofSize: 15) self.timeLabel.textColor = UIColor.lightGray self.contentView.addSubview(self.timeLabel) self.authorLabel = UILabel() self.authorLabel.font = UIFont.systemFont(ofSize: 17) self.authorLabel.textColor = UIColor.darkText self.contentView.addSubview(self.authorLabel) self.contentLabel = UILabel() self.contentLabel.font = UIFont.systemFont(ofSize: 16) self.contentLabel.textColor = UIColor.darkText self.contentLabel.numberOfLines = 0 self.contentView.addSubview(self.contentLabel) let dividingLineView = UIView() dividingLineView.backgroundColor = UIColor.lightGray self.contentView.addSubview(dividingLineView) // AutoLayout self.titleLabel.snp.makeConstraints { (make) in make.left.equalTo(8) make.top.equalTo(10) make.right.equalTo(-8) } self.timeLabel.snp.makeConstraints { (make) in make.left.equalTo(8) make.top.equalTo(self.titleLabel.snp.bottom).offset(10) } self.authorLabel.snp.makeConstraints { (make) in make.left.equalTo(self.timeLabel.snp.right).offset(8) make.centerY.equalTo(self.timeLabel.snp.centerY) } dividingLineView.snp.makeConstraints { (make) in make.left.equalTo(8) make.right.equalTo(-8) make.top.equalTo(self.timeLabel.snp.bottom).offset(8) make.height.equalTo(1) } self.contentLabel.snp.makeConstraints { (make) in make.left.equalTo(8) make.right.equalTo(-8) make.top.equalTo(dividingLineView.snp.bottom).offset(8) make.bottom.equalTo(-8) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } open func configure(title: String, time: String, author: String, content: String ) { self.titleLabel.text = title self.timeLabel.text = time self.authorLabel.text = author self.contentLabel.text = content } } class NoticeDetailTableViewController: UITableViewController { private var id_ = "" private var data: (title: String, time: String, author: String, content: String)? override func viewDidLoad() { super.viewDidLoad() self.title = "公告详情" self.tableView.register(NoticeDetailVC_TableViewCell.self, forCellReuseIdentifier: "NoticeDetailVC_TableViewCell") self.tableView.separatorStyle = .none self.tableView.bounces = false self.reloadDataFromServer() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } open func configure(id: String) { self.id_ = id } private func reloadDataFromServer() { let parameters = ["adminid": UserCenter.shareInstance().uid!, "timekey": NSDate.nowTimeToTimeStamp(), "token": UserCenter.shareInstance().token!, "cfrom": "appiphone", "appapikey": UserCenter.shareInstance().apikey!, "id": (id_ as NSString).intValue] as [String : Any] YCOA_NetWork.get(url: "/index.php?d=taskrun&m=gong|appapi&a=viewinfor&ajaxbool=true", parameters: parameters) { (error, returnValue) in guard error == nil else{ self.navigationController?.view.jrShow(withTitle: error!.domain) return } guard let dataDic = (returnValue as! NSDictionary).value(forKey: "data") as? NSDictionary else{ self.navigationController?.view.jrShow(withTitle: "暂无数据") return } guard dataDic.count > 0 else{ self.navigationController?.view.jrShow(withTitle: "暂无数据") return } //同步数据 self.data = (dataDic["title"] as! String, dataDic["indate"] as! String, dataDic["optname"] as! String, dataDic["content"] as! String) self.tableView.reloadData() } } // MARK: - Table view data source override func numberOfSections(in tableView: UITableView) -> Int { // #warning Incomplete implementation, return the number of sections return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.data == nil ? 0 : 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell: NoticeDetailVC_TableViewCell = tableView.dequeueReusableCell(withIdentifier: "NoticeDetailVC_TableViewCell", for: indexPath) as! NoticeDetailVC_TableViewCell cell.configure(title: self.data!.title, time: self.data!.time, author: self.data!.author, content: self.data!.content) return cell } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return tableView.fd_heightForCell(withIdentifier: "NoticeDetailVC_TableViewCell", cacheBy: indexPath, configuration: { (cell) in (cell as! NoticeDetailVC_TableViewCell).configure(title: self.data!.title, time: self.data!.time, author: self.data!.author, content: self.data!.content) }) } }
mit
987e2977427921aa221077ca09381109
35.25
175
0.608908
4.911785
false
false
false
false
EvsenevDev/SmartReceiptsiOS
SmartReceipts/Modules/Graphs/DataSets/GraphsPaymentMethodsDataSet.swift
2
1473
// // GraphsPaymentMethodsDataSet.swift // SmartReceipts // // Created by Bogdan Evsenev on 06.05.2020. // Copyright © 2020 Will Baumann. All rights reserved. // import Foundation import Charts struct GraphsPaymentMethodDataSet: ChartDataSetProtocol { let data: [GraphsPaymentMethodData] let xLabels: [String] let entries: [ChartDataEntry] let chartType: ChartType = .barChart var title: String { return LocalizedString("column_item_payment_method") } init(data: [GraphsPaymentMethodData], maxCount: Int = 5) { self.data = data var filteredDataSets = data .sorted(by: { $0.total.amount.doubleValue > $1.total.amount.doubleValue }) .filter { $0.total.amount.doubleValue != 0 } if filteredDataSets.count > maxCount { filteredDataSets = Array(filteredDataSets[..<maxCount]) } self.entries = filteredDataSets .enumerated() .map { index, dataSet in return BarChartDataEntry(x: Double(index), y: dataSet.total.amount.doubleValue) } self.xLabels = filteredDataSets.reduce([String]()) { result, dataSet -> [String] in return result.adding(dataSet.paymentMethod.presentedValue()) } } } extension GraphsPaymentMethodDataSet { struct GraphsPaymentMethodData { let paymentMethod: PaymentMethod let total: Price } }
agpl-3.0
8d028ec2e22edb0823dfa8c48d09f163
28.44
95
0.631793
4.61442
false
false
false
false
Antondomashnev/Sourcery
SourceryTests/Stub/Performance-Code/Kiosk/App/Models/Bid.swift
2
463
import Foundation import SwiftyJSON final class Bid: NSObject, JSONAbleType { let id: String let amountCents: Int init(id: String, amountCents: Int) { self.id = id self.amountCents = amountCents } static func fromJSON(_ json: [String: Any]) -> Bid { let json = JSON(json) let id = json["id"].stringValue let amount = json["amount_cents"].int return Bid(id: id, amountCents: amount!) } }
mit
9ce92bf043b727912e6223a7b80fd402
22.15
56
0.606911
3.957265
false
false
false
false
inamiy/VTree
Tests/ApplySpec.swift
1
5979
#if os(iOS) || os(tvOS) @testable import VTree import Quick import Nimble class ApplySpec: QuickSpec { override func spec() { describe("apply") { let defaultChildren: [AnyVTree<NoMsg>] = [ *VView(key: key1), *VView(key: key2), *VLabel(text: "1") ] it("no diff") { let tree1 = VView(children: defaultChildren) let tree2 = VView(children: defaultChildren) let view1 = tree1.createView() let patch = diff(old: tree1, new: tree2) let view2 = apply(patch: patch, to: view1) expect(view2) == view1 // reuse } it("root type changed -> new view") { let tree1 = VView(children: defaultChildren) let tree2 = VImageView(children: defaultChildren) let view1 = tree1.createView() let patch = diff(old: tree1, new: tree2) let view2 = apply(patch: patch, to: view1) expect(view2).notTo(beNil()) expect(view2) != view1 // replaced } it("root property (value type) changed") { let tree1 = VView(styles: VViewStyles { $0.isHidden = false }, children: defaultChildren) let tree2 = VView(styles: VViewStyles { $0.isHidden = true }, children: defaultChildren) let view1 = tree1.createView() let patch = diff(old: tree1, new: tree2) let view2 = apply(patch: patch, to: view1) expect(view2) == view1 // reuse } it("root property (value type) changed to nil") { let tree1 = VLabel<NoMsg>(text: "hello") let tree2 = VLabel<NoMsg>(text: nil) let view1 = tree1.createView() expect(view1.text) == "hello" let patch = diff(old: tree1, new: tree2) let view2 = apply(patch: patch, to: view1) as! Label expect(view2) == view1 // reuse expect(view2.text).to(beNil()) } it("root property (reference type) changed") { let tree1 = VView<NoMsg>(styles: VViewStyles { $0.backgroundColor = .white }) let tree2 = VView<NoMsg>(styles: VViewStyles { $0.backgroundColor = .black }) let view1 = tree1.createView() expect(view1.backgroundColor) == .white let patch = diff(old: tree1, new: tree2) let view2 = apply(patch: patch, to: view1) expect(view2) == view1 // reuse expect(view2?.backgroundColor) == .black } it("root property (reference type) changed to nil") { let tree1 = VView<NoMsg>(styles: VViewStyles { $0.backgroundColor = .white }) let tree2 = VView<NoMsg>(styles: VViewStyles { $0.backgroundColor = nil }) let view1 = tree1.createView() expect(view1.backgroundColor) == .white let patch = diff(old: tree1, new: tree2) let view2 = apply(patch: patch, to: view1) expect(view2) == view1 // reuse expect(view2?.backgroundColor).to(beNil()) } it("child type changed") { let tree1 = VView<NoMsg>(children: [ *VView(key: key1), *VView(key: key2), *VLabel(text: "1") ]) let tree2 = VView<NoMsg>(children: [ *VView(key: key1), *VView(key: key2), *VImageView() ]) let view1 = tree1.createView() expect(view1.subviews[2] as? ImageView).to(beNil()) let patch = diff(old: tree1, new: tree2) let view2 = apply(patch: patch, to: view1) expect(view2) == view1 // reuse expect(view1.subviews[2] as? ImageView).notTo(beNil()) } it("child property changed") { let tree1 = VView<NoMsg>(children: [ *VView(key: key1), *VView(key: key2), *VLabel(text: "1") ]) let tree2 = VView<NoMsg>(children: [ *VView(key: key1), *VView(key: key2), *VLabel(text: "2") ]) let view1 = tree1.createView() let label1 = view1.subviews[2] as! Label expect(label1.text) == "1" let patch = diff(old: tree1, new: tree2) let view2 = apply(patch: patch, to: view1) let label2 = view2!.subviews[2] as! Label expect(view2) == view1 // reuse expect(label2) == label1 // reuse expect(label2.text) == "2" } it("child reordered") { let tree1 = VView<NoMsg>(children: [ *VView(key: key1), *VView(key: key2), *VLabel(text: "1") ]) let tree2 = VView<NoMsg>(children: [ *VView(key: key2), *VView(key: key1), *VLabel(text: "1") ]) let view1 = tree1.createView() let subview0 = view1.subviews[0] let subview1 = view1.subviews[1] let patch = diff(old: tree1, new: tree2) let view2 = apply(patch: patch, to: view1) expect(view2) == view1 // reuse expect(view2?.subviews[0]) == subview1 // reuse expect(view2?.subviews[1]) == subview0 // reuse } } } } #endif
mit
c8f2ac98929ed5ea782480893edbf4dd
31.145161
105
0.460947
4.23742
false
false
false
false
Eonil/SQLite3
Sources/HighLevel/TableCollection.swift
2
3613
// // TableCollection.swift // EonilSQLite3 // // Created by Hoon H. on 11/2/14. // // import Foundation /// `TableCollection` is a utility helper to iterate table. /// Users are responsible to keep table object alive. /// It keeps weak links to instantiated tables. /// And use them to provide sole instance for same table name. /// /// DDL operations are not supported in this object. Schema /// must not be mutated while accessing data. /// See `Connection.schema` for that. public final class TableCollection: SequenceType { unowned let owner:Database // private var _linkmap = [:] as [String:()->Table?] private var _links = [] as [()->Table?] //// init(owner:Database) { self.owner = owner } deinit { _assertNoDeadLinks() assert(_links.count == 0, "You're deinitialising a `TableCollection` (or `Database`) object while there're some live `Table` object. Kill the tables first before deinitialising `TableCollection` or `Database`.") } //// public var database:Database { get { return owner } } public func generate() -> GeneratorOf<Table> { _assertNoDeadLinks() let rs = database.connection.prepare("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;").execute().allDictionaries() var g1 = rs.generate() return GeneratorOf { if let r = g1.next() { let n = r["name"]! return Table(owner: self, name: n.text!) } return nil } } public var count:Int { get { return _countAllTablesInCurrentDatabase() } } public subscript(name:String) -> Table { get { _assertNoDeadLinks() let t1 = _findInLinksByName(name) ||| _makeAndLinkTableForNameIfExists(name)! return t1 } } //// internal var links:[()->Table?] { get { return _links } } internal func registerByBornOfTable(t:Table) { _assertNoDeadLinks() _links.append(linkWeakly(t)) } internal func unregisterByDeathOfTable(t:Table) { // Weak references becomes nil before `deinit` of the object to be called. // Then, just remove dead links like collecting garbages. _links = _links.filter {$0() != nil && $0()! !== t} _assertNoDeadLinks() } //// private func _assertNoDeadLinks() { assert(_links.filter {$0() == nil}.count == 0, "We have some dead links to some `Table` objects. This shouldn't happen.") } private func _makeAndLinkTableForNameIfExists(name:String) -> Table? { let ok = _checkTableExistenceOnDatabase(name) if ok { return Table(owner: self, name: name) } else { return nil } } private func _findInLinksByName(name:String) -> Table? { let a = _links.filter {$0()!.info.name == name} assert(a.count <= 1) return a.first?() } private func _checkTableExistenceOnDatabase(name:String) -> Bool { return filter(_generateAllTableNamesInCurrentDatabase(), {$0 == name}).count > 0 } private func _generateAllTableNamesInCurrentDatabase() -> GeneratorOf<String> { // let rs = database.compile("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name;").execute().allDictionaries() let s = database.compile("SELECT name FROM sqlite_master WHERE type='table';") let rs = s.execute().allDictionaries() var g1 = rs.generate() return GeneratorOf { if let r = g1.next() { return r["name"]!.text! } return nil } } private func _countAllTablesInCurrentDatabase() -> Int { let rs = database.compile("SELECT count(*) FROM sqlite_master WHERE type='table';").execute().allArrays() assert(rs.count == 1) let r = rs[0] assert(r.count == 1) return Int(r[0].integer!) } }
mit
61625d263bb1f134a0dccafc68a4b9b6
20.505952
213
0.659563
3.155459
false
false
false
false
ObjSer/objser-swift
ObjSer/util/FloatType.swift
1
3612
// // FloatType.swift // ObjSer // // The MIT License (MIT) // // Copyright (c) 2015 Greg Omelaenko // // 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(iOS) import CoreGraphics #endif public protocol FloatType : NumericType, Comparable, Equatable, Hashable { init<T: FloatType>(_ v: T) init(_ v: Float32) init(_ v: Float64) init(_ v: CGFloat) } extension FloatType { public init<T : FloatType>(_ v: T) { switch v { case let v as Float32: self = Self(v) case let v as Float64: self = Self(v) case let v as CGFloat: self = Self(v) default: preconditionFailure("Unrecognised FloatType type \(T.self).") } } } extension Float32: FloatType { } extension Float64: FloatType { } extension CGFloat: FloatType { } /// A type-erased float. public struct AnyFloat { private enum Box { case Single(Float32) case Double(Float64) } private let box: Box public init<T : FloatType>(_ v: T) { switch v { case let v as AnyFloat: self = v case let v as Float32: box = .Single(v) case let v as Float64: box = .Double(v) case let v as CGFloat: self = AnyFloat(v.native) default: preconditionFailure("Unrecognised FloatType type \(T.self).") } } public var exactFloat32Value: Float32? { guard case .Single(let v) = box else { return nil } return v } } extension FloatType { public init(_ v: AnyFloat) { switch v.box { case .Single(let v): self.init(v) case .Double(let v): self.init(v) } } } extension AnyFloat : Hashable { public var hashValue: Int { switch box { case .Single(let v): return v.hashValue case .Double(let v): return v.hashValue } } } public func ==(a: AnyFloat, b: AnyFloat) -> Bool { switch (a.box, b.box) { case (.Single(let a), .Single(let b)): return a == b case (.Double(let a), .Double(let b)): return a == b case (.Single(let a), .Double(let b)): return Float64(a) == b case (.Double(let a), .Single(let b)): return a == Float64(b) } } public func <(a: AnyFloat, b: AnyFloat) -> Bool { switch (a.box, b.box) { case (.Single(let a), .Single(let b)): return a < b case (.Double(let a), .Double(let b)): return a < b case (.Single(let a), .Double(let b)): return Float64(a) < b case (.Double(let a), .Single(let b)): return a < Float64(b) } } extension AnyFloat : Equatable, Comparable { }
mit
e512e8ef5b2876a95deb42fcb855c776
27.440945
82
0.631506
3.697032
false
false
false
false
tominated/Quake-3-BSP-Renderer
Quake 3 BSP Renderer/Q3Map.swift
1
9362
// // Q3Map.swift // Quake 3 BSP Renderer // // Created by Thomas Brunoli on 13/01/2016. // Copyright © 2016 Thomas Brunoli. All rights reserved. // import Foundation import simd private struct Q3DirectoryEntry { var offset: Int32 var length: Int32 } private struct Q3PolygonFace { let indices: Array<UInt32> init(meshverts: [UInt32], firstVertex: Int, firstMeshvert: Int, meshvertCount: Int) { let meshvertIndices = firstMeshvert..<(firstMeshvert + meshvertCount) indices = meshvertIndices.map { meshverts[$0] + UInt32(firstVertex) } } } private struct Q3PatchFace { var vertices: Array<Q3Vertex> = [] fileprivate var indices: Array<UInt32> = [] init(vertices: Array<Q3Vertex>, firstVertex: Int, vertexCount: Int, size: (Int, Int)) { let numPatchesX = ((size.0) - 1) / 2 let numPatchesY = ((size.1) - 1) / 2 let numPatches = numPatchesX * numPatchesY for patchNumber in 0..<numPatches { // Find the x & y of this patch in the grid let xStep = patchNumber % numPatchesX let yStep = patchNumber / numPatchesX // Initialise the vertex grid var vertexGrid: [[Q3Vertex]] = Array( repeating: Array( repeating: Q3Vertex(), count: Int(size.1) ), count: Int(size.0) ) var gridX = 0 var gridY = 0 for index in firstVertex..<(firstVertex + vertexCount) { // Place the vertices from the face in the vertex grid vertexGrid[gridX][gridY] = vertices[index] gridX += 1 if gridX == Int(size.0) { gridX = 0 gridY += 1 } } let vi = 2 * xStep let vj = 2 * yStep var controlVertices: [Q3Vertex] = [] for i in 0..<3 { for j in 0..<3 { controlVertices.append(vertexGrid[Int(vi + j)][Int(vj + i)]) } } let bezier = Bezier(controls: controlVertices) self.indices.append( contentsOf: bezier.indices.map { i in i + UInt32(self.vertices.count) } ) self.vertices.append(contentsOf: bezier.vertices) } } func offsetIndices(_ offset: UInt32) -> Array<UInt32> { return self.indices.map { $0 + offset } } } // Encapsulates the reading of graphics data from a Quake 3 BSP. // Reads vertices, faces, texture and lightmap data from the map and turns them // in to a format to easily consume in a modern graphics API. // Performs tessellation on bezier patch faces and integrates them with all of // the other face vertices and index arrays class Q3Map { var entities: Array<Dictionary<String, String>> = [] var vertices: Array<Q3Vertex> = [] var faces: Array<Q3Face> = [] var textureNames: Array<String> = [] var lightmaps: Array<Q3Lightmap> = [] fileprivate var buffer: BinaryReader fileprivate var directoryEntries: Array<Q3DirectoryEntry> = [] fileprivate var meshverts: Array<UInt32> = [] // Read the map data from an NSData buffer containing the bsp file init(data: Data) { buffer = BinaryReader(data: data) readHeaders() entities = readEntities() textureNames = readTextureNames() vertices = readVertices() meshverts = readMeshverts() lightmaps = readLightmaps() faces = readFaces() } fileprivate func readHeaders() { // Magic should always equal IBSP for Q3 maps let magic = buffer.getASCII(4)! assert(magic == "IBSP", "Magic must be equal to \"IBSP\"") // Version should always equal 0x2e for Q3 maps let version = buffer.getInt32() assert(version == 0x2e, "Version must be equal to 0x2e") // Directory entries define the position and length of a section for _ in 0..<17 { let entry = Q3DirectoryEntry(offset: buffer.getInt32(), length: buffer.getInt32()) directoryEntries.append(entry) } } fileprivate func readEntities() -> Array<Dictionary<String, String>> { let entry = directoryEntries[0] buffer.jump(Int(entry.offset)) let entities = buffer.getASCII(Int(entry.length)) let parser = Q3EntityParser(entitiesString: entities! as String) return parser.parse() } fileprivate func readTextureNames() -> Array<String> { return readEntry(1, length: 72) { buffer in return buffer.getASCIIUntilNull(64) } } fileprivate func readVertices() -> Array<Q3Vertex> { return readEntry(10, length: 44) { buffer in let position = self.swizzle(float4(buffer.getFloat32(), buffer.getFloat32(), buffer.getFloat32(), 1.0)) let textureCoord = float2(buffer.getFloat32(), buffer.getFloat32()) let lightmapCoord = float2(buffer.getFloat32(), buffer.getFloat32()) let normal = self.swizzle(float4(buffer.getFloat32(), buffer.getFloat32(), buffer.getFloat32(), 1.0)) let r = Float(buffer.getUInt8()) / 255 let g = Float(buffer.getUInt8()) / 255 let b = Float(buffer.getUInt8()) / 255 let a = Float(buffer.getUInt8()) / 255 let color = float4(r, g, b, a) return Q3Vertex( position: position, normal: normal, color: color, textureCoord: textureCoord, lightmapCoord: lightmapCoord ) } } fileprivate func readMeshverts() -> Array<UInt32> { return readEntry(11, length: 4) { buffer in return UInt32(buffer.getInt32()) } } fileprivate func readLightmaps() -> Array<Q3Lightmap> { return readEntry(14, length: 128 * 128 * 3) { buffer in var lm: Q3Lightmap = [] for _ in 0..<(128 * 128) { lm.append((buffer.getUInt8(), buffer.getUInt8(), buffer.getUInt8(), 255)) } return lm } } fileprivate func readFaces() -> Array<Q3Face> { return readEntry(13, length: 104) { buffer in let textureIndex = Int(buffer.getInt32()) buffer.skip(4) // effect let type = Q3FaceType(rawValue: Int(buffer.getInt32()))! let firstVertex = Int(buffer.getInt32()) let vertexCount = Int(buffer.getInt32()) let firstMeshvert = Int(buffer.getInt32()) let meshvertCount = Int(buffer.getInt32()) let lightmapIndex = Int(buffer.getInt32()) buffer.skip(64) // Extranious lightmap info let patchSizeX = Int(buffer.getInt32()) let patchSizeY = Int(buffer.getInt32()) let textureName = self.textureNames[textureIndex] if type == .polygon || type == .mesh { let polygonFace = Q3PolygonFace( meshverts: self.meshverts, firstVertex: firstVertex, firstMeshvert: firstMeshvert, meshvertCount: meshvertCount ) return Q3Face( textureName: textureName, lightmapIndex: lightmapIndex, vertexIndices: polygonFace.indices ) } else if type == .patch { let patchFace = Q3PatchFace( vertices: self.vertices, firstVertex: firstVertex, vertexCount: vertexCount, size: (patchSizeX, patchSizeY) ) // The indices for a patch will be for it's own vertices. // Offset them by the amount of vertices in the map, then add // the patch's own vertices to the list let indices = patchFace.offsetIndices(UInt32(self.vertices.count)) self.vertices.append(contentsOf: patchFace.vertices) return Q3Face( textureName: textureName, lightmapIndex: lightmapIndex, vertexIndices: indices ) } return nil } } fileprivate func readEntry<T>(_ index: Int, length: Int, each: (BinaryReader) -> T?) -> Array<T> { let entry = directoryEntries[index] let itemCount = Int(entry.length) / length var accumulator: Array<T> = [] for i in 0..<itemCount { buffer.jump(Int(entry.offset) + (i * length)) if let value = each(buffer) { accumulator.append(value) } } return accumulator } fileprivate func swizzle(_ v: float3) -> float3 { return float3(v.x, v.z, -v.y) } fileprivate func swizzle(_ v: float4) -> float4 { return float4(v.x, v.z, -v.y, 1) } }
mit
6ac323847499360f30a4ecbef7bc2cf4
34.458333
115
0.542998
4.432292
false
false
false
false
NghiaTranUIT/Titan
TitanCore/TitanCore/TextFieldCellView.swift
2
2018
// // DatabaseValueCell.swift // Titan // // Created by Nghia Tran on 2/12/17. // Copyright © 2017 fe. All rights reserved. // import Cocoa import SwiftyPostgreSQL import SnapKit open class TextFieldCellView: BaseTableCellView { // // MARK: - Init required public init(frame frameRect: NSRect) { super.init(frame: frameRect) // Setup layout self.setupLayout() } required public init?(coder: NSCoder) { super.init(coder: coder) // Setup layout self.setupLayout() } override open func becomeFirstResponder() -> Bool { self.textField?.becomeFirstResponder() return super.becomeFirstResponder() } // // MARK: - Public public func configureCell(with field: Field, column: Column) { guard let textField = self.textField else {return} // Show raw data if field.isNull { textField.placeholderString = field.rawData textField.stringValue = "" } else { textField.stringValue = field.rawData } // Layout self.setupTextAlignment(with: column) } } // // MARK: - Private extension TextFieldCellView { fileprivate func setupLayout() { let textField = NSTextField(frame: NSRect.zero) textField.maximumNumberOfLines = 2 textField.isBordered = false textField.drawsBackground = false textField.cell?.sendsActionOnEndEditing = true textField.translatesAutoresizingMaskIntoConstraints = false textField.lineBreakMode = .byTruncatingTail self.addSubview(textField) textField.snp.makeConstraints { (make) in make.edges.equalTo(self).inset(EdgeInsets(top: 0, left: 4, bottom: 0, right: 4)) } self.textField = textField } fileprivate func setupTextAlignment(with column: Column) { self.textField?.alignment = column.textAlignment } }
mit
a510ed927e9a08ed4e54ac47f1cdbb30
24.858974
92
0.616758
4.980247
false
false
false
false
CartoDB/mobile-ios-samples
AdvancedMap.Swift/Feature Demo/VectorObjectEditingController.swift
1
2873
// // VectorObjectEditingController.swift // AdvancedMap.Swift // // Created by Aare Undo on 28/06/2017. // Copyright © 2017 CARTO. All rights reserved. // import Foundation import UIKit import CartoMobileSDK class VectorObjectEditingController : BaseController, VectorElementSelectDelegate, VectorElementDeselectDelegate, EditEventDelegate { var contentView: VectorObjectEditingView! var editListener: EditEventListener! var selectListener: VectorElementSelectListener! var deselectListener: VectorElementDeselectListener! override func viewDidLoad() { super.viewDidLoad() contentView = VectorObjectEditingView() view = contentView editListener = EditEventListener() editListener?.initialize() selectListener = VectorElementSelectListener() deselectListener = VectorElementDeselectListener() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) contentView.addRecognizers() contentView.editLayer.setVectorEditEventListener(editListener) selectListener?.delegate = self contentView.editLayer.setVectorElementEventListener(selectListener) deselectListener?.delegate = self contentView.map.setMapEventListener(deselectListener) let recognizer = UITapGestureRecognizer(target: self, action: #selector(self.deleteClick(_:))) contentView.trashCan.addGestureRecognizer(recognizer) contentView.addElements() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) contentView.removeRecognizers() contentView.editLayer.setVectorEditEventListener(nil) selectListener.delegate = nil contentView.editLayer.setVectorElementEventListener(nil) deselectListener.delegate = nil contentView.map.setMapEventListener(nil) contentView.trashCan.gestureRecognizers?.forEach(contentView.trashCan.removeGestureRecognizer) } @objc func deleteClick(_ sender: UITapGestureRecognizer) { contentView.editSource.remove(contentView.editLayer.getSelectedVectorElement()) } func selected(element: NTVectorElement) { contentView.editLayer.setSelectedVectorElement(element) DispatchQueue.main.async { self.contentView.trashCan.isHidden = false } } func deselect() { contentView.editLayer.setSelectedVectorElement(nil) DispatchQueue.main.async { self.contentView.trashCan.isHidden = true } } func onDelete(element: NTVectorElement) { contentView.editSource.remove(element) deselect() } }
bsd-2-clause
b5b9f126bf3e70352de60829bc5e4486
28.608247
133
0.679666
5.449715
false
false
false
false
bananafish911/SmartReceiptsiOS
SmartReceipts/Log/Logger.swift
1
5430
// // Logger.swift // SmartReceipts // // Created by Jaanus Siim on 31/05/16. // Copyright © 2016 Will Baumann. All rights reserved. // import Foundation import CocoaLumberjack.Swift /// Logger wrapper /// /// Notes: /// * iOS 10 CocoaLumberjack bug - all logs are duplicated, waiting for new release /// more info: https://github.com/CocoaLumberjack/CocoaLumberjack/issues/765 /// final class Logger: NSObject { private static let sharedInstance = Logger() private let fileLogger = DDFileLogger() // File logger instance // MARK: - /// Initial setup, call it if you want to enable logger private override init() { // Default level: // Variables are setted in Project Build Settings, “Swift Compiler – Custom Flags” section, “Other Swift Flags” // “-DDEBUG” to the Debug section // “-DRELEASE” to the Release section #if DEBUG defaultDebugLevel = .all #else defaultDebugLevel = .info #endif // custom formatter let formatter = DDLogCustomFormatter() // Loggers: // TTY = Xcode console if let ttyLogger = DDTTYLogger.sharedInstance { ttyLogger.logFormatter = formatter DDLog.add(ttyLogger, with: defaultDebugLevel) } // ASL = Apple System Logs if let aslLogger = DDASLLogger.sharedInstance { aslLogger.logFormatter = formatter DDLog.add(aslLogger, with: defaultDebugLevel) } // Persistent log file that saves up to 1MB of logs to disk, which can be attached as part of the support email. if let fileLogger = fileLogger { fileLogger.logFormatter = formatter fileLogger.rollingFrequency = 0 // no limits fileLogger.maximumFileSize = UInt64(1024 * 1024 * 1) // 1 MB fileLogger.logFileManager.maximumNumberOfLogFiles = 0 fileLogger.logFileManager.logFilesDiskQuota = UInt64(1024 * 1024 * 2) // quota is 2 MB max DDLog.add(fileLogger, with: defaultDebugLevel) } } /// Log files /// /// - Returns: An array of DDLogFileInfo instances class func logFiles() -> [DDLogFileInfo] { return sharedInstance.fileLogger?.logFileManager.sortedLogFileInfos ?? [] } // MARK: - Log levels /// Verbose logging /// /// - Parameters: /// - message: Descriptive message class func verbose(_ message: String, file: String = #file, function: String = #function, line: UInt = #line) { sharedInstance.logMacro(message: message, flag: .verbose, file: file, function: function, line: line) } /// Diagnosing details /// /// - Parameters: /// - message: Descriptive message class func debug(_ message: String, file: String = #file, function: String = #function, line: UInt = #line) { sharedInstance.logMacro(message: message, flag: .debug, file: file, function: function, line: line) } /// Confirmation, that things are working as expected /// /// - Parameters: /// - message: Descriptive message class func info(_ message: String, file: String = #file, function: String = #function, line: UInt = #line) { sharedInstance.logMacro(message: message, flag: .info, file: file, function: function, line: line) } /// An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. /// /// - Parameters: /// - message: Descriptive message class func warning(_ message: String, file: String = #file, function: String = #function, line: UInt = #line) { sharedInstance.logMacro(message: message, flag: .warning, file: file, function: function, line: line) } /// Due to a more serious problem, the software has not been able to perform some function. /// /// - Parameters: /// - message: Descriptive message class func error(_ message: String, file: String = #file, function: String = #function, line: UInt = #line) { sharedInstance.logMacro(message: message, flag: .error, file: file, function: function, line: line) } // MARK: - Private /// Log message constructor private func logMacro(message: String, flag: DDLogFlag, file: String, function: String, line: UInt) { let message = DDLogMessage(message: message, level: defaultDebugLevel, flag: flag, context: 0, file: file, function: function, line: line, tag: nil, options: [.copyFunction, .copyFile], timestamp: Date()) // The default philosophy for asynchronous logging is very simple: // Log messages with errors should be executed synchronously. // All other log messages, such as debug output, are executed asynchronously. let trueForErrors = (flag == DDLogFlag.error) ? true : false DDLog.log(asynchronous: trueForErrors, message: message) } }
agpl-3.0
79360e543a4b2023fa99556b2426fd47
38.467153
174
0.5946
4.70993
false
false
false
false
Elm-Tree-Island/Shower
Shower/Carthage/Checkouts/ReactiveCocoa/ReactiveCocoaTests/UIKit/UIActivityIndicatorViewSpec.swift
6
885
import Quick import Nimble import ReactiveSwift import ReactiveCocoa import Result class UIActivityIndicatorSpec: QuickSpec { override func spec() { var activityIndicatorView: UIActivityIndicatorView! weak var _activityIndicatorView: UIActivityIndicatorView? beforeEach { activityIndicatorView = UIActivityIndicatorView(frame: .zero) _activityIndicatorView = activityIndicatorView } afterEach { activityIndicatorView = nil expect(_activityIndicatorView).to(beNil()) } it("should accept changes from bindings to its animating state") { let (pipeSignal, observer) = Signal<Bool, NoError>.pipe() activityIndicatorView.reactive.isAnimating <~ SignalProducer(pipeSignal) observer.send(value: true) expect(activityIndicatorView.isAnimating) == true observer.send(value: false) expect(activityIndicatorView.isAnimating) == false } } }
gpl-3.0
f7ef488311205259f2420f3d7acef9b7
25.818182
75
0.770621
4.783784
false
false
false
false
christophhagen/Signal-iOS
Signal/src/environment/ExperienceUpgrades/ExperienceUpgradeFinder.swift
1
3929
// // Copyright (c) 2017 Open Whisper Systems. All rights reserved. // import Foundation import SignalServiceKit enum ExperienceUpgradeId: String { case videoCalling = "001", callKit = "002", introducingProfiles = "003", introducingReadReceipts = "004" } class ExperienceUpgradeFinder: NSObject { // MARK - Singleton class @objc(sharedManager) public static let shared = ExperienceUpgradeFinder() private override init() { super.init() SwiftSingletons.register(self) } var videoCalling: ExperienceUpgrade { return ExperienceUpgrade(uniqueId: ExperienceUpgradeId.videoCalling.rawValue, title: NSLocalizedString("UPGRADE_EXPERIENCE_VIDEO_TITLE", comment: "Header for upgrade experience"), body: NSLocalizedString("UPGRADE_EXPERIENCE_VIDEO_DESCRIPTION", comment: "Description of video calling to upgrading (existing) users"), image: #imageLiteral(resourceName: "introductory_splash_video_calling")) } var callKit: ExperienceUpgrade { return ExperienceUpgrade(uniqueId: ExperienceUpgradeId.callKit.rawValue, title: NSLocalizedString("UPGRADE_EXPERIENCE_CALLKIT_TITLE", comment: "Header for upgrade experience"), body: NSLocalizedString("UPGRADE_EXPERIENCE_CALLKIT_DESCRIPTION", comment: "Description of CallKit to upgrading (existing) users"), image: #imageLiteral(resourceName: "introductory_splash_callkit")) } var introducingProfiles: ExperienceUpgrade { return ExperienceUpgrade(uniqueId: ExperienceUpgradeId.introducingProfiles.rawValue, title: NSLocalizedString("UPGRADE_EXPERIENCE_INTRODUCING_PROFILES_TITLE", comment: "Header for upgrade experience"), body: NSLocalizedString("UPGRADE_EXPERIENCE_INTRODUCING_PROFILES_DESCRIPTION", comment: "Description of new profile feature for upgrading (existing) users"), image:#imageLiteral(resourceName: "introductory_splash_profile")) } var introducingReadReceipts: ExperienceUpgrade { return ExperienceUpgrade(uniqueId: ExperienceUpgradeId.introducingReadReceipts.rawValue, title: NSLocalizedString("UPGRADE_EXPERIENCE_INTRODUCING_READ_RECEIPTS_TITLE", comment: "Header for upgrade experience"), body: NSLocalizedString("UPGRADE_EXPERIENCE_INTRODUCING_READ_RECEIPTS_DESCRIPTION", comment: "Description of new profile feature for upgrading (existing) users"), image:#imageLiteral(resourceName: "introductory_splash_read_receipts")) } // Keep these ordered by increasing uniqueId. private var allExperienceUpgrades: [ExperienceUpgrade] { return [ // Disable old experience upgrades. Most people have seen them by now, and accomodating multiple makes layout harder. // Note if we ever want to show multiple experience upgrades again // we'll have to update the layout in ExperienceUpgradesPageViewController // // videoCalling, // (UIDevice.current.supportsCallKit ? callKit : nil), // introducingProfiles, introducingReadReceipts ].flatMap { $0 } } // MARK: - Instance Methods public func allUnseen(transaction: YapDatabaseReadTransaction) -> [ExperienceUpgrade] { return allExperienceUpgrades.filter { ExperienceUpgrade.fetch(uniqueId: $0.uniqueId!, transaction: transaction) == nil } } public func markAllAsSeen(transaction: YapDatabaseReadWriteTransaction) { Logger.info("\(logTag) marking experience upgrades as seen") allExperienceUpgrades.forEach { $0.save(with: transaction) } } }
gpl-3.0
8ae76c192c2b9001f2c0402b66f573d7
48.1125
195
0.666327
5.14941
false
false
false
false
MingLeiVV/MLEmoticon
MLEmoticon/MLEmoticon/MLEmoticonController.swift
1
6083
// // MLEmoticonController.swift // 表情排版 // // Created by 吴明磊 on 15/5/6. // Copyright © 2015年 wuminglei. All rights reserved. // import UIKit private let EmoticonCellIdentifier = "EmoticonCellIdentifier" class MLEmoticonController: UIViewController { let selectEmoticonCallBack : (emoticon : Emoticons?) ->() init(selectEmoticon : (emoticon : Emoticons?) ->()) { selectEmoticonCallBack = selectEmoticon super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupUI() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() let index = NSIndexPath(forItem: 0, inSection: 1) emoticonView.scrollToItemAtIndexPath(index, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true) } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } //MARK: 监听方法 func emoticonSwitch (sender : UIBarButtonItem) { let indexPath = NSIndexPath(forItem: 0, inSection: sender.tag) emoticonView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true) } //MARK: 设置UI private func setupUI () { view.addSubview(toolBar) view.addSubview(emoticonView) prepareTooBar() prepareCollectionView() toolBar.ff_AlignInner(type: ff_AlignType.BottomCenter, referView: view, size: CGSize(width: UIScreen.mainScreen().bounds.width, height: 49)) emoticonView.ff_AlignInner(type: ff_AlignType.TopLeft, referView: view, size: nil) emoticonView.ff_AlignVertical(type: ff_AlignType.TopRight, referView: toolBar, size: nil) } /// 准备toolBar private func prepareTooBar () { var item = [UIBarButtonItem]() var index = 0 for emoticons in emoticonPackage { let btn = UIBarButtonItem(title: emoticons.group_name_cn, style: UIBarButtonItemStyle.Plain, target: self, action: "emoticonSwitch:") btn.tag = index++ btn.tintColor = UIColor.lightGrayColor() item.append(btn) item.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil)) } item.removeLast() toolBar.items = item } /// 准备collectionView private func prepareCollectionView () { emoticonView.dataSource = self emoticonView.delegate = self emoticonView.registerClass(MLEmoticonCell.self, forCellWithReuseIdentifier: EmoticonCellIdentifier) } private lazy var emoticonPackage : [MLEmoticon] = MLEmoticon.emoticonPage private lazy var toolBar = UIToolbar() private lazy var emoticonView = UICollectionView(frame: CGRectZero, collectionViewLayout: MLCollectionFlowLayout()) private lazy var emoticonBtn : UIButton = UIButton() } //MARK: 自定义cell private class MLEmoticonCell : UICollectionViewCell{ var emoticons : Emoticons? { didSet{ setup() } } private func setup () { contentView.addSubview(emoticonBtn) emoticonBtn.ff_Fill(contentView) emoticonBtn.setImage(UIImage(named: emoticons!.imagePath!), forState: UIControlState.Normal) emoticonBtn.setTitle(emoticons!.emoj, forState: UIControlState.Normal) } private lazy var emoticonBtn : UIButton = { let btn = UIButton() btn.titleLabel?.font = UIFont.systemFontOfSize(32) btn.userInteractionEnabled = false return btn }() } //MARK: 扩展类、collectionview的数据源方法 extension MLEmoticonController : UICollectionViewDataSource,UICollectionViewDelegate { func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return emoticonPackage.count } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return emoticonPackage[section].emoticons?.count ?? 0 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCellIdentifier, forIndexPath: indexPath) as! MLEmoticonCell cell.emoticons = emoticonPackage[indexPath.section].emoticons?[indexPath.item] return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { let selectEmoticon = emoticonPackage[indexPath.section].emoticons?[indexPath.item] selectEmoticonCallBack(emoticon: selectEmoticon) if indexPath.section > 0 { MLEmoticon.addEmoticon(selectEmoticon!) } } } //MARK: 流式布局 private class MLCollectionFlowLayout : UICollectionViewFlowLayout { private override func prepareLayout() { let WH = UIScreen.mainScreen().bounds.width / 7 collectionView?.backgroundColor = UIColor.whiteColor() let set = (collectionView!.bounds.height - 3 * WH) * 0.499 itemSize = CGSize(width: WH, height: WH) scrollDirection = UICollectionViewScrollDirection.Horizontal collectionView?.showsHorizontalScrollIndicator = false collectionView?.contentInset = UIEdgeInsets(top: set, left: 0, bottom: set, right: 0) collectionView?.pagingEnabled = true minimumInteritemSpacing = 0 minimumLineSpacing = 0 } }
apache-2.0
cb910a341a9c9830681fe8ae0e1e6f09
29.06
148
0.646374
5.505495
false
false
false
false
vlevschanov/CheckRecognition
CheckRecognition/CheckRecognition/Model/CheckResult/CheckResultComponent.swift
1
1601
// // CheckResultComponent.swift // CheckRecognition // // Created by Viktor Levshchanov on 3/6/15. // Copyright (c) 2015 Viktor Levshchanov. All rights reserved. // import UIKit class CheckResultComponent: NSObject { private struct Static { static let nonDigitSet = NSCharacterSet(charactersInString: "0123456789. ").invertedSet // static let numberFormatter = Static.setupNumberFormatter() // // private static func setupNumberFormatter() -> NSNumberFormatter { // return NSNumberFormatter() // } } let confidence: Int let text: NSString let rect: CGRect var selected : Bool = false var digitValue : NSDecimalNumber? { get { let str = getCleanText().stringByReplacingOccurrencesOfString(" ", withString: "") return NSDecimalNumber(string: str) //return Static.numberFormatter.numberFromString(str) } } private var cleanText : NSString? init(text: NSString, rect: CGRect, confidence: Int) { self.text = text self.rect = rect self.confidence = confidence super.init() } func getCleanText() -> NSString { if cleanText == nil { cleanText = ((self.text as NSString).componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) as NSArray).componentsJoinedByString("") } return cleanText! } func isDigit() -> Bool { return getCleanText().rangeOfCharacterFromSet(Static.nonDigitSet).location == NSNotFound } }
apache-2.0
73de33b75764b44630e50608c9fa2cf8
28.109091
164
0.633979
4.987539
false
false
false
false
achiwhane/ReadHN
ReadHN/AskHNStoriesTableViewController.swift
1
1592
// // AskHNStoriesTableViewController.swift // ReadHN // // Created by Akshay Chiwhane on 8/8/15. // Copyright (c) 2015 Akshay Chiwhane. All rights reserved. // import UIKit class AskHNStoriesTableViewContoller: StoriesTableViewController{ override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) updateUI() } private func updateUI() { super.categoryUrl = "https://hacker-news.firebaseio.com/v0/askstories.json" super.brain.delegate = self super.refresh() } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { switch identifier { case "View AskHN Content": if let wvc = segue.destinationViewController as? WebViewController { if let cell = sender as? UITableViewCell { wvc.pageTitle = cell.textLabel?.text if let cellIndexPath = self.tableView.indexPathForCell(cell) { let data = Submission.loadSaved(storyTableCellData[cellIndexPath.row] ?? 0) wvc.pageUrl = data?.url print(wvc.pageUrl) } } } default: break } } } override func tableView(tableView: UITableView, accessoryButtonTappedForRowWithIndexPath indexPath: NSIndexPath) { performSegueWithIdentifier("View AskHN Content", sender: self) } }
mit
d3d55b1924c13aed4dc8b9d957cecf49
31.489796
118
0.584799
5.135484
false
false
false
false
yannickl/QRCodeReader.swift
Example/QRCodeReader.swift/ViewController.swift
1
5092
/* * QRCodeReader.swift * * Copyright 2014-present Yannick Loriot. * http://yannickloriot.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. * */ import AVFoundation import UIKit class ViewController: UIViewController, QRCodeReaderViewControllerDelegate { @IBOutlet weak var previewView: QRCodeReaderView! { didSet { previewView.setupComponents(with: QRCodeReaderViewControllerBuilder { $0.reader = reader $0.showTorchButton = false $0.showSwitchCameraButton = false $0.showCancelButton = false $0.showOverlayView = true $0.rectOfInterest = CGRect(x: 0.2, y: 0.2, width: 0.6, height: 0.6) }) } } lazy var reader: QRCodeReader = QRCodeReader() lazy var readerVC: QRCodeReaderViewController = { let builder = QRCodeReaderViewControllerBuilder { $0.reader = QRCodeReader(metadataObjectTypes: [.qr], captureDevicePosition: .back) $0.showTorchButton = true $0.preferredStatusBarStyle = .lightContent $0.showOverlayView = true $0.rectOfInterest = CGRect(x: 0.2, y: 0.2, width: 0.6, height: 0.6) $0.reader.stopScanningWhenCodeIsFound = false } return QRCodeReaderViewController(builder: builder) }() // MARK: - Actions private func checkScanPermissions() -> Bool { do { return try QRCodeReader.supportsMetadataObjectTypes() } catch let error as NSError { let alert: UIAlertController switch error.code { case -11852: alert = UIAlertController(title: "Error", message: "This app is not authorized to use Back Camera.", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Setting", style: .default, handler: { (_) in DispatchQueue.main.async { if let settingsURL = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.openURL(settingsURL) } } })) alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) default: alert = UIAlertController(title: "Error", message: "Reader not supported by the current device", preferredStyle: .alert) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) } present(alert, animated: true, completion: nil) return false } } @IBAction func scanInModalAction(_ sender: AnyObject) { guard checkScanPermissions() else { return } readerVC.modalPresentationStyle = .formSheet readerVC.delegate = self readerVC.completionBlock = { (result: QRCodeReaderResult?) in if let result = result { print("Completion with result: \(result.value) of type \(result.metadataType)") } } present(readerVC, animated: true, completion: nil) } @IBAction func scanInPreviewAction(_ sender: Any) { guard checkScanPermissions(), !reader.isRunning else { return } reader.didFindCode = { result in print("Completion with result: \(result.value) of type \(result.metadataType)") } reader.startScanning() } // MARK: - QRCodeReader Delegate Methods func reader(_ reader: QRCodeReaderViewController, didScanResult result: QRCodeReaderResult) { reader.stopScanning() dismiss(animated: true) { [weak self] in let alert = UIAlertController( title: "QRCodeReader", message: String (format:"%@ (of type %@)", result.value, result.metadataType), preferredStyle: .alert ) alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil)) self?.present(alert, animated: true, completion: nil) } } func reader(_ reader: QRCodeReaderViewController, didSwitchCamera newCaptureDevice: AVCaptureDeviceInput) { print("Switching capture to: \(newCaptureDevice.device.localizedName)") } func readerDidCancel(_ reader: QRCodeReaderViewController) { reader.stopScanning() dismiss(animated: true, completion: nil) } }
mit
6ad5dc81217f09bb62dae5284e400704
35.113475
132
0.679694
4.64175
false
false
false
false
xxxAIRINxxx/ViewPagerController
Proj/Demo/NavSampleViewController.swift
1
2842
// // NavSampleViewController.swift // Demo // // Created by xxxAIRINxxx on 2016/01/05. // Copyright © 2016 xxxAIRINxxx. All rights reserved. // import UIKit import ViewPagerController class NavSampleViewController : UIViewController { @IBOutlet weak var layerView : UIView! var pagerController : ViewPagerController? override func viewDidLoad() { super.viewDidLoad() let pagerController = ViewPagerController() pagerController.setParentController(self, parentView: self.layerView) var appearance = ViewPagerControllerAppearance() appearance.tabMenuHeight = 44.0 appearance.scrollViewMinPositionY = 20.0 appearance.scrollViewObservingType = .navigationBar(targetNavigationBar: self.navigationController!.navigationBar) appearance.tabMenuAppearance.backgroundColor = UIColor.darkGray appearance.tabMenuAppearance.selectedViewBackgroundColor = UIColor.blue appearance.tabMenuAppearance.selectedViewInsets = UIEdgeInsets(top: 39, left: 0, bottom: 0, right: 0) pagerController.updateAppearance(appearance) pagerController.willBeginTabMenuUserScrollingHandler = { selectedView in selectedView.alpha = 0.0 } pagerController.didEndTabMenuUserScrollingHandler = { selectedView in selectedView.alpha = 1.0 } pagerController.changeObserveScrollViewHandler = { controller in let detailController = controller as! DetailViewController return detailController.tableView } pagerController.didChangeHeaderViewHeightHandler = { height in print("call didShowViewControllerHandler : \(height)") } for title in sampleDataTitles { let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "DetailViewController") as! DetailViewController controller.view.clipsToBounds = true controller.title = title controller.parentController = self pagerController.addContent(title, viewController: controller) } self.pagerController = pagerController self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "remove", style: .plain, target: self, action: #selector(NavSampleViewController.remove)) } @objc fileprivate func remove() { guard let c = self.pagerController?.childViewControllers.first else { return } self.pagerController?.removeContent(c) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) self.pagerController?.resetNavigationBarHeight(true) } }
mit
0c2f2b6ceb53644b9a40a02bb3eee500
35.896104
161
0.675466
5.845679
false
false
false
false
tardieu/swift
test/PlaygroundTransform/control-flow.swift
12
1189
// RUN: rm -rf %t // RUN: mkdir -p %t // RUN: cp %s %t/main.swift // RUN: %target-build-swift -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift // RUN: %target-run %t/main | %FileCheck %s // RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -debugger-support -o %t/main %S/Inputs/PlaygroundsRuntime.swift %S/Inputs/SilentPCMacroRuntime.swift %t/main.swift // RUN: %target-run %t/main | %FileCheck %s // REQUIRES: executable_test var a = true if (a) { 5 } else { 7 } for i in 0..<3 { i } // CHECK: [{{.*}}] $builtin_log[a='true'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='5'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='0'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='1'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit // CHECK-NEXT: [{{.*}}] $builtin_log_scope_entry // CHECK-NEXT: [{{.*}}] $builtin_log[='2'] // CHECK-NEXT: [{{.*}}] $builtin_log_scope_exit
apache-2.0
d05c4bc0efa3d165aa1c880cec0d46fb
36.15625
197
0.612279
3.040921
false
false
false
false
nRewik/ArtHIstory
ArtHistory/ArtHistory/Game.swift
1
1865
// // Game.swift // ArtHistory // // Created by Nutchaphon Rewik on 29/01/2016. // Copyright © 2016 Nutchaphon Rewik. All rights reserved. // import Foundation import SwiftyJSON struct Game{ var questions: [GameQuestion] = [] static func randomGameFromLesson(index: Int)-> Game{ precondition(index >= 1 && index <= 3, "Game must be in 1 to 3") let dataPath = NSBundle.mainBundle().pathForResource("game-lesson-\(index)", ofType: "json")! let data = NSData(contentsOfFile: dataPath)! let json = JSON(data: data) let questionPairs = json.map{ string, aQuestion -> (title: String, image: String) in let title = aQuestion["title"].stringValue let imagePath = aQuestion["image"].stringValue return (title: title, image: imagePath) } let images = questionPairs.map{$1} let otherImagesPath = zip(questionPairs.indices, questionPairs).map{ index, questionPair -> [String] in var imagesToRandom = images imagesToRandom.removeAtIndex(index) var otherImagePaths: [String] = [] for _ in 1...3{ let randomIndex = Int( arc4random_uniform( UInt32(imagesToRandom.count) ) ) otherImagePaths += [ imagesToRandom[randomIndex] ] imagesToRandom.removeAtIndex(randomIndex) } return otherImagePaths } let questions = zip(questionPairs, otherImagesPath).map{ GameQuestion(title: $0.title, correctImagePath: $0.image, otherImagePaths: $1) } return Game(questions: questions.shuffle()) } } struct GameQuestion{ var title = "" var correctImagePath = "" var otherImagePaths: [String] = [] }
mit
332d415d98010140d446420568ae5afe
28.587302
145
0.58691
4.45933
false
false
false
false
pedrovsn/2reads
reads2/reads2/Livro.swift
1
1756
// // Livro.swift // reads2 // // Created by Student on 11/29/16. // Copyright © 2016 Student. All rights reserved. // import Foundation public class Livro{ var autor: String? var titulo: String? var ano: Int? var descricao: String? var categoria: String? var imagem: String? var editora: Editora var url: String? init(autor: String, titulo: String, editora: Editora, categoria: String,descricao: String, ano: Int, imagem: String, url: String){ self.autor = autor self.titulo = titulo self.editora = editora self.descricao = descricao self.ano = ano self.imagem = imagem self.categoria = categoria self.url = url } static func getList() -> [Livro] { let livro1 = Livro(autor: "Joãozinho de Jesus", titulo: "Fundamentos de física", editora: Editora(nome: "Editora de João"), categoria: "Física", descricao: "Livro de física", ano: 2000, imagem: "capa-o-livro-das-princesas", url: "http://profesores.cengage.com.br/downloads/8522108056_apendices.pdf") let livro2 = Livro(autor: "Marcos Silva", titulo: "Coração de aço", editora: Editora(nome: "Editora de João"), categoria: "Literatura", descricao: "Livro de aço", ano: 2000, imagem: "coracao-de-aco", url: "http://redeetec.mec.gov.br/images/stories/pdf/proeja/matematica_fin.pdf") let livro3 = Livro(autor: "Antonio Paulo", titulo: "Contratos", editora: Editora(nome: "Editora de João"), categoria: "Direito", descricao: "Livro de contratos", ano: 2000, imagem: "contratos", url: "https://ayrtonbecalle.files.wordpress.com/2015/07/brown-d-inferno.pdf") return [ livro1, livro2, livro3 ] } }
mit
e698271c07416bd302d294f8de47fe1f
39.581395
307
0.645069
2.976109
false
false
false
false
bigscreen/mangindo-ios
Mangindo/Modules/NewReleased/NewReleasedViewController.swift
1
5375
// // ViewController.swift // Mangindo // // Created by Gallant Pratama on 2/17/17. // Copyright © 2017 Gallant Pratama. All rights reserved. // import UIKit import SDWebImage class NewReleasedViewController: UIViewController { @IBOutlet weak var newReleaseCollectionView: UICollectionView! @IBOutlet weak var loadingIndicator: UIActivityIndicatorView! @IBOutlet weak var searchTextField: UITextField! internal let newReleaseCellID = "NewReleasedViewCell" var presenter: INewReleasedPresenter! override func viewDidLoad() { super.viewDidLoad() self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Sort by", style: .plain, target: self, action: #selector(sortButtonTap)) newReleaseCollectionView.register(UINib(nibName: newReleaseCellID, bundle: nil), forCellWithReuseIdentifier: newReleaseCellID) searchTextField.delegate = self presenter = NewReleasedPresenter(view: self, service: NetworkService.shared) presenter.fetchNewReleased() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "showChapters" { ChaptersModule(segue: segue).instantiate( pageTitle: presenter.selectedTitle, mangaTitleId: presenter.selectedTitleId ) } } @objc func sortButtonTap() { let actionSheet = UIAlertController(title: "Select sort by", message: nil, preferredStyle: .actionSheet) actionSheet.addAction(UIAlertAction(title: "Release Date", style: .default, handler: { _ in self.presenter.sortMangas(type: .DATE) })) actionSheet.addAction(UIAlertAction(title: "Manga Title", style: .default, handler: { _ in self.presenter.sortMangas(type: .TITLE) })) actionSheet.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil)) present(actionSheet, animated: true, completion: nil) } } extension NewReleasedViewController: UITextFieldDelegate { func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool { if let searchText = (textField.text as NSString?)?.replacingCharacters(in: range, with: string) { presenter.search(mangaName: searchText) } return true } func textFieldShouldClear(_ textField: UITextField) -> Bool { presenter.search(mangaName: "") return true } func textFieldShouldReturn(_ textField: UITextField) -> Bool { self.view.endEditing(true) return false } } extension NewReleasedViewController: INewReleasedView { func startLoading() { self.navigationItem.rightBarButtonItem?.isEnabled = false loadingIndicator.startAnimating() } func stopLoading() { self.navigationItem.rightBarButtonItem?.isEnabled = true loadingIndicator.stopAnimating() } func showData() { newReleaseCollectionView.reloadData() } func showAlert(message: String) { let alert = UIAlertController(title: "Oops!", message: message, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default, handler: nil)) alert.addAction(UIAlertAction(title: "Reload", style: UIAlertActionStyle.default, handler: { action in self.presenter.fetchNewReleased() })) self.present(alert, animated: true, completion: nil) } } extension NewReleasedViewController: UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return presenter.mangas.count } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let cellWidth = (collectionView.frame.size.width - 24) / 3; let cellHeight = cellWidth * 1.5 return CGSize(width: cellWidth, height: cellHeight) } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: newReleaseCellID, for: indexPath as IndexPath) as! NewReleasedViewCell cell.newReleasedManga = presenter.mangas[indexPath.item] return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { presenter.selectManga(index: indexPath.item) self.performSegue(withIdentifier: "showChapters", sender: self) } func collectionView(_ collectionView: UICollectionView, didHighlightItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! NewReleasedViewCell cell.setHighlighted() } func collectionView(_ collectionView: UICollectionView, didUnhighlightItemAt indexPath: IndexPath) { let cell = collectionView.cellForItem(at: indexPath) as! NewReleasedViewCell cell.backgroundColor = UIColor.white cell.setUnhighlighted() } }
mit
b1edcf57aa78fe8be1747df7285ce1f1
39.406015
160
0.699479
5.242927
false
false
false
false
AlexRamey/mbird-iOS
iOS Client/Store/MBArticlesStore.swift
1
13286
// // MBArticlesStore.swift // iOS Client // // Created by Alex Ramey on 12/10/17. // Copyright © 2017 Mockingbird. All rights reserved. // import Foundation import CoreData import PromiseKit class MBArticlesStore: NSObject, ArticleDAO, AuthorDAO, CategoryDAO { private let client: MBClient private let managedObjectContext: NSManagedObjectContext init(context: NSManagedObjectContext) { client = MBClient() self.managedObjectContext = context super.init() } /***** Author DAO *****/ func getAuthorById(_ authorId: Int) -> Author? { let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: MBAuthor.entityName) fetchRequest.predicate = NSPredicate(format: "authorID == %d", authorId) if let results = performFetch(fetchRequest: fetchRequest) as? [MBAuthor] { return results.first?.toDomain() } return nil } /***** Category DAO *****/ func getAllTopLevelCategories() -> [Category] { let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: MBCategory.entityName) let sort = NSSortDescriptor(key: #keyPath(MBCategory.name), ascending: true) fetchRequest.sortDescriptors = [sort] fetchRequest.predicate = NSPredicate(format: "parentID == %d", 0) if let categories = performFetch(fetchRequest: fetchRequest) as? [MBCategory] { // filter out categories without at least one article return categories.filter { (category) -> Bool in let lineage = [Int(category.categoryID)] + category.getAllDescendants().map { return Int($0.categoryID) } return getLatestCategoryArticles(categoryIDs: lineage, skip: 0).count > 0 }.map { return $0.toDomain() } } else { return [] } } func getCategoriesById(_ ids: [Int]) -> [Category] { let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: MBCategory.entityName) fetchRequest.predicate = NSPredicate(format: "categoryID in %@", ids) if let results = performFetch(fetchRequest: fetchRequest) as? [MBCategory] { return results.map { $0.toDomain() } } return [] } func getCategoryByName(_ name: String) -> Category? { let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: MBCategory.entityName) fetchRequest.predicate = NSPredicate(format: "name == %@", name) guard let results = performFetch(fetchRequest: fetchRequest) as? [MBCategory] else { return nil } return results.first?.toDomain() } func getDescendentsOfCategory(cat: Category) -> [Category] { let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: MBCategory.entityName) fetchRequest.predicate = NSPredicate(format: "categoryID == %d", cat.categoryId) if let results = performFetch(fetchRequest: fetchRequest) as? [MBCategory] { return results.first?.getAllDescendants().map { return $0.toDomain() } ?? [] } return [] } /***** Article DAO *****/ func downloadImageURLsForArticle(_ article: Article, withCompletion completion: @escaping (URL?) -> Void) { guard let entity = MBArticle.newArticle(fromArticle: article, inContext: self.managedObjectContext) else { completion(nil) return } self.client.getImageById(Int(entity.imageID)) { image in self.managedObjectContext.perform { do { entity.thumbnailLink = image?.thumbnailUrl?.absoluteString try self.managedObjectContext.save() if let imageLink = entity.thumbnailLink, let url = URL(string: imageLink) { completion(url) } else { completion(nil) } } catch { print("😅 unable to save image url for \(entity.articleID)") completion(nil) } } } } func getLatestArticles(skip: Int) -> [Article] { let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: MBArticle.entityName) let sort = NSSortDescriptor(key: #keyPath(MBArticle.date), ascending: false) fetchRequest.sortDescriptors = [sort] fetchRequest.fetchOffset = skip if let articles = performFetch(fetchRequest: fetchRequest) as? [MBArticle] { return articles.map { return $0.toDomain() } } else { return [] } } func getLatestCategoryArticles(categoryIDs: [Int], skip: Int) -> [Article] { let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: MBArticle.entityName) let sort = NSSortDescriptor(key: #keyPath(MBArticle.date), ascending: false) fetchRequest.sortDescriptors = [sort] fetchRequest.fetchOffset = skip fetchRequest.predicate = NSPredicate(format: "ANY categories.categoryID in %@", categoryIDs) return (performFetch(fetchRequest: fetchRequest) as? [MBArticle])?.map { $0.toDomain() } ?? [] } func bookmarkArticle(_ article: Article) -> Error? { guard Bookmark.newBookmark(fromArticle: article, inContext: self.managedObjectContext) != nil else { return NSError(domain: "CD Adapter", code: 0, userInfo: nil) } var err: Error? self.managedObjectContext.performAndWait { do { try self.managedObjectContext.save() } catch { err = error } } return err } func nukeAndPave() -> Promise<[Article]> { return Promise { fulfill, reject in firstly { when(fulfilled: client.getAuthors(), client.getCategories(), client.getRecentArticles(inCategories: [], offset: 0, pageSize: 100, before: nil, after: nil, asc: false)) }.then { authors, categories, articles -> Void in // build map of image id to image link let imageLinkCache = self.getLinks() // flush db if let nukeErr = self.nuke() { throw nukeErr } var saveError: Error? // save data self.managedObjectContext.performAndWait { do { authors.forEach { MBAuthor.newAuthor(fromAuthor: $0, inContext: self.managedObjectContext ) } try self.managedObjectContext.save() categories.forEach {MBCategory.newCategory(fromCategory: $0, inContext: self.managedObjectContext)} try self.managedObjectContext.save() if let linkErr = self.linkCategoriesTogether() { throw linkErr } articles.forEach {MBArticle.newArticle(fromArticle: $0, inContext: self.managedObjectContext)} try self.managedObjectContext.save() } catch { saveError = error } } if let saveError = saveError { throw saveError } self.resolveArticleImageURLs(cache: imageLinkCache) fulfill(self.getLatestArticles(skip: 0)) }.catch { error in print("There was an error downloading data! \(error)") reject(error) } } } private func nuke() -> Error? { let articles = self.performFetch(fetchRequest: NSFetchRequest<NSManagedObject>(entityName: MBArticle.entityName)) let authors = self.performFetch(fetchRequest: NSFetchRequest<NSManagedObject>(entityName: MBAuthor.entityName)) let categories = self.performFetch(fetchRequest: NSFetchRequest<NSManagedObject>(entityName: MBCategory.entityName)) let objects = articles + authors + categories var retVal: Error? self.managedObjectContext.performAndWait { for object in objects { self.managedObjectContext.delete(object) } do { try self.managedObjectContext.save() } catch { retVal = error } } return retVal } private func getLinks() -> [Int: String] { let request = NSFetchRequest<NSManagedObject>(entityName: MBArticle.entityName) request.predicate = NSPredicate(format: "thumbnailLink != NULL AND thumbnailLink != %@", "") let articles = self.performFetch(fetchRequest: request) as? [MBArticle] ?? [] var retVal: [Int: String] = [:] articles.forEach { (article) in if let link = article.thumbnailLink { retVal[Int(article.imageID)] = link } else { print("fail") } } return retVal } func saveArticles(articles: [Article]) -> Error? { var saveErr: Error? self.managedObjectContext.performAndWait { articles.forEach { _ = MBArticle.newArticle(fromArticle: $0, inContext: self.managedObjectContext) } do { try self.managedObjectContext.save() } catch { print("unable to save articles: \(error)") saveErr = error } } return saveErr } /***** Read from Core Data *****/ func getArticleEntities() -> [MBArticle] { let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: MBArticle.entityName) let sort = NSSortDescriptor(key: #keyPath(MBArticle.date), ascending: false) fetchRequest.sortDescriptors = [sort] return performFetch(fetchRequest: fetchRequest) as? [MBArticle] ?? [] } private func performFetch(fetchRequest: NSFetchRequest<NSManagedObject>) -> [NSManagedObject] { var retVal: [NSManagedObject] = [] self.managedObjectContext.performAndWait { do { retVal = try managedObjectContext.fetch(fetchRequest) } catch let error as NSError { print("Could not fetch. \(error), \(error.userInfo)") retVal = [] } } return retVal } private func resolveArticleImageURLs(cache: [Int: String]) { let articles = self.getArticleEntities() // resolve image links from cache to prevent unnecessary network calls // for image resources self.managedObjectContext.performAndWait { articles.forEach { (article) in if let link = cache[Int(article.imageID)] { article.thumbnailLink = link } } do { try self.managedObjectContext.save() } catch { print("😅 wat \(error as Any)") } } // for the other articles whose image id couldn't be resolved to a link // from the cache, go ahead and pull down the link self.managedObjectContext.perform { articles.forEach { (article) in if (article.imageID > 0) && (article.thumbnailLink == nil) { self.client.getImageById(Int(article.imageID), completion: { (image) in self.managedObjectContext.perform { article.thumbnailLink = image?.thumbnailUrl?.absoluteString do { try self.managedObjectContext.save() } catch { print("😅 wat \(error as Any)") } } }) } } } } private func linkCategoriesTogether() -> Error? { let fetchRequest: NSFetchRequest<MBCategory> = MBCategory.fetchRequest() fetchRequest.sortDescriptors = [NSSortDescriptor(key: "parentID", ascending: true)] var caughtError: Error? = nil self.managedObjectContext.performAndWait { do { let fetchedCategories = try self.managedObjectContext.fetch(fetchRequest) as [MBCategory] var categoriesByID = [Int32: MBCategory]() fetchedCategories.forEach({ (category) in categoriesByID[category.categoryID] = category }) fetchedCategories.forEach({ (category) in category.parent = categoriesByID[category.parentID] }) try self.managedObjectContext.save() } catch { print("Could not fetch. \(error) \(error.localizedDescription)") caughtError = error } } return caughtError } }
mit
5adf0d6ca9e48683449b34283844fe9e
39.47561
183
0.559506
5.483684
false
false
false
false
BackNotGod/localizationCommand
Sources/commandService/commandLineService.swift
1
2021
import Foundation import PathKit import Rainbow import Progress public struct localizationCommand :RegexStringsSearcher,RegexStringsWriter{ let projectPath : Path let exceptPath : [Path] internal var ocPath : [Path] = [] internal var swiftPath : [Path] = [] var patterns: [String] var progress: ProgressBar var localizationName = "" public init(projPath:String,except:[String],localizationName:String){ let path = Path(projPath).absolute() projectPath = path exceptPath = except.map{path + Path($0)} patterns = [] progress = ProgressBar.init(count: 0) self.localizationName = localizationName } func search(in content: String) {} public mutating func findTargetPath(){ let optonalPaths = try? projectPath.recursiveChildren() guard let paths = optonalPaths else {return} for itemPath in Progress(pathsFilter(paths: paths, except: exceptPath)){ let swifts = itemPath.glob(FileType.swift.rawValue) for item in swifts { swiftPath.append(item) } let ocs = itemPath.glob(FileType.oc.rawValue) for item in ocs { ocPath.append(item) } } return search() } mutating func search() { for item in Progress(swiftPath) { patterns = [SWIFT_REGEX] search(in: item) } for item in Progress(ocPath) { patterns = [OC_REGEX] search(in: item) } return write() } func write () { for path in findAllLocalizable(with: projectPath, excluded: exceptPath){ if path.parent().lastComponent == "zh-Hans.lproj" && path.lastComponentWithoutExtension == localizationName{ writeToLocalizable(to: path) } } DataHandleManager.defaltManager.mapError() } }
mit
63175050b83ed2108e60d592b309f527
25.592105
120
0.575458
4.755294
false
false
false
false
harlanhaskins/swift
test/Driver/PrivateDependencies/check-interface-implementation-fine.swift
1
2369
/// The fine-grained dependency graph has implicit dependencies from interfaces to implementations. /// These are not presently tested because depends nodes are marked as depending in the interface, /// as of 1/9/20. But this test will check fail if those links are not followed. // RUN: %empty-directory(%t) // RUN: cp -r %S/Inputs/check-interface-implementation-fine/* %t // RUN: touch -t 201401240005 %t/* // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./a.swift ./c.swift ./bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s // RUN: %FileCheck -check-prefix=CHECK-RECORD-CLEAN %s < %t/main~buildrecord.swiftdeps // CHECK-FIRST-NOT: warning // CHECK-FIRST: Handled a.swift // CHECK-FIRST: Handled c.swift // CHECK-FIRST: Handled bad.swift // CHECK-RECORD-CLEAN-DAG: "./a.swift": [ // CHECK-RECORD-CLEAN-DAG: "./bad.swift": [ // CHECK-RECORD-CLEAN-DAG: "./c.swift": [ // RUN: touch -t 201401240006 %t/a.swift // RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./a.swift ./bad.swift ./c.swift -module-name main -j1 -v -driver-show-incremental > %t/a.txt 2>&1 // RUN: %FileCheck -check-prefix=CHECK-A %s < %t/a.txt // RUN: %FileCheck -check-prefix=NEGATIVE-A %s < %t/a.txt // RUN: %FileCheck -check-prefix=CHECK-RECORD-A %s < %t/main~buildrecord.swiftdeps // CHECK-A: Handled a.swift // CHECK-A: Handled bad.swift // NEGATIVE-A-NOT: Handled c.swift // CHECK-RECORD-A-DAG: "./a.swift": [ // CHECK-RECORD-A-DAG: "./bad.swift": !private [ // CHECK-RECORD-A-DAG: "./c.swift": !private [ // RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents -experimental-private-intransitive-dependencies ./a.swift ./bad.swift ./c.swift -module-name main -j1 -v -driver-show-incremental 2>&1 | %FileCheck -check-prefix CHECK-BC %s // CHECK-BC-NOT: Handled a.swift // CHECK-BC-DAG: Handled bad.swift // CHECK-BC-DAG: Handled c.swift
apache-2.0
62cfa45f2aecef35f9f59362474d1f54
58.225
362
0.711271
3.129458
false
false
false
false
jarjarapps/berrysigner
berrysigner/ProjectPage.swift
1
1455
// // Page.swift // berrysigner // // Created by Maciej Gibas on 1/8/17. // Copyright © 2017 Maciej Gibas. All rights reserved. // import Foundation import UIKit class ProjectPage: UIDocument{ private static let dataFileName: String = "data.file" private static let imageFileName: String = "image.file" private var documentWrapper: FileWrapper? var imageUrl: URL! var dataUrl: URL! override init(fileURL url: URL) { super.init(fileURL: url) self.imageUrl = self.fileURL.appendingPathComponent(ProjectPage.imageFileName) self.dataUrl = self.fileURL.appendingPathComponent(ProjectPage.dataFileName) } override func contents(forType typeName: String) throws -> Any { self.documentWrapper = FileWrapper(directoryWithFileWrappers: [:]) let dataFileWrapper = FileWrapper(regularFileWithContents:Data()) dataFileWrapper.preferredFilename = ProjectPage.dataFileName let imageWrapper = FileWrapper(regularFileWithContents: Data()) imageWrapper.preferredFilename = ProjectPage.imageFileName self.documentWrapper?.addFileWrapper(dataFileWrapper) self.documentWrapper?.addFileWrapper(imageWrapper) return self.documentWrapper! } override func load(fromContents contents: Any, ofType typeName: String?) throws { self.documentWrapper = contents as? FileWrapper } }
unlicense
15d0d771d8e06bf1e3365c1712613579
32.045455
86
0.697387
4.630573
false
false
false
false
GraphKit/MaterialKit
Sources/iOS/NavigationDrawerController.swift
3
43065
/* * Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit @objc(NavigationDrawerPosition) public enum NavigationDrawerPosition: Int { case left case right } extension UIViewController { /** A convenience property that provides access to the NavigationDrawerController. This is the recommended method of accessing the NavigationDrawerController through child UIViewControllers. */ public var navigationDrawerController: NavigationDrawerController? { var viewController: UIViewController? = self while nil != viewController { if viewController is NavigationDrawerController { return viewController as? NavigationDrawerController } viewController = viewController?.parent } return nil } } @objc(NavigationDrawerControllerDelegate) public protocol NavigationDrawerControllerDelegate { /** An optional delegation method that is fired before the NavigationDrawerController opens. - Parameter navigationDrawerController: A NavigationDrawerController. - Parameter position: The NavigationDrawerPosition. */ @objc optional func navigationDrawerController(navigationDrawerController: NavigationDrawerController, willOpen position: NavigationDrawerPosition) /** An optional delegation method that is fired after the NavigationDrawerController opened. - Parameter navigationDrawerController: A NavigationDrawerController. - Parameter position: The NavigationDrawerPosition. */ @objc optional func navigationDrawerController(navigationDrawerController: NavigationDrawerController, didOpen position: NavigationDrawerPosition) /** An optional delegation method that is fired before the NavigationDrawerController closes. - Parameter navigationDrawerController: A NavigationDrawerController. - Parameter position: The NavigationDrawerPosition. */ @objc optional func navigationDrawerController(navigationDrawerController: NavigationDrawerController, willClose position: NavigationDrawerPosition) /** An optional delegation method that is fired after the NavigationDrawerController closed. - Parameter navigationDrawerController: A NavigationDrawerController. - Parameter position: The NavigationDrawerPosition. */ @objc optional func navigationDrawerController(navigationDrawerController: NavigationDrawerController, didClose position: NavigationDrawerPosition) /** An optional delegation method that is fired when the NavigationDrawerController pan gesture begins. - Parameter navigationDrawerController: A NavigationDrawerController. - Parameter didBeginPanAt point: A CGPoint. - Parameter position: The NavigationDrawerPosition. */ @objc optional func navigationDrawerController(navigationDrawerController: NavigationDrawerController, didBeginPanAt point: CGPoint, position: NavigationDrawerPosition) /** An optional delegation method that is fired when the NavigationDrawerController pan gesture changes position. - Parameter navigationDrawerController: A NavigationDrawerController. - Parameter didChangePanAt point: A CGPoint. - Parameter position: The NavigationDrawerPosition. */ @objc optional func navigationDrawerController(navigationDrawerController: NavigationDrawerController, didChangePanAt point: CGPoint, position: NavigationDrawerPosition) /** An optional delegation method that is fired when the NavigationDrawerController pan gesture ends. - Parameter navigationDrawerController: A NavigationDrawerController. - Parameter didEndPanAt point: A CGPoint. - Parameter position: The NavigationDrawerPosition. */ @objc optional func navigationDrawerController(navigationDrawerController: NavigationDrawerController, didEndPanAt point: CGPoint, position: NavigationDrawerPosition) /** An optional delegation method that is fired when the NavigationDrawerController tap gesture executes. - Parameter navigationDrawerController: A NavigationDrawerController. - Parameter didTapAt point: A CGPoint. - Parameter position: The NavigationDrawerPosition. */ @objc optional func navigationDrawerController(navigationDrawerController: NavigationDrawerController, didTapAt point: CGPoint, position: NavigationDrawerPosition) /** An optional delegation method that is fired when the status bar is about to change display, isHidden or not. - Parameter navigationDrawerController: A NavigationDrawerController. - Parameter statusBar isHidden: A boolean. */ @objc optional func navigationDrawerController(navigationDrawerController: NavigationDrawerController, statusBar isHidden: Bool) } @objc(NavigationDrawerController) open class NavigationDrawerController: RootController { /** A CGFloat property that is used internally to track the original (x) position of the container view when panning. */ fileprivate var originalX: CGFloat = 0 /** A UIPanGestureRecognizer property internally used for the leftView pan gesture. */ internal fileprivate(set) var leftPanGesture: UIPanGestureRecognizer? /** A UITapGestureRecognizer property internally used for the leftView tap gesture. */ internal fileprivate(set) var leftTapGesture: UITapGestureRecognizer? /** A UIPanGestureRecognizer property internally used for the rightView pan gesture. */ internal fileprivate(set) var rightPanGesture: UIPanGestureRecognizer? /** A UITapGestureRecognizer property internally used for the rightView tap gesture. */ internal fileprivate(set) var rightTapGesture: UITapGestureRecognizer? /** A CGFloat property that accesses the leftView threshold of the NavigationDrawerController. When the panning gesture has ended, if the position is beyond the threshold, the leftView is opened, if it is below the threshold, the leftView is closed. */ @IBInspectable public var leftThreshold: CGFloat = 64 fileprivate var leftViewThreshold: CGFloat = 0 /** A CGFloat property that accesses the rightView threshold of the NavigationDrawerController. When the panning gesture has ended, if the position is beyond the threshold, the rightView is closed, if it is below the threshold, the rightView is opened. */ @IBInspectable public var rightThreshold: CGFloat = 64 fileprivate var rightViewThreshold: CGFloat = 0 /** A NavigationDrawerControllerDelegate property used to bind the delegation object. */ open weak var delegate: NavigationDrawerControllerDelegate? /** A CGFloat property that sets the animation duration of the leftView when closing and opening. Defaults to 0.25. */ @IBInspectable open var animationDuration: TimeInterval = 0.25 /** A Boolean property that enables and disables the leftView from opening and closing. Defaults to true. */ @IBInspectable open var isEnabled: Bool { get { return isLeftViewEnabled || isRightViewEnabled } set(value) { if nil != leftView { isLeftViewEnabled = value } if nil != rightView { isRightViewEnabled = value } } } /** A Boolean property that enables and disables the leftView from opening and closing. Defaults to true. */ @IBInspectable open var isLeftViewEnabled = false { didSet { isLeftPanGestureEnabled = isLeftViewEnabled isLeftTapGestureEnabled = isLeftViewEnabled } } /// Enables the left pan gesture. @IBInspectable open var isLeftPanGestureEnabled = false { didSet { if isLeftPanGestureEnabled { prepareLeftPanGesture() } else { removeLeftPanGesture() } } } /// Enables the left tap gesture. @IBInspectable open var isLeftTapGestureEnabled = false { didSet { if isLeftTapGestureEnabled { prepareLeftTapGesture() } else { removeLeftTapGesture() } } } /** A Boolean property that enables and disables the rightView from opening and closing. Defaults to true. */ @IBInspectable open var isRightViewEnabled = false { didSet { isRightPanGestureEnabled = isRightViewEnabled isRightTapGestureEnabled = isRightViewEnabled } } /// Enables the right pan gesture. @IBInspectable open var isRightPanGestureEnabled = false { didSet { if isRightPanGestureEnabled { prepareRightPanGesture() } else { removeRightPanGesture() } } } /// Enables the right tap gesture. @IBInspectable open var isRightTapGestureEnabled = false { didSet { if isRightTapGestureEnabled { prepareRightTapGesture() } else { removeRightTapGesture() } } } /** A Boolean property that triggers the status bar to be isHidden when the leftView is opened. Defaults to true. */ @IBInspectable open var isHiddenStatusBarEnabled = true /** A DepthPreset property that is used to set the depth of the leftView when opened. */ open var depthPreset = DepthPreset.depth1 /** A UIView property that is used to hide and reveal the leftViewController. It is very rare that this property will need to be accessed externally. */ open fileprivate(set) var leftView: UIView? /** A UIView property that is used to hide and reveal the rightViewController. It is very rare that this property will need to be accessed externally. */ open fileprivate(set) var rightView: UIView? /// Indicates whether the leftView or rightView is opened. open var isOpened: Bool { return isLeftViewOpened || isRightViewOpened } /// indicates if the leftView is opened. open var isLeftViewOpened: Bool { guard nil != leftView else { return false } return leftView!.x != -leftViewWidth } /// Indicates if the rightView is opened. open var isRightViewOpened: Bool { guard nil != rightView else { return false } return rightView!.x != Screen.width } /** Content view controller to encompase the entire component. This is primarily used when the StatusBar is being isHidden. The alpha value of the rootViewController decreases, and shows the StatusBar. To avoid this, and to add a isHidden transition viewController for complex situations, the contentViewController was added. */ open fileprivate(set) lazy var contentViewController = UIViewController() /** A UIViewController property that references the active left UIViewController. */ open fileprivate(set) var leftViewController: UIViewController? /** A UIViewController property that references the active right UIViewController. */ open fileprivate(set) var rightViewController: UIViewController? /** A CGFloat property to access the width that the leftView opens up to. */ @IBInspectable open fileprivate(set) var leftViewWidth: CGFloat! /** A CGFloat property to access the width that the rightView opens up to. */ @IBInspectable open fileprivate(set) var rightViewWidth: CGFloat! /** 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 with an Optional nib and bundle. - Parameter nibNameOrNil: An Optional String for the nib. - Parameter bundle: An Optional NSBundle where the nib is located. */ public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) prepare() } /** An initializer for the NavigationDrawerController. - Parameter rootViewController: The main UIViewController. - Parameter leftViewController: An Optional left UIViewController. - Parameter rightViewController: An Optional right UIViewController. */ public init(rootViewController: UIViewController, leftViewController: UIViewController? = nil, rightViewController: UIViewController? = nil) { super.init(rootViewController: rootViewController) self.leftViewController = leftViewController self.rightViewController = rightViewController prepare() } open override func transition(to viewController: UIViewController, duration: TimeInterval = 0.5, options: UIViewAnimationOptions = [], animations: (() -> Void)? = nil, completion: ((Bool) -> Void)? = nil) { super.transition(to: viewController, duration: duration, options: options, animations: animations) { [weak self, completion = completion] (result) in guard let s = self else { return } s.view.sendSubview(toBack: s.contentViewController.view) completion?(result) } } /// Layout subviews. open override func layoutSubviews() { super.layoutSubviews() toggleStatusBar() if let v = leftView { v.width = leftViewWidth v.height = view.bounds.height leftViewThreshold = leftViewWidth / 2 if let vc = leftViewController { vc.view.width = v.width vc.view.height = v.height vc.view.center = CGPoint(x: v.width / 2, y: v.height / 2) } } if let v = rightView { v.width = rightViewWidth v.height = view.bounds.height rightViewThreshold = view.bounds.width - rightViewWidth / 2 if let vc = rightViewController { vc.view.width = v.width vc.view.height = v.height vc.view.center = CGPoint(x: v.width / 2, y: v.height / 2) } } } open override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransition(to: size, with: coordinator) // Ensures the view is isHidden. guard let v = rightView else { return } v.position.x = size.width + (isRightViewOpened ? -v.width : v.width) / 2 } /** 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 override func prepare() { super.prepare() prepareContentViewController() prepareLeftView() prepareRightView() } /** A method that is used to set the width of the leftView when opened. This is the recommended method of setting the leftView width. - Parameter width: A CGFloat value to set as the new width. - Parameter isHidden: A Boolean value of whether the leftView should be isHidden after the width has been updated or not. - Parameter animated: A Boolean value that indicates to animate the leftView width change. */ open func setLeftViewWidth(width: CGFloat, isHidden: Bool, animated: Bool, duration: TimeInterval = 0.5) { guard let v = leftView else { return } leftViewWidth = width var hide = isHidden if isRightViewOpened { hide = true } if animated { v.isShadowPathAutoSizing = false if hide { UIView.animate(withDuration: duration, animations: { [weak self] in if let s = self { v.bounds.size.width = width v.position.x = -width / 2 s.rootViewController.view.alpha = 1 } }) { [weak self] _ in if let s = self { v.isShadowPathAutoSizing = true s.layoutSubviews() s.hideView(container: v) } } } else { UIView.animate(withDuration: duration, animations: { [weak self] in if let s = self { v.bounds.size.width = width v.position.x = width / 2 s.rootViewController.view.alpha = 0.5 } }) { [weak self] _ in if let s = self { v.isShadowPathAutoSizing = true s.layoutSubviews() s.showView(container: v) } } } } else { v.bounds.size.width = width if hide { hideView(container: v) v.position.x = -v.width / 2 rootViewController.view.alpha = 1 } else { v.isShadowPathAutoSizing = false showView(container: v) v.position.x = width / 2 rootViewController.view.alpha = 0.5 v.isShadowPathAutoSizing = true } layoutSubviews() } } /** A method that is used to set the width of the rightView when opened. This is the recommended method of setting the rightView width. - Parameter width: A CGFloat value to set as the new width. - Parameter isHidden: A Boolean value of whether the rightView should be isHidden after the width has been updated or not. - Parameter animated: A Boolean value that indicates to animate the rightView width change. */ open func setRightViewWidth(width: CGFloat, isHidden: Bool, animated: Bool, duration: TimeInterval = 0.5) { guard let v = rightView else { return } rightViewWidth = width var hide = isHidden if isLeftViewOpened { hide = true } if animated { v.isShadowPathAutoSizing = false if hide { UIView.animate(withDuration: duration, animations: { [weak self] in if let s = self { v.bounds.size.width = width v.position.x = s.view.bounds.width + width / 2 s.rootViewController.view.alpha = 1 } }) { [weak self] _ in if let s = self { v.isShadowPathAutoSizing = true s.layoutSubviews() s.hideView(container: v) } } } else { UIView.animate(withDuration: duration, animations: { [weak self] in if let s = self { v.bounds.size.width = width v.position.x = s.view.bounds.width - width / 2 s.rootViewController.view.alpha = 0.5 } }) { [weak self] _ in if let s = self { v.isShadowPathAutoSizing = true s.layoutSubviews() s.showView(container: v) } } } } else { v.bounds.size.width = width if hide { hideView(container: v) v.position.x = view.bounds.width + v.width / 2 rootViewController.view.alpha = 1 } else { v.isShadowPathAutoSizing = false showView(container: v) v.position.x = view.bounds.width - width / 2 rootViewController.view.alpha = 0.5 v.isShadowPathAutoSizing = true } layoutSubviews() } } /** A method that toggles the leftView opened if previously closed, or closed if previously opened. - Parameter velocity: A CGFloat value that sets the velocity of the user interaction when animating the leftView. Defaults to 0. */ open func toggleLeftView(velocity: CGFloat = 0) { isLeftViewOpened ? closeLeftView(velocity: velocity) : openLeftView(velocity: velocity) } /** A method that toggles the rightView opened if previously closed, or closed if previously opened. - Parameter velocity: A CGFloat value that sets the velocity of the user interaction when animating the leftView. Defaults to 0. */ open func toggleRightView(velocity: CGFloat = 0) { isRightViewOpened ? closeRightView(velocity: velocity) : openRightView(velocity: velocity) } /** A method that opens the leftView. - Parameter velocity: A CGFloat value that sets the velocity of the user interaction when animating the leftView. Defaults to 0. */ open func openLeftView(velocity: CGFloat = 0) { guard isLeftViewEnabled else { return } guard let v = leftView else { return } hideStatusBar() showView(container: v) isUserInteractionEnabled = false delegate?.navigationDrawerController?(navigationDrawerController: self, willOpen: .left) UIView.animate(withDuration: TimeInterval(0 == velocity ? animationDuration : fmax(0.1, fmin(1, Double(v.x / velocity)))), animations: { [weak self, v = v] in guard let s = self else { return } v.position.x = v.width / 2 s.rootViewController.view.alpha = 0.5 }) { [weak self] _ in guard let s = self else { return } s.delegate?.navigationDrawerController?(navigationDrawerController: s, didOpen: .left) } } /** A method that opens the rightView. - Parameter velocity: A CGFloat value that sets the velocity of the user interaction when animating the leftView. Defaults to 0. */ open func openRightView(velocity: CGFloat = 0) { guard isRightViewEnabled else { return } guard let v = rightView else { return } hideStatusBar() showView(container: v) isUserInteractionEnabled = false delegate?.navigationDrawerController?(navigationDrawerController: self, willOpen: .right) UIView.animate(withDuration: TimeInterval(0 == velocity ? animationDuration : fmax(0.1, fmin(1, Double(v.x / velocity)))), animations: { [weak self, v = v] in guard let s = self else { return } v.position.x = s.view.bounds.width - v.width / 2 s.rootViewController.view.alpha = 0.5 }) { [weak self] _ in guard let s = self else { return } s.delegate?.navigationDrawerController?(navigationDrawerController: s, didOpen: .right) } } /** A method that closes the leftView. - Parameter velocity: A CGFloat value that sets the velocity of the user interaction when animating the leftView. Defaults to 0. */ open func closeLeftView(velocity: CGFloat = 0) { guard isLeftViewEnabled else { return } guard let v = leftView else { return } isUserInteractionEnabled = true delegate?.navigationDrawerController?(navigationDrawerController: self, willClose: .left) UIView.animate(withDuration: TimeInterval(0 == velocity ? animationDuration : fmax(0.1, fmin(1, Double(v.x / velocity)))), animations: { [weak self, v = v] in guard let s = self else { return } v.position.x = -v.width / 2 s.rootViewController.view.alpha = 1 }) { [weak self] _ in guard let s = self else { return } s.hideView(container: v) s.toggleStatusBar() s.delegate?.navigationDrawerController?(navigationDrawerController: s, didClose: .left) } } /** A method that closes the rightView. - Parameter velocity: A CGFloat value that sets the velocity of the user interaction when animating the leftView. Defaults to 0. */ open func closeRightView(velocity: CGFloat = 0) { guard isRightViewEnabled else { return } guard let v = rightView else { return } isUserInteractionEnabled = true delegate?.navigationDrawerController?(navigationDrawerController: self, willClose: .right) UIView.animate(withDuration: TimeInterval(0 == velocity ? animationDuration : fmax(0.1, fmin(1, Double(v.x / velocity)))), animations: { [weak self, v = v] in guard let s = self else { return } v.position.x = s.view.bounds.width + v.width / 2 s.rootViewController.view.alpha = 1 }) { [weak self] _ in guard let s = self else { return } s.hideView(container: v) s.toggleStatusBar() s.delegate?.navigationDrawerController?(navigationDrawerController: s, didClose: .right) } } /// A method that removes the passed in pan and leftView tap gesture recognizers. fileprivate func removeLeftViewGestures() { removeLeftPanGesture() removeLeftTapGesture() } /// Removes the left pan gesture. fileprivate func removeLeftPanGesture() { guard let v = leftPanGesture else { return } view.removeGestureRecognizer(v) leftPanGesture = nil } /// Removes the left tap gesture. fileprivate func removeLeftTapGesture() { guard let v = leftTapGesture else { return } view.removeGestureRecognizer(v) leftTapGesture = nil } /// A method that removes the passed in pan and rightView tap gesture recognizers. fileprivate func removeRightViewGestures() { removeRightPanGesture() removeRightTapGesture() } /// Removes the right pan gesture. fileprivate func removeRightPanGesture() { guard let v = rightPanGesture else { return } view.removeGestureRecognizer(v) rightPanGesture = nil } /// Removes the right tap gesture. fileprivate func removeRightTapGesture() { guard let v = rightTapGesture else { return } view.removeGestureRecognizer(v) rightTapGesture = nil } /// Shows the statusBar. fileprivate func showStatusBar() { DispatchQueue.main.async { [weak self] in guard let s = self else { return } guard let v = Application.keyWindow else { return } v.windowLevel = UIWindowLevelNormal s.delegate?.navigationDrawerController?(navigationDrawerController: s, statusBar: false) } } /// Hides the statusBar. fileprivate func hideStatusBar() { guard isHiddenStatusBarEnabled else { return } DispatchQueue.main.async { [weak self] in guard let s = self else { return } guard let v = Application.keyWindow else { return } v.windowLevel = UIWindowLevelStatusBar + 1 s.delegate?.navigationDrawerController?(navigationDrawerController: s, statusBar: true) } } /// Toggles the statusBar fileprivate func toggleStatusBar() { if isOpened { hideStatusBar() } else { showStatusBar() } } /** A method that determines whether the passed point is contained within the bounds of the leftViewThreshold and height of the NavigationDrawerController view frame property. - Parameter point: A CGPoint to test against. - Returns: A Boolean of the result, true if yes, false otherwise. */ fileprivate func isPointContainedWithinLeftThreshold(point: CGPoint) -> Bool { return point.x <= leftThreshold } /** A method that determines whether the passed point is contained within the bounds of the rightViewThreshold and height of the NavigationDrawerController view frame property. - Parameter point: A CGPoint to test against. - Returns: A Boolean of the result, true if yes, false otherwise. */ fileprivate func isPointContainedWithinRighThreshold(point: CGPoint) -> Bool { return point.x >= view.bounds.width - rightThreshold } /** A method that determines whether the passed in point is contained within the bounds of the passed in container view. - Parameter container: A UIView that sets the bounds to test against. - Parameter point: A CGPoint to test whether or not it is within the bounds of the container parameter. - Returns: A Boolean of the result, true if yes, false otherwise. */ fileprivate func isPointContainedWithinView(container: UIView, point: CGPoint) -> Bool { return container.bounds.contains(point) } /** A method that shows a view. - Parameter container: A container view. */ fileprivate func showView(container: UIView) { container.depthPreset = depthPreset container.isHidden = false } /** A method that hides a view. - Parameter container: A container view. */ fileprivate func hideView(container: UIView) { container.depthPreset = .none container.isHidden = true } } extension NavigationDrawerController { /// Prepares the contentViewController. fileprivate func prepareContentViewController() { contentViewController.view.backgroundColor = .black prepare(viewController: contentViewController, withContainer: view) view.sendSubview(toBack: contentViewController.view) } /// A method that prepares the leftViewController. fileprivate func prepareLeftViewController() { guard let v = leftView else { return } prepare(viewController: leftViewController, withContainer: v) } /// A method that prepares the rightViewController. fileprivate func prepareRightViewController() { guard let v = rightView else { return } prepare(viewController: rightViewController, withContainer: v) } /// A method that prepares the leftView. fileprivate func prepareLeftView() { guard nil != leftViewController else { return } isLeftViewEnabled = true leftViewWidth = .phone == Device.userInterfaceIdiom ? 280 : 320 leftView = UIView() leftView!.frame = CGRect(x: 0, y: 0, width: leftViewWidth, height: view.height) leftView!.backgroundColor = nil view.addSubview(leftView!) leftView!.isHidden = true leftView!.position.x = -leftViewWidth / 2 leftView!.zPosition = 2000 prepareLeftViewController() } /// A method that prepares the leftView. fileprivate func prepareRightView() { guard nil != rightViewController else { return } isRightViewEnabled = true rightViewWidth = .phone == Device.userInterfaceIdiom ? 280 : 320 rightView = UIView() rightView!.frame = CGRect(x: view.width, y: 0, width: rightViewWidth, height: view.height) rightView!.backgroundColor = nil view.addSubview(rightView!) rightView!.isHidden = true rightView!.position.x = view.bounds.width + rightViewWidth / 2 rightView!.zPosition = 2000 prepareRightViewController() } /// Prepare the left pan gesture. fileprivate func prepareLeftPanGesture() { guard nil == leftPanGesture else { return } leftPanGesture = UIPanGestureRecognizer(target: self, action: #selector(handleLeftViewPanGesture(recognizer:))) leftPanGesture!.delegate = self view.addGestureRecognizer(leftPanGesture!) } /// Prepare the left tap gesture. fileprivate func prepareLeftTapGesture() { guard nil == leftTapGesture else { return } leftTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleLeftViewTapGesture(recognizer:))) leftTapGesture!.delegate = self leftTapGesture!.cancelsTouchesInView = false view.addGestureRecognizer(leftTapGesture!) } /// Prepares the right pan gesture. fileprivate func prepareRightPanGesture() { guard nil == rightPanGesture else { return } rightPanGesture = UIPanGestureRecognizer(target: self, action: #selector(handleRightViewPanGesture(recognizer:))) rightPanGesture!.delegate = self view.addGestureRecognizer(rightPanGesture!) } /// Prepares the right tap gesture. fileprivate func prepareRightTapGesture() { guard nil == rightTapGesture else { return } rightTapGesture = UITapGestureRecognizer(target: self, action: #selector(handleRightViewTapGesture(recognizer:))) rightTapGesture!.delegate = self rightTapGesture!.cancelsTouchesInView = false view.addGestureRecognizer(rightTapGesture!) } } extension NavigationDrawerController: UIGestureRecognizerDelegate { /** Detects the gesture recognizer being used. - Parameter gestureRecognizer: A UIGestureRecognizer to detect. - Parameter touch: The UITouch event. - Returns: A Boolean of whether to continue the gesture or not. */ @objc open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if !isRightViewOpened && gestureRecognizer == leftPanGesture && (isLeftViewOpened || isPointContainedWithinLeftThreshold(point: touch.location(in: view))) { return true } if !isLeftViewOpened && gestureRecognizer == rightPanGesture && (isRightViewOpened || isPointContainedWithinRighThreshold(point: touch.location(in: view))) { return true } if isLeftViewOpened && gestureRecognizer == leftTapGesture { return true } if isRightViewOpened && gestureRecognizer == rightTapGesture { return true } return false } /** A method that is fired when the pan gesture is recognized for the leftView. - Parameter recognizer: A UIPanGestureRecognizer that is passed to the handler when recognized. */ @objc fileprivate func handleLeftViewPanGesture(recognizer: UIPanGestureRecognizer) { if isLeftViewEnabled && (isLeftViewOpened || !isRightViewOpened && isPointContainedWithinLeftThreshold(point: recognizer.location(in: view))) { guard let v = leftView else { return } let point = recognizer.location(in: view) // Animate the panel. switch recognizer.state { case .began: originalX = v.position.x showView(container: v) delegate?.navigationDrawerController?(navigationDrawerController: self, didBeginPanAt: point, position: .left) case .changed: let w = v.width let translationX = recognizer.translation(in: v).x v.position.x = originalX + translationX > (w / 2) ? (w / 2) : originalX + translationX let a = 1 - v.position.x / v.width rootViewController.view.alpha = 0.5 < a && v.position.x <= v.width / 2 ? a : 0.5 if translationX >= leftThreshold { hideStatusBar() } delegate?.navigationDrawerController?(navigationDrawerController: self, didChangePanAt: point, position: .left) case .ended, .cancelled, .failed: let p = recognizer.velocity(in: recognizer.view) let x = p.x >= 1000 || p.x <= -1000 ? p.x : 0 delegate?.navigationDrawerController?(navigationDrawerController: self, didEndPanAt: point, position: .left) if v.x <= -leftViewWidth + leftViewThreshold || x < -1000 { closeLeftView(velocity: x) } else { openLeftView(velocity: x) } case .possible:break } } } /** A method that is fired when the pan gesture is recognized for the rightView. - Parameter recognizer: A UIPanGestureRecognizer that is passed to the handler when recognized. */ @objc fileprivate func handleRightViewPanGesture(recognizer: UIPanGestureRecognizer) { if isRightViewEnabled && (isRightViewOpened || !isLeftViewOpened && isPointContainedWithinRighThreshold(point: recognizer.location(in: view))) { guard let v = rightView else { return } let point = recognizer.location(in: view) // Animate the panel. switch recognizer.state { case .began: originalX = v.position.x showView(container: v) delegate?.navigationDrawerController?(navigationDrawerController: self, didBeginPanAt: point, position: .right) case .changed: let w = v.width let translationX = recognizer.translation(in: v).x v.position.x = originalX + translationX < view.bounds.width - (w / 2) ? view.bounds.width - (w / 2) : originalX + translationX let a = 1 - (view.bounds.width - v.position.x) / v.width rootViewController.view.alpha = 0.5 < a && v.position.x >= v.width / 2 ? a : 0.5 if translationX <= -rightThreshold { hideStatusBar() } delegate?.navigationDrawerController?(navigationDrawerController: self, didChangePanAt: point, position: .right) case .ended, .cancelled, .failed: let p = recognizer.velocity(in: recognizer.view) let x = p.x >= 1000 || p.x <= -1000 ? p.x : 0 delegate?.navigationDrawerController?(navigationDrawerController: self, didEndPanAt: point, position: .right) if v.x >= rightViewThreshold || x > 1000 { closeRightView(velocity: x) } else { openRightView(velocity: x) } case .possible:break } } } /** A method that is fired when the tap gesture is recognized for the leftView. - Parameter recognizer: A UITapGestureRecognizer that is passed to the handler when recognized. */ @objc fileprivate func handleLeftViewTapGesture(recognizer: UITapGestureRecognizer) { guard isLeftViewOpened else { return } guard let v = leftView else { return } delegate?.navigationDrawerController?(navigationDrawerController: self, didTapAt: recognizer.location(in: view), position: .left) if isLeftViewEnabled && isLeftViewOpened && !isPointContainedWithinView(container: v, point: recognizer.location(in: v)) { closeLeftView() } } /** A method that is fired when the tap gesture is recognized for the rightView. - Parameter recognizer: A UITapGestureRecognizer that is passed to the handler when recognized. */ @objc fileprivate func handleRightViewTapGesture(recognizer: UITapGestureRecognizer) { guard isRightViewOpened else { return } guard let v = rightView else { return } delegate?.navigationDrawerController?(navigationDrawerController: self, didTapAt: recognizer.location(in: view), position: .right) if isRightViewEnabled && isRightViewOpened && !isPointContainedWithinView(container: v, point: recognizer.location(in: v)) { closeRightView() } } }
agpl-3.0
20fd3c77b926161f57a4c5f85d042cf1
33.396965
210
0.622199
5.206746
false
false
false
false
seanwoodward/IBAnimatable
IBAnimatable/ActivityIndicatorAnimationBallClipRotateMultiple.swift
1
3026
// // Created by Tom Baranes on 23/08/16. // Copyright (c) 2016 IBAnimatable. All rights reserved. // import UIKit public class ActivityIndicatorAnimationBallClipRotateMultiple: ActivityIndicatorAnimating { // MARK: Properties private let duration: CFTimeInterval = 0.7 // MARK: ActivityIndicatorAnimating public func configAnimation(in layer: CALayer, size: CGSize, color: UIColor) { let bigCircleSize: CGFloat = size.width let smallCircleSize: CGFloat = size.width / 2 let longDuration: CFTimeInterval = 1 let timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionEaseInEaseOut) circleOf(shape: .RingTwoHalfHorizontal, duration: longDuration, timingFunction: timingFunction, layer: layer, size: bigCircleSize, color: color, reverse: false) circleOf(shape: .RingTwoHalfVertical, duration: longDuration, timingFunction: timingFunction, layer: layer, size: smallCircleSize, color: color, reverse: true) } } // MARK: - Setup private extension ActivityIndicatorAnimationBallClipRotateMultiple { func createAnimationIn(duration duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, reverse: Bool) -> CAAnimation { // Scale animation let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale") scaleAnimation.keyTimes = [0, 0.5, 1] scaleAnimation.timingFunctions = [timingFunction, timingFunction] scaleAnimation.values = [1, 0.6, 1] scaleAnimation.duration = duration // Rotate animation let rotateAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.z") rotateAnimation.keyTimes = scaleAnimation.keyTimes rotateAnimation.timingFunctions = [timingFunction, timingFunction] if !reverse { rotateAnimation.values = [0, M_PI, 2 * M_PI] } else { rotateAnimation.values = [0, -M_PI, -2 * M_PI] } rotateAnimation.duration = duration // Animation let animation = CAAnimationGroup() animation.animations = [scaleAnimation, rotateAnimation] animation.duration = duration animation.repeatCount = .infinity animation.removedOnCompletion = false return animation } // swiftlint:disable:next function_parameter_count func circleOf(shape shape: ActivityIndicatorShape, duration: CFTimeInterval, timingFunction: CAMediaTimingFunction, layer: CALayer, size: CGFloat, color: UIColor, reverse: Bool) { let circle = shape.createLayerWith(size: CGSize(width: size, height: size), color: color) let frame = CGRect(x: (layer.bounds.size.width - size) / 2, y: (layer.bounds.size.height - size) / 2, width: size, height: size) let animation = createAnimationIn(duration: duration, timingFunction: timingFunction, reverse: reverse) circle.frame = frame circle.addAnimation(animation, forKey: "animation") layer.addSublayer(circle) } }
mit
5e5bcc40470ca7e711843a0419d967c3
35.02381
181
0.696299
4.88853
false
false
false
false
ming1016/smck
smck/Lib/RxSwift/CompositeDisposable.swift
47
5546
// // CompositeDisposable.swift // RxSwift // // Created by Krunoslav Zaher on 2/20/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // /// Represents a group of disposable resources that are disposed together. public final class CompositeDisposable : DisposeBase, Disposable, Cancelable { /// Key used to remove disposable from composite disposable public struct DisposeKey { fileprivate let key: BagKey fileprivate init(key: BagKey) { self.key = key } } private var _lock = SpinLock() // state private var _disposables: Bag<Disposable>? = Bag() public var isDisposed: Bool { _lock.lock(); defer { _lock.unlock() } return _disposables == nil } public override init() { } /// Initializes a new instance of composite disposable with the specified number of disposables. public init(_ disposable1: Disposable, _ disposable2: Disposable) { // This overload is here to make sure we are using optimized version up to 4 arguments. let _ = _disposables!.insert(disposable1) let _ = _disposables!.insert(disposable2) } /// Initializes a new instance of composite disposable with the specified number of disposables. public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) { // This overload is here to make sure we are using optimized version up to 4 arguments. let _ = _disposables!.insert(disposable1) let _ = _disposables!.insert(disposable2) let _ = _disposables!.insert(disposable3) } /// Initializes a new instance of composite disposable with the specified number of disposables. public init(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposable4: Disposable, _ disposables: Disposable...) { // This overload is here to make sure we are using optimized version up to 4 arguments. let _ = _disposables!.insert(disposable1) let _ = _disposables!.insert(disposable2) let _ = _disposables!.insert(disposable3) let _ = _disposables!.insert(disposable4) for disposable in disposables { let _ = _disposables!.insert(disposable) } } /// Initializes a new instance of composite disposable with the specified number of disposables. public init(disposables: [Disposable]) { for disposable in disposables { let _ = _disposables!.insert(disposable) } } /** Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed. - parameter disposable: Disposable to add. - returns: Key that can be used to remove disposable from composite disposable. In case dispose bag was already disposed `nil` will be returned. */ public func insert(_ disposable: Disposable) -> DisposeKey? { let key = _insert(disposable) if key == nil { disposable.dispose() } return key } private func _insert(_ disposable: Disposable) -> DisposeKey? { _lock.lock(); defer { _lock.unlock() } let bagKey = _disposables?.insert(disposable) return bagKey.map(DisposeKey.init) } /// - returns: Gets the number of disposables contained in the `CompositeDisposable`. public var count: Int { _lock.lock(); defer { _lock.unlock() } return _disposables?.count ?? 0 } /// Removes and disposes the disposable identified by `disposeKey` from the CompositeDisposable. /// /// - parameter disposeKey: Key used to identify disposable to be removed. public func remove(for disposeKey: DisposeKey) { _remove(for: disposeKey)?.dispose() } private func _remove(for disposeKey: DisposeKey) -> Disposable? { _lock.lock(); defer { _lock.unlock() } return _disposables?.removeKey(disposeKey.key) } /// Disposes all disposables in the group and removes them from the group. public func dispose() { if let disposables = _dispose() { disposeAll(in: disposables) } } private func _dispose() -> Bag<Disposable>? { _lock.lock(); defer { _lock.unlock() } let disposeBag = _disposables _disposables = nil return disposeBag } } extension Disposables { /// Creates a disposable with the given disposables. public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable) -> Cancelable { return CompositeDisposable(disposable1, disposable2, disposable3) } /// Creates a disposable with the given disposables. public static func create(_ disposable1: Disposable, _ disposable2: Disposable, _ disposable3: Disposable, _ disposables: Disposable ...) -> Cancelable { var disposables = disposables disposables.append(disposable1) disposables.append(disposable2) disposables.append(disposable3) return CompositeDisposable(disposables: disposables) } /// Creates a disposable with the given disposables. public static func create(_ disposables: [Disposable]) -> Cancelable { switch disposables.count { case 2: return Disposables.create(disposables[0], disposables[1]) default: return CompositeDisposable(disposables: disposables) } } }
apache-2.0
3e47e0e494e6718639d0201c1e26c83b
35.721854
157
0.64743
4.973094
false
false
false
false
overtake/TelegramSwift
Telegram-Mac/InputDataControllerEntries.swift
1
26289
// // InputDataControllerEntries.swift // Telegram // // Created by Mikhail Filimonov on 21/03/2018. // Copyright © 2018 Telegram. All rights reserved. // import Cocoa import TGUIKit import TelegramCore import SwiftSignalKit enum InputDataEntryId : Hashable { case desc(Int32) case input(InputDataIdentifier) case general(InputDataIdentifier) case selector(InputDataIdentifier) case dataSelector(InputDataIdentifier) case dateSelector(InputDataIdentifier) case custom(InputDataIdentifier) case search(InputDataIdentifier) case loading case sectionId(Int32) var hashValue: Int { return 0 } var identifier: InputDataIdentifier? { switch self { case let .input(identifier), let .selector(identifier), let .dataSelector(identifier), let .dateSelector(identifier), let .general(identifier), let .custom(identifier), let .search(identifier): return identifier default: return nil } } } enum InputDataInputMode : Equatable { case plain case secure } public protocol _HasCustomInputDataEquatableRepresentation { func _toCustomInputDataEquatable() -> InputDataEquatable? } internal protocol _InputDataEquatableBox { var _typeID: ObjectIdentifier { get } func _unbox<T : Equatable>() -> T? func _isEqual(to: _InputDataEquatableBox) -> Bool? var _base: Any { get } func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool } internal struct _ConcreteEquatableBox<Base : Equatable> : _InputDataEquatableBox { internal var _baseEquatable: Base internal init(_ base: Base) { self._baseEquatable = base } internal var _typeID: ObjectIdentifier { return ObjectIdentifier(type(of: self)) } internal func _unbox<T : Equatable>() -> T? { return (self as _InputDataEquatableBox as? _ConcreteEquatableBox<T>)?._baseEquatable } internal func _isEqual(to rhs: _InputDataEquatableBox) -> Bool? { if let rhs: Base = rhs._unbox() { return _baseEquatable == rhs } return nil } internal var _base: Any { return _baseEquatable } internal func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool { guard let value = _baseEquatable as? T else { return false } result.initialize(to: value) return true } } struct InputDataComparableIndex : Comparable { let data: Any let compare:(Any, Any)->Bool let equatable:(Any, Any)->Bool static func <(lhs: InputDataComparableIndex, rhs: InputDataComparableIndex) -> Bool { return lhs.compare(lhs.data, rhs.data) } static func ==(lhs: InputDataComparableIndex, rhs: InputDataComparableIndex) -> Bool { return lhs.equatable(lhs.data, rhs.data) } } public struct InputDataEquatable { internal var _box: _InputDataEquatableBox internal var _usedCustomRepresentation: Bool public init<H : Equatable>(_ base: H) { if let customRepresentation = (base as? _HasCustomInputDataEquatableRepresentation)?._toCustomInputDataEquatable() { self = customRepresentation self._usedCustomRepresentation = true return } self._box = _ConcreteEquatableBox(base) self._usedCustomRepresentation = false } internal init<H : Equatable>(_usingDefaultRepresentationOf base: H) { self._box = _ConcreteEquatableBox(base) self._usedCustomRepresentation = false } public var base: Any { return _box._base } internal func _downCastConditional<T>(into result: UnsafeMutablePointer<T>) -> Bool { // Attempt the downcast. if _box._downCastConditional(into: result) { return true } return false } } extension InputDataEquatable : Equatable { public static func == (lhs: InputDataEquatable, rhs: InputDataEquatable) -> Bool { if let result = lhs._box._isEqual(to: rhs._box) { return result } return false } } extension InputDataEquatable : CustomStringConvertible { public var description: String { return String(describing: base) } } extension InputDataEquatable : CustomDebugStringConvertible { public var debugDescription: String { return "InputDataEquatable(" + String(reflecting: base) + ")" } } extension InputDataEquatable : CustomReflectable { public var customMirror: Mirror { return Mirror( self, children: ["value": base]) } } public // COMPILER_INTRINSIC func _convertToInputDataEquatable<H : Equatable>(_ value: H) -> InputDataEquatable { return InputDataEquatable(value) } internal func _convertToInputDataEquatableIndirect<H : Equatable>( _ value: H, _ target: UnsafeMutablePointer<InputDataEquatable> ) { target.initialize(to: InputDataEquatable(value)) } internal func _InputDataEquatableDownCastConditionalIndirect<T>( _ value: UnsafePointer<InputDataEquatable>, _ target: UnsafeMutablePointer<T> ) -> Bool { return value.pointee._downCastConditional(into: target) } struct InputDataInputPlaceholder : Equatable { let placeholder: String? let drawBorderAfterPlaceholder: Bool let icon: CGImage? let action: (()-> Void)? let hasLimitationText: Bool let insets: NSEdgeInsets init(_ placeholder: String? = nil, icon: CGImage? = nil, drawBorderAfterPlaceholder: Bool = false, hasLimitationText: Bool = false, insets: NSEdgeInsets = NSEdgeInsets(), action: (()-> Void)? = nil) { self.drawBorderAfterPlaceholder = drawBorderAfterPlaceholder self.hasLimitationText = hasLimitationText self.placeholder = placeholder self.icon = icon self.action = action self.insets = insets } static func ==(lhs: InputDataInputPlaceholder, rhs: InputDataInputPlaceholder) -> Bool { return lhs.placeholder == rhs.placeholder && lhs.icon === rhs.icon && lhs.drawBorderAfterPlaceholder == rhs.drawBorderAfterPlaceholder && lhs.insets == rhs.insets } } final class InputDataGeneralData : Equatable { let name: String let color: NSColor let icon: CGImage? let type: GeneralInteractedType let viewType: GeneralViewType let description: String? let action: (()->Void)? let disabledAction:(()->Void)? let enabled: Bool let justUpdate: Int64? let menuItems:(()->[ContextMenuItem])? let theme: GeneralRowItem.Theme? let disableBorder: Bool init(name: String, color: NSColor, icon: CGImage? = nil, type: GeneralInteractedType = .none, viewType: GeneralViewType = .legacy, enabled: Bool = true, description: String? = nil, justUpdate: Int64? = nil, action: (()->Void)? = nil, disabledAction: (()->Void)? = nil, menuItems:(()->[ContextMenuItem])? = nil, theme: GeneralRowItem.Theme? = nil, disableBorder: Bool = false) { self.name = name self.color = color self.icon = icon self.type = type self.viewType = viewType self.description = description self.action = action self.enabled = enabled self.justUpdate = justUpdate self.disabledAction = disabledAction self.menuItems = menuItems self.theme = theme self.disableBorder = disableBorder } static func ==(lhs: InputDataGeneralData, rhs: InputDataGeneralData) -> Bool { return lhs.name == rhs.name && lhs.icon === rhs.icon && lhs.color.hexString == rhs.color.hexString && lhs.type == rhs.type && lhs.description == rhs.description && lhs.viewType == rhs.viewType && lhs.enabled == rhs.enabled && lhs.justUpdate == rhs.justUpdate && lhs.theme == rhs.theme && lhs.disableBorder == rhs.disableBorder } } final class InputDataTextInsertAnimatedViewData : NSObject { let context: AccountContext let file: TelegramMediaFile init(context: AccountContext, file: TelegramMediaFile) { self.context = context self.file = file } static func == (lhs: InputDataTextInsertAnimatedViewData, rhs: InputDataTextInsertAnimatedViewData) -> Bool { return lhs.file == rhs.file } static var attributeKey: NSAttributedString.Key { return NSAttributedString.Key("InputDataTextInsertAnimatedDataKey") } } struct InputDataGeneralTextRightData : Equatable { let isLoading: Bool let text: NSAttributedString? init(isLoading: Bool, text: NSAttributedString?) { self.isLoading = isLoading self.text = text } } final class InputDataGeneralTextData : Equatable { let color: NSColor let detectBold: Bool let viewType: GeneralViewType let rightItem: InputDataGeneralTextRightData let fontSize: CGFloat? let contextMenu:(()->[ContextMenuItem])? let clickable: Bool let inset: NSEdgeInsets init(color: NSColor = theme.colors.listGrayText, detectBold: Bool = true, viewType: GeneralViewType = .legacy, rightItem: InputDataGeneralTextRightData = InputDataGeneralTextRightData(isLoading: false, text: nil), fontSize: CGFloat? = nil, contextMenu:(()->[ContextMenuItem])? = nil, clickable: Bool = false, inset: NSEdgeInsets = .init(left: 30.0, right: 30.0, top:4, bottom:2)) { self.color = color self.detectBold = detectBold self.viewType = viewType self.rightItem = rightItem self.inset = inset self.fontSize = fontSize self.contextMenu = contextMenu self.clickable = clickable } static func ==(lhs: InputDataGeneralTextData, rhs: InputDataGeneralTextData) -> Bool { return lhs.color == rhs.color && lhs.detectBold == rhs.detectBold && lhs.viewType == rhs.viewType && lhs.rightItem == rhs.rightItem && lhs.fontSize == rhs.fontSize && lhs.clickable == rhs.clickable && lhs.inset == rhs.inset } } final class InputDataRowData : Equatable { let viewType: GeneralViewType let rightItem: InputDataRightItem? let defaultText: String? let pasteFilter:((String)->(Bool, String))? let maxBlockWidth: CGFloat? let canMakeTransformations: Bool let customTheme: GeneralRowItem.Theme? init(viewType: GeneralViewType = .legacy, rightItem: InputDataRightItem? = nil, defaultText: String? = nil, maxBlockWidth: CGFloat? = nil, canMakeTransformations: Bool = false, pasteFilter:((String)->(Bool, String))? = nil, customTheme: GeneralRowItem.Theme? = nil) { self.viewType = viewType self.rightItem = rightItem self.defaultText = defaultText self.pasteFilter = pasteFilter self.maxBlockWidth = maxBlockWidth self.canMakeTransformations = canMakeTransformations self.customTheme = customTheme } static func ==(lhs: InputDataRowData, rhs: InputDataRowData) -> Bool { return lhs.viewType == rhs.viewType && lhs.rightItem == rhs.rightItem && lhs.defaultText == rhs.defaultText && lhs.maxBlockWidth == rhs.maxBlockWidth && lhs.canMakeTransformations == rhs.canMakeTransformations && lhs.customTheme == rhs.customTheme } } enum InputDataSectionType : Equatable { case normal case legacy case custom(CGFloat) case customModern(CGFloat) var height: CGFloat { switch self { case .normal: return 30 case .legacy: return 20 case let .custom(height): return height case let .customModern(height): return height } } } enum InputDataEntry : Identifiable, Comparable { case desc(sectionId: Int32, index: Int32, text: GeneralRowTextType, data: InputDataGeneralTextData) case input(sectionId: Int32, index: Int32, value: InputDataValue, error: InputDataValueError?, identifier: InputDataIdentifier, mode: InputDataInputMode, data: InputDataRowData, placeholder: InputDataInputPlaceholder?, inputPlaceholder: String, filter:(String)->String, limit: Int32) case general(sectionId: Int32, index: Int32, value: InputDataValue, error: InputDataValueError?, identifier: InputDataIdentifier, data: InputDataGeneralData) case dateSelector(sectionId: Int32, index: Int32, value: InputDataValue, error: InputDataValueError?, identifier: InputDataIdentifier, placeholder: String) case selector(sectionId: Int32, index: Int32, value: InputDataValue, error: InputDataValueError?, identifier: InputDataIdentifier, placeholder: String, viewType: GeneralViewType, values:[ValuesSelectorValue<InputDataValue>]) case dataSelector(sectionId: Int32, index: Int32, value: InputDataValue, error: InputDataValueError?, identifier: InputDataIdentifier, placeholder: String, description: String?, icon: CGImage?, action:()->Void) case custom(sectionId: Int32, index: Int32, value: InputDataValue, identifier: InputDataIdentifier, equatable: InputDataEquatable?, comparable: InputDataComparableIndex?, item:(NSSize, InputDataEntryId)->TableRowItem) case search(sectionId: Int32, index: Int32, value: InputDataValue, identifier: InputDataIdentifier, update:(SearchState)->Void) case loading case sectionId(Int32, type: InputDataSectionType) var comparable: InputDataComparableIndex? { switch self { case let .custom(_, _, _, _, _, comparable, _): return comparable default: return nil } } var stableId: InputDataEntryId { switch self { case let .desc(_, index, _, _): return .desc(index) case let .input(_, _, _, _, identifier, _, _, _, _, _, _): return .input(identifier) case let .general(_, _, _, _, identifier, _): return .general(identifier) case let .selector(_, _, _, _, identifier, _, _, _): return .selector(identifier) case let .dataSelector(_, _, _, _, identifier, _, _, _, _): return .dataSelector(identifier) case let .dateSelector(_, _, _, _, identifier, _): return .dateSelector(identifier) case let .custom(_, _, _, identifier, _, _, _): return .custom(identifier) case let .search(_, _, _, identifier, _): return .custom(identifier) case let .sectionId(index, _): return .sectionId(index) case .loading: return .loading } } var stableIndex: Int32 { switch self { case let .desc(_, index, _, _): return index case let .input(_, index, _, _, _, _, _, _, _, _, _): return index case let .general(_, index, _, _, _, _): return index case let .selector(_, index, _, _, _, _, _, _): return index case let .dateSelector(_, index, _, _, _, _): return index case let .dataSelector(_, index, _, _, _, _, _, _, _): return index case let .custom(_, index, _, _, _, _, _): return index case let .search(_, index, _, _, _): return index case .loading: return 0 case .sectionId: fatalError() } } var sectionIndex: Int32 { switch self { case let .desc(index, _, _, _): return index case let .input(index, _, _, _, _, _, _, _, _, _, _): return index case let .selector(index, _, _, _, _, _, _, _): return index case let .general(index, _, _, _, _, _): return index case let .dateSelector(index, _, _, _, _, _): return index case let .dataSelector(index, _, _, _, _, _, _, _, _): return index case let .custom(index, _, _, _, _, _, _): return index case let .search(index, _, _, _, _): return index case .loading: return 0 case .sectionId: fatalError() } } var index: Int32 { switch self { case let .sectionId(sectionId, _): return (sectionId + 1) * 100000 - sectionId default: return (sectionIndex * 100000) + stableIndex } } func item(arguments: InputDataArguments, initialSize: NSSize) -> TableRowItem { switch self { case let .sectionId(_, type): let viewType: GeneralViewType switch type { case .legacy, .custom: viewType = .legacy default: viewType = .separator } return GeneralRowItem(initialSize, height: type.height, stableId: stableId, viewType: viewType) case let .desc(_, _, text, data): return GeneralTextRowItem(initialSize, stableId: stableId, text: text, detectBold: data.detectBold, textColor: data.color, inset: data.inset, viewType: data.viewType, rightItem: data.rightItem, fontSize: data.fontSize, contextMenu: data.contextMenu, clickable: data.clickable) case let .custom(_, _, _, _, _, _, item): return item(initialSize, stableId) case let .selector(_, _, value, error, _, placeholder, viewType, values): return InputDataDataSelectorRowItem(initialSize, stableId: stableId, value: value, error: error, placeholder: placeholder, viewType: viewType, updated: arguments.dataUpdated, values: values) case let .dataSelector(_, _, _, error, _, placeholder, description, icon, action): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: placeholder, icon: icon, nameStyle: ControlStyle(font: .normal(.title), foregroundColor: theme.colors.accent), description: description, type: .none, action: action, error: error) case let .general(_, _, value, error, identifier, data): return GeneralInteractedRowItem(initialSize, stableId: stableId, name: data.name, icon: data.icon, nameStyle: ControlStyle(font: .normal(.title), foregroundColor: data.color), description: data.description, type: data.type, viewType: data.viewType, action: { data.action != nil ? data.action?() : arguments.select((identifier, value)) }, enabled: data.enabled, error: error, disabledAction: data.disabledAction ?? {}, menuItems: data.menuItems, customTheme: data.theme, disableBorder: data.disableBorder) case let .dateSelector(_, _, value, error, _, placeholder): return InputDataDateRowItem(initialSize, stableId: stableId, value: value, error: error, updated: arguments.dataUpdated, placeholder: placeholder) case let .input(_, _, value, error, _, mode, data, placeholder, inputPlaceholder, filter, limit: limit): return InputDataRowItem(initialSize, stableId: stableId, mode: mode, error: error, viewType: data.viewType, currentText: value.stringValue ?? "", currentAttributedText: value.attributedString, placeholder: placeholder, inputPlaceholder: inputPlaceholder, defaultText: data.defaultText, rightItem: data.rightItem, canMakeTransformations: data.canMakeTransformations, maxBlockWidth: data.maxBlockWidth, filter: filter, updated: { _ in arguments.dataUpdated() }, pasteFilter: data.pasteFilter, limit: limit, customTheme: data.customTheme) case .loading: return SearchEmptyRowItem(initialSize, stableId: stableId, isLoading: true) case let .search(_, _, value, _, update): return SearchRowItem(initialSize, stableId: stableId, searchInteractions: SearchInteractions({ state, _ in update(state) }, { state in update(state) }), inset: NSEdgeInsets(left: 10,right: 10, top: 10, bottom: 10)) } } } func <(lhs: InputDataEntry, rhs: InputDataEntry) -> Bool { if let lhsComparable = lhs.comparable, let rhsComparable = rhs.comparable { return lhsComparable < rhsComparable } return lhs.index < rhs.index } func ==(lhs: InputDataEntry, rhs: InputDataEntry) -> Bool { switch lhs { case let .desc(sectionId, index, text, data): if case .desc(sectionId, index, text, data) = rhs { return true } else { return false } case let .input(sectionId, index, lhsValue, lhsError, identifier, mode, data, placeholder, inputPlaceholder, _, limit): if case .input(sectionId, index, let rhsValue, let rhsError, identifier, mode, data, placeholder, inputPlaceholder, _, limit) = rhs { return lhsValue == rhsValue && lhsError == rhsError } else { return false } case let .general(sectionId, index, lhsValue, lhsError, identifier, data): if case .general(sectionId, index, let rhsValue, let rhsError, identifier, data) = rhs { return lhsValue == rhsValue && lhsError == rhsError } else { return false } case let .selector(sectionId, index, lhsValue, lhsError, identifier, placeholder, viewType, lhsValues): if case .selector(sectionId, index, let rhsValue, let rhsError, identifier, placeholder, viewType, let rhsValues) = rhs { return lhsValues == rhsValues && lhsValue == rhsValue && lhsError == rhsError } else { return false } case let .dateSelector(sectionId, index, lhsValue, lhsError, identifier, placeholder): if case .dateSelector(sectionId, index, let rhsValue, let rhsError, identifier, placeholder) = rhs { return lhsValue == rhsValue && lhsError == rhsError } else { return false } case let .dataSelector(sectionId, index, lhsValue, lhsError, identifier, placeholder, description, lhsIcon, _): if case .dataSelector(sectionId, index, let rhsValue, let rhsError, identifier, placeholder, description, let rhsIcon, _) = rhs { return lhsValue == rhsValue && lhsError == rhsError && lhsIcon == rhsIcon } else { return false } case let .custom(_, _, value, identifier, lhsEquatable, comparable, _): if case .custom(_, _, value, identifier, let rhsEquatable, comparable, _) = rhs { return lhsEquatable == rhsEquatable } else { return false } case let .search(sectionId, index, value, identifier, _): if case .search(sectionId, index, value, identifier, _) = rhs { return true } else { return false } case let .sectionId(id, type): if case .sectionId(id, type) = rhs { return true } else { return false } case .loading: if case .loading = rhs { return true } else { return false } } } let InputDataEmptyIdentifier = InputDataIdentifier("") struct InputDataIdentifier : Hashable { let identifier: String init(_ identifier: String) { self.identifier = identifier } func hash(into hasher: inout Hasher) { hasher.combine(identifier) } } func ==(lhs: InputDataIdentifier, rhs: InputDataIdentifier) -> Bool { return lhs.identifier == rhs.identifier } enum InputDataValue : Equatable { case string(String?) case attributedString(NSAttributedString?) case date(Int32?, Int32?, Int32?) case gender(SecureIdGender?) case secureIdDocument(SecureIdVerificationDocument) case none var stringValue: String? { switch self { case let .string(value): return value default: return nil } } var attributedString:NSAttributedString? { switch self { case let .attributedString(value): return value default: return nil } } var secureIdDocument: SecureIdVerificationDocument? { switch self { case let .secureIdDocument(document): return document default: return nil } } var gender: SecureIdGender? { switch self { case let .gender(gender): return gender default: return nil } } } func ==(lhs: InputDataValue, rhs: InputDataValue) -> Bool { switch lhs { case let .string(lhsValue): if case let .string(rhsValue) = rhs { return lhsValue == rhsValue } else { return false } case let .attributedString(lhsValue): if case let .attributedString(rhsValue) = rhs { return lhsValue == rhsValue } else { return false } case let .gender(lhsValue): if case let .gender(rhsValue) = rhs { return lhsValue == rhsValue } else { return false } case let .secureIdDocument(lhsValue): if case let .secureIdDocument(rhsValue) = rhs { return lhsValue.isEqual(to: rhsValue) } else { return false } case let .date(lhsDay, lhsMonth, lhsYear): if case let .date(rhsDay, rhsMonth,rhsYear) = rhs { return lhsDay == rhsDay && lhsMonth == rhsMonth && lhsYear == rhsYear } else { return false } case .none: if case .none = rhs { return true } else { return false } } } enum InputDataValidationFailAction { case shake case shakeWithData(Any) } enum InputDataValidationBehaviour { case navigationBack case navigationBackWithPushAnimation case custom(()->Void) } enum InputDataFailResult { case alert(String) case doSomething(next: (@escaping(InputDataValidation)->Void) -> Void) case textAfter(String, InputDataIdentifier) case fields([InputDataIdentifier: InputDataValidationFailAction]) case none } enum InputDataValidation { case success(InputDataValidationBehaviour) case fail(InputDataFailResult) case none var isSuccess: Bool { switch self { case .success: return true case .fail, .none: return false } } } enum InputDoneValue : Equatable { case enabled(String) case disabled(String) case invisible case loading }
gpl-2.0
562728129860bdc85576453e12b93cc9
36.077574
444
0.634092
4.736577
false
false
false
false
STShenZhaoliang/iOS-GuidesAndSampleCode
精通Swift设计模式/Chapter 11/SportsStore/SportsStore/ViewController.swift
1
3809
import UIKit class ProductTableCell : UITableViewCell { @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var descriptionLabel: UILabel! @IBOutlet weak var stockStepper: UIStepper! @IBOutlet weak var stockField: UITextField! var product:Product?; } var handler = { (p:Product) in println("Change: \(p.name) \(p.stockLevel) items in stock"); }; class ViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var totalStockLabel: UILabel! @IBOutlet weak var tableView: UITableView! var productStore = ProductDataStore(); override func viewDidLoad() { super.viewDidLoad() displayStockTotal(); productStore.callback = {(p:Product) in for cell in self.tableView.visibleCells() { if let pcell = cell as? ProductTableCell { if pcell.product?.name == p.name { pcell.stockStepper.value = Double(p.stockLevel); pcell.stockField.text = String(p.stockLevel); } } } self.displayStockTotal(); } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return productStore.products.count; } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let product = productStore.products[indexPath.row]; let cell = tableView.dequeueReusableCellWithIdentifier("ProductCell") as ProductTableCell; cell.product = productStore.products[indexPath.row]; cell.nameLabel.text = product.name; cell.descriptionLabel.text = product.productDescription; cell.stockStepper.value = Double(product.stockLevel); cell.stockField.text = String(product.stockLevel); return cell; } @IBAction func stockLevelDidChange(sender: AnyObject) { if var currentCell = sender as? UIView { while (true) { currentCell = currentCell.superview!; if let cell = currentCell as? ProductTableCell { if let product = cell.product? { if let stepper = sender as? UIStepper { product.stockLevel = Int(stepper.value); } else if let textfield = sender as? UITextField { if let newValue = textfield.text.toInt()? { product.stockLevel = newValue; } } cell.stockStepper.value = Double(product.stockLevel); cell.stockField.text = String(product.stockLevel); productLogger.logItem(product); } break; } } displayStockTotal(); } } func displayStockTotal() { let finalTotals:(Int, Double) = productStore.products.reduce((0, 0.0), {(totals, product) -> (Int, Double) in return ( totals.0 + product.stockLevel, totals.1 + product.stockValue ); }); var factory = StockTotalFactory.getFactory(StockTotalFactory.Currency.GBP); var totalAmount = factory.converter?.convertTotal(finalTotals.1); var formatted = factory.formatter?.formatTotal(totalAmount!); totalStockLabel.text = "\(finalTotals.0) Products in Stock. " + "Total Value: \(formatted!)"; } }
mit
4b63120dc149b163be066ac412d57665
36.343137
83
0.559464
5.275623
false
false
false
false
moudd974/uCAB
Clients/Tablette/AreaMap.swift
1
1669
// // demo.swift // graphique // // Created by Rémi LAVIELLE on 19/10/2015. // Copyright © 2015 Rémi LAVIELLE. All rights reserved. // import Foundation import UIKit import Socket_IO_Client_Swift import SwiftyJSON class AreaMap: UIView { // Tableau de point var points = [CGPoint(x:0, y:0)] // Dimension du point let pointSize = CGSize(width: 30, height: 30) // INstenciation objet client let monClient = Client() /////////////////////////////////////////////////////////////////////////////////////////////// // GRAPHIQUE /////////////////////////////////////////////////////////////////////////////////////////////// // fonction de dessin surdefini override func drawRect(rect: CGRect) { monClient.dialogueServeur() remplirTablleau(monClient.cercle) } ///////////////////////////////////////////////////////////////////////// // FONCTIONS ///////////////////////////////////////////////////////////////////////// func remplirTablleau(tableau: [CGPoint]) -> [CGPoint] { for var i = 0; i<self.monClient.cercle.capacity; i++ { let q = CGPoint( x: self.monClient.cercle[i].x - pointSize.width/2, y: self.monClient.cercle[i].y - pointSize.height/2) points[i].x = q.x points[i].y = q.y print(points[i].x) print(points[i].y) } print("cont") print(points.capacity) return points } }
gpl-3.0
c63dd7f2784ba75823d36de602cf1653
21.226667
99
0.406963
4.514905
false
false
false
false
muenzpraeger/salesforce-einstein-vision-swift
SalesforceEinsteinVision/Classes/model/Example.swift
1
764
// // Example.swift // predictivevision // // Created by René Winkelmeyer on 02/28/2017. // Copyright © 2016 René Winkelmeyer. All rights reserved. // import Foundation import SwiftyJSON public struct Example { public var id: Int? public var name: String? public var location: String? public var createdAt: String? public var label: Label? public var object: String? init?() { } init?(jsonObject: SwiftyJSON.JSON) { id = jsonObject["id"].int name = jsonObject["name"].string location = jsonObject["location"].string createdAt = jsonObject["createdAt"].string label = Label(jsonObject: jsonObject["label"]) object = jsonObject["object"].string } }
apache-2.0
a17f075bdbbdc56765ac3d148168f8cd
22.060606
59
0.630749
4.227778
false
false
false
false
mercadopago/sdk-ios
MercadoPagoSDKExamples/MercadoPagoSDKExamples/AppDelegate.swift
1
6540
// // AppDelegate.swift // MercadoPagoSDKExamples // // Created by Matias Gualino on 6/4/15. // Copyright (c) 2015 MercadoPago. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? var nav: UINavigationController? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Initialize window self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window?.backgroundColor = UIColor.whiteColor() self.nav = UINavigationController() let exmaplesViewController = ExamplesViewController() // Put vaultController at the top of navigator. self.nav!.pushViewController(exmaplesViewController, animated: false) self.window?.rootViewController = self.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 throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. // Saves changes in the application's managed object context before the application terminates. self.saveContext() } // MARK: - Core Data stack lazy var applicationDocumentsDirectory: NSURL = { // The directory the application uses to store the Core Data store file. This code uses a directory named "com.mercadopago.MercadoPagoSDKExamples" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("MercadoPagoSDKExamples", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("MercadoPagoSDKExamples.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." do { var aux : AnyObject? = try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil) if aux == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict) // Replace this with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } catch { } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { do { try moc.save() if moc.hasChanges { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } catch { } } } }
mit
411e9c6c28daad69acfb08a8de39a55c
48.172932
290
0.72737
5.481978
false
false
false
false
SmallElephant/FEAlgorithm-Swift
2-Dynamic/2-Dynamic/Elevator.swift
1
1824
// // Elevator.swift // 2-Dynamic // // Created by keso on 2017/2/25. // Copyright © 2017年 FlyElephant. All rights reserved. // import Foundation class Elevator { var person:[Int] = [] func compute(person:[Int],maxFloor:Int) -> (Int,Int) { var minFloor:Int = 0 var targetFloor:Int = 0 for i in 1...maxFloor { // 电梯停留在i层 var temp:Int = 0 for j in 1...maxFloor { temp += person[j] * abs(i - j) } if i == 1 { minFloor = temp targetFloor = 1 } else { if temp < minFloor { minFloor = temp targetFloor = i } } } return (minFloor,targetFloor) } func compute2(person:[Int],maxFloor:Int) -> (Int,Int) { var n1:Int = 0 // 第i层以下的人数 var n2:Int = person[1] // 第i层的人数 var n3:Int = 0 // 第i层以上的人数 var countFloor:Int = 0 // 第i层的时候所走的楼层总数 var targetFloor:Int = 1 for i in 2...maxFloor { countFloor += person[i] * (i - 1) n3 += person[i] } // 如果楼层变为i-1层 总层为 count + (n2 + n3 - n1) // 如果楼层变为i+1层 总层为 count + (n1 + n2 - n3) for i in 2...maxFloor { if n1+n2 < n3 { targetFloor = i countFloor += n1 + n2 - n3 n1 += n2 //n1 增加 n2 = person[i] n3 -= person[i] // n3 减少 } else { break } } return (countFloor,targetFloor) } }
mit
5482ba6ce15505c79838ef1c5831a06e
22.273973
59
0.413184
3.524896
false
false
false
false
ryanbaldwin/Restivus
Tests/HTTPURLResponse+ExtensionsSpec.swift
1
2372
// // HTTPURLResponse+ExtensionsSpec.swift // Restivus // // Created by Ryan Baldwin on 2017-10-01. //Copyright © 2017 bunnyhug.me. All rights reserved. // import Quick import Nimble class HTTPURLResponse_ExtensionsSpec: QuickSpec { override func spec() { describe("HTTPURLResponse") { it("isInformational when statusCode is 1xx") { let response = makeURLResponse(102) expect(response.isInformational) == true expect(response.isSuccess) == false expect(response.isRedirection) == false expect(response.isClientError) == false expect(response.isServerError) == false } it("isSuccess when statusCode is 2xx") { let response = makeURLResponse(204) expect(response.isInformational) == false expect(response.isSuccess) == true expect(response.isRedirection) == false expect(response.isClientError) == false expect(response.isServerError) == false } it("isRedirection when statusCode is 3xx") { let response = makeURLResponse(302) expect(response.isInformational) == false expect(response.isSuccess) == false expect(response.isRedirection) == true expect(response.isClientError) == false expect(response.isServerError) == false } it("isClientError when statusCode is 4xx") { let response = makeURLResponse(401) expect(response.isInformational) == false expect(response.isSuccess) == false expect(response.isRedirection) == false expect(response.isClientError) == true expect(response.isServerError) == false } it("isServerError when statusCode is 5xx") { let response = makeURLResponse(500) expect(response.isInformational) == false expect(response.isSuccess) == false expect(response.isRedirection) == false expect(response.isClientError) == false expect(response.isServerError) == true } } } }
apache-2.0
74a0d8cd89ea8214ff393961125859b9
37.868852
58
0.554618
5.316143
false
false
false
false
zisko/swift
stdlib/public/core/CTypes.swift
1
7536
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // C Primitive Types //===----------------------------------------------------------------------===// /// The C 'char' type. /// /// This will be the same as either `CSignedChar` (in the common /// case) or `CUnsignedChar`, depending on the platform. public typealias CChar = Int8 /// The C 'unsigned char' type. public typealias CUnsignedChar = UInt8 /// The C 'unsigned short' type. public typealias CUnsignedShort = UInt16 /// The C 'unsigned int' type. public typealias CUnsignedInt = UInt32 /// The C 'unsigned long' type. #if os(Windows) && arch(x86_64) public typealias CUnsignedLong = UInt32 #else public typealias CUnsignedLong = UInt #endif /// The C 'unsigned long long' type. public typealias CUnsignedLongLong = UInt64 /// The C 'signed char' type. public typealias CSignedChar = Int8 /// The C 'short' type. public typealias CShort = Int16 /// The C 'int' type. public typealias CInt = Int32 /// The C 'long' type. #if os(Windows) && arch(x86_64) public typealias CLong = Int32 #else public typealias CLong = Int #endif /// The C 'long long' type. public typealias CLongLong = Int64 /// The C 'float' type. public typealias CFloat = Float /// The C 'double' type. public typealias CDouble = Double // FIXME: long double // FIXME: Is it actually UTF-32 on Darwin? // /// The C++ 'wchar_t' type. public typealias CWideChar = Unicode.Scalar // FIXME: Swift should probably have a UTF-16 type other than UInt16. // /// The C++11 'char16_t' type, which has UTF-16 encoding. public typealias CChar16 = UInt16 /// The C++11 'char32_t' type, which has UTF-32 encoding. public typealias CChar32 = Unicode.Scalar /// The C '_Bool' and C++ 'bool' type. public typealias CBool = Bool /// A wrapper around an opaque C pointer. /// /// Opaque pointers are used to represent C pointers to types that /// cannot be represented in Swift, such as incomplete struct types. @_fixed_layout public struct OpaquePointer { @_versioned internal var _rawValue: Builtin.RawPointer @_inlineable // FIXME(sil-serialize-all) @_versioned @_transparent internal init(_ v: Builtin.RawPointer) { self._rawValue = v } /// Creates an `OpaquePointer` from a given address in memory. @_inlineable // FIXME(sil-serialize-all) @_transparent public init?(bitPattern: Int) { if bitPattern == 0 { return nil } self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue) } /// Creates an `OpaquePointer` from a given address in memory. @_inlineable // FIXME(sil-serialize-all) @_transparent public init?(bitPattern: UInt) { if bitPattern == 0 { return nil } self._rawValue = Builtin.inttoptr_Word(bitPattern._builtinWordValue) } /// Converts a typed `UnsafePointer` to an opaque C pointer. @_inlineable // FIXME(sil-serialize-all) @_transparent public init<T>(_ from: UnsafePointer<T>) { self._rawValue = from._rawValue } /// Converts a typed `UnsafePointer` to an opaque C pointer. /// /// The result is `nil` if `from` is `nil`. @_inlineable // FIXME(sil-serialize-all) @_transparent public init?<T>(_ from: UnsafePointer<T>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } /// Converts a typed `UnsafeMutablePointer` to an opaque C pointer. @_inlineable // FIXME(sil-serialize-all) @_transparent public init<T>(_ from: UnsafeMutablePointer<T>) { self._rawValue = from._rawValue } /// Converts a typed `UnsafeMutablePointer` to an opaque C pointer. /// /// The result is `nil` if `from` is `nil`. @_inlineable // FIXME(sil-serialize-all) @_transparent public init?<T>(_ from: UnsafeMutablePointer<T>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } } extension OpaquePointer: Equatable { @_inlineable // FIXME(sil-serialize-all) public static func == (lhs: OpaquePointer, rhs: OpaquePointer) -> Bool { return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue)) } } extension OpaquePointer: Hashable { /// The pointer's hash value. /// /// The hash value is not guaranteed to be stable across different /// invocations of the same program. Do not persist the hash value across /// program runs. @_inlineable // FIXME(sil-serialize-all) public var hashValue: Int { return Int(Builtin.ptrtoint_Word(_rawValue)) } } extension OpaquePointer : CustomDebugStringConvertible { /// A textual representation of the pointer, suitable for debugging. @_inlineable // FIXME(sil-serialize-all) public var debugDescription: String { return _rawPointerToString(_rawValue) } } extension Int { /// Creates a new value with the bit pattern of the given pointer. /// /// The new value represents the address of the pointer passed as `pointer`. /// If `pointer` is `nil`, the result is `0`. /// /// - Parameter pointer: The pointer to use as the source for the new /// integer. @_inlineable // FIXME(sil-serialize-all) public init(bitPattern pointer: OpaquePointer?) { self.init(bitPattern: UnsafeRawPointer(pointer)) } } extension UInt { /// Creates a new value with the bit pattern of the given pointer. /// /// The new value represents the address of the pointer passed as `pointer`. /// If `pointer` is `nil`, the result is `0`. /// /// - Parameter pointer: The pointer to use as the source for the new /// integer. @_inlineable // FIXME(sil-serialize-all) public init(bitPattern pointer: OpaquePointer?) { self.init(bitPattern: UnsafeRawPointer(pointer)) } } /// A wrapper around a C `va_list` pointer. @_fixed_layout public struct CVaListPointer { @_versioned // FIXME(sil-serialize-all) internal var value: UnsafeMutableRawPointer @_inlineable // FIXME(sil-serialize-all) public // @testable init(_fromUnsafeMutablePointer from: UnsafeMutableRawPointer) { value = from } } extension CVaListPointer : CustomDebugStringConvertible { /// A textual representation of the pointer, suitable for debugging. @_inlineable // FIXME(sil-serialize-all) public var debugDescription: String { return value.debugDescription } } @_versioned @_inlineable internal func _memcpy( dest destination: UnsafeMutableRawPointer, src: UnsafeRawPointer, size: UInt ) { let dest = destination._rawValue let src = src._rawValue let size = UInt64(size)._value Builtin.int_memcpy_RawPointer_RawPointer_Int64( dest, src, size, /*alignment:*/ Int32()._value, /*volatile:*/ false._value) } /// Copy `count` bytes of memory from `src` into `dest`. /// /// The memory regions `source..<source + count` and /// `dest..<dest + count` may overlap. @_versioned @_inlineable internal func _memmove( dest destination: UnsafeMutableRawPointer, src: UnsafeRawPointer, size: UInt ) { let dest = destination._rawValue let src = src._rawValue let size = UInt64(size)._value Builtin.int_memmove_RawPointer_RawPointer_Int64( dest, src, size, /*alignment:*/ Int32()._value, /*volatile:*/ false._value) }
apache-2.0
d1c1d038597bb51d79ec7b30505954cb
27.984615
80
0.675027
4.091205
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/Platform/Sources/PlatformUIKit/TodayExtension/TodayAssetPriceView/TodayAssetPriceView.swift
1
1849
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import RxCocoa import RxSwift public final class TodayAssetPriceView: UIView { // MARK: - Injected public var presenter: TodayAssetPriceViewPresenter! { willSet { disposeBag = DisposeBag() } didSet { guard let presenter = presenter else { return } presenter.alignment .drive(stackView.rx.alignment) .disposed(by: disposeBag) presenter.state .compactMap(\.value) .bindAndCatch(to: rx.values) .disposed(by: disposeBag) } } // MARK: - Private Properties fileprivate let priceLabel = UILabel() fileprivate let changeLabel = UILabel() private let stackView = UIStackView() private var disposeBag = DisposeBag() // MARK: - Setup override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } private func setup() { backgroundColor = .clear addSubview(stackView) stackView.fillSuperview() stackView.layout(dimension: .height, to: 32, priority: .defaultLow) stackView.addArrangedSubview(priceLabel) stackView.addArrangedSubview(changeLabel) stackView.distribution = .fillProportionally stackView.axis = .vertical stackView.spacing = 4.0 } } // MARK: - Rx extension Reactive where Base: TodayAssetPriceView { var values: Binder<TodayAssetPriceViewPresenter.Presentation> { Binder(base) { view, values in view.priceLabel.content = values.price view.changeLabel.attributedText = values.change } } }
lgpl-3.0
6c21acabaec261fe81b8def36cd9edc2
25.028169
75
0.604978
5.021739
false
false
false
false
RichardLClark/TimeView
TimeViewDemo/TestTimeViewAlignment/ViewController.swift
1
3254
// // ViewController.swift // TestTimeViewAlignment // // Created by Richard Clark on 10/10/15. // Copyright © 2015 Richard Clark. All rights reserved. // import UIKit class ViewController: UIViewController { var timeView: TimeView = TimeView() @IBOutlet weak var fontSlider: UISlider? @IBOutlet weak var amPmPctSlider: UISlider? @IBOutlet weak var timeSlider: UISlider? @IBOutlet weak var alignmentChoice: UISegmentedControl? @IBOutlet weak var is24HourSwitch: UISwitch? @IBOutlet weak var amPmBelowSwitch: UISwitch? var startDate: NSDate = NSDate() override func viewDidLoad() { super.viewDidLoad() view.addSubview(timeView) timeView.y = 20 timeView.amPmBelow = true timeView.alignment = TimeViewAlignment.Left // timeView.debugColors = true timeView.backgroundColor = UIColor.darkGrayColor() timeView.textColor = UIColor.cyanColor() timeView.mainFontName = "HelveticaNeue-Thin" timeView.amPmFontName = "HelveticaNeue-Thin" timeView.timeIsValid = false fontSlider!.value = Float(timeView.mainFontSize) amPmPctSlider?.value = Float(timeView.amPmFontSize / timeView.mainFontSize) is24HourSwitch?.on = timeView.is24Hour amPmBelowSwitch?.on = timeView.amPmBelow let comps = NSDateComponents() comps.hour = 0 comps.minute = 0 startDate = NSCalendar.currentCalendar().dateFromComponents(comps)! } override func viewDidLayoutSubviews() { switch timeView.alignment { case .Left: timeView.x = 20 case .Center, .Fixed: timeView.centerX = view.width / 2 case .Right: timeView.rightX = view.width - 20 } } @IBAction func fontSliderValueChanged(sender: UISlider) { timeView.mainFontSize = CGFloat(fontSlider!.value) timeView.amPmFontSize = CGFloat(amPmPctSlider!.value) * timeView.mainFontSize viewDidLayoutSubviews() } @IBAction func amPmPctSliderValueChanged(sender: UISlider) { timeView.amPmFontSize = CGFloat(amPmPctSlider!.value) * timeView.mainFontSize viewDidLayoutSubviews() } @IBAction func timeSliderValueChanged(sender: UISlider) { timeView.time = startDate.dateByAddingTimeInterval(60 * NSTimeInterval(timeSlider!.value)) timeView.timeIsValid = true viewDidLayoutSubviews() } @IBAction func alignmentChoiceChanged(sender: UISegmentedControl) { switch alignmentChoice!.selectedSegmentIndex { case 0: timeView.alignment = TimeViewAlignment.Left case 1: timeView.alignment = TimeViewAlignment.Center case 2: timeView.alignment = TimeViewAlignment.Right case 3: timeView.alignment = TimeViewAlignment.Fixed default: break; } viewDidLayoutSubviews() } @IBAction func is24HourSwitchFlipped() { timeView.is24Hour = is24HourSwitch!.on viewDidLayoutSubviews() } @IBAction func amPmBelowSwitchFlipped() { timeView.amPmBelow = amPmBelowSwitch!.on viewDidLayoutSubviews() } }
mit
34d32542aad8d81c58a95e84142d3f9c
31.858586
98
0.659699
4.714493
false
false
false
false
mbalex99/RippleEffectView
Demo/RippleEffectDemo/ViewController.swift
1
4186
// // ViewController.swift // RippleEffectDemo // // Created by Alex Sergeev on 8/21/16. // Copyright © 2016 ALSEDI Group. All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import UIKit extension UIColor { static var random: UIColor { get { let hue = CGFloat(Double(arc4random() % 360) / 360.0) // 0.0 to 1.0 let saturation: CGFloat = 0.7 let brightness: CGFloat = 0.8 return UIColor(hue: hue, saturation: saturation, brightness: brightness, alpha: 1.0) } } } class ViewController: UIViewController { var rippleEffectView: RippleEffectView! override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { rippleEffectView = RippleEffectView() rippleEffectView.tileImage = UIImage(named: "cell-image") rippleEffectView.magnitude = 0.2 rippleEffectView.cellSize = CGSize(width:50, height:50) rippleEffectView.rippleType = .Heartbeat view.addSubview(rippleEffectView) //Example, simple tile image customization /* rippleEffectView.tileImageCustomizationClosure = {rows, columns, row, column, image in if (row % 2 == 0 && column % 2 == 0) { let newImage = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) UIGraphicsBeginImageContextWithOptions(image.size, false, newImage.scale) UIColor.random.set() newImage.drawInRect(CGRectMake(0, 0, image.size.width, newImage.size.height)); if let titledImage = UIGraphicsGetImageFromCurrentImageContext() { UIGraphicsEndImageContext() return titledImage } UIGraphicsEndImageContext() } return image } */ //Example 2: Complex tile image customization rippleEffectView.tileImageCustomizationClosure = { rows, columns, row, column, image in let newImage = image.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) UIGraphicsBeginImageContextWithOptions(image.size, false, newImage.scale) let xmiddle = (columns % 2 != 0) ? columns/2 : columns/2 + 1 let ymiddle = (rows % 2 != 0) ? rows/2 : rows/2 + 1 let xoffset = abs(xmiddle - column) let yoffset = abs(ymiddle - row) UIColor(hue: 206/360.0, saturation: 1, brightness: 0.95, alpha: 1).colorWithAlphaComponent(1.0 - CGFloat((xoffset + yoffset)) * 0.1).set() newImage.drawInRect(CGRectMake(0, 0, image.size.width, newImage.size.height)); if let titledImage = UIGraphicsGetImageFromCurrentImageContext() { UIGraphicsEndImageContext() return titledImage } UIGraphicsEndImageContext() return image } rippleEffectView.setupView() rippleEffectView.animationDidStop = { [unowned self] in //Each time animation sequency finished this callback will change background of the wrapper view. UIView.animateWithDuration(1.5) { _ in self.rippleEffectView.backgroundColor = UIColor.random.colorWithAlphaComponent(0.25) } } } override func viewDidAppear(animated: Bool) { rippleEffectView.startAnimating() } }
mit
b85cbf11fb24bbd7be041e4868d1a3db
37.394495
144
0.701314
4.543974
false
false
false
false
XGBCCC/LittleKnowledgePoint
字符串算法.playground/Contents.swift
1
5979
//: Playground - noun: a place where people can play import UIKit //var str = "Hello, playground" // //let string = "abcabab" // //求一个字符串中连续出现次数最多的子串,请给出分析和代码 //解析:这里首先要搞清楚子串的概念,1个字符当然也算字串,注意看题目,是求连续 出现次数最多的子串。如果字符串是abcbcbcabc,这个连续出现次数最多的子串是bc,连续 出现次数为3次。如果类似于abcccabc,则连续出现次数最多的子串为c,次数也是3次。这个 题目可以首先逐个子串扫描来记录每个子串出现的次数。比如:abc这个字串,对应子串为 a/b/c/ab/bc/abc,各出现过一次,然后再逐渐缩小字符子串来得出正确的结果。 func test1(str:String)->String{ var tt = [String]() for i in 0..<str.characters.count-1 { let endIndex = str.index(str.startIndex, offsetBy: i) tt.append(str.substring(from: endIndex)) } var maxCount = 0 var count = 0 var subStr = "" for i in 0..<str.characters.count-1 { print("-----------") for j in i+1..<str.characters.count-1{ if j-i > tt[j].characters.count { break } var startIndex = str.index(str.startIndex, offsetBy: i) var endIndex = str.index(str.startIndex, offsetBy: j-i) print(tt[i]) print(tt[j]) print("比较:\(tt[j].substring(with: str.startIndex..<endIndex))") if tt[i].substring(with: str.startIndex..<endIndex) == tt[j].substring(with: str.startIndex..<endIndex) { print("匹配") count += 1 var k = j if k+(k-i)>=str.characters.count-1 { if count>maxCount { var subEndIndex = str.index(str.startIndex, offsetBy: j-i) maxCount = count subStr = tt[i].substring(with: tt[i].startIndex..<subEndIndex) print("1--\(subStr)") break } }else{ while k<str.characters.count-1 { var subEndIndex = str.index(str.startIndex, offsetBy: j-i) if tt[i].substring(with: startIndex..<subEndIndex) == tt[k].substring(with: str.startIndex..<subEndIndex) { count += 1 if count>maxCount { maxCount = count subStr = tt[i].substring(with: tt[i].startIndex..<subEndIndex) print(tt[k]) print("count:\(maxCount)--\(subStr)") } } k = k+(j-i) } } } } } return subStr } //找出最长相同的子串 func test2(str:String){ var tt = [String]() for i in 0..<str.characters.count{ let endIndex = str.index(str.startIndex, offsetBy: i) tt.append(str.substring(from: endIndex)) } var maxCount = 0 var count = 0 var subStr = "" for i in 0..<str.characters.count { for j in i+1..<str.characters.count{ var startIndex = str.index(str.startIndex, offsetBy: i) var endIndex = str.index(str.startIndex, offsetBy: tt[j].characters.count) print(tt[i]) print(tt[j]) print("比较:\(tt[j].substring(with: str.startIndex..<endIndex))") if tt[i].substring(with: str.startIndex..<endIndex) == tt[j].substring(with: str.startIndex..<endIndex) { if tt[i].substring(with: tt[i].startIndex..<endIndex).characters.count > subStr.characters.count { subStr = tt[i].substring(with: tt[i].startIndex..<endIndex) print("结果:\(subStr)") } } } } } //转换字符串格式为原来字符串里的字符+该字符连续出现的个数,例如字符串 1233422222,转化为1121324125(1出现1次,2出现1次,3出现2次……)。 func tttt(str:String){ var currentStr = "" var currentCount = 0 var newString = "" for i in 0..<str.characters.count { let startIndex = str.index(str.startIndex, offsetBy: i) let endIndex = str.index(startIndex, offsetBy: 1) let temp = str.substring(with: startIndex..<endIndex) if currentStr == temp { currentCount += 1 if i == str.characters.count - 1 { newString.append("\(currentCount)") } }else{ if currentCount > 0 { newString.append("\(currentCount)") } currentStr = str.substring(with: startIndex..<endIndex) currentCount = 1 newString.append("\(currentStr)") } } print(newString) } tttt(str: "1233422222") //移动字符串内容,传入参数char *a和m,规则如下:将a中字符串的倒数m个字符移到字符串前面,其余依次像右移。例如:ABCDEFGHI,M=3,那么移到之后就是GHIABCDEF func qqqq(str:[String],count:Int){ var tt = str var count = count if tt.count>count { while count>0 { var tmp = tt[0] tt[0] = tt[tt.count-1]; var i = str.count - 1 while i>=1 { if i == 1 { tt[i] = tmp print(tt) }else{ tt[i] = tt[i-1] print(tt) } i -= 1 } count -= 1 } } print(tt) } qqqq(str: ["A","B","C","D","E","F","G","H","I"], count: 3)
mit
78a796993f28b0b2ec5e81f9805d0c0a
32.929936
220
0.486953
3.778014
false
false
false
false
ndevenish/KerbalHUD
KerbalHUD/LadderHorizonWidget.swift
1
6308
// // LadderHorizonWidget.swift // KerbalHUD // // Created by Nicholas Devenish on 07/09/2015. // Copyright © 2015 Nicholas Devenish. All rights reserved. // import UIKit import GLKit private struct LadderHorizonSettings { /// Use a 180 or 360 degree horizon var use360Horizon : Bool = true /// The vertical angle of view for the horizon var verticalAngleView : Float = 90 /// The color of the ladder lines var foregroundColor : Color4 = Color4.Green /// Show the prograde marker? var progradeMarker : Bool = true var progradeColor : Color4 = Color4(0.84, 0.98, 0, 1) } private struct FlightData { var Pitch : Float = 0 var Roll : Float = 0 var AngleOfAttack : Float? } class LadderHorizonWidget : Widget { private(set) var bounds : Bounds private(set) var variables : [String] = [ Vars.Flight.Pitch, Vars.Flight.Roll ] private let drawing : DrawingTools private let text : TextRenderer private var data : FlightData? private let settings = LadderHorizonSettings() // private var progradeMarker : Drawable? private let progradeMarker : Texture? init(tools : DrawingTools, bounds : Bounds) { self.drawing = tools self.text = tools.textRenderer("Menlo") self.bounds = bounds // Generate a prograde marker if we want one if settings.progradeMarker { variables.append(Vars.Aero.AngleOfAttack) progradeMarker = tools.images["Prograde"] } else { progradeMarker = nil } } func update(data : [String : JSON]) { if let pitch = data[Vars.Flight.Pitch]?.float, let roll = data[Vars.Flight.Roll]?.float { let aOa = data[Vars.Aero.AngleOfAttack]?.float self.data = FlightData(Pitch: pitch, Roll: roll, AngleOfAttack: aOa) } else { self.data = nil } } func draw() { guard let data = self.data else { return } // Constrain drawing to the bounds drawing.ConstrainDrawing(bounds) // Draw a background drawing.program.setModelView(GLKMatrix4Identity) // Set the drawing color drawing.program.setColor(settings.foregroundColor) // Because of roll corners, effective size is increased according to aspect let pitchHeight = settings.verticalAngleView * sqrt(pow(bounds.size.aspect, 2)+1) // Calculate the angle range to draw lines and text for let angleRangeFor360 = (min: Int(floor((data.Pitch - pitchHeight/2)/10)*10), max: Int(ceil( (data.Pitch + pitchHeight/2)/10)*10)) let angleRange = settings.use360Horizon ? angleRangeFor360 : (min: max(angleRangeFor360.min, -90), max: min(angleRangeFor360.max, 90)) // Build a transform to apply to all drawing to put us in horizon frame var frame = GLKMatrix4Identity // Put us in the center of the bounds frame = GLKMatrix4Translate(frame, bounds.center.x, bounds.center.y, 0) // Rotate according to the roll frame = GLKMatrix4Rotate(frame, data.Roll*π/180, 0, 0, -1) // And translate for pitch in the center let preScaleFrame = GLKMatrix4Translate(frame, 0, (-data.Pitch/settings.verticalAngleView)*bounds.height, 0) // And scale so the height = vertical view let heightScale = settings.verticalAngleView / bounds.height frame = GLKMatrix4Scale(preScaleFrame, bounds.width, 1/heightScale, 1) // Draw bars every 5 degrees let maxBarWidth : Float = 0.4 for var angle = angleRange.min; angle <= angleRange.max; angle += 5 { let width : GLfloat if angle % 20 == 0 { width = 0.4 } else if angle % 10 == 0 { width = 0.6*0.4 } else { width = 0.2*0.4 } let thickness : GLfloat = angle % 20 == 0 ? 1 : 0.5 let y = GLfloat(angle) drawing.DrawLine( from: (-width/2, y), to: (width/2, y), width: thickness, transform: frame) } // Do the text labels // Additionally transform the frame so that the axis are equal aspect // frame = GLKMatrix4Scale(frame, 1, heightScale*bounds.height, 1) let textOffset = (maxBarWidth + 0.05) / 2 let baseFontSize : Float = 5 // / heightScale for var angle = angleRange.min; angle <= angleRange.max; angle += 10 { if angle % 20 != 0 { continue } let y = GLfloat(angle)///heightScale text.draw(String(format: "%d", angle), size: (angle == 0 ? baseFontSize*1.6 : baseFontSize), position: (-textOffset, y), align: .Left, rotation: π, transform: frame) text.draw(String(format: "%d", angle), size: (angle == 0 ? baseFontSize*1.6 : baseFontSize), position: (textOffset, y), align: .Left, rotation: 0, transform: frame) } // Prograde marker if let aoa = data.AngleOfAttack, let pgm = progradeMarker { // Set the color and start building the transformation drawing.program.setColor(Color4.White) var progradeFrame = preScaleFrame // Re-apply the scaling, but in an equal-aspect way progradeFrame = GLKMatrix4Scale(progradeFrame, 1/heightScale, 1/heightScale, 1) // Move it, in the frame of reference of the angles progradeFrame = GLKMatrix4Translate(progradeFrame, 0, data.Pitch-aoa, 0) // Scale this to match the frame scale // Scale to the right size e.g. 10 degrees tall progradeFrame = GLKMatrix4Scale(progradeFrame, 20, 20, 1) // And roll backwards... progradeFrame = GLKMatrix4Rotate(progradeFrame, -data.Roll*π/180, 0, 0, -1) drawing.program.setModelView(progradeFrame) drawing.bind(pgm) drawing.draw(drawing.texturedCenterSquare!) } // Remove the stencil constraints drawing.UnconstrainDrawing() } } func GenerateProgradeMarker(tools: DrawingTools, size : GLfloat = 1) -> Drawable { // Calculate scale so that the marker ends up covering -size...size let scale = size / 32 var tris = GenerateCircleTriangles(11.0 * scale, w: 4.0*scale) tris.appendContentsOf(GenerateBoxTriangles(-30*scale, bottom: -1*scale, right: -14*scale, top: 1*scale)) tris.appendContentsOf(GenerateBoxTriangles(-1*scale, bottom: 14*scale, right: 1*scale, top: 30*scale)) tris.appendContentsOf(GenerateBoxTriangles(14*scale, bottom: -1*scale, right: 30*scale, top: 1*scale)) return tools.LoadTriangles(tris) }
mit
3059d5e924483872d5c6f29bf5e23cc3
35.445087
112
0.664023
3.743468
false
false
false
false
adis300/Swift-Learn
SwiftLearn/Source/Extension/Collection.swift
1
962
// // Collection.swift // Swift-Learn // // Created by Disi A on 11/26/16. // Copyright © 2016 Votebin. All rights reserved. // import Foundation extension MutableCollection /*where Indices.Iterator.Element == Index*/ { /// Shuffles the contents of this collection. mutating func shuffle() { let c = count guard c > 1 else { return } for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) { let d: IndexDistance = numericCast(arc4random_uniform(numericCast(unshuffledCount))) guard d != 0 else { continue } let i = index(firstUnshuffled, offsetBy: d) self.swapAt(firstUnshuffled, i) } } } extension Sequence { /// Returns an array with the contents of this sequence, shuffled. public func shuffled() -> [Iterator.Element] { var result = Array(self) result.shuffle() return result } }
apache-2.0
3aeeeb17d3c78ad8aead34cb92e3f705
28.121212
97
0.617066
4.160173
false
false
false
false
aiwalle/LiveProject
LiveProject/Tools/Emitterable.swift
1
1555
// // Emitterable.swift // LiveProject // // Created by liang on 2017/8/30. // Copyright © 2017年 liang. All rights reserved. // import UIKit protocol Emitterable { } extension Emitterable where Self : UIViewController { func startEmittering(_ point : CGPoint) { // 粒子动画 let emmiter = CAEmitterLayer() emmiter.emitterPosition = point emmiter.preservesDepth = true var cells = [CAEmitterCell]() for i in 0..<10 { let cell = CAEmitterCell() cell.birthRate = 10 cell.lifetime = 3 cell.lifetimeRange = 2 cell.scale = 0.7 cell.scaleRange = 0.2 cell.emissionLongitude = CGFloat(-Double.pi / 2) cell.emissionRange = CGFloat(Double.pi / 12) cell.velocity = 50 cell.velocityRange = 20 cell.contents = UIImage(named: "good\(i)_30x30")?.cgImage cell.birthRate = 2 cell.spin = CGFloat(.pi / 2.0) cell.spinRange = CGFloat(.pi / 4.0 ) cells.append(cell) } emmiter.emitterCells = cells view.layer.addSublayer(emmiter) } func stopEmittering() { /* for layer in view.layer.sublayers! { if layer.isKind(of: CAEmitterLayer.self) { layer.removeFromSuperlayer() } } */ view.layer.sublayers?.filter({ $0.isKind(of: CAEmitterLayer.self)}).first?.removeFromSuperlayer() } }
mit
da6374a2b0a2efd138d2c7c1bce90e07
26.087719
105
0.545984
4.39886
false
false
false
false
Pluto-Y/SwiftyEcharts
SwiftyEcharts/Models/Legend.swift
1
13737
// // Legend.swift // SwiftyEcharts // // Created by Pluto Y on 02/12/2016. // Copyright © 2016 com.pluto-y. All rights reserved. // /// 图例组件。 /// 图例组件展现了不同系列的标记(symbol),颜色和名字。可以通过点击图例控制哪些系列不显示。 /// ECharts 3 中单个 echarts 实例中可以存在多个图例组件,会方便多个图例的布局。 public final class Legend: Borderable, Displayable, Formatted, Shadowable, Zable { /// 图例的数据数组。数组项通常为一个字符串,每一项代表一个系列的 `name`(如果是饼图,也可以是饼图单个数据的 `name`)。图例组件会自动获取对应系列的颜色,图形标记(symbol)作为自己绘制的颜色和标记,特殊字符串 `''`(空字符串)或者 `'\n'`(换行字符串)用于图例的换行。 /// /// 如果要设置单独一项的样式,也可以把该项写成配置项对象。此时必须使用 name 属性对应表示系列的 name。 /// /// 示例 /// /// data: [{ /// name: '系列1', /// // 强制设置图形为圆。 /// icon: 'circle', /// // 设置文本为红色 /// textStyle: { /// color: 'red' /// } /// }] public final class Data { /// 图例项的名称,应等于某系列的`name`值(如果是饼图,也可以是饼图单个数据的`name`)。 public var name: String? /// 图例项的 icon。 public var icon: Symbol? /// 图例项的文本样式。 public var textStyle: TextStyle? public init() { } } public var show: Bool? /// 所有图形的 zlevel 值。 /// zlevel用于 Canvas 分层,不同zlevel值的图形会放置在不同的 Canvas 中,Canvas 分层是一种常见的优化手段。我们可以把一些图形变化频繁(例如有动画)的组件设置成一个单独的zlevel。需要注意的是过多的 Canvas 会引起内存开销的增大,在手机端上需要谨慎使用以防崩溃。 /// zlevel 大的 Canvas 会放在 zlevel 小的 Canvas 的上面。 public var zlevel: Float? /// 组件的所有图形的z值。控制图形的前后顺序。z值小的图形会被z值大的图形覆盖。 /// z相比zlevel优先级更低,而且不会创建新的 Canvas。 public var z: Float? /// 图例组件离容器左侧的距离。 public var left: Position? /// 图例组件离容器上侧的距离。 public var top: Position? /// 图例组件离容器右侧的距离。 public var right: Position? /// 图例组件离容器下侧的距离。 public var bottom: Position? /// 图例组件的宽度。为空时,为自适应。 public var width: Float? /// 图例组件的高度。为空时,为自适应。 public var height: Float? /// 图例列表的布局朝向。 public var orient: Orient? /// 图例标记和文本的对齐。默认自动,根据组件的位置和 orient 决定,当组件的 left 值为 'right' 以及纵向布局(orient 为 'vertical')的时候为右对齐,及为 'right'。 public var align: Align? /// 图例内边距,单位px,默认各方向内边距为5,接受数组分别设定上右下左边距。 public var padding: Padding? /// 图例每项之间的间隔。横向布局时为水平间隔,纵向布局时为纵向间隔。 public var itemGap: Float? /// 图例标记的图形宽度。 public var itemWidth: Float? /// 图例标记的图形搞度。 public var itemHeight: Float? /// 用来格式化图例文本,支持字符串模板和回调函数两种形式。 public var formatter: Formatter? /// 图例选择的模式,控制是否可以通过点击图例改变系列的显示状态。 public var selectedMode: SelectedMode? /// 图例关闭时的颜色。 public var inactiveColor: Color? /// 图例选中状态表。 /// /// 示例: /// /// selected: { /// // 选中'系列1' /// '系列1': true, /// // 不选中'系列2' /// '系列2': false /// } public var selected: [String: Bool]? /// 图例的公用文本样式。 public var textStyle: TextStyle? /// 图例的 tooltip 配置,配置项同 tooltip。默认不显示,可以在 legend 文字很多的时候对文字做裁剪并且开启 tooltip, /// /// 如下示例: /// /// legend: { /// formatter: function (name) { /// return echarts.format.truncateText(name, 40, '14px Microsoft Yahei', '…'); /// }, /// tooltip: { /// show: true /// } /// } public var tooltip: Tooltip? /// 图例的数据数组。 public var data: [Jsonable]? public var backgroundColor: Color? public var borderColor: Color? public var borderWidth: Float? /// 注意:此配置项生效的前提是,设置了 show: `true` 以及值不为 `tranparent` 的背景色 `backgroundColor。 public var shadowBlur: Float? /// 阴影颜色。支持的格式同color。 /// 注意:此配置项生效的前提是,设置了 show: `true`。 public var shadowColor: Color? /// 注意:此配置项生效的前提是,设置了 show: `true`。 public var shadowOffsetX: Float? /// 注意:此配置项生效的前提是,设置了 show: `true`。 public var shadowOffsetY: Float? public init() { } } extension Legend.Data: Enumable { public enum Enums { case name(String), icon(Symbol), textStyle(TextStyle) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .name(name): self.name = name case let .icon(icon): self.icon = icon case let .textStyle(textStyle): self.textStyle = textStyle } } } } extension Legend.Data: Mappable { public func mapping(_ map: Mapper) { map["name"] = name map["icon"] = icon map["textStyle"] = textStyle } } extension Legend: Enumable { public enum Enums { case show(Bool), zlevel(Float), z(Float), left(Position), x(Position), top(Position), y(Position), right(Position), bottom(Position), width(Float), height(Float), orient(Orient), align(Align), padding(Padding), itemGap(Float), itemWidth(Float), itemHeight(Float), formatter(Formatter), selectedMode(SelectedMode), inactiveColor(Color), selected([String: Bool]), textStyle(TextStyle), tooltip(Tooltip), data([Jsonable]), backgroundColor(Color), borderColor(Color), borderWidth(Float), shadowBlur(Float), shadowColor(Color), shadowOffsetX(Float), shadowOffsetY(Float) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .show(show): self.show = show case let .zlevel(zlevel): self.zlevel = zlevel case let .z(z): self.z = z case let .left(left): self.left = left case let .x(left): self.left = left case let .top(top): self.top = top case let .y(top): self.top = top case let .right(right): self.right = right case let .bottom(bottom): self.bottom = bottom case let .width(width): self.width = width case let .height(height): self.height = height case let .orient(orient): self.orient = orient case let .align(align): self.align = align case let .padding(padding): self.padding = padding case let .itemGap(itemGap): self.itemGap = itemGap case let .itemWidth(itemWidth): self.itemWidth = itemWidth case let .itemHeight(itemHeight): self.itemHeight = itemHeight case let .formatter(formatter): self.formatter = formatter case let .selectedMode(selectedMode): self.selectedMode = selectedMode case let .inactiveColor(inactiveColor): self.inactiveColor = inactiveColor case let .selected(selected): self.selected = selected case let .textStyle(textStyle): self.textStyle = textStyle case let .tooltip(tooltip): self.tooltip = tooltip case let .data(data): self.data = data case let .backgroundColor(backgroundColor): self.backgroundColor = backgroundColor case let .borderColor(color): self.borderColor = color case let .borderWidth(width): self.borderWidth = width case let .shadowBlur(blur): self.shadowBlur = blur case let .shadowColor(color): self.shadowColor = color case let .shadowOffsetX(x): self.shadowOffsetX = x case let .shadowOffsetY(y): self.shadowOffsetY = y } } } } extension Legend: Mappable { public func mapping(_ map: Mapper) { map["show"] = show map["zlevel"] = zlevel map["z"] = z map["left"] = left map["top"] = top map["right"] = right map["bottom"] = bottom map["width"] = width map["height"] = height map["orient"] = orient map["align"] = align map["padding"] = padding map["itemGap"] = itemGap map["itemWidth"] = itemWidth map["itemHeight"] = itemHeight map["formatter"] = formatter map["selectedMode"] = selectedMode map["inactiveColor"] = inactiveColor map["selected"] = selected map["textStyle"] = textStyle map["tooltip"] = tooltip map["data"] = data map["backgroundColor"] = backgroundColor map["borderColor"] = borderColor map["borderWidth"] = borderWidth map["shadowBlur"] = shadowBlur map["shadowColor"] = shadowColor map["shadowOffsetX"] = shadowOffsetX map["shadowOffsetY"] = shadowOffsetY } } // MARK: - Actions /// 选中图例的Action public final class LegendSelect: EchartsAction { public var type: EchartsActionType { return .legendSelect } /// 图例名称 public var name: String? public enum Enums { case name(String) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .name(name): self.name = name } } } public func mapping(_ map: Mapper) { map["type"] = type map["name"] = name } } /// 取消选中图例的Action public final class LegendUnSelect: EchartsAction { public var type: EchartsActionType { return .legendUnSelect } /// 图例名称 public var name: String? public enum Enums { case name(String) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .name(name): self.name = name } } } public func mapping(_ map: Mapper) { map["type"] = type map["name"] = name } } /// 切换图例的选中状态的Action public final class LegendToggleSelect: EchartsAction { public var type: EchartsActionType { return .legendToggleSelect } /// 图例名称 public var name: String? public enum Enums { case name(String) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .name(name): self.name = name } } } public func mapping(_ map: Mapper) { map["type"] = type map["name"] = name } } /// 控制图例的滚动。当 legend.type 为 'scroll' 时有效。 public final class LegendScroll: EchartsAction { public var type: EchartsActionType { return .legendScroll } public var scrollDataIndex: Int? public var legendId: String? public enum Enums { case scrollDataIndex(Int), legendId(String) } public typealias ContentEnum = Enums public convenience init(_ elements: Enums...) { self.init() for ele in elements { switch ele { case let .scrollDataIndex(scrollDataIndex): self.scrollDataIndex = scrollDataIndex case let .legendId(legendId): self.legendId = legendId } } } public func mapping(_ map: Mapper) { map["type"] = type map["scrollDataIndex"] = scrollDataIndex map["legendId"] = legendId } }
mit
0fb57c9a56a6e5a9a8e9ca580bee8f4d
28.954082
573
0.550843
4.035052
false
false
false
false
zapdroid/RXWeather
Pods/RxCocoa/RxCocoa/Traits/SharedSequence/SharedSequence.swift
1
6668
// // SharedSequence.swift // RxCocoa // // Created by Krunoslav Zaher on 8/27/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // #if !RX_NO_MODULE import RxSwift #endif /** Trait that represents observable sequence that shares computation resources with following properties: - it never fails - it delivers events on `SharingStrategy.scheduler` - sharing strategy is customizable using `SharingStrategy.share` behavior `SharedSequence<Element>` can be considered a builder pattern for observable sequences that share computation resources. To find out more about units and how to use them, please visit `Documentation/Traits.md`. */ public struct SharedSequence<S: SharingStrategyProtocol, Element>: SharedSequenceConvertibleType { public typealias E = Element public typealias SharingStrategy = S let _source: Observable<E> init(_ source: Observable<E>) { _source = S.share(source) } init(raw: Observable<E>) { _source = raw } #if EXPANDABLE_SHARED_SEQUENCE /** This method is extension hook in case this unit needs to extended from outside the library. By defining `EXPANDABLE_SHARED_SEQUENCE` one agrees that it's up to him to ensure shared sequence properties are preserved after extension. */ public static func createUnsafe<O: ObservableType>(source: O) -> SharedSequence<S, O.E> { return SharedSequence<S, O.E>(raw: source.asObservable()) } #endif /** - returns: Built observable sequence. */ public func asObservable() -> Observable<E> { return _source } /** - returns: `self` */ public func asSharedSequence() -> SharedSequence<SharingStrategy, E> { return self } } /** Different `SharedSequence` sharing strategies must conform to this protocol. */ public protocol SharingStrategyProtocol { /** Scheduled on which all sequence events will be delivered. */ static var scheduler: SchedulerType { get } /** Computation resources sharing strategy for multiple sequence observers. E.g. One can choose `shareReplayWhenConnected`, `shareReplay` or `share` as sequence event sharing strategies, but also do something more exotic, like implementing promises or lazy loading chains. */ static func share<E>(_ source: Observable<E>) -> Observable<E> } /** A type that can be converted to `SharedSequence`. */ public protocol SharedSequenceConvertibleType: ObservableConvertibleType { associatedtype SharingStrategy: SharingStrategyProtocol /** Converts self to `SharedSequence`. */ func asSharedSequence() -> SharedSequence<SharingStrategy, E> } extension SharedSequenceConvertibleType { public func asObservable() -> Observable<E> { return asSharedSequence().asObservable() } } extension SharedSequence { /** Returns an empty observable sequence, using the specified scheduler to send out the single `Completed` message. - returns: An observable sequence with no elements. */ public static func empty() -> SharedSequence<S, E> { return SharedSequence(raw: Observable.empty().subscribeOn(S.scheduler)) } /** Returns a non-terminating observable sequence, which can be used to denote an infinite duration. - returns: An observable sequence whose observers will never get called. */ public static func never() -> SharedSequence<S, E> { return SharedSequence(raw: Observable.never()) } /** Returns an observable sequence that contains a single element. - parameter element: Single element in the resulting observable sequence. - returns: An observable sequence containing the single specified element. */ public static func just(_ element: E) -> SharedSequence<S, E> { return SharedSequence(raw: Observable.just(element).subscribeOn(S.scheduler)) } /** Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes. - parameter observableFactory: Observable factory function to invoke for each observer that subscribes to the resulting sequence. - returns: An observable sequence whose observers trigger an invocation of the given observable factory function. */ public static func deferred(_ observableFactory: @escaping () -> SharedSequence<S, E>) -> SharedSequence<S, E> { return SharedSequence(Observable.deferred { observableFactory().asObservable() }) } /** This method creates a new Observable instance with a variable number of elements. - seealso: [from operator on reactivex.io](http://reactivex.io/documentation/operators/from.html) - parameter elements: Elements to generate. - returns: The observable sequence whose elements are pulled from the given arguments. */ public static func of(_ elements: E ...) -> SharedSequence<S, E> { let source = Observable.from(elements, scheduler: S.scheduler) return SharedSequence(raw: source) } } extension SharedSequence where Element: SignedInteger { /** Returns an observable sequence that produces a value after each period, using the specified scheduler to run timers and to send out observer messages. - seealso: [interval operator on reactivex.io](http://reactivex.io/documentation/operators/interval.html) - parameter period: Period for producing the values in the resulting sequence. - returns: An observable sequence that produces a value after each period. */ public static func interval(_ period: RxTimeInterval) -> SharedSequence<S, E> { return SharedSequence(Observable.interval(period, scheduler: S.scheduler)) } } // MARK: timer extension SharedSequence where Element: SignedInteger { /** Returns an observable sequence that periodically produces a value after the specified initial relative due time has elapsed, using the specified scheduler to run timers. - seealso: [timer operator on reactivex.io](http://reactivex.io/documentation/operators/timer.html) - parameter dueTime: Relative time at which to produce the first value. - parameter period: Period to produce subsequent values. - returns: An observable sequence that produces a value after due time has elapsed and then each period. */ public static func timer(_ dueTime: RxTimeInterval, period: RxTimeInterval) -> SharedSequence<S, E> { return SharedSequence(Observable.timer(dueTime, period: period, scheduler: S.scheduler)) } }
mit
57cfafd82a5fdf0fc9212eb71b71bf57
34.462766
174
0.705565
5.005255
false
false
false
false
xedin/swift
benchmark/single-source/DictTest4Legacy.swift
24
3664
//===--- DictTest4.swift --------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2018 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 TestsUtils // This benchmark mostly measures lookups in dictionaries with complex keys, // using the legacy hashValue API. public let Dictionary4Legacy = [ BenchmarkInfo( name: "Dictionary4Legacy", runFunction: run_Dictionary4Legacy, tags: [.validation, .api, .Dictionary]), BenchmarkInfo( name: "Dictionary4OfObjectsLegacy", runFunction: run_Dictionary4OfObjectsLegacy, tags: [.validation, .api, .Dictionary]), ] extension Int { mutating func combine(_ value: Int) { self = 16777619 &* self ^ value } } struct LargeKey: Hashable { let i: Int let j: Int let k: Double let l: UInt32 let m: Bool let n: Bool let o: Bool let p: Bool let q: Bool var hashValue: Int { var hash = i.hashValue hash.combine(j.hashValue) hash.combine(k.hashValue) hash.combine(l.hashValue) hash.combine(m.hashValue) hash.combine(n.hashValue) hash.combine(o.hashValue) hash.combine(p.hashValue) hash.combine(q.hashValue) return hash } func hash(into hasher: inout Hasher) { hasher.combine(self.hashValue) } init(_ value: Int) { self.i = value self.j = 2 * value self.k = Double(value) / 7 self.l = UInt32(truncatingIfNeeded: value) self.m = value & 1 == 0 self.n = value & 2 == 0 self.o = value & 4 == 0 self.p = value & 8 == 0 self.q = value & 16 == 0 } } @inline(never) public func run_Dictionary4Legacy(_ N: Int) { let size1 = 100 let reps = 20 let ref_result = "1 99 \(reps) \(reps * 99)" var hash1 = [LargeKey: Int]() var hash2 = [LargeKey: Int]() var res = "" for _ in 1...N { // Test insertions hash1 = [:] for i in 0..<size1 { hash1[LargeKey(i)] = i } hash2 = hash1 // Test lookups & value replacement for _ in 1..<reps { for (k, v) in hash1 { hash2[k] = hash2[k]! + v } } res = "\(hash1[LargeKey(1)]!) \(hash1[LargeKey(99)]!)" + " \(hash2[LargeKey(1)]!) \(hash2[LargeKey(99)]!)" if res != ref_result { break } } CheckResults(res == ref_result) } class Box<T : Hashable> : Hashable { var value: T init(_ v: T) { value = v } func hash(into hasher: inout Hasher) { hasher.combine(value) } var hashValue: Int { return value.hashValue } static func ==(lhs: Box, rhs: Box) -> Bool { return lhs.value == rhs.value } } @inline(never) public func run_Dictionary4OfObjectsLegacy(_ N: Int) { let size1 = 100 let reps = 20 let ref_result = "1 99 \(reps) \(reps * 99)" var hash1 = [Box<LargeKey>: Int]() var hash2 = [Box<LargeKey>: Int]() var res = "" for _ in 1...N { // Test insertions hash1 = [:] for i in 0..<size1 { hash1[Box(LargeKey(i))] = i } hash2 = hash1 // Test lookups & value replacement for _ in 1..<reps { for (k, v) in hash1 { hash2[k] = hash2[k]! + v } } res = "\(hash1[Box(LargeKey(1))]!) \(hash1[Box(LargeKey(99))]!)" + " \(hash2[Box(LargeKey(1))]!) \(hash2[Box(LargeKey(99))]!)" if res != ref_result { break } } CheckResults(res == ref_result) }
apache-2.0
4e40f67c7d3e7cae6fa62d36a3e151d2
21.617284
80
0.576146
3.446849
false
false
false
false
honghaoz/CrackingTheCodingInterview
Swift/LeetCode/Array/938_Range Sum of BST.swift
1
1686
// 938_Range Sum of BST // https://leetcode.com/problems/range-sum-of-bst/ // // Created by Honghao Zhang on 9/19/19. // Copyright © 2019 Honghaoz. All rights reserved. // // Description: // Given the root node of a binary search tree, return the sum of values of all nodes with value between L and R (inclusive). // //The binary search tree is guaranteed to have unique values. // // // //Example 1: // //Input: root = [10,5,15,3,7,null,18], L = 7, R = 15 //Output: 32 //Example 2: // //Input: root = [10,5,15,3,7,13,18,1,null,6], L = 6, R = 10 //Output: 23 // // //Note: // //The number of nodes in the tree is at most 10000. //The final answer is guaranteed to be less than 2^31. // import Foundation class Num938 { // Recursive DFS func rangeSumBST_recursive(_ root: TreeNode?, _ L: Int, _ R: Int) -> Int { if root == nil { return 0 } var sum = 0 if root!.val >= L, root!.val <= R { sum += root!.val } if root!.val >= L { sum += rangeSumBST_recursive(root!.left, L, R) } if root!.val <= R { sum += rangeSumBST_recursive(root!.right, L, R) } return sum } // Iterative func rangeSumBST_iterative(_ root: TreeNode?, _ L: Int, _ R: Int) -> Int { if root == nil { return 0 } var sum = 0 var stack: [TreeNode] = [root!] while !stack.isEmpty { let last = stack.popLast()! if last.val >= L, last.val <= R { sum += last.val } // If left vals has some overlap if let left = last.left, last.val > L { stack.append(left) } if let right = last.right, last.val < R { stack.append(right) } } return sum } }
mit
fd3aae87be167b5f9081883a530cd73f
20.883117
125
0.569139
3.161351
false
false
false
false
ZoranPandovski/al-go-rithms
sort/gnome_sort/Swift/GnomeSort.swift
1
865
//Normal algorithm func gnomeSort<T: Comparable>(_ array: inout [T]) { var i: Int = 1 var j: Int = 2 while i < array.count { if array[i - 1] <= array[i] { i = j j += 1 } else { array.swapAt(i - 1, i) i -= 1 if i == 0 { i = j j += 1 } } } } //Optimized algorithm func optimizedGnomeSort<T: Comparable>(_ array: inout [T]) { for pos in 1..<array.count { gnomeSort(&array, pos) } } func gnomeSort<T: Comparable>(_ array: inout [T], _ upperBound: Int) { var pos = upperBound while pos > 0 && array[pos-1] > array[pos] { array.swapAt(pos-1, pos) pos -= 1 } } //Sample var array = [10, 8, 4, 3, 1, 10, 9, 0, 2, 7, 5, 6] optimizedGnomeSort(&array) //gnomeSort(&array) print(array)
cc0-1.0
c2af5d558ae7df1acbceb511f6fcf2fa
21.179487
70
0.478613
3.191882
false
false
false
false
longjianjiang/ZombieConga
CombieConga/CombieConga/MainMenuScene.swift
1
775
// // MainMenuScene.swift // CombieConga // // Created by longjianjiang on 16/11/23. // Copyright © 2016年 Jiang. All rights reserved. // import UIKit import SpriteKit class MainMenuScene: SKScene { override func didMove(to view: SKView) { let background = SKSpriteNode(imageNamed: "MainMenu") background.position = CGPoint(x: size.width/2, y: size.height/2) addChild(background) } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { sceneTapped() } func sceneTapped() { let scene = GameScene(size: size) scene.scaleMode = scaleMode let reveal = SKTransition.doorway(withDuration: 1.5) view?.presentScene(scene, transition: reveal) } }
apache-2.0
9a59f8e72683627624a435c7d9e8e52c
24.733333
79
0.642487
4.020833
false
false
false
false
macram/rxNetflixRoulette
NetflixRoulette/ViewModel.swift
1
1117
// // ViewModel.swift // NetflixRoulette // // Created by Manu Mateos on 18/8/17. // Copyright © 2017 Liquid Squad. All rights reserved. // import UIKit import RxSwift import RxCocoa class ViewModel: NSObject { var fachada: Fachada! var film: Variable<Film> = Variable<Film>(Film(jsonDict: [:])) var title: Variable<String> = Variable<String>("") var disposeBag = DisposeBag() init(fachada: Fachada) { super.init() self.fachada = fachada self.setUpBindings() } func getFilms(title: String) -> Observable<Film> { return fachada.getFilms(title: title) } func setUpBindings() { title.asDriver().throttle(1) .drive(onNext: { (t) in print(t) self.getFilms(title: t).subscribe(onNext: { (film) in self.film.value = film }, onError: nil, onCompleted: nil, onDisposed: nil) .addDisposableTo(self.disposeBag) }, onCompleted: nil, onDisposed: nil) .addDisposableTo(disposeBag) } }
unlicense
68188487a33dcc56590c9056bd2321ba
24.363636
69
0.570789
3.929577
false
false
false
false
hryk224/PCLBlurEffectAlert
Sources/PCLBlurEffectAlert+Action.swift
1
1670
// // PCLBlurEffectAlert+Action.swift // PCLBlurEffectAlert // // Created by yoshida hiroyuki on 2016/09/15. // Copyright © 2016年 hiroyuki yoshida. All rights reserved. // import UIKit public typealias PCLBlurEffectAlertAction = PCLBlurEffectAlert.Action extension PCLBlurEffectAlert { open class Action { var tag: Int = -1 var title: String? open var style: PCLBlurEffectAlert.ActionStyle var handler: ((PCLBlurEffectAlert.Action?) -> Void)? var button: UIButton! var visualEffectView: UIVisualEffectView? lazy var backgroundView: UIView = { return UIView() }() open var isEnabled: Bool = true { didSet { guard oldValue != isEnabled else { return } PCLBlurEffectAlert.NotificationManager.shared.postAlertActionEnabledDidChangeNotification() } } public init(title: String, style: PCLBlurEffectAlert.ActionStyle, handler: ((PCLBlurEffectAlert.Action?) -> Void)?) { self.title = title self.style = style self.handler = handler let button = UIButton(type: .custom) button.tag = tag button.adjustsImageWhenHighlighted = false button.adjustsImageWhenDisabled = false button.layer.masksToBounds = true button.setTitle(title, for: .normal) button.titleLabel?.numberOfLines = 1 button.titleLabel?.lineBreakMode = .byTruncatingTail button.titleLabel?.textAlignment = .center self.button = button } } }
mit
ae756c510726f644349ac13b2292b342
33.729167
107
0.610078
4.946588
false
false
false
false
ArtKirillov/PDFReader
PDFReader/PDFDocument.swift
1
5377
// // PDFDocument.swift // PDFReader // // Created by Artem Kirillov on 24.02.17. // Copyright © 2017 Artem Kirillov. All rights reserved. // import CoreGraphics import UIKit public final class PDFDocument { public let pageCount: Int public let fileName: String let fileURL: URL let coreDocument: CGPDFDocument let password: String? /// Image cache with the page index and and image of the page let images = NSCache<NSNumber, UIImage>() /// Returns a newly initialized document which is located on the file system. /// /// - parameter fileURL: the file URL where the locked `.pdf` document exists on the file system /// - parameter password: password for the locked pdf /// /// - returns: A newly initialized `PDFDocument`. public init?(fileURL: URL, password: String? = nil) { print("- INIT PDFDocument") self.fileURL = fileURL self.fileName = fileURL.lastPathComponent guard let coreDocument = CGPDFDocument(fileURL as CFURL) else { return nil } if let password = password, let cPasswordString = password.cString(using: .utf8) { // Try a blank password first, per Apple's Quartz PDF example if coreDocument.isEncrypted && !coreDocument.unlockWithPassword("") { // Nope, now let's try the provided password to unlock the PDF if !coreDocument.unlockWithPassword(cPasswordString) { print("CGPDFDocumentCreateX: Unable to unlock \(fileURL)") } self.password = password } else { self.password = nil } } else { self.password = nil } self.coreDocument = coreDocument self.pageCount = coreDocument.numberOfPages } deinit { print ("- DEINIT PDFDocument") } /// Image of the spread /// /// - parameter for: page number index of the page /// - returns: Image representation of the spread func spread(for pageNumber: Int, in bounds: CGRect) -> UIImage? { guard let image1 = image(for: pageNumber), let image2 = image(for: pageNumber + 1) else { return nil } UIGraphicsBeginImageContextWithOptions(bounds.size, false, 0.0) let rect1 = CGRect(x: 0, y: 0, width: bounds.width / 2, height: bounds.height) let rect2 = CGRect(x: bounds.width / 2, y: 0, width: bounds.width / 2, height: bounds.height) image1.draw(in: rect1) image2.draw(in: rect2) let spreadImage = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return spreadImage } /// Image of the document page, first looking at the cache, proccesses otherwise /// /// - parameter for: page number index of the page /// - returns: Image representation of the document page func image(for pageNumber: Int) -> UIImage? { if let image = images.object(forKey: NSNumber(value: pageNumber)) { //print("-- Using cached image for page \(pageNumber)") return image } else { //print("-- Proccess image for page \(pageNumber)") if let image = proccessImage(for: pageNumber) { images.setObject(image, forKey: NSNumber(value: pageNumber)) return image } } return nil } /// Proccesses the raw image representation of the document page from the document reference /// /// - parameter for: page number index of the page /// - returns: Image representation of the document page private func proccessImage(for pageNumber: Int) -> UIImage? { guard let page = coreDocument.page(at: pageNumber) else { return nil } // Determine the size of the PDF page. var pageRect = page.getBoxRect(.mediaBox) let scalingConstant: CGFloat = 240 let pdfScale = min(scalingConstant/pageRect.size.width, scalingConstant/pageRect.size.height) pageRect.size = CGSize(width: pageRect.size.width * pdfScale, height: pageRect.size.height * pdfScale) // Create a low resolution image representation of the PDF page to display before the TiledPDFView renders its content. UIGraphicsBeginImageContextWithOptions(pageRect.size, true, 1) guard let context = UIGraphicsGetCurrentContext() else { return nil } // First fill the background with white. context.setFillColor(red: 1, green: 1, blue: 1, alpha: 1) context.fill(pageRect) context.saveGState() // Flip the context so that the PDF page is rendered right side up. context.translateBy(x: 0, y: pageRect.size.height) context.scaleBy(x: 1, y: -1) // Scale the context so that the PDF page is rendered at the correct size for the zoom level. context.scaleBy(x: pdfScale, y: pdfScale) context.drawPDFPage(page) context.restoreGState() defer { UIGraphicsEndImageContext() } guard let backgroundImage = UIGraphicsGetImageFromCurrentImageContext() else { return nil } return backgroundImage } }
mit
cfadfa3cb3e31994a74073e27c75f9f2
36.075862
127
0.613653
4.869565
false
false
false
false
YuraKr/AllUniteSdk
Example/Tests/Tests.swift
1
1181
// https://github.com/Quick/Quick import Quick import Nimble class TableOfContentsSpec: QuickSpec { override func spec() { describe("these will fail") { // it("can do maths") { // expect(1) == 2 // } // // it("can read") { // expect("number") == "string" // } // // it("will eventually fail") { // expect("time").toEventually( equal("done") ) // } context("these will pass") { it("can do maths") { expect(23) == 23 } it("can read") { expect("🐮") == "🐮" } it("will eventually pass") { var time = "passing" dispatch_async(dispatch_get_main_queue()) { time = "done" } waitUntil { done in NSThread.sleepForTimeInterval(0.5) expect(time) == "done" done() } } } } } }
mit
20dc848d4eb029c3222c771efded74e0
22.979592
63
0.348936
5.042918
false
false
false
false
benlangmuir/swift
test/SILGen/local_recursion.swift
9
5547
// RUN: %target-swift-emit-silgen -parse-as-library %s | %FileCheck %s // CHECK-LABEL: sil hidden [ossa] @$s15local_recursionAA_1yySi_SitF : $@convention(thin) (Int, Int) -> () { // CHECK: bb0([[X:%0]] : $Int, [[Y:%1]] : $Int): func local_recursion(_ x: Int, y: Int) { func self_recursive(_ a: Int) { self_recursive(x + a) } // Invoke local functions by passing all their captures. // CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE:@\$s15local_recursionAA_1yySi_SitF14self_recursiveL_yySiF]] // CHECK: apply [[SELF_RECURSIVE_REF]]([[X]], [[X]]) self_recursive(x) // CHECK: [[SELF_RECURSIVE_REF:%.*]] = function_ref [[SELF_RECURSIVE]] // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[SELF_RECURSIVE_REF]]([[X]]) // CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [lexical] [[CLOSURE]] // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]] let sr = self_recursive // CHECK: [[B:%.*]] = begin_borrow [[CLOSURE_COPY]] // CHECK: apply [[B]]([[Y]]) // CHECK: end_borrow [[B]] // CHECK: destroy_value [[CLOSURE_COPY]] sr(y) func mutually_recursive_1(_ a: Int) { mutually_recursive_2(x + a) } func mutually_recursive_2(_ b: Int) { mutually_recursive_1(y + b) } // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1:@\$s15local_recursionAA_1yySi_SitF20mutually_recursive_1L_yySiF]] // CHECK: apply [[MUTUALLY_RECURSIVE_REF]]([[X]], [[Y]], [[X]]) mutually_recursive_1(x) // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1]] _ = mutually_recursive_1 func transitive_capture_1(_ a: Int) -> Int { return x + a } func transitive_capture_2(_ b: Int) -> Int { return transitive_capture_1(y + b) } // CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE:@\$s15local_recursionAA_1yySi_SitF20transitive_capture_2L_yS2iF]] // CHECK: apply [[TRANS_CAPTURE_REF]]([[X]], [[X]], [[Y]]) transitive_capture_2(x) // CHECK: [[TRANS_CAPTURE_REF:%.*]] = function_ref [[TRANS_CAPTURE]] // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[TRANS_CAPTURE_REF]]([[X]], [[Y]]) // CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [lexical] [[CLOSURE]] // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]] let tc = transitive_capture_2 // CHECK: [[B:%.*]] = begin_borrow [[CLOSURE_COPY]] // CHECK: apply [[B]]([[X]]) // CHECK: end_borrow [[B]] // CHECK: destroy_value [[CLOSURE_COPY]] tc(x) // CHECK: [[CLOSURE_REF:%.*]] = function_ref @$s15local_recursionAA_1yySi_SitFySiXEfU_ // CHECK: apply [[CLOSURE_REF]]([[X]], [[X]], [[Y]]) let _: Void = { self_recursive($0) transitive_capture_2($0) }(x) // CHECK: [[CLOSURE_REF:%.*]] = function_ref @$s15local_recursionAA_1yySi_SitFySicfU0_ // CHECK: [[CLOSURE:%.*]] = partial_apply [callee_guaranteed] [[CLOSURE_REF]]([[X]], [[Y]]) // CHECK: [[BORROWED_CLOSURE:%.*]] = begin_borrow [lexical] [[CLOSURE]] // CHECK: [[CLOSURE_COPY:%.*]] = copy_value [[BORROWED_CLOSURE]] // CHECK: [[B:%.*]] = begin_borrow [[CLOSURE_COPY]] // CHECK: apply [[B]]([[X]]) // CHECK: end_borrow [[B]] // CHECK: destroy_value [[CLOSURE_COPY]] let f: (Int) -> () = { self_recursive($0) transitive_capture_2($0) } f(x) } // CHECK: sil private [ossa] [[SELF_RECURSIVE]] : // CHECK: bb0([[A:%0]] : $Int, [[X:%1]] : $Int): // CHECK: [[SELF_REF:%.*]] = function_ref [[SELF_RECURSIVE]] : // CHECK: apply [[SELF_REF]]({{.*}}, [[X]]) // CHECK: sil private [ossa] [[MUTUALLY_RECURSIVE_1]] // CHECK: bb0([[A:%0]] : $Int, [[Y:%1]] : $Int, [[X:%2]] : $Int): // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_2:@\$s15local_recursionAA_1yySi_SitF20mutually_recursive_2L_yySiF]] // CHECK: apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[X]], [[Y]]) // CHECK: sil private [ossa] [[MUTUALLY_RECURSIVE_2]] // CHECK: bb0([[B:%0]] : $Int, [[X:%1]] : $Int, [[Y:%2]] : $Int): // CHECK: [[MUTUALLY_RECURSIVE_REF:%.*]] = function_ref [[MUTUALLY_RECURSIVE_1]] // CHECK: apply [[MUTUALLY_RECURSIVE_REF]]({{.*}}, [[Y]], [[X]]) // CHECK: sil private [ossa] [[TRANS_CAPTURE_1:@\$s15local_recursionAA_1yySi_SitF20transitive_capture_1L_yS2iF]] // CHECK: bb0([[A:%0]] : $Int, [[X:%1]] : $Int): // CHECK: sil private [ossa] [[TRANS_CAPTURE]] // CHECK: bb0([[B:%0]] : $Int, [[X:%1]] : $Int, [[Y:%2]] : $Int): // CHECK: [[TRANS_CAPTURE_1_REF:%.*]] = function_ref [[TRANS_CAPTURE_1]] // CHECK: apply [[TRANS_CAPTURE_1_REF]]({{.*}}, [[X]]) func plus<T>(_ x: T, _ y: T) -> T { return x } func toggle<T, U>(_ x: T, _ y: U) -> U { return y } func generic_local_recursion<T, U>(_ x: T, y: U) { func self_recursive(_ a: T) { self_recursive(plus(x, a)) } self_recursive(x) _ = self_recursive func transitive_capture_1(_ a: T) -> U { return toggle(a, y) } func transitive_capture_2(_ b: U) -> U { return transitive_capture_1(toggle(b, x)) } transitive_capture_2(y) _ = transitive_capture_2 func no_captures() {} no_captures() _ = no_captures func transitive_no_captures() { no_captures() } transitive_no_captures() _ = transitive_no_captures } func local_properties(_ x: Int, y: Int) -> Int { var self_recursive: Int { return x + self_recursive } var transitive_capture_1: Int { return x } var transitive_capture_2: Int { return transitive_capture_1 + y } func transitive_capture_fn() -> Int { return transitive_capture_2 } return self_recursive + transitive_capture_fn() }
apache-2.0
c0d070e18ec9e21c1433739e58fbd9e2
34.107595
146
0.590049
3.032805
false
false
false
false
tamanyan/SwiftPageMenu
Sources/Util/UIColor+Extension.swift
1
944
// // UIColor+Extension.swift // SwiftPageMenu // // Created by Tamanyan on 3/10/17. // Copyright © 2017 Tamanyan. All rights reserved. // import Foundation import UIKit extension UIColor { fileprivate func components() -> (CGFloat, CGFloat, CGFloat, CGFloat) { guard let c = cgColor.components else { return (0, 0, 0, 1) } if cgColor.numberOfComponents == 2 { return (c[0], c[0], c[0], c[1]) } else { return (c[0], c[1], c[2], c[3]) } } static func interpolate(from: UIColor, to: UIColor, with fraction: CGFloat) -> UIColor { let f = min(1, max(0, fraction)) let c1 = from.components() let c2 = to.components() let r = c1.0 + (c2.0 - c1.0) * f let g = c1.1 + (c2.1 - c1.1) * f let b = c1.2 + (c2.2 - c1.2) * f let a = c1.3 + (c2.3 - c1.3) * f return UIColor(red: r, green: g, blue: b, alpha: a) } }
mit
b79181b9013ca68002de8a7b5cb7ff93
26.735294
92
0.535525
2.984177
false
false
false
false
sudiptasahoo/IVP-Luncheon
IVP Luncheon/SSUIUtilities.swift
1
857
// // SSUIUtilities.swift // IVP Luncheon // // Created by Sudipta on 29/05/17. // Copyright © 2017 Sudipta Sahoo <[email protected]>. This file is part of Indus Valley Partners interview process. This file can not be copied and/or distributed without the express permission of Sudipta Sahoo. All rights reserved. // import UIKit class SSUIUtilities: NSObject { class func getSizeForLabel(_ withText:String, font:UIFont, width: CGFloat) -> CGRect{ var currSize:CGRect! let label:UILabel = UILabel(frame: CGRect(x:0, y:0, width: width, height:CGFloat.greatestFiniteMagnitude)) label.numberOfLines = 0 label.lineBreakMode = NSLineBreakMode.byWordWrapping label.font = font label.text = withText label.sizeToFit() currSize = label.frame label.removeFromSuperview() return currSize } }
apache-2.0
9a5f333dffcc7ea1153e550e75f61433
27.533333
236
0.713785
4
false
false
false
false
phatblat/realm-cocoa
Realm/Tests/Swift/SwiftSetTests.swift
2
11552
//////////////////////////////////////////////////////////////////////////// // // Copyright 2020 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Foundation import Realm import XCTest #if canImport(RealmTestSupport) import RealmTestSupport #endif class SwiftRLMSetTests: RLMTestCase { // Swift models func testDeleteLinksAndObjectsInSet() { let realm = realmWithTestPath() realm.beginWriteTransaction() let po1 = SwiftRLMEmployeeObject() po1.age = 40 po1.name = "Joe" po1.hired = true let po2 = SwiftRLMEmployeeObject() po2.age = 30 po2.name = "John" po2.hired = false let po3 = SwiftRLMEmployeeObject() po3.age = 25 po3.name = "Jill" po3.hired = true realm.add(po1) realm.add(po2) realm.add(po3) let company = SwiftRLMCompanyObject() realm.add(company) company.employeeSet.addObjects(SwiftRLMEmployeeObject.allObjects(in: realm)) try! realm.commitWriteTransaction() let peopleInCompany = company.employeeSet XCTAssertEqual(peopleInCompany.count, UInt(3), "No links should have been deleted") realm.beginWriteTransaction() peopleInCompany.remove(po2) // Should delete link to employee try! realm.commitWriteTransaction() XCTAssertEqual(peopleInCompany.count, UInt(2), "link deleted when accessing via links") let test = peopleInCompany.allObjects[0] XCTAssertTrue(((test.age == po1.age) || (test.age == po3.age)), "Should be equal") XCTAssertEqual(test.name, po1.name, "Should be equal") XCTAssertEqual(test.hired, po1.hired, "Should be equal") realm.beginWriteTransaction() peopleInCompany.remove(po1) XCTAssertEqual(peopleInCompany.count, UInt(1), "1 remaining link") peopleInCompany.add(po1) XCTAssertEqual(peopleInCompany.count, UInt(2), "2 links") peopleInCompany.removeAllObjects() XCTAssertEqual(peopleInCompany.count, UInt(0), "0 remaining links") try! realm.commitWriteTransaction() } // Objective-C models func testFastEnumeration_objc() { let realm = realmWithTestPath() realm.beginWriteTransaction() let po1 = SwiftRLMEmployeeObject() po1.age = 40 po1.name = "Joe" po1.hired = true let po2 = SwiftRLMEmployeeObject() po2.age = 30 po2.name = "John" po2.hired = false let po3 = SwiftRLMEmployeeObject() po3.age = 25 po3.name = "Jill" po3.hired = true realm.add(po1) realm.add(po2) realm.add(po3) let company = SwiftRLMCompanyObject() realm.add(company) company.employeeSet.addObjects(SwiftRLMEmployeeObject.allObjects(in: realm)) try! realm.commitWriteTransaction() XCTAssertEqual(company.employeeSet.count, UInt(3), "3 objects added") var totalSum: Int = 0 for obj in company.employeeSet { if let ao = obj as? SwiftRLMEmployeeObject { totalSum += ao.age } } XCTAssertEqual(totalSum, 95, "total sum should be 95") } func testObjectAggregate_objc() { let dateMinInput = Date() let dateMaxInput = dateMinInput.addingTimeInterval(1000) let realm = realmWithTestPath() realm.beginWriteTransaction() let aggSet = SwiftRLMAggregateSet() aggSet.set.add(SwiftRLMAggregateObject.create(in: realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])) aggSet.set.add(SwiftRLMAggregateObject.create(in: realm, withValue: [10, 0 as Float, 2.5 as Double, false, dateMaxInput])) aggSet.set.add(SwiftRLMAggregateObject.create(in: realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])) aggSet.set.add(SwiftRLMAggregateObject.create(in: realm, withValue: [10, 0 as Float, 2.5 as Double, false, dateMaxInput])) aggSet.set.add(SwiftRLMAggregateObject.create(in: realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])) aggSet.set.add(SwiftRLMAggregateObject.create(in: realm, withValue: [10, 0 as Float, 2.5 as Double, false, dateMaxInput])) aggSet.set.add(SwiftRLMAggregateObject.create(in: realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])) aggSet.set.add(SwiftRLMAggregateObject.create(in: realm, withValue: [10, 0 as Float, 2.5 as Double, false, dateMaxInput])) aggSet.set.add(SwiftRLMAggregateObject.create(in: realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])) aggSet.set.add(SwiftRLMAggregateObject.create(in: realm, withValue: [10, 1.2 as Float, 0 as Double, true, dateMinInput])) realm.add(aggSet) try! realm.commitWriteTransaction() // SUM :::::::::::::::::::::::::::::::::::::::::::::: // Test int sum XCTAssertEqual(aggSet.set.sum(ofProperty: "intCol").intValue, 100, "Sum should be 100") // Test float sum XCTAssertEqual(aggSet.set.sum(ofProperty: "floatCol").floatValue, Float(7.20), accuracy: 0.1, "Sum should be 0.0") // Test double sum XCTAssertEqual(aggSet.set.sum(ofProperty: "doubleCol").doubleValue, Double(10), accuracy: 0.1, "Sum should be 10.0") // Average :::::::::::::::::::::::::::::::::::::::::::::: // Test int average XCTAssertEqual(aggSet.set.average(ofProperty: "intCol")!.doubleValue, Double(10.0), accuracy: 0.1, "Average should be 1.0") // Test float average XCTAssertEqual(aggSet.set.average(ofProperty: "floatCol")!.doubleValue, Double(0.72), accuracy: 0.1, "Average should be 0.0") // Test double average XCTAssertEqual(aggSet.set.average(ofProperty: "doubleCol")!.doubleValue, Double(1.0), accuracy: 0.1, "Average should be 2.5") // MIN :::::::::::::::::::::::::::::::::::::::::::::: // Test int min var min = aggSet.set.min(ofProperty: "intCol") as! NSNumber XCTAssertEqual(min.int32Value, Int32(10), "Minimum should be 10") // Test float min min = aggSet.set.min(ofProperty: "floatCol") as! NSNumber XCTAssertEqual(min.floatValue, Float(0), accuracy: 0.1, "Minimum should be 0.0f") // Test double min min = aggSet.set.min(ofProperty: "doubleCol") as! NSNumber XCTAssertEqual(min.doubleValue, Double(0.0), accuracy: 0.1, "Minimum should be 1.5") // Test date min let dateMinOutput = aggSet.set.min(ofProperty: "dateCol") as! Date XCTAssertEqual(dateMinOutput, dateMinInput, "Minimum should be dateMaxInput") // MAX :::::::::::::::::::::::::::::::::::::::::::::: // Test int max var max = aggSet.set.max(ofProperty: "intCol") as! NSNumber XCTAssertEqual(max.intValue, 10, "Maximum should be 10") // Test float max max = aggSet.set.max(ofProperty: "floatCol") as! NSNumber XCTAssertEqual(max.floatValue, Float(1.2), accuracy: 0.1, "Maximum should be 0.0f") // Test double max max = aggSet.set.max(ofProperty: "doubleCol") as! NSNumber XCTAssertEqual(max.doubleValue, Double(2.5), accuracy: 0.1, "Maximum should be 3.5") // Test date max let dateMaxOutput = aggSet.set.max(ofProperty: "dateCol") as! Date XCTAssertEqual(dateMaxOutput, dateMaxInput, "Maximum should be dateMaxInput") } func testSetDescription_objc() { let realm = realmWithTestPath() realm.beginWriteTransaction() for _ in 0..<300 { let po1 = SwiftRLMEmployeeObject() po1.age = 40 po1.name = "Joe" po1.hired = true let po2 = SwiftRLMEmployeeObject() po2.age = 30 po2.name = "Mary" po2.hired = false let po3 = SwiftRLMEmployeeObject() po3.age = 24 po3.name = "Jill" po3.hired = true realm.add(po1) realm.add(po2) realm.add(po3) } let company = SwiftRLMCompanyObject() realm.add(company) company.employeeSet.addObjects(SwiftRLMEmployeeObject.allObjects(in: realm)) try! realm.commitWriteTransaction() let description = company.employeeSet.description XCTAssertTrue((description as NSString).range(of: "name").location != Foundation.NSNotFound, "property names should be displayed when calling \"description\" on RLMSet") XCTAssertTrue((description as NSString).range(of: "Mary").location != Foundation.NSNotFound, "property values should be displayed when calling \"description\" on RLMSet") XCTAssertTrue((description as NSString).range(of: "age").location != Foundation.NSNotFound, "property names should be displayed when calling \"description\" on RLMSet") XCTAssertTrue((description as NSString).range(of: "24").location != Foundation.NSNotFound, "property values should be displayed when calling \"description\" on RLMSet") XCTAssertTrue((description as NSString).range(of: "800 objects skipped").location != Foundation.NSNotFound, "'800 objects skipped' should be displayed when calling \"description\" on RLMSet") } func makeEmployee(_ realm: RLMRealm, _ age: Int32, _ name: String, _ hired: Bool) -> EmployeeObject { let employee = EmployeeObject() employee.age = age employee.name = name employee.hired = hired realm.add(employee) return employee } func testDeleteLinksAndObjectsInSet_objc() { let realm = realmWithTestPath() realm.beginWriteTransaction() let po1 = makeEmployee(realm, 40, "Joe", true) _ = makeEmployee(realm, 30, "John", false) let po3 = makeEmployee(realm, 25, "Jill", true) let company = CompanyObject() company.name = "name" realm.add(company) company.employeeSet.addObjects(EmployeeObject.allObjects(in: realm)) try! realm.commitWriteTransaction() let peopleInCompany: RLMSet<EmployeeObject> = company.employeeSet! XCTAssertEqual(peopleInCompany.count, UInt(3), "No links should have been deleted") realm.beginWriteTransaction() peopleInCompany.remove(po3) // Should delete link to employee try! realm.commitWriteTransaction() XCTAssertEqual(peopleInCompany.count, UInt(2), "link deleted when accessing via links") let test = peopleInCompany.allObjects[0] XCTAssertEqual(test.age, po1.age, "Should be equal") XCTAssertEqual(test.name!, po1.name!, "Should be equal") XCTAssertEqual(test.hired, po1.hired, "Should be equal") let allPeople = EmployeeObject.allObjects(in: realm) XCTAssertEqual(allPeople.count, UInt(3), "Only links should have been deleted, not the employees") } }
apache-2.0
59a8d02f74031a8ec365c74f215b88c6
38.426621
199
0.634003
4.036338
false
true
false
false
HassanEskandari/Eureka
Eureka.playground/Contents.swift
5
5439
//: **Eureka Playground** - let us walk you through Eureka! cool features, we will show how to //: easily create powerful forms using Eureka! //: It allows us to create complex dynamic table view forms and obviously simple static table view. It's ideal for data entry task or settings pages. import UIKit import XCPlayground import PlaygroundSupport //: Start by importing Eureka module import Eureka //: Any **Eureka** form must extend from `FormViewController` let formController = FormViewController() PlaygroundPage.current.liveView = formController.view let b = [Int]() b.last let f = Form() f.last //: ## Operators //: ### +++ //: Adds a Section to a Form when the left operator is a Form let form = Form() +++ Section() //: When both operators are a Section it creates a new Form containing both Section and return the created form. let form2 = Section("First") +++ Section("Second") +++ Section("Third") //: Notice that you don't need to add parenthesis in the above expresion, +++ operator is left associative so it will create a form containing the 2 first sections and then append last Section (Third) to the created form. //: form and form2 don't have any row and are not useful at all. Let's add some rows. //: ### +++ //: Can be used to append a row to a form without having to create a Section to contain the row. The form section is implicitly created as a result of the +++ operator. formController.form +++ TextRow("Text") //: it can also be used to append a Section like this: formController.form +++ Section() //: ### <<< //: Can be used to append rows to a section. formController.form.last! <<< SwitchRow("Switch") { $0.title = "Switch"; $0.value = true } //: it can also be used to create a section and append rows to it. Let's use that to add a new section to the form formController.form +++ PhoneRow("Phone") { $0.title = "Phone"} <<< IntRow("IntRow") { $0.title = "Int"; $0.value = 5 } formController.view //: # Callbacks //: Rows might have several closures associated to be called at different events. Let's see them one by one. Sadly, we can not interact with it in our playground. //: ### onChange callback //: Will be called when the value of a row changes. Lots of things can be done with this feature. Let's create a new section for the new rows: formController.form +++ Section("Callbacks") <<< SwitchRow("scr1") { $0.title = "Switch to turn red"; $0.value = false } .onChange({ row in if row.value == true { row.cell.backgroundColor = .red } else { row.cell.backgroundColor = .black } }) //: Now when we change the value of this row its background color will change to red. Try that by (un)commenting the following line: formController.view formController.form.last?.last?.baseValue = true formController.view //: Notice that we set the `baseValue` attribute because we did not downcast the result of `formController.form.last?.last`. It is essentially the same as the `value` attribute //: ### cellSetup and cellUpdate callbacks //: The cellSetup will be called when the cell of this row is configured (just once at the beginning) //: and the cellUpdate will be called when it is updated (each time it reappears on screen). Here you should define the appearance of the cell formController.form.last! <<< SegmentedRow<String>("Segments") { $0.title = "Choose an animal"; $0.value = "🐼"; $0.options = ["🐼", "🐶", "🐻"]}.cellSetup({ cell, _ in cell.backgroundColor = .red }).cellUpdate({ (cell, _) -> Void in cell.textLabel?.textColor = .yellow }) //: ### onSelection and onPresent callbacks //: OnSelection will be called when this row is selected (tapped by the user). It might be useful for certain rows instead of the onChange callback. //: OnPresent will be called when a row that presents another view controller is tapped. It might be useful to set up the presented view controller. //: We can not try them out in the playground but they can be set just like the others. formController.form.last! <<< SegmentedRow<String>("Segments2") { $0.title = "Choose an animal"; $0.value = "🐼"; $0.options = ["🐼", "🐶", "🐻"] }.onCellSelection { cell, row in print("\(cell) for \(row) got selected") } formController.view //: ### Hiding rows //: We can hide rows by defining conditions that will tell if they should appear on screen or not. Let's create a row that will hide when the previous one is "🐼". formController.form.last! <<< LabelRow("Confirm") { $0.title = "Are you sure you do not want the 🐼?" $0.hidden = "$Segments2 == '🐼'" } //: Now let's see how this works: formController.view formController.form.rowBy(tag: "Segments2")?.baseValue = "🐶" formController.view //: We can do the same using functions. Functions are specially useful for more complicated conditions. //: This applies when the value of the row we depend on is not compatible with NSPredicates (which is not the current case, but anyway). formController.form.last! <<< LabelRow("Confirm2") { $0.title = "Well chosen!!" $0.hidden = Condition.function(["Segments2"]) { form in if let r: SegmentedRow<String> = form.rowBy(tag: "Segments2") { return r.value != "🐼" } return true } } //: Now let's see how this works: formController.view formController.form.rowBy(tag: "Segments2")?.baseValue = "🐼" formController.view
mit
dd18d08272c4278756d564aba13697af
43.975
221
0.696313
4.064006
false
false
false
false
lyle-luan/firefox-ios
ClientTests/TestHistory.swift
2
8377
import Foundation import XCTest import Storage class TestHistory : AccountTest { private func innerAddSite(history: History, url: String, title: String, callback: (success: Bool) -> Void) { // Add an entry let site = Site(url: url, title: title) let visit = Visit(site: site, date: NSDate()) history.addVisit(visit) { success in callback(success: success) } } private func addSite(history: History, url: String, title: String, s: Bool = true) { let expectation = self.expectationWithDescription("Wait for history") innerAddSite(history, url: url, title: title) { success in XCTAssertEqual(success, s, "Site added \(url)") expectation.fulfill() } } private func innerCheckSites(history: History, callback: (cursor: Cursor) -> Void) { // Retrieve the entry history.get(nil, complete: { cursor in callback(cursor: cursor) }) } private func checkSites(history: History, urls: [String: String], s: Bool = true) { let expectation = self.expectationWithDescription("Wait for history") // Retrieve the entry innerCheckSites(history) { cursor in XCTAssertEqual(cursor.status, CursorStatus.Success, "returned success \(cursor.statusMessage)") XCTAssertEqual(cursor.count, urls.count, "cursor has \(urls.count) entries") for index in 0..<cursor.count { let s = cursor[index] as Site XCTAssertNotNil(s, "cursor has a site for entry") let title = urls[s.url] XCTAssertNotNil(title, "Found right url") XCTAssertEqual(s.title, title!, "Found right title") } expectation.fulfill() } self.waitForExpectationsWithTimeout(100, handler: nil) } private func innerClear(history: History, callback: (s: Bool) -> Void) { history.clear({ success in callback(s: success) }) } private func clear(history: History, s: Bool = true) { let expectation = self.expectationWithDescription("Wait for history") innerClear(history) { success in XCTAssertEqual(s, success, "Sites cleared") expectation.fulfill() } self.waitForExpectationsWithTimeout(100, handler: nil) } private func checkVisits(history: History, url: String) { let expectation = self.expectationWithDescription("Wait for history") history.get(nil) { cursor in let options = QueryOptions() options.filter = url history.get(options) { cursor in XCTAssertEqual(cursor.status, CursorStatus.Success, "returned success \(cursor.statusMessage)") // XXX - We don't allow querying much info about visits here anymore, so there isn't a lot to do expectation.fulfill() } } self.waitForExpectationsWithTimeout(100, handler: nil) } // This is a very basic test. Adds an entry. Retrieves it, and then clears the database func testHistory() { withTestAccount { account -> Void in let h = account.history self.addSite(h, url: "url1", title: "title") self.addSite(h, url: "url1", title: "title") self.addSite(h, url: "url1", title: "title 2") self.addSite(h, url: "url2", title: "title") self.addSite(h, url: "url2", title: "title") self.checkSites(h, urls: ["url1": "title 2", "url2": "title"]) self.checkVisits(h, url: "url1") self.checkVisits(h, url: "url2") self.clear(h) account.files.remove("browser.db") } } let NumThreads = 5 let NumCmds = 10 func testInsertPerformance() { withTestAccount { account -> Void in let h = account.history var j = 0 self.measureBlock({ () -> Void in for i in 0...self.NumCmds { self.addSite(h, url: "url \(j)", title: "title \(j)") j++ } self.clear(h) }) account.files.remove("browser.db") } } func testGetPerformance() { withTestAccount { account -> Void in let h = account.history var j = 0 var urls = [String: String]() self.clear(h) for i in 0...self.NumCmds { self.addSite(h, url: "url \(j)", title: "title \(j)") urls["url \(j)"] = "title \(j)" j++ } self.measureBlock({ () -> Void in self.checkSites(h, urls: urls) return }) self.clear(h) account.files.remove("browser.db") } } // Fuzzing tests. These fire random insert/query/clear commands into the history database from threads. The don't check // the results. Just look for crashes. func testRandomThreading() { withTestAccount { account -> Void in var queue = dispatch_queue_create("My Queue", DISPATCH_QUEUE_CONCURRENT) var done = [Bool]() var counter = 0 let expectation = self.expectationWithDescription("Wait for history") for i in 0..<self.NumThreads { var history = account.history self.runRandom(&history, queue: queue, cb: { () -> Void in counter++ if counter == self.NumThreads { expectation.fulfill() } }) } self.waitForExpectationsWithTimeout(10, handler: nil) account.files.remove("browser.db") } } // Same as testRandomThreading, but uses one history connection for all threads func testRandomThreading2() { withTestAccount { account -> Void in var queue = dispatch_queue_create("My Queue", DISPATCH_QUEUE_CONCURRENT) var history = account.history var counter = 0 let expectation = self.expectationWithDescription("Wait for history") for i in 0..<self.NumThreads { self.runRandom(&history, queue: queue, cb: { () -> Void in counter++ if counter == self.NumThreads { expectation.fulfill() } }) } self.waitForExpectationsWithTimeout(10, handler: nil) account.files.remove("browser.db") } } // Runs a random command on a database. Calls cb when finished private func runRandom(inout history: History, cmdIn: Int, cb: () -> Void) { var cmd = cmdIn if cmd < 0 { cmd = Int(rand() % 5) } switch cmd { case 0...1: let url = "url \(rand() % 100)" let title = "title \(rand() % 100)" innerAddSite(history, url: url, title: title) { success in cb() } case 2...3: innerCheckSites(history) { cursor in for site in cursor { let s = site as Site } } cb() default: innerClear(history) { success in cb() } } } // Calls numCmds random methods on this database. val is a counter used by this interally (i.e. always pass zero for it) // Calls cb when finished private func runMultiRandom(inout history: History, val: Int, numCmds: Int, cb: () -> Void) { if val == numCmds { cb() return } else { runRandom(&history, cmdIn: -1) { _ in self.runMultiRandom(&history, val: val+1, numCmds: numCmds, cb: cb) } } } // Helper for starting a new thread running NumCmds random methods on it. Calls cb when done private func runRandom(inout history: History, queue: dispatch_queue_t, cb: () -> Void) { dispatch_async(queue) { // Each thread creates its own history provider self.runMultiRandom(&history, val: 0, numCmds: self.NumCmds) { _ in dispatch_async(dispatch_get_main_queue(), cb) } } } }
mpl-2.0
e0d836f8f854326f6e65e36ed6040249
34.5
124
0.544467
4.547774
false
true
false
false
ktatroe/MPA-Horatio
Horatio/Horatio/Classes/Services/ServiceRequestOperation.swift
2
9448
// // Copyright © 2016 Kevin Tatroe. All rights reserved. // See LICENSE.txt for this sample’s licensing information import Foundation /// Contains Data from the service response public protocol ServiceResponseDataContainable { var responseData: Data? { get } } /// Responsible for fetching a response from a service public protocol ServiceResponseFetching { var request: ServiceRequest { get } } /// Responsible for processing the service response public protocol ServiceResponseProcessing { var request: ServiceRequest { get } var responseProcessor: ServiceResponseProcessor { get } } public typealias ServiceFetchOperation = Operation & ServiceResponseFetching & ServiceResponseDataContainable public typealias ServiceProcessOperation = Operation & ServiceResponseProcessing & ServiceResponseDataContainable /** Handles downloading and processing of a `ServiceRequest`. Callers provide a `ServiceResponseProcessor` responsible for processing the response once it's successfully fetched. */ public class FetchServiceResponseOperation: GroupOperation { private var errorHandler: (([Error]) -> Void)? // MARK: - Initialization public init(request: ServiceRequest, session: ServiceSession? = nil, urlSession: URLSession = URLSession.shared, responseProcessor: ServiceResponseProcessor) { let fetchOperation: ServiceFetchOperation switch request.requestMethod { case .data: fetchOperation = DataServiceResponseOperation(request: request, session: session, urlSession: urlSession) case .download: let cacheFileURL = FetchServiceResponseOperation.constructCacheFileURL(for: request) fetchOperation = DownloadServiceResponseOperation(request: request, session: session, cacheFileURL: cacheFileURL, urlSession: urlSession) errorHandler = { _ in try? FileManager.default.removeItem(at: cacheFileURL) } } let processOperation = ProcessServiceResponseOperation(request: request, responseProcessor: responseProcessor) let dataPassingOperation = BlockOperation { processOperation.responseData = fetchOperation.responseData } dataPassingOperation.addDependency(fetchOperation) processOperation.addDependency(dataPassingOperation) super.init(operations: [fetchOperation, processOperation, dataPassingOperation]) #if os(iOS) || os(tvOS) let timeout = TimeoutObserver(timeout: 20.0) addObserver(timeout) #endif let networkObserver = NetworkObserver() addObserver(networkObserver) name = "Fetch Service Request Operation" } override open func finished(_ errors: [NSError]) { errorHandler?(errors) } // MARK: - Private private static func constructCacheFileURL(for request: ServiceRequest) -> URL { let cachesFolder = try! FileManager.default.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor: nil, create: true) let cacheFileName = generatedCacheFileName(request) return cachesFolder.appendingPathComponent(cacheFileName) } private static func generatedCacheFileName(_ request: ServiceRequest) -> String { guard let url = request.url else { return UUID().uuidString } let cacheComponent = url.lastPathComponent let hasValidCacheComponent = !(url.hasDirectoryPath && cacheComponent.count == 1) return hasValidCacheComponent ? cacheComponent : UUID().uuidString } } /** Handles the downloading of an HTTP request via a `NSURLSession` data task. */ public class DataServiceResponseOperation: GroupOperation, ServiceResponseFetching, ServiceResponseDataContainable { // MARK: - Properties public let request: ServiceRequest public private(set) var responseData: Data? // MARK: - Initialization public init(request: ServiceRequest, session: ServiceSession? = nil, urlSession: URLSession = URLSession.shared) { self.request = request super.init(operations: []) guard let urlRequest = request.makeURLRequest(session), let url = urlRequest.url else { return } name = "Data Service Request Operation \(url)" let task = urlSession.dataTask(with: urlRequest) { [weak self] (data, response, error) in guard error == nil else { self?.finishWithError(error) return } self?.responseData = data } let taskOperation = URLSessionTaskOperation(task: task) addOperation(taskOperation) } } /** Handles the downloading of an HTTP request via a `NSURLSession` download task and storing the downloaded file in a cache file location that continued operations can pick up and manipulate. */ public class DownloadServiceResponseOperation: GroupOperation, ServiceResponseFetching, ServiceResponseDataContainable { // MARK: - Properties public let request: ServiceRequest public let cacheFileURL: URL public private(set) var responseData: Data? // MARK: - Initialization public init(request: ServiceRequest, session: ServiceSession? = nil, cacheFileURL: URL, urlSession: URLSession = URLSession.shared) { self.request = request self.cacheFileURL = cacheFileURL super.init(operations: []) guard let urlRequest = request.makeURLRequest(session), let url = urlRequest.url else { return } name = "Download Service Request Operation \(url)" let task = urlSession.downloadTask(with: urlRequest) { [weak self] (url, _, error) in self?.downloadFinished(url, error: error) } let taskOperation = URLSessionTaskOperation(task: task) addOperation(taskOperation) } // MARK: - Private private func downloadFinished(_ url: URL?, error: Error?) { if let localURL = url { try? FileManager.default.removeItem(at: cacheFileURL) do { try FileManager.default.moveItem(at: localURL, to: cacheFileURL) responseData = try Data(contentsOf: cacheFileURL) } catch let error as NSError { aggregateError(error) } } else if let error = error { aggregateError(error) } else { // do nothing and let the operation complete } } } public enum ProcessServiceResponseError: Error { case noData case notProcessed } /** Uses a provided `ServiceResponseProcessor` to process a response downloaded into a cache file. */ public class ProcessServiceResponseOperation: Operation, ServiceResponseProcessing, ServiceResponseDataContainable { // MARK: - Properties public let request: ServiceRequest public let responseProcessor: ServiceResponseProcessor public fileprivate(set) var responseData: Data? // MARK: - Initialization public init(request: ServiceRequest, responseProcessor: ServiceResponseProcessor, responseData: Data? = nil) { self.request = request self.responseProcessor = responseProcessor self.responseData = responseData } // MARK: - Operation execute override override public func execute() { guard let data = responseData else { finishWithError(ProcessServiceResponseError.noData) return } self.responseProcessor.process(request, input: .data(data)) { (response: ServiceResponseProcessorParam) in switch response { case .stream(_), .data(_): self.finish() case .processed(let processed): let error = processed ? nil : ProcessServiceResponseError.notProcessed self.finishWithError(error) case .error(let error): self.finishWithError(error) } } } } /** Handles moving data from one processor to another. A value may either be terminal or non-terminal. Terminal values indicate that processing is complete and the input is "consumed". Non-terminal values provide new input that may be further processed (for example, in a pipeline of processors). */ public enum ServiceResponseProcessorParam { /// Initial input is typically a memory-efficient `NSInputStream`. case stream(InputStream) /// `NSData` can be used to pipe data from one processor to the next. case data(Data) /// The processor was terminal, with an indication of whether the data was completely processed. case processed(Bool) /// The processor was terminal, and ended with a known error. case error(NSError) } /** Handles input delivered via `ServiceResponseProcessorParam`, processes the data, and returns a new `ServiceResponseProcessorParam`, which can then be further processed or, if terminal, complete the processing stage of the operation. */ public protocol ServiceResponseProcessor: class { func process(_ request: ServiceRequest, input: ServiceResponseProcessorParam, completionBlock: @escaping (ServiceResponseProcessorParam) -> Void) }
mit
d29439e89e3a79425cc330d5808753d7
33.59707
163
0.674749
5.390982
false
false
false
false
buyiyang/iosstar
iOSStar/Marco/AppConst.swift
3
8638
// // AppConfig.swift // viossvc // // Created by yaowang on 2016/10/31. // Copyright © 2016年 ywwlcom.yundian. All rights reserved. // import UIKit typealias CompleteBlock = (AnyObject?) ->() typealias ErrorBlock = (NSError) ->() typealias paramBlock = (AnyObject?) ->()? let kScreenWidth = UIScreen.main.bounds.size.width let kScreenHeight = UIScreen.main.bounds.size.height //MARK: --正则表达 func isTelNumber(num: String)->Bool{ let predicate:NSPredicate = NSPredicate(format: "SELF MATCHES %@", "^1[3|4|5|7|8][0-9]\\d{8}$") return predicate.evaluate(with: num) } // 密码校验 func isPassWord(pwd: String) ->Bool { let predicate:NSPredicate = NSPredicate(format: "SELF MATCHES %@", "(^[A-Za-z0-9]{6,20}$)") return predicate.evaluate(with: pwd) } class AppConst { static let DefaultPageSize = 15 static let UMAppkey = "584a3eb345297d271600127e" static let isMock = false static let sha256Key = "t1@s#df!" static let pid = 1002 static let frozeCode = -101 static let bundleId = "com.newxfin.goods" static let loginSuccess = "loginSuccess" static let loginSuccessNotice = "loginSuccessNotice" static let chooseServiceTypeSuccess = "chooseServiceTypeSuccess" static let valueStarCode = "valueStarCode" static let getStarService = "getStarService" static let imageTokenUrl = "http://122.144.169.219:3378/imageToken" static let meetCityDefault = "杭州" static let didmiss = "杭州" static let ipUrl = "http://ip.chinaz.com/getip.aspx" static let shareUrl = "http://star.grwme.com" static let ipInfoUrl = "http://ip.taobao.com/service/getIpInfo.php?ip=125.121.228.115" enum KVOKey: String { case selectProduct = "selectProduct" case allProduct = "allProduct" case currentUserId = "currentUserId" case balance = "balance" } enum NoticeKey: String { case logoutNotice = "LogoutNotice" case onlyLogin = "onlyLogin" case frozeUser = "frozeUser" case checkUpdte = "checkUpdate" case WYIMLoginSuccess = "WYIMLoginSuccess" } class Color { static let main = "921224" static let orange = "FB9938" static let up = "CB4232" static let down = "18B03F" static let titleColor = "8C0808" static let background = "background" static let auxiliary = "auxiliary" static let lightBlue = "lightBlue" } enum ColorKey: UInt32 { case main = 0x8c0808 case bgColor = 0xfafafa case label6 = 0x666666 case label3 = 0x333333 case label9 = 0x999999 case closeColor = 0xFFFFFF case linkColor = 0x75c1e7 } class SystemFont { static let S1 = UIFont.systemFont(ofSize: 18) static let S2 = UIFont.systemFont(ofSize: 15) static let S3 = UIFont.systemFont(ofSize: 13) static let S4 = UIFont.systemFont(ofSize: 12) static let S5 = UIFont.systemFont(ofSize: 10) static let S14 = UIFont.systemFont(ofSize: 14) } enum iconFontName: String { case backItem = "\u{e61a}" case closeIcon = "\u{e63e}" case newsIcon = "\u{e629}" case userPlaceHolder = "\u{e62b}" case thumpUpIcon = "\u{e624}" case newsPlaceHolder = "\u{e62a}" case addIcon = "\u{e611}" case commentIcon = "\u{e635}" case thumbIcon = "\u{e62f}" case showIcon = "\u{e665}" case handleIcon = "\u{e663}" } enum guideKey: String { case joinToBuy = "joinToBuy.jpg" case leftRight = "leftRight.jpg" case StarIntroduce = "StarIntroduce.jpg" case starSearch = "starSearch.jpg" case starsNews = "starsNews" case timeBusiness = "timeBusiness.jpg" case upDown = "upDown.jpg" case feedBack = "feedBack" } class Network { #if true //是否测试环境 //139.224.34.22 //122.144.169.214 //nsb.smartdata-x.com // static let TcpServerIP:String = "nsb.smartdata-x.com"; // static let TcpServerPort:UInt16 = 16006 // static let TcpServerIP:String = "101.132.27.138"; // static let TcpServerPort:UInt16 = 17001 // static let TcpServerIP:String = "cloud.a.smartdata-x.com"; // static let TcpServerPort:UInt16 = 17001 // static let TcpServerIP:String = "cloud.p.smartdata-x.com"; // static let TcpServerPort:UInt16 = 17001 static let TcpServerIP:String = "nsb.smartdata-x.com"; static let TcpServerPort:UInt16 = 16006 // static let TcpServerIP:String = "139.224.34.22"; // static let TcpServerPort:UInt16 = 16070 static let TttpHostUrl:String = "dapi.star.smartdata-x.com"; #else static let TcpServerIP:String = "tapi.smartdata-x.com"; static let TcpServerPort:UInt16 = 16006 static let HttpHostUrl:String = "tapi.smartdata-x.com"; #endif static let TimeoutSec:UInt16 = 10 static let qiniuHost = "http://ofr5nvpm7.bkt.clouddn.com/" } class Text { static let deviceToken = "deviceToken" static let PhoneFormatErr = "请输入正确的手机号" static let VerifyCodeErr = "请输入正确的验证码" static let SMSVerifyCodeErr = "获取验证码失败" static let PasswordTwoErr = "两次密码不一致" static let ReSMSVerifyCode = "重新获取" static let ErrorDomain = "com.redsky.starshare" static let PhoneFormat = "^1[3|4|5|7|8][0-9]\\d{8}$" static let RegisterPhoneError = "输入的手机号已注册" static let numberReg = "^(?!0(\\d|\\.0+$|$))\\d+(\\.\\d{1,2})?$" } enum Action:UInt { case callPhone = 10001 case handleOrder = 11001 } enum BundleInfo:String { case CFBundleDisplayName = "CFBundleDisplayName" case CFBundleShortVersionString = "CFBundleShortVersionString" case CFBundleVersion = "CFBundleVersion" } enum StoryBoardName:String { case Markt = "Market" case News = "News" case Deal = "Deal" case User = "User" case Login = "Login" case Exchange = "Exchange" case Discover = "Discover" } enum RegisterIdentifier:String { case MarketDetailMenuView = "MarketDetailMenuView" case PubInfoHeaderView = "PubInfoHeaderView" case MaketBannerCell = "MaketBannerCell" case MarketInfoCell = "MarketInfoCell" case MarketExperienceCell = "MarketExperienceCell" case FansListHeaderView = "FansListHeaderView" case MarketFansCell = "MarketFansCell" case MarketCommentCell = "MarketCommentCell" case NewsListCell = "NewsListCell" } enum SegueIdentifier:String { case newsToDeatail = "newsToDeatail" case showPubPage = "showPubPage" } enum DealType:Int { case buy = 1 case sell = -1 } enum OrderStatus:Int32 { case pending = 0 case matching = 1 case complete = 2 } enum SortType:Int { case down = 0 case up = 1 } enum DealDetailType:UInt16 { //当日成交 case todayComplete = 6007 //当日委托 case todayEntrust = 6001 //历史委托 case allEntrust = 6005 //历史交易 case allDeal = 6009 } enum StarStatus { //预售 case presell //发售 case selling //求购 case askToBuy //更多 case more } class WechatKey { static let Scope = "snsapi_userinfo" static let State = "wpstate" static let AccessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token" static let Appid = "wxa75d31be7fcb762f" static let Secret = "edd6e7ea7293049951b563dbc803ebea" static let ErrorCode = "ErrorCode" static let wechetUserInfo = "https://api.weixin.qq.com/sns/userinfo" } class aliPay { static let aliPayCode = "aliPayCode" } class WechatPay { static let WechatKeyErrorCode = "WechatKeyErrorCode" } class UnionPay { static let UnionErrorCode = "UnionErrorCode" } class NotifyDefine { } enum UserDefaultKey: String { case uid = "uid" case phone = "phone" case token = "token" case tokenTime = "token_time" case token_value = "token_value" } }
gpl-3.0
5564d20e6c7958ad042c0926aaf8cc79
29.879562
99
0.608675
3.77218
false
false
false
false
kean/Nuke
Sources/Nuke/Processing/ImageProcessing.swift
1
3652
// The MIT License (MIT) // // Copyright (c) 2015-2022 Alexander Grebenyuk (github.com/kean). import Foundation /// Performs image processing. /// /// For basic processing needs, implement the following method: /// /// ```swift /// func process(image: PlatformImage) -> PlatformImage? /// ``` /// /// If your processor needs to manipulate image metadata (``ImageContainer``), or /// get access to more information via the context (``ImageProcessingContext``), /// there is an additional method that allows you to do that: /// /// ```swift /// func process(image container: ImageContainer, context: ImageProcessingContext) -> ImageContainer? /// ``` /// /// You must implement either one of those methods. public protocol ImageProcessing: Sendable { /// Returns a processed image. By default, returns `nil`. /// /// - note: Gets called a background queue managed by the pipeline. func process(_ image: PlatformImage) -> PlatformImage? /// Optional method. Returns a processed image. By default, this calls the /// basic `process(image:)` method. /// /// - note: Gets called a background queue managed by the pipeline. func process(_ container: ImageContainer, context: ImageProcessingContext) throws -> ImageContainer /// Returns a string that uniquely identifies the processor. /// /// Consider using the reverse DNS notation. var identifier: String { get } /// Returns a unique processor identifier. /// /// The default implementation simply returns `var identifier: String` but /// can be overridden as a performance optimization - creating and comparing /// strings is _expensive_ so you can opt-in to return something which is /// fast to create and to compare. See ``ImageProcessors/Resize`` for an example. /// /// - note: A common approach is to make your processor `Hashable` and return `self` /// as a hashable identifier. var hashableIdentifier: AnyHashable { get } } extension ImageProcessing { /// The default implementation simply calls the basic /// `process(_ image: PlatformImage) -> PlatformImage?` method. public func process(_ container: ImageContainer, context: ImageProcessingContext) throws -> ImageContainer { guard let output = process(container.image) else { throw ImageProcessingError.unknown } var container = container container.image = output return container } /// The default impleemntation simply returns `var identifier: String`. public var hashableIdentifier: AnyHashable { identifier } } extension ImageProcessing where Self: Hashable { public var hashableIdentifier: AnyHashable { self } } /// Image processing context used when selecting which processor to use. public struct ImageProcessingContext: Sendable { public var request: ImageRequest public var response: ImageResponse public var isCompleted: Bool public init(request: ImageRequest, response: ImageResponse, isCompleted: Bool) { self.request = request self.response = response self.isCompleted = isCompleted } } public enum ImageProcessingError: Error, CustomStringConvertible, Sendable { case unknown public var description: String { "Unknown" } } func == (lhs: [any ImageProcessing], rhs: [any ImageProcessing]) -> Bool { guard lhs.count == rhs.count else { return false } // Lazily creates `hashableIdentifiers` because for some processors the // identifiers might be expensive to compute. return zip(lhs, rhs).allSatisfy { $0.hashableIdentifier == $1.hashableIdentifier } }
mit
74c4eeaf75704f59468ab2c8dd0e56a2
35.158416
112
0.697152
4.928475
false
false
false
false
KimBin/DTTableViewManager
Example/Example/Example controllers/Search/CoreDataSearchViewController.swift
1
2343
// // CoreDataSearchViewController.swift // DTTableViewManager // // Created by Denys Telezhkin on 20.08.15. // Copyright (c) 2015 Denys Telezhkin. All rights reserved. // import UIKit import DTTableViewManager import CoreData import DTModelStorage class CoreDataSearchViewController: UIViewController, DTTableViewManageable { @IBOutlet weak var tableView: UITableView! let searchController = UISearchController(searchResultsController: nil) let fetchResultsController: NSFetchedResultsController = { let context = CoreDataManager.sharedInstance.managedObjectContext let request = NSFetchRequest(entityName: "Bank") request.fetchBatchSize = 20 request.sortDescriptors = [NSSortDescriptor(key: "zip", ascending: true)] let fetchResultsController = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: "state", cacheName: nil) try! fetchResultsController.performFetch() return fetchResultsController }() override func viewDidLoad() { super.viewDidLoad() manager.startManagingWithDelegate(self) manager.registerCellClass(BankCell) manager.storage = CoreDataStorage(fetchedResultsController: fetchResultsController) manager.afterContentUpdate { [weak self] in self?.tableView.hidden = self?.tableView.numberOfSections == 0 } searchController.searchResultsUpdater = self searchController.hidesNavigationBarDuringPresentation = true searchController.searchBar.sizeToFit() tableView.tableHeaderView = searchController.searchBar } } extension CoreDataSearchViewController : UISearchResultsUpdating { func updateSearchResultsForSearchController(searchController: UISearchController) { let searchString = searchController.searchBar.text ?? "" if searchString == "" { self.fetchResultsController.fetchRequest.predicate = nil } else { let predicate = NSPredicate(format: "name contains %@ OR city contains %@ OR state contains %@",searchString,searchString,searchString) self.fetchResultsController.fetchRequest.predicate = predicate } try! fetchResultsController.performFetch() manager.storageNeedsReloading() } }
mit
1fb79dd40cda740cccdb50308f25a1cb
38.711864
162
0.729407
6.101563
false
false
false
false
rockgarden/swift_language
Playground/Swift Language Guide.playground/Pages/Methods.xcplaygroundpage/Contents.swift
1
12763
//: [Previous](@previous) import UIKit /*: # Methods Methods are functions that are associated with a particular type. Classes, structures, and enumerations can all define instance methods, which encapsulate specific tasks and functionality for working with an instance of a given type. Classes, structures, and enumerations can also define type methods, which are associated with the type itself. Type methods are similar to class methods in Objective-C. 方法是与特定类型相关联的函数。 类,结构和枚举都可以定义实例方法,它封装了用于处理给定类型的实例的特定任务和功能。 类,结构和枚举也可以定义类型方法,它们与类型本身相关联。 类型方法类似于Objective-C中的类方法。 The fact that structures and enumerations can define methods in Swift is a major difference from C and Objective-C. In Objective-C, classes are the only types that can define methods. In Swift, you can choose whether to define a class, structure, or enumeration, and still have the flexibility to define methods on the type you create. 结构和枚举可以在Swift中定义方法的事实是与C和Objective-C的主要区别。 在Objective-C中,类是唯一可以定义方法的类型。 在Swift中,您可以选择是定义类,结构还是枚举,还可以灵活地定义创建类型的方法。 */ /*: # Instance Methods 实例方法 Instance methods are functions that belong to instances of a particular class, structure, or enumeration. They support the functionality of those instances, either by providing ways to access and modify instance properties, or by providing functionality related to the instance’s purpose. Instance methods have exactly the same syntax as functions. You write an instance method within the opening and closing braces of the type it belongs to. An instance method has implicit access to all other instance methods and properties of that type. An instance method can be called only on a specific instance of the type it belongs to. It cannot be called in isolation without an existing instance. */ class Counter { var count = 0 func increment() { count += 1 } func increment(by amount: Int) { count += amount } func reset() { count = 0 } } do { let counter = Counter() // the initial counter value is 0 counter.increment() // the counter's value is now 1 counter.increment(by: 5) // the counter's value is now 6 counter.reset() // the counter's value is now 0 } /*: ## The self Property Every instance of a type has an implicit property called self, which is exactly equivalent to the instance itself. You use the self property to refer to the current instance within its own instance methods. In practice, you don’t need to write self in your code very often. If you don’t explicitly write self, Swift assumes that you are referring to a property or method of the current instance whenever you use a known property or method name within a method. The main exception to this rule occurs when a parameter name for an instance method has the same name as a property of that instance. In this situation, the parameter name takes precedence, and it becomes necessary to refer to the property in a more qualified way. You use the self property to distinguish between the parameter name and the property name. */ class CounterSelf: Counter { override func increment() { self.count += 1 } } struct Point { var x = 0.0, y = 0.0 static var xy = 0.0 func isToTheRightOf(x: Double) -> Bool { return self.x > x } mutating func moveByX(deltaX: Double, y deltaY: Double) { x += deltaX y += deltaY /// Reassigning self is also possible because of the mutating prefix. Note that this is only possible for value types self = Point(x: x + deltaX, y: y + deltaY) } //This is a type method. static func unlockLevel(level: Double) { if xy > level { xy = level } } } do { let somePoint = Point(x: 4.0, y: 5.0) if somePoint.isToTheRightOf(x: 1.0) { print("This point is to the right of the line where x == 1.0") } // Prints "This point is to the right of the line where x == 1.0" } /*: ## Modifying Value Types from Within Instance Methods Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods. 结构和枚举是值类型。 默认情况下,不能在其实例方法内修改值类型的属性。 However, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method. The method can then mutate (that is, change) its properties from within the method, and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit self property, and this new instance will replace the existing one when the method ends. 但是,如果您需要修改特定方法中的结构或枚举的属性,则可以选择对该方法进行突变行为。 然后,该方法可以在方法内改变(即改变)其属性,并且当该方法结束时,它所做的任何改变被写回到原始结构。 该方法还可以为其隐式自我属性分配一个完全新的实例,并且当该方法结束时,这个新实例将替换现有实例。 */ do { struct Point { var x = 0.0, y = 0.0 /// This is a mutating method. Allows for modifying value types, the properties will be replaced with new values, thanks to the mutating prefix mutating func moveBy(x deltaX: Double, y deltaY: Double) { x += deltaX y += deltaY } } var somePoint = Point(x: 1.0, y: 1.0) somePoint.moveBy(x: 2.0, y: 3.0) print("The point is now at (\(somePoint.x), \(somePoint.y))") // Prints "The point is now at (3.0, 4.0)" /// Note that you cannot call a mutating method on a constant of structure type, because its properties cannot be changed, even if they are variable properties, as described in Stored Properties of https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html#//apple_ref/doc/uid/TP40014097-CH14-ID256: let fixedPoint = Point(x: 3.0, y: 3.0) //fixedPoint.moveBy(x: 2.0, y: 3.0) // this will report an error } /*: ## Assigning to self Within a Mutating Method Mutating methods can assign an entirely new instance to the implicit self property. */ do { struct Point { var x = 0.0, y = 0.0 mutating func moveBy(x deltaX: Double, y deltaY: Double) { /// Reassigning self is also possible because of the mutating prefix. Note that this is only possible for value types self = Point(x: x + deltaX, y: y + deltaY) } } } //: Mutating methods for enumerations can set the implicit self parameter to be a different case from the same enumeration: do { enum TriStateSwitch { case off, low, high mutating func next() { switch self { case .off: self = .low case .low: self = .high case .high: self = .off } } } var ovenLight = TriStateSwitch.low ovenLight.next() // ovenLight is now equal to .high ovenLight.next() // ovenLight is now equal to .off } /*: ## Type Methods Instance methods, as described above, are methods that are called on an instance of a particular type. You can also define methods that are called on the type itself. These kinds of methods are called type methods. You indicate type methods by writing the static keyword before the method’s func keyword. Classes may also use the class keyword to allow subclasses to override the superclass’s implementation of that method. 如上所述,实例方法是在特定类型的实例上调用的方法。 您还可以定义在类型本身上调用的方法。 这些类型的方法称为类型方法。 通过在方法的func关键字之前写入static关键字来指示类型方法。 类也可以使用class关键字来允许子类重写超类的方法实现。 - NOTE: In Objective-C, you can define type-level methods only for Objective-C classes. In Swift, you can define type-level methods for all classes, structures, and enumerations. Each type method is explicitly scoped to the type it supports. */ class SomeClass { class func someTypeMethod() { // type method implementation goes here } } SomeClass.someTypeMethod() /*: Within the body of a type method, the implicit self property refers to the type itself, rather than an instance of that type. This means that you can use self to disambiguate between type properties and type method parameters, just as you do for instance properties and instance method parameters. 在类型方法的主体中,implicit self属性引用类型本身,而不是该类型的实例。这意味着您可以使用self消除类型属性和类型方法参数之间的歧义,就像对实例属性和实例方法参数一样。 More generally, any unqualified method and property names that you use within the body of a type method will refer to other type-level methods and properties. A type method can call another type method with the other method’s name, without needing to prefix it with the type name. Similarly, type methods on structures and enumerations can access type properties by using the type property’s name without a type name prefix. 更一般地说,在类型方法的主体中使用的任何非限定方法和属性名将引用其他类型级方法和属性。类型方法可以使用另一个方法的名称调用另一个类型方法,而无需使用类型名称作为前缀。类似地,对结构和枚举的类型方法可以通过使用type属性的名称而没有类型名称前缀来访问类型属性。 */ struct LevelTracker { static var highestUnlockedLevel = 1 var currentLevel = 1 static func unlock(_ level: Int) { if level > highestUnlockedLevel { highestUnlockedLevel = level } } static func isUnlocked(_ level: Int) -> Bool { return level <= highestUnlockedLevel } @discardableResult mutating func advance(to level: Int) -> Bool { if LevelTracker.isUnlocked(level) { currentLevel = level return true } else { return false } } } do { class Player { var tracker = LevelTracker() let playerName: String func complete(level: Int) { LevelTracker.unlock(level + 1) tracker.advance(to: level + 1) } init(name: String) { playerName = name } } var player = Player(name: "Argyrios") player.complete(level: 1) print("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)") // Prints "highest unlocked level is now 2" player = Player(name: "Beto") if player.tracker.advance(to: 6) { print("player is now on level 6") } else { print("level 6 has not yet been unlocked") } // Prints "level 6 has not yet been unlocked" } //: # Example class ViewController: UIViewController { var count = 0 //This is an instance method func increment() { count += 1 } } class Dog { let name: String let license: Int let whatDogsSay = "Woof" init(name: String, license: Int) { self.name = name self.license = license } func bark() { print(self.whatDogsSay) } func speak() { self.bark() print("I'm \(self.name)") } func speak2() { bark() print("I'm \(name)") } func say(_ s: String, times: Int) { for _ in 1...times { print(s) } } } struct Greeting { static let friendly = "hello there" static let hostile = "go away" static var ambivalent: String { return self.friendly + " but " + self.hostile } static func beFriendly() { print(self.friendly) } } do { class Dog { static var whatDogsSay = "Woof" func bark() { print(Dog.whatDogsSay) } } } //: ## Example : what just happened!? do { class MyClass { var s = "" func store(s: String) { self.s = s } } let m = MyClass() let f = MyClass.store(m) //what just happened!? print(m.s) f("howdy") (m.s) // howdy } //: [Next](@next)
mit
c87cb546d6bf96c81d7e15341bfea949
38.704861
497
0.683953
3.978775
false
false
false
false
jeevanRao7/Swift_Playgrounds
Swift Playgrounds/Challenges/Matrix_challenge.playground/Contents.swift
1
889
/* Problem Statement : Given a square matrix of size , calculate the absolute difference between the sums of its diagonals. Input : 3 11 2 4 4 5 6 10 8 -12 Result : 15 Explanation : Diagonal 1 is 11 5 -12 And sum is : 4 Diagonal 2 is 4 5 10 And sum is : 19 Difference: |4 - 19| = 15 */ import Foundation // read the integer n let n = 3 // declare 2d array var arr: [[Int]] = [ [11,2,4], [4,5,6], [10,8,-12] ] var first_diag_Sum = 0; for index in 0..<n{ first_diag_Sum = first_diag_Sum + arr[index][index]; } var second_diag_Sum = 0; for index in 0..<n{ second_diag_Sum = second_diag_Sum + arr[index][n-index-1]; } print(abs(first_diag_Sum - second_diag_Sum))
mit
2b31e592882cdb644ffab386cb1b5ee4
10.545455
101
0.493813
3.244526
false
false
false
false
JusticeBao/animated-tab-bar
RAMAnimatedTabBarController/Animations/BounceAnimation/RAMBounceAnimation.swift
26
2757
// RAMBounceAnimation.swift // // Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import UIKit class RAMBounceAnimation : RAMItemAnimation { override func playAnimation(icon : UIImageView, textLabel : UILabel) { playBounceAnimation(icon) textLabel.textColor = textSelectedColor } override func deselectAnimation(icon : UIImageView, textLabel : UILabel, defaultTextColor : UIColor) { textLabel.textColor = defaultTextColor if let iconImage = icon.image { let renderImage = iconImage.imageWithRenderingMode(.AlwaysTemplate) icon.image = renderImage icon.tintColor = defaultTextColor } } override func selectedState(icon : UIImageView, textLabel : UILabel) { textLabel.textColor = textSelectedColor if let iconImage = icon.image { let renderImage = iconImage.imageWithRenderingMode(.AlwaysTemplate) icon.image = renderImage icon.tintColor = textSelectedColor } } func playBounceAnimation(icon : UIImageView) { let bounceAnimation = CAKeyframeAnimation(keyPath: "transform.scale") bounceAnimation.values = [1.0 ,1.4, 0.9, 1.15, 0.95, 1.02, 1.0] bounceAnimation.duration = NSTimeInterval(duration) bounceAnimation.calculationMode = kCAAnimationCubic icon.layer.addAnimation(bounceAnimation, forKey: "bounceAnimation") if let iconImage = icon.image { let renderImage = iconImage.imageWithRenderingMode(.AlwaysTemplate) icon.image = renderImage icon.tintColor = iconSelectedColor } } }
mit
88720901c0763afaae895e24d8b886e6
38.956522
106
0.704026
5.105556
false
false
false
false
ahoppen/swift
stdlib/public/core/BidirectionalCollection.swift
2
15814
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// /// A collection that supports backward as well as forward traversal. /// /// Bidirectional collections offer traversal backward from any valid index, /// not including a collection's `startIndex`. Bidirectional collections can /// therefore offer additional operations, such as a `last` property that /// provides efficient access to the last element and a `reversed()` method /// that presents the elements in reverse order. In addition, bidirectional /// collections have more efficient implementations of some sequence and /// collection methods, such as `suffix(_:)`. /// /// Conforming to the BidirectionalCollection Protocol /// ================================================== /// /// To add `BidirectionalProtocol` conformance to your custom types, implement /// the `index(before:)` method in addition to the requirements of the /// `Collection` protocol. /// /// Indices that are moved forward and backward in a bidirectional collection /// move by the same amount in each direction. That is, for any valid index `i` /// into a bidirectional collection `c`: /// /// - If `i >= c.startIndex && i < c.endIndex`, then /// `c.index(before: c.index(after: i)) == i`. /// - If `i > c.startIndex && i <= c.endIndex`, then /// `c.index(after: c.index(before: i)) == i`. /// /// Valid indices are exactly those indices that are reachable from the /// collection's `startIndex` by repeated applications of `index(after:)`, up /// to, and including, the `endIndex`. public protocol BidirectionalCollection: Collection where SubSequence: BidirectionalCollection, Indices: BidirectionalCollection { // FIXME: Only needed for associated type inference. override associatedtype Element override associatedtype Index override associatedtype SubSequence override associatedtype Indices /// Returns the position immediately before the given index. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. /// - Returns: The index value immediately before `i`. func index(before i: Index) -> Index /// Replaces the given index with its predecessor. /// /// - Parameter i: A valid index of the collection. `i` must be greater than /// `startIndex`. func formIndex(before i: inout Index) /// Returns the position immediately after the given index. /// /// The successor of an index must be well defined. For an index `i` into a /// collection `c`, calling `c.index(after: i)` returns the same index every /// time. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. /// - Returns: The index value immediately after `i`. override func index(after i: Index) -> Index /// Replaces the given index with its successor. /// /// - Parameter i: A valid index of the collection. `i` must be less than /// `endIndex`. override func formIndex(after i: inout Index) /// Returns an index that is the specified distance from the given index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// /// let s = "Swift" /// let i = s.index(s.startIndex, offsetBy: 4) /// print(s[i]) /// // Prints "t" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// - Returns: An index offset by `distance` from the index `i`. If /// `distance` is positive, this is the same value as the result of /// `distance` calls to `index(after:)`. If `distance` is negative, this /// is the same value as the result of `abs(distance)` calls to /// `index(before:)`. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute /// value of `distance`. @_nonoverride func index(_ i: Index, offsetBy distance: Int) -> Index /// Returns an index that is the specified distance from the given index, /// unless that distance is beyond a given limiting index. /// /// The following example obtains an index advanced four positions from a /// string's starting index and then prints the character at that position. /// The operation doesn't require going beyond the limiting `s.endIndex` /// value, so it succeeds. /// /// let s = "Swift" /// if let i = s.index(s.startIndex, offsetBy: 4, limitedBy: s.endIndex) { /// print(s[i]) /// } /// // Prints "t" /// /// The next example attempts to retrieve an index six positions from /// `s.startIndex` but fails, because that distance is beyond the index /// passed as `limit`. /// /// let j = s.index(s.startIndex, offsetBy: 6, limitedBy: s.endIndex) /// print(j) /// // Prints "nil" /// /// The value passed as `distance` must not offset `i` beyond the bounds of /// the collection, unless the index passed as `limit` prevents offsetting /// beyond those bounds. /// /// - Parameters: /// - i: A valid index of the collection. /// - distance: The distance to offset `i`. `distance` must not be negative /// unless the collection conforms to the `BidirectionalCollection` /// protocol. /// - limit: A valid index of the collection to use as a limit. If /// `distance > 0`, a limit that is less than `i` has no effect. /// Likewise, if `distance < 0`, a limit that is greater than `i` has no /// effect. /// - Returns: An index offset by `distance` from the index `i`, unless that /// index would be beyond `limit` in the direction of movement. In that /// case, the method returns `nil`. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the absolute /// value of `distance`. @_nonoverride func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? /// Returns the distance between two indices. /// /// Unless the collection conforms to the `BidirectionalCollection` protocol, /// `start` must be less than or equal to `end`. /// /// - Parameters: /// - start: A valid index of the collection. /// - end: Another valid index of the collection. If `end` is equal to /// `start`, the result is zero. /// - Returns: The distance between `start` and `end`. The result can be /// negative only if the collection conforms to the /// `BidirectionalCollection` protocol. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the /// resulting distance. @_nonoverride func distance(from start: Index, to end: Index) -> Int /// The indices that are valid for subscripting the collection, in ascending /// order. /// /// A collection's `indices` property can hold a strong reference to the /// collection itself, causing the collection to be non-uniquely referenced. /// If you mutate the collection while iterating over its indices, a strong /// reference can cause an unexpected copy of the collection. To avoid the /// unexpected copy, use the `index(after:)` method starting with /// `startIndex` to produce indices instead. /// /// var c = MyFancyCollection([10, 20, 30, 40, 50]) /// var i = c.startIndex /// while i != c.endIndex { /// c[i] /= 5 /// i = c.index(after: i) /// } /// // c == MyFancyCollection([2, 4, 6, 8, 10]) override var indices: Indices { get } /// Accesses a contiguous subrange of the collection's elements. /// /// The accessed slice uses the same indices for the same elements as the /// original collection uses. Always use the slice's `startIndex` property /// instead of assuming that its indices start at a particular value. /// /// This example demonstrates getting a slice of an array of strings, finding /// the index of one of the strings in the slice, and then using that index /// in the original array. /// /// let streets = ["Adams", "Bryant", "Channing", "Douglas", "Evarts"] /// let streetsSlice = streets[2 ..< streets.endIndex] /// print(streetsSlice) /// // Prints "["Channing", "Douglas", "Evarts"]" /// /// let index = streetsSlice.firstIndex(of: "Evarts") // 4 /// print(streets[index!]) /// // Prints "Evarts" /// /// - Parameter bounds: A range of the collection's indices. The bounds of /// the range must be valid indices of the collection. /// /// - Complexity: O(1) override subscript(bounds: Range<Index>) -> SubSequence { get } // FIXME: Only needed for associated type inference. @_borrowed override subscript(position: Index) -> Element { get } override var startIndex: Index { get } override var endIndex: Index { get } } /// Default implementation for bidirectional collections. extension BidirectionalCollection { @inlinable // protocol-only @inline(__always) public func formIndex(before i: inout Index) { i = index(before: i) } @inlinable // protocol-only public func index(_ i: Index, offsetBy distance: Int) -> Index { return _index(i, offsetBy: distance) } @inlinable // protocol-only internal func _index(_ i: Index, offsetBy distance: Int) -> Index { if distance >= 0 { return _advanceForward(i, by: distance) } var i = i for _ in stride(from: 0, to: distance, by: -1) { formIndex(before: &i) } return i } @inlinable // protocol-only public func index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { return _index(i, offsetBy: distance, limitedBy: limit) } @inlinable // protocol-only internal func _index( _ i: Index, offsetBy distance: Int, limitedBy limit: Index ) -> Index? { if distance >= 0 { return _advanceForward(i, by: distance, limitedBy: limit) } var i = i for _ in stride(from: 0, to: distance, by: -1) { if i == limit { return nil } formIndex(before: &i) } return i } @inlinable // protocol-only public func distance(from start: Index, to end: Index) -> Int { return _distance(from: start, to: end) } @inlinable // protocol-only internal func _distance(from start: Index, to end: Index) -> Int { var start = start var count = 0 if start < end { while start != end { count += 1 formIndex(after: &start) } } else if start > end { while start != end { count -= 1 formIndex(before: &start) } } return count } } extension BidirectionalCollection where SubSequence == Self { /// Removes and returns the last element of the collection. /// /// You can use `popLast()` to remove the last element of a collection that /// might be empty. The `removeLast()` method must be used only on a /// nonempty collection. /// /// - Returns: The last element of the collection if the collection has one /// or more elements; otherwise, `nil`. /// /// - Complexity: O(1) @inlinable // protocol-only public mutating func popLast() -> Element? { guard !isEmpty else { return nil } let element = last! self = self[startIndex..<index(before: endIndex)] return element } /// Removes and returns the last element of the collection. /// /// The collection must not be empty. To remove the last element of a /// collection that might be empty, use the `popLast()` method instead. /// /// - Returns: The last element of the collection. /// /// - Complexity: O(1) @inlinable // protocol-only @discardableResult public mutating func removeLast() -> Element { let element = last! self = self[startIndex..<index(before: endIndex)] return element } /// Removes the given number of elements from the end of the collection. /// /// - Parameter k: The number of elements to remove. `k` must be greater /// than or equal to zero, and must be less than or equal to the number of /// elements in the collection. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of /// elements to remove. @inlinable // protocol-only public mutating func removeLast(_ k: Int) { if k == 0 { return } _precondition(k >= 0, "Number of elements to remove should be non-negative") guard let end = index(endIndex, offsetBy: -k, limitedBy: startIndex) else { _preconditionFailure( "Can't remove more items from a collection than it contains") } self = self[startIndex..<end] } } extension BidirectionalCollection { /// Returns a subsequence containing all but the specified number of final /// elements. /// /// If the number of elements to drop exceeds the number of elements in the /// collection, the result is an empty subsequence. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.dropLast(2)) /// // Prints "[1, 2, 3]" /// print(numbers.dropLast(10)) /// // Prints "[]" /// /// - Parameter k: The number of elements to drop off the end of the /// collection. `k` must be greater than or equal to zero. /// - Returns: A subsequence that leaves off `k` elements from the end. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is the number of /// elements to drop. @inlinable // protocol-only public __consuming func dropLast(_ k: Int) -> SubSequence { _precondition( k >= 0, "Can't drop a negative number of elements from a collection") let end = index( endIndex, offsetBy: -k, limitedBy: startIndex) ?? startIndex return self[startIndex..<end] } /// Returns a subsequence, up to the given maximum length, containing the /// final elements of the collection. /// /// If the maximum length exceeds the number of elements in the collection, /// the result contains the entire collection. /// /// let numbers = [1, 2, 3, 4, 5] /// print(numbers.suffix(2)) /// // Prints "[4, 5]" /// print(numbers.suffix(10)) /// // Prints "[1, 2, 3, 4, 5]" /// /// - Parameter maxLength: The maximum number of elements to return. /// `maxLength` must be greater than or equal to zero. /// - Returns: A subsequence terminating at the end of the collection with at /// most `maxLength` elements. /// /// - Complexity: O(1) if the collection conforms to /// `RandomAccessCollection`; otherwise, O(*k*), where *k* is equal to /// `maxLength`. @inlinable // protocol-only public __consuming func suffix(_ maxLength: Int) -> SubSequence { _precondition( maxLength >= 0, "Can't take a suffix of negative length from a collection") let start = index( endIndex, offsetBy: -maxLength, limitedBy: startIndex) ?? startIndex return self[start..<endIndex] } }
apache-2.0
dada72bf1a3216f0a616f741c994a6ac
36.562945
80
0.638675
4.200266
false
false
false
false
watson-developer-cloud/ios-sdk
Sources/AssistantV1/Models/CreateEntity.swift
1
3466
/** * (C) Copyright IBM Corp. 2018, 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 import IBMSwiftSDKCore /** CreateEntity. */ public struct CreateEntity: Codable, Equatable { /** The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - If you specify an entity name beginning with the reserved prefix `sys-`, it must be the name of a system entity that you want to enable. (Any entity content specified with the request is ignored.). */ public var entity: String /** The description of the entity. This string cannot contain carriage return, newline, or tab characters. */ public var description: String? /** Any metadata related to the entity. */ public var metadata: [String: JSON]? /** Whether to use fuzzy matching for the entity. */ public var fuzzyMatch: Bool? /** The timestamp for creation of the object. */ public var created: Date? /** The timestamp for the most recent update to the object. */ public var updated: Date? /** An array of objects describing the entity values. */ public var values: [CreateValue]? // Map each property name to the key that shall be used for encoding/decoding. private enum CodingKeys: String, CodingKey { case entity = "entity" case description = "description" case metadata = "metadata" case fuzzyMatch = "fuzzy_match" case created = "created" case updated = "updated" case values = "values" } /** Initialize a `CreateEntity` with member variables. - parameter entity: The name of the entity. This string must conform to the following restrictions: - It can contain only Unicode alphanumeric, underscore, and hyphen characters. - If you specify an entity name beginning with the reserved prefix `sys-`, it must be the name of a system entity that you want to enable. (Any entity content specified with the request is ignored.). - parameter description: The description of the entity. This string cannot contain carriage return, newline, or tab characters. - parameter metadata: Any metadata related to the entity. - parameter fuzzyMatch: Whether to use fuzzy matching for the entity. - parameter values: An array of objects describing the entity values. - returns: An initialized `CreateEntity`. */ public init( entity: String, description: String? = nil, metadata: [String: JSON]? = nil, fuzzyMatch: Bool? = nil, values: [CreateValue]? = nil ) { self.entity = entity self.description = description self.metadata = metadata self.fuzzyMatch = fuzzyMatch self.values = values } }
apache-2.0
123e5cea642b702f1c2a1cea4863e9b7
32.326923
121
0.668494
4.696477
false
false
false
false
vmouta/VMLogger
Pod/Classes/LogLevel.swift
1
4166
/** * @name LogLevel.swift * @partof zucred AG * @description * @author Vasco Mouta * @created 21/11/15 * * Copyright (c) 2015 zucred AG All rights reserved. * This material, including documentation and any related * computer programs, is protected by copyright controlled by * zucred AG. All rights are reserved. Copying, * including reproducing, storing, adapting or translating, any * or all of this material requires the prior written consent of * zucred AG. This material also contains confidential * information which may not be disclosed to others without the * prior written consent of zucred AG. */ import Foundation @_versioned internal let AllString: String = "All" @_versioned internal let VerboseString: String = "Verbose" @_versioned internal let DebugString: String = "Debug" @_versioned internal let InfoString: String = "Info" @_versioned internal let WarningString: String = "Warning" @_versioned internal let ErrorString: String = "Error" @_versioned internal let SevereString: String = "Severe" @_versioned internal let EventString: String = "Event" @_versioned internal let OffString: String = "OFF" // MARK: - Enums public enum LogLevel: Int, Comparable, CustomStringConvertible { /** The lowest severity, used for detailed or frequently occurring debugging and diagnostic information. Not intended for use in production code. */ case all = 0 /** The lowest severity, used for detailed or frequently occurring debugging and diagnostic information. Not intended for use in production code. */ case verbose = 1 /** Used for debugging and diagnostic information. Not intended for use in production code. */ case debug = 2 /** Used to indicate something of interest that is not problematic. */ case info = 3 /** Used to indicate that something appears amiss and potentially problematic. The situation bears looking into before a larger problem arises. */ case warning = 4 /** The highest severity, used to indicate that something has gone wrong; a fatal error may be imminent. */ case error = 5 case severe = 6 case event = 7 /** turn OFF all logging (children can override) */ case off = 8 public init(level: String = InfoString) { if(AllString.caseInsensitiveCompare(level) == ComparisonResult.orderedSame) { self = .all } else if(VerboseString.caseInsensitiveCompare(level) == ComparisonResult.orderedSame) { self = .verbose } else if(DebugString.caseInsensitiveCompare(level) == ComparisonResult.orderedSame) { self = .debug } else if(InfoString.caseInsensitiveCompare(level) == ComparisonResult.orderedSame) { self = .info } else if(WarningString.caseInsensitiveCompare(level) == ComparisonResult.orderedSame) { self = .warning } else if(ErrorString.caseInsensitiveCompare(level) == ComparisonResult.orderedSame) { self = .error } else if(SevereString.caseInsensitiveCompare(level) == ComparisonResult.orderedSame) { self = .severe } else if(EventString.caseInsensitiveCompare(level) == ComparisonResult.orderedSame) { self = .event } else { self = .off } } public var description: String { switch self { case .all: return AllString case .verbose: return VerboseString case .debug: return DebugString case .info: return InfoString case .warning: return WarningString case .error: return ErrorString case .severe: return SevereString case .event: return EventString case .off: return OffString } } public static let allLevels: [LogLevel] = [.verbose, .debug, .info, .warning, .error, .severe, .event] } public func <(lhs: LogLevel, rhs: LogLevel) -> Bool { return lhs.rawValue < rhs.rawValue }
mit
1a86b234a566ac4ac243a534da965890
34.606838
106
0.648344
4.744875
false
false
false
false
emilstahl/swift
test/Interpreter/optional.swift
10
4565
// RUN: %target-run-simple-swift | FileCheck %s // REQUIRES: executable_test class A { func printA() { print("A", terminator: "") } } class B : A { override func printA() { print("B", terminator: "") } } func printA(v: A) { v.printA() } func printOpt<T>(subprint: T->())(x: T?) { switch (x) { case .Some(let y): print(".Some(", terminator: ""); subprint(y); print(")", terminator: "") case .None: print(".None", terminator: "") } } func test(v: A????, _ cast: (A????) -> B?) { printOpt(printOpt(printOpt(printOpt(printA))))(x: v) print(" as? B: ", terminator: "") printOpt(printA)(x: cast(v)) print("\n", terminator: "") } test(.Some(.Some(.Some(.Some(A())))), { $0 as? B }) test(.Some(.Some(.Some(.Some(B())))), { $0 as? B }) test(.Some(.Some(.Some(.None))), { $0 as? B }) test(.Some(.Some(.None)), { $0 as? B }) test(.Some(.None), { $0 as? B }) test(.None, { $0 as? B }) // CHECK: .Some(.Some(.Some(.Some(A)))) as? B: .None // CHECK: .Some(.Some(.Some(.Some(B)))) as? B: .Some(B) // CHECK: .Some(.Some(.Some(.None))) as? B: .None // CHECK: .Some(.Some(.None)) as? B: .None // CHECK: .Some(.None) as? B: .None // CHECK: .None as? B: .None func test(v: A????, _ cast: (A????) -> B??) { printOpt(printOpt(printOpt(printOpt(printA))))(x: v) print(" as? B?: ", terminator: "") printOpt(printOpt(printA))(x: cast(v)) print("\n", terminator: "") } test(.Some(.Some(.Some(.Some(A())))), { $0 as? B? }) test(.Some(.Some(.Some(.Some(B())))), { $0 as? B? }) test(.Some(.Some(.Some(.None))), { $0 as? B? }) test(.Some(.Some(.None)), { $0 as? B? }) test(.Some(.None), { $0 as? B? }) test(.None, { $0 as? B? }) // CHECK: .Some(.Some(.Some(.Some(A)))) as? B?: .None // CHECK: .Some(.Some(.Some(.Some(B)))) as? B?: .Some(.Some(B)) // CHECK: .Some(.Some(.Some(.None))) as? B?: .Some(.None) // CHECK: .Some(.Some(.None)) as? B?: .None // CHECK: .Some(.None) as? B?: .None // CHECK: .None as? B?: .None func test(v: A????, _ cast: (A????) -> B???) { printOpt(printOpt(printOpt(printOpt(printA))))(x: v) print(" as? B??: ", terminator: "") printOpt(printOpt(printOpt(printA)))(x: cast(v)) print("\n", terminator: "") } test(.Some(.Some(.Some(.Some(A())))), { $0 as? B?? }) test(.Some(.Some(.Some(.Some(B())))), { $0 as? B?? }) test(.Some(.Some(.Some(.None))), { $0 as? B?? }) test(.Some(.Some(.None)), { $0 as? B?? }) test(.Some(.None), { $0 as? B?? }) test(.None, { $0 as? B?? }) // CHECK: .Some(.Some(.Some(.Some(A)))) as? B??: .None // CHECK: .Some(.Some(.Some(.Some(B)))) as? B??: .Some(.Some(.Some(B))) // CHECK: .Some(.Some(.Some(.None))) as? B??: .Some(.Some(.None)) // CHECK: .Some(.Some(.None)) as? B??: .Some(.None) // CHECK: .Some(.None) as? B??: .None // CHECK: .None as? B??: .None class Foo : Equatable { } func ==(a : Foo, b : Foo) -> Bool { return a === b } var x_foo: Foo! = nil if x_foo == nil { print("x_foo is nil") } // CHECK: x_foo is nil if x_foo != nil { print("x_foo is not nil") } else { print("x_foo is nil") } // CHECK: x_foo is nil if nil == x_foo { print("x_foo is nil") } // CHECK: x_foo is nil if nil != x_foo { print("x_foo is not nil") } else { print("x_foo is nil") } // CHECK: x_foo is nil var y_foo: Foo? = nil if y_foo == nil { print("y_foo is nil") } // CHECK: y_foo is nil if y_foo != nil { print("y_foo is not nil") } else { print("y_foo is nil") } // CHECK: y_foo is nil if nil == y_foo { print("y_foo is nil") } // CHECK: y_foo is nil if nil != y_foo { print("y_foo is not nil") } else { print("y_foo is nil") } // CHECK: y_foo is nil var x : Int? = nil var y : Int?? = x var z : Int?? = nil switch y { case nil: print("y is nil") case .Some(nil): print("y is .Some(nil)") case .Some(let v): print("y is .Some(\(v))") } // CHECK: y is .Some(nil) switch z { case nil: print("z is nil") case .Some(nil): print("z is .Some(nil)") case .Some(let v): print("z is .Some(\(v))") } // CHECK: z is nil // Validate nil equality comparisons with non-equatable optional types class C {} var c: C? = nil print(c == nil) // CHECK: true print(nil == c) // CHECK: true print(c != nil) // CHECK: false print(nil != c) // CHECK: false var c2: C? = C() print(c2 == nil) // CHECK: false print(nil == c2) // CHECK: false print(c2 != nil) // CHECK: true print(nil != c2) // CHECK: true var c3: C! = nil print(c3 == nil) // CHECK: true print(nil == c3) // CHECK: true print(c3 != nil) // CHECK: false print(nil != c3) // CHECK: false var c4: C! = C() print(c4 == nil) // CHECK: false print(nil == c4) // CHECK: false print(c4 != nil) // CHECK: true print(nil != c4) // CHECK: true
apache-2.0
48196ca0d5cbfdb4e607c1c8bdf5197d
25.085714
93
0.548959
2.571831
false
true
false
false
Jamnitzer/Metal_ImageProcessing
Metal_ImageProcessing/Metal_ImageProcessing/TViewController.swift
1
9781
//------------------------------------------------------------------------------ // Derived from Apple's WWDC example "MetalImageProcessing" // Created by Jim Wrenholt on 12/6/14. //------------------------------------------------------------------------------ import UIKit //----------------------------------------------------------------------------- @objc protocol TViewControllerDelegate { //------------------------------------------------------ // Note this method is called from the // thread the main game loop is run //------------------------------------------------------ func update(controller:TViewController) //------------------------------------------------------ // called whenever the main game loop is paused, // such as when the app is backgrounded //------------------------------------------------------ func viewController(controller:TViewController, willPause:Bool) } //----------------------------------------------------------------------------- class TViewController: UIViewController { @IBOutlet weak var delegate: TViewControllerDelegate! //------------------------------------------------------ // What vsync refresh interval to fire at. // (Sets CADisplayLink frameinterval property) set to 1 by default, // which is the CADisplayLink default setting (60 FPS). // Setting to 2, will cause gameloop to trigger every // other vsync (throttling to 30 FPS) //------------------------------------------------------ var interval:Int = 1 // Used to pause and resume the controller. var paused:Bool = false // app control var timer: CADisplayLink! = nil // boolean to determine if the first draw has occured var _firstDrawOccurred:Bool = false //the time interval from the last draw var _timeSinceLastDraw: Double = 0 var _timeSinceLastDrawPreviousTime:Double = 0 // pause/resume var _gameLoopPaused:Bool = false // our renderer instance var renderer:TRenderer? //------------------------------------------------------------------------- deinit { NSNotificationCenter.defaultCenter().removeObserver( self, name: UIApplicationDidEnterBackgroundNotification, object:nil) NSNotificationCenter.defaultCenter().removeObserver( self, name: UIApplicationWillEnterForegroundNotification, object: nil) if (timer != nil) { stopGameLoop() } } //------------------------------------------------------------------------- func initCommon() { renderer = TRenderer() self.delegate = renderer! //-------------------------------------------------- // Register notifications to start/stop drawing as // this app moves into the background //-------------------------------------------------- NSNotificationCenter.defaultCenter().addObserver( self, selector: Selector("didEnterBackground"), name: UIApplicationDidEnterBackgroundNotification, object:nil) NSNotificationCenter.defaultCenter().addObserver( self, selector: Selector("willEnterForeground"), name: UIApplicationWillEnterForegroundNotification, object: nil) interval = 1 } //------------------------------------------------------------------------- // override init() // { // super.init() // initCommon() // } //------------------------------------------------------------------------- // called when loaded from nib //------------------------------------------------------------------------- override init(nibName: String?, bundle nibBundle: NSBundle?) { super.init(nibName: nibName, bundle: nibBundle) initCommon() } //------------------------------------------------------------------------- required init(coder aDecoder: NSCoder) { super.init(coder:aDecoder)! initCommon() } //------------------------------------------------------------------------- override func viewDidLoad() { super.viewDidLoad() let renderView = self.view as! TView renderView.delegate = renderer // load all renderer assets before starting game loop renderer!.configure(renderView) } //------------------------------------------------------------------------- func dispatchGameLoop() { //------------------------------------------------------------ // create a game loop timer using a display link //------------------------------------------------------------ timer = CADisplayLink(target: self, selector: Selector("gameloop:")) timer!.frameInterval = interval timer!.addToRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode) } //------------------------------------------------------------------------- // the main game loop called by the timer above //------------------------------------------------------------------------- func gameloop(displayLink: CADisplayLink) { //------------------------------------------------------------------- // tell our delegate to update itself here. //------------------------------------------------------------------- delegate.update(self) if (!_firstDrawOccurred) { //--------------------------------------------------------------- // set up timing data for display since this is the // first time through this loop //--------------------------------------------------------------- _timeSinceLastDraw = 0.0 _timeSinceLastDrawPreviousTime = CACurrentMediaTime() _firstDrawOccurred = true } else { //--------------------------------------------------------------- // figure out the time since we last we drew //--------------------------------------------------------------- let currentTime:CFTimeInterval = CACurrentMediaTime() _timeSinceLastDraw = currentTime - _timeSinceLastDrawPreviousTime //--------------------------------------------------------------- // keep track of the time interval between draws //--------------------------------------------------------------- _timeSinceLastDrawPreviousTime = currentTime } //------------------------------------------------------------------- // display (render) //------------------------------------------------------------------- assert(view is TView) // isKindOfClass //------------------------------------------------------------------- // call the display method directly on the render view // (setNeedsDisplay: has been disabled in the renderview by default) //------------------------------------------------------------------- let myview:TView = self.view as! TView myview.display() } //------------------------------------------------------------------------- func stopGameLoop() { //------------------------------------------------------------------- // use invalidates the main game loop. // when the app is set to terminate //------------------------------------------------------------------- if ( timer != nil) { timer!.invalidate() } } //------------------------------------------------------------------------- func set_Paused(pause:Bool) { if (_gameLoopPaused == true) { return } if (timer != nil) { //------------------------------------------------- // inform the delegate we are about to pause //------------------------------------------------- delegate.viewController(self, willPause:pause) if (pause == true) { _gameLoopPaused = true timer!.paused = true //------------------------------------------------- // ask the view to release textures until its resumed //------------------------------------------------- let myview:TView = self.view as! TView myview.releaseTextures() } else { _gameLoopPaused = false timer!.paused = false } } } //------------------------------------------------------------------------- func isPaused() -> Bool { return _gameLoopPaused } //------------------------------------------------------------------------- func didEnterBackground(notification:NSNotification) { self.set_Paused(true) } //------------------------------------------------------------------------- func willEnterForeground(notification:NSNotification) { self.set_Paused(false) } //------------------------------------------------------------------------- override func viewWillAppear(animated:Bool) { super.viewWillAppear(animated) self.dispatchGameLoop() // run the game loop } //------------------------------------------------------------------------- override func viewWillDisappear(animated:Bool) { super.viewWillDisappear(animated) self.stopGameLoop() // end the gameloop } //------------------------------------------------------------------------- }
bsd-2-clause
f753276356d021da12b266cb45943f7c
37.972112
83
0.372559
7.34861
false
false
false
false
ben-ng/swift
validation-test/compiler_crashers_fixed/01209-llvm-errs.swift
1
613
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func n<w>() -> (w, w -> w) -> w { o m o.q = { } { w) { k } } protocol n { } class o: n{ class func q {} func p(e: Int = x) { } let c = p protocol p : p { } protocol p { } class e: p { } k e.w == l> { } func p(c {
apache-2.0
2b57a4ef308aff4cb242bd4734945a69
19.433333
79
0.642741
2.905213
false
false
false
false
VadimPavlov/Swifty
Sources/Swifty/ios/Notifications/NotificationDescriptor.swift
1
1752
// // NotificationToken.swift // Swifty // // Created by Vadym Pavlov on 12.05.17. // Copyright © 2017 Vadym Pavlov. All rights reserved. // import Foundation public struct NotificationDescriptor<A> { let name: Notification.Name let convert: (Notification) -> A public init(name: Notification.Name, convert: @escaping (Notification) -> A) { self.name = name self.convert = convert } } public struct CustomNotificationDescriptor<A> { let name: Notification.Name public init(name: Notification.Name) { self.name = name } } public extension NotificationCenter { func addObserver<A>(descriptor: NotificationDescriptor<A>, object: Any? = nil, queue: OperationQueue? = nil, using block: @escaping (A) -> Void) -> NotificationToken { let token = self.addObserver(forName: descriptor.name, object: object, queue: queue) { notification in block(descriptor.convert(notification)) } return NotificationToken(token: token, center: self) } func addObserver<A>(descriptor: CustomNotificationDescriptor<A>, object: Any? = nil, queue: OperationQueue? = nil, using block: @escaping (A) -> Void) -> NotificationToken { let token = self.addObserver(forName: descriptor.name, object: object, queue: queue) { notification in let object = (notification.object is NSNull ? nil : notification.object) as Any block(object as! A) } return NotificationToken(token: token, center: self) } func post<A>(descriptor: CustomNotificationDescriptor<A>, value: A) { post(name: descriptor.name, object: value) } } public struct NoUserInfo { public init(notification: Notification) {} }
mit
8ed4aa5ed11755c3964982e3c4bf22c9
32.673077
177
0.668761
4.229469
false
false
false
false
google/JacquardSDKiOS
JacquardSDK/Classes/IMUDataCollection/IMUSample.swift
1
3094
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Foundation /// Holds the data for a recorded IMU session. /// /// - SeeAlso: `IMUSessionInfo` & `IMUSample`. public struct IMUSessionData { /// Metadata for a recorded IMU session. public let metadata: IMUSessionInfo /// IMU Samples recorded during the IMU session. public let samples: [IMUSample] init(metadata: Google_Jacquard_Protocol_DataCollectionMetadata, samples: [IMUSample]) { let info = IMUSessionInfo(metadata: metadata) self.metadata = info self.samples = samples } } /// UJT contains an Inertial Measurement Unit (IMU) sensor that consists of an accelerometer and gyroscope. /// /// This will hold the data for the sensors in vector, and the timestamp for the sample. /// Binary format description: go/jacquard-dc-framework#heading=h.lgt57q4p2c8c public struct IMUSample: Equatable { /// Accelorometer data for the sample. public var acceleration: Vector /// Gyroscope data for the sample. public var gyro: Vector /// Timestamp of the sample, Relative to the start of the recording. public var timestamp: UInt32 /// :nodoc: public static func == (lhs: IMUSample, rhs: IMUSample) -> Bool { return lhs.timestamp == rhs.timestamp } /// :nodoc: public struct Vector { /// X axis data for accelorometer, also corresponds to Roll for gyroscope data. public var x: Int16 /// Y axis data for accelorometer, also corresponds to Pitch for gyroscope data. public var y: Int16 /// Z axis data for accelorometer, also corresponds to Yaw for gyroscope data. public var z: Int16 } } extension IMUSample.Vector { // Assumes adequately sized buffer. fileprivate init(buffer: UnsafeMutablePointer<UInt8>) throws { // Need to initialize before capturing in closure. self.x = 0 self.y = 0 self.z = 0 // Parse consecutive integer bytes into vectors x,y & z. buffer.withMemoryRebound(to: Int16.self, capacity: 3) { ptr in x = ptr.pointee y = ptr.successor().pointee z = ptr.successor().successor().pointee } } } extension IMUSample { init(buffer: UnsafeMutablePointer<UInt8>) throws { acceleration = try Vector(buffer: buffer) gyro = try Vector(buffer: buffer.advanced(by: 6)) // Need to initialize before capturing in closure. self.timestamp = 0 // 12 bytes because x,y,z data for acclerometer and gyro each take up 2 bytes. buffer.advanced(by: 12).withMemoryRebound(to: UInt32.self, capacity: 1) { ptr in timestamp = ptr.pointee } } }
apache-2.0
d565a6979b067d36bc70e2ae4864c418
33.377778
107
0.71073
3.946429
false
false
false
false
Woooop/WPPrintBoard
WPPrintBoardDemo/WPPrintBoardDemo/WPPrintBoard.swift
1
6008
// // WPPrintBoard.swift // WPPrintBoardDemo // // Created by Wupeng on 8/11/16. // Copyright © 2016 Wooop. All rights reserved. // import UIKit protocol WPPrintBoardDelegate { func didNeedToUpdageImage(image : UIImage) } class WPPrintBoard: UIView { let size = UIScreen.mainScreen().bounds private var currentPoints = [CGPoint]() //记录当前位置的点集 private var currentPenWidth : CGFloat = 5; private var currentPenColor : CGColor = UIColor.blackColor().CGColor; private var currentPath = [WPBezierModel]() //当前路径 private var pathArray = [[WPBezierModel]]() //所有路径数据和(在当前路径还在绘制的过程中不包含当前路径) private var tempPaths = [[WPBezierModel]]() //当做队列维护,用于服务于撤销后恢复的功能 private var DEBUG : Bool = false private var isEndTouch : Bool = false private var image : UIImage? { get { return makeImageWithCurrentView() } set { self.image = newValue } } var delegate : WPPrintBoardDelegate? override init(frame: CGRect) { super.init(frame: frame) self.backgroundColor = UIColor.clearColor() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func drawRect(rect: CGRect) { if isEndTouch { printWithPaths(self.pathArray) } printWithCurrent(self.currentPath) } func printWithPaths(paths : [[WPBezierModel]]){ for path in paths { for bezierModel in path { self.printBezierLine(bezierModel) } } } func printWithCurrent(path : [WPBezierModel]){ for bezierModel in path { self.printBezierLine(bezierModel) } } func printBezierLine(bezierModel : WPBezierModel){ let ctx = UIGraphicsGetCurrentContext() CGContextSetLineWidth(ctx, bezierModel.penWidth) CGContextSetStrokeColorWithColor(ctx, bezierModel.penColor) CGContextSetLineCap(ctx, .Round) CGContextSetLineJoin(ctx, .Round) CGContextMoveToPoint(ctx, bezierModel.startPoint.x, bezierModel.startPoint.y) CGContextAddQuadCurveToPoint(ctx, bezierModel.controlPoint.x, bezierModel.controlPoint.y, bezierModel.endPoint.x, bezierModel.endPoint.y) CGContextStrokePath(ctx) if self.DEBUG { CGContextSetLineWidth(ctx, 2) CGContextSetStrokeColorWithColor(ctx, UIColor.redColor().CGColor) CGContextStrokeRect(ctx, CGRectMake(bezierModel.controlPoint.x, bezierModel.controlPoint.y, 1, 1)) CGContextSetStrokeColorWithColor(ctx, UIColor.blueColor().CGColor) CGContextStrokeRect(ctx, CGRectMake(bezierModel.startPoint.x, bezierModel.startPoint.y, 1, 1)) CGContextSetStrokeColorWithColor(ctx, UIColor.greenColor().CGColor) CGContextStrokeRect(ctx, CGRectMake(bezierModel.endPoint.x, bezierModel.endPoint.y, 1, 1)) } } func makeImageWithCurrentView() -> UIImage{ UIGraphicsBeginImageContext(self.bounds.size) self.layer.renderInContext(UIGraphicsGetCurrentContext()!) let image = UIGraphicsGetImageFromCurrentImageContext() UIGraphicsEndImageContext() return image } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { self.isEndTouch = false let touch = touches.first let point = touch!.locationInView(self) if currentPath.count != 0 { currentPath.removeAll() } if tempPaths.count != 0 { tempPaths.removeAll() } self.currentPoints = [point,point,point] currentPath.append(WPBezierModel(startP: point, endP: point, controlP: point, pColor: currentPenColor, pWidth: currentPenWidth)) self.setNeedsDisplay() } override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { let touch = touches.first let point = touch!.locationInView(self) self.currentPoints = [currentPoints[1],currentPoints[2],point] let bezierStartPoint = CGPointMake((currentPoints[0].x+currentPoints[1].x)/2, (currentPoints[0].y+currentPoints[1].y)/2) let bezierEndPoint = CGPointMake((currentPoints[1].x+currentPoints[2].x)/2, (currentPoints[1].y+currentPoints[2].y)/2) currentPath.append(WPBezierModel(startP: bezierStartPoint, endP: bezierEndPoint, controlP: currentPoints[1], pColor: currentPenColor, pWidth: currentPenWidth)) self.setNeedsDisplay() } override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) { self.isEndTouch = true self.pathArray.append(currentPath) if currentPath.count != 0 { currentPath.removeAll() } self.setNeedsDisplay() self.delegate?.didNeedToUpdageImage(self.image!) } } extension WPPrintBoard { func setPenColor(color : CGColor){ self.currentPenColor = color } func setPenWidth(width : CGFloat){ self.currentPenWidth = width } func clearBoard() { self.currentPath.removeAll() self.pathArray.removeAll() self.setNeedsDisplay() self.delegate?.didNeedToUpdageImage(self.image!) } func revoke() { if pathArray.count != 0 { self.tempPaths.append(pathArray.last!) self.pathArray.removeLast() } self.setNeedsDisplay() self.delegate?.didNeedToUpdageImage(self.image!) } func recover() { if self.tempPaths.count != 0 { self.pathArray.append(tempPaths.last!) self.tempPaths.removeLast() } self.setNeedsDisplay() self.delegate?.didNeedToUpdageImage(self.image!) } }
mit
1b1d81324019fd5d97c04ddc5686c5fc
33.426901
167
0.642772
4.521505
false
false
false
false
eonil/BTree
Sources/BTreeIndex.swift
2
6337
// // BTreeIndex.swift // BTree // // Created by Károly Lőrentey on 2016-02-11. // Copyright © 2015–2017 Károly Lőrentey. // /// An index into a collection that uses a B-tree for storage. /// /// BTree indices belong to a specific tree instance. Trying to use them with any other tree /// instance (including one holding the exact same elements, or one derived from a mutated version of the /// original instance) will cause a runtime error. /// /// This index satisfies `Collection`'s requirement for O(1) access, but /// it is only suitable for read-only processing -- most tree mutations will /// invalidate all existing indexes. /// /// - SeeAlso: `BTreeCursor` for an efficient way to modify a batch of values in a B-tree. public struct BTreeIndex<Key: Comparable, Value> { typealias Node = BTreeNode<Key, Value> typealias State = BTreeWeakPath<Key, Value> internal private(set) var state: State internal init(_ state: State) { self.state = state } /// Advance to the next index. /// /// - Requires: self is valid and not the end index. /// - Complexity: Amortized O(1). mutating func increment() { state.moveForward() } /// Advance to the previous index. /// /// - Requires: self is valid and not the start index. /// - Complexity: Amortized O(1). mutating func decrement() { state.moveBackward() } /// Advance this index by `distance` elements. /// /// - Complexity: O(log(*n*)) where *n* is the number of elements in the tree. mutating func advance(by distance: Int) { state.move(toOffset: state.offset + distance) } @discardableResult mutating func advance(by distance: Int, limitedBy limit: BTreeIndex) -> Bool { let originalDistance = limit.state.offset - state.offset if (distance >= 0 && originalDistance >= 0 && distance > originalDistance) || (distance <= 0 && originalDistance <= 0 && distance < originalDistance) { self = limit return false } state.move(toOffset: state.offset + distance) return true } } extension BTreeIndex: Comparable { /// Return true iff `a` is equal to `b`. public static func ==(a: BTreeIndex, b: BTreeIndex) -> Bool { precondition(a.state.root === b.state.root, "Indices to different trees cannot be compared") return a.state.offset == b.state.offset } /// Return true iff `a` is less than `b`. public static func <(a: BTreeIndex, b: BTreeIndex) -> Bool { precondition(a.state.root === b.state.root, "Indices to different trees cannot be compared") return a.state.offset < b.state.offset } } /// A mutable path in a B-tree, holding weak references to nodes on the path. /// This path variant does not support modifying the tree itself; it is suitable for use in indices. /// /// After a path of this kind has been created, the original tree might mutated in a way that invalidates /// the path, setting some of its weak references to nil, or breaking the consistency of its trail of slot indices. /// The path checks for this during navigation, and traps if it finds itself invalidated. /// internal struct BTreeWeakPath<Key: Comparable, Value>: BTreePath { typealias Node = BTreeNode<Key, Value> var _root: Weak<Node> var offset: Int var _path: [Weak<Node>] var _slots: [Int] var _node: Weak<Node> var slot: Int? init(root: Node) { self._root = Weak(root) self.offset = root.count self._path = [] self._slots = [] self._node = Weak(root) self.slot = nil } var root: Node { guard let root = _root.value else { invalid() } return root } var count: Int { return root.count } var length: Int { return _path.count + 1} var node: Node { guard let node = _node.value else { invalid() } return node } internal func expectRoot(_ root: Node) { expectValid(_root.value === root) } internal func expectValid(_ expression: @autoclosure () -> Bool, file: StaticString = #file, line: UInt = #line) { precondition(expression(), "Invalid BTreeIndex", file: file, line: line) } internal func invalid(_ file: StaticString = #file, line: UInt = #line) -> Never { preconditionFailure("Invalid BTreeIndex", file: file, line: line) } mutating func popFromSlots() { assert(self.slot != nil) let node = self.node offset += node.count - node.offset(ofSlot: slot!) slot = nil } mutating func popFromPath() { assert(_path.count > 0 && slot == nil) let child = node _node = _path.removeLast() expectValid(node.children[_slots.last!] === child) slot = _slots.removeLast() } mutating func pushToPath() { assert(self.slot != nil) let child = node.children[slot!] _path.append(_node) _node = Weak(child) _slots.append(slot!) slot = nil } mutating func pushToSlots(_ slot: Int, offsetOfSlot: Int) { assert(self.slot == nil) offset -= node.count - offsetOfSlot self.slot = slot } func forEach(ascending: Bool, body: (Node, Int) -> Void) { if ascending { var child: Node? = node body(child!, slot!) for i in (0 ..< _path.count).reversed() { guard let node = _path[i].value else { invalid() } let slot = _slots[i] expectValid(node.children[slot] === child) child = node body(node, slot) } } else { for i in 0 ..< _path.count { guard let node = _path[i].value else { invalid() } let slot = _slots[i] expectValid(node.children[slot] === (i < _path.count - 1 ? _path[i + 1].value : _node.value)) body(node, slot) } body(node, slot!) } } func forEachSlot(ascending: Bool, body: (Int) -> Void) { if ascending { body(slot!) _slots.reversed().forEach(body) } else { _slots.forEach(body) body(slot!) } } }
mit
2f84208cef02d169feeb89096a4cc8b9
31.628866
118
0.589889
4.091791
false
false
false
false
Jesse-calkin/Unwind-Segue-Demo
Unwind Segue Demo/RedViewController.swift
1
1444
// // RedViewController.swift // Unwind Segue Demo // // Created by jesse calkin on 6/8/16. // Copyright © 2016 Shoshin Boogie. All rights reserved. // import UIKit class RedViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() if let navigationController = navigationController, appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { navigationController.delegate = appDelegate } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { guard let identifier = segue.identifier else { return } print(identifier) } @IBAction func unwindToRedViewController(segue: UIStoryboardSegue) {} override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool { guard let navigationController = navigationController else { return true } if identifier == "PushGreen" && navigationController.childViewControllers.filter({ $0.isKindOfClass(GreenViewController) }).count > 0 { performSegueWithIdentifier("unwindGreen", sender: self) return false } else if identifier == "PushBlue" && navigationController.childViewControllers.filter({ $0.isKindOfClass(BlueViewController) }).count > 0 { performSegueWithIdentifier("unwindBlue", sender: self) return false } return true } }
mit
45714d49eb0468f88d8e378b3c68d74b
34.195122
148
0.693694
5.324723
false
false
false
false
prebid/prebid-mobile-ios
InternalTestApp/OpenXMockServer/Network/ApiEndpoint.swift
1
2233
/*   Copyright 2018-2021 Prebid.org, Inc.  Licensed under the Apache License, Version 2.0 (the "License");  you may not use this file except in compliance with the License.  You may obtain a copy of the License at  http://www.apache.org/licenses/LICENSE-2.0  Unless required by applicable law or agreed to in writing, software  distributed under the License is distributed on an "AS IS" BASIS,  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the License for the specific language governing permissions and  limitations under the License.  */ import Alamofire internal struct ApiEndpoint { static let host = "10.0.2.2" static let port = 8000 private static let scheme = "https" private static let subpath = "/api" let path: String let queryItems: [String: String] static func addMock() -> ApiEndpoint { return ApiEndpoint(path: "add_mock") } static func setRandomNoBids() -> ApiEndpoint { return ApiEndpoint(path: "set_random_no_bids") } static func cancelRandomNoBids() -> ApiEndpoint { return ApiEndpoint(path: "cancel_random_no_bids") } static func getLogs() -> ApiEndpoint { return ApiEndpoint(path: "logs") } static func clearLogs() -> ApiEndpoint { return ApiEndpoint(path: "clear_logs") } static func bannerImage() -> ApiEndpoint { return ApiEndpoint(path: "image") } static func logEvents() -> ApiEndpoint { return ApiEndpoint(path: "events") } } extension ApiEndpoint { init(path: String) { self.init(path: path, queryItems: [:]) } } extension ApiEndpoint: URLConvertible { func asURL() throws -> URL { var components = URLComponents() components.scheme = ApiEndpoint.scheme components.host = ApiEndpoint.host components.port = ApiEndpoint.port components.path = "\(ApiEndpoint.subpath)/\(path)" if !queryItems.isEmpty { components.queryItems = queryItems.map(URLQueryItem.init) } guard let url = components.url else { fatalError("URL failed to construct") } return url } }
apache-2.0
cad2130390214cc3f3016936bdece938
27.126582
73
0.650315
4.470825
false
false
false
false
rogeruiz/MacPin
modules/MacPin/OSX/OmniBoxController.swift
2
6634
/// MacPin OmniBoxController /// /// Controls a textfield that displays a WebViewController's current URL and accepts editing to change loaded URL in WebView import AppKit import WebKit extension WKWebView { override public func setValue(value: AnyObject?, forUndefinedKey key: String) { if key != "URL" { super.setValue(value, forUndefinedKey: key) } //prevents URLbox from trying to directly rewrite webView.URL } } import AppKit class URLAddressField: NSTextField { // FIXMEios UILabel + UITextField var isLoading: Bool = false { didSet { needsDisplay = true } } var progress: Double = Double(0.0) { didSet { needsDisplay = true } } override func drawRect(dirtyRect: NSRect) { if isLoading { // draw a Safari style progress-line along edge of the text box's focus ring //var progressRect = NSOffsetRect(bounds, 0, 4) // top edge var progressRect = NSOffsetRect(bounds, 0, NSMaxY(bounds) - 4) // bottom edge progressRect.size.height = 6 // line thickness progressRect.size.width *= progress == 1.0 ? 0 : CGFloat(progress) // only draw line when downloading NSColor(calibratedRed:0.0, green: 0.0, blue: 1.0, alpha: 0.4).set() // transparent blue line NSRectFillUsingOperation(progressRect, .CompositeSourceOver) } else { //NSRectFillUsingOperation(bounds, .CompositeClear) NSRectFillUsingOperation(bounds, .CompositeCopy) } super.drawRect(dirtyRect) } } /* iOS progbar: http://stackoverflow.com/questions/29410849/unable-to-display-subview-added-to-wkwebview?rq=1 webview?.addObserver(self, forKeyPath: "estimatedProgress", options: .New, context: nil) let progressView = UIProgressView(progressViewStyle: .Bar) progressView.center = view.center progressView.progress = 20.0/30.0 progressView.trackTintColor = UIColor.lightGrayColor() progressView.tintColor = UIColor.blueColor() webview?.addSubview(progressView) */ @objc class OmniBoxController: NSViewController { let urlbox = URLAddressField() var webview: MPWebView? = nil { didSet { //KVC to copy updates to webviews url & title (user navigations, history.pushState(), window.title=) if let wv = webview { view.bind(NSToolTipBinding, toObject: wv, withKeyPath: "title", options: nil) view.bind(NSValueBinding, toObject: wv, withKeyPath: "URL", options: nil) view.bind(NSFontBoldBinding, toObject: wv, withKeyPath: "hasOnlySecureContent", options: nil) view.bind("isLoading", toObject: wv, withKeyPath: "isLoading", options: nil) view.bind("progress", toObject: wv, withKeyPath: "estimatedProgress", options: nil) nextResponder = wv view.nextKeyView = wv } } willSet(newwv) { if let wv = webview { nextResponder = nil view.nextKeyView = nil view.unbind(NSToolTipBinding) view.unbind(NSValueBinding) view.unbind(NSFontBoldBinding) view.unbind("progress") view.unbind("isLoading") } } } required init?(coder: NSCoder) { super.init(coder: coder) } override init!(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName:nil, bundle:nil) } // calls loadView() override func loadView() { view = urlbox } // NIBless /* convenience init(webViewController: WebViewController?) { self.init() preferredContentSize = CGSize(width: 600, height: 24) //app hangs on view presentation without this! if let wvc = webViewController { representedObject = wvc } } */ convenience init() { self.init(nibName:nil, bundle:nil) preferredContentSize = CGSize(width: 600, height: 24) //app hangs on view presentation without this! } override func viewDidLoad() { super.viewDidLoad() // prepareForReuse() {...} ? urlbox.wantsLayer = true urlbox.bezelStyle = .RoundedBezel urlbox.drawsBackground = false urlbox.textColor = NSColor.labelColor() urlbox.toolTip = "" //urlbox.menu = NSMenu //ctrl-click context menu // search with DuckDuckGo // go to URL // js: addOmniBoxActionHandler('send to app',handleCustomOmniAction) // tab menu? urlbox.delegate = self if let cell = urlbox.cell() as? NSTextFieldCell { cell.placeholderString = "Navigate to URL" cell.scrollable = true cell.action = Selector("userEnteredURL") cell.target = self cell.sendsActionOnEndEditing = false //only send action when Return is pressed cell.usesSingleLineMode = true cell.focusRingType = .None //cell.currentEditor()?.delegate = self // do live validation of input URL before Enter is pressed } // should have a grid of all tabs below the urlbox, safari style. NSCollectionView? // https://developer.apple.com/library/mac/samplecode/GridMenu/Listings/ReadMe_txt.html#//apple_ref/doc/uid/DTS40010559-ReadMe_txt-DontLinkElementID_14 // or just show a segmented tabcontrol if clicking in the urlbox? } override func viewWillAppear() { super.viewWillAppear() } override func viewDidAppear() { super.viewDidAppear() } func userEnteredURL() { if let tf = view as? NSTextField, url = validateURL(tf.stringValue) { if let wv = webview { //would be cool if I could just kick up gotoURL to nextResponder as NSResponder view.window?.makeFirstResponder(wv) // no effect if this vc was brought up as a modal sheet wv.gotoURL(url as NSURL) cancelOperation(self) } else { // tab-less browser window ... parentViewController?.addChildViewController(WebViewControllerOSX(webview: MPWebView(url: url))) // is parentVC the toolbar or contentView VC?? } } else { warn("invalid url was requested!") //displayAlert //NSBeep() } } override func cancelOperation(sender: AnyObject?) { view.resignFirstResponder() // relinquish key focus to webview presentingViewController?.dismissViewController(self) //if a thoust art a popover, close thyself } deinit { webview = nil; representedObject = nil } } extension OmniBoxController: NSTextFieldDelegate { //func textShouldBeginEditing(textObject: NSText) -> Bool { return true } //allow editing //replace textvalue with URL value, should normally be bound to title //func textDidChange(aNotification: NSNotification) func textShouldEndEditing(textObject: NSText) -> Bool { //user attempting to focus out of field if let url = validateURL(textObject.string ?? "") { return true } //allow focusout warn("invalid url entered: \(textObject.string)") return false //NSBeep()s, keeps focus } //func textDidEndEditing(aNotification: NSNotification) { } } extension OmniBoxController: NSPopoverDelegate { func popoverWillShow(notification: NSNotification) { //urlbox.sizeToFit() //fixme: makes the box undersized sometimes } }
gpl-3.0
9e0762fc6c8806416548f67ca2e298e2
37.795322
153
0.725806
3.850261
false
false
false
false
jcollas/WhirlyGlobeSwift
WhirlyGlobeComponentTester/WhirlyGlobeComponentTester/AppDelegate.swift
1
2610
// // AppDelegate.swift // SwiftTest // // Created by Juan J. Collas on 8/27/2014. // Copyright (c) 2014 mousebird consulting. 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. self.window = UIWindow(frame: UIScreen.mainScreen().bounds) self.window!.backgroundColor = UIColor.whiteColor() let startViewC = StartupViewController() let navC = UINavigationController(rootViewController: startViewC) navC.navigationBar.barStyle = .Black self.window!.rootViewController = navC 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 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:. } }
apache-2.0
2e43eb81c67c1b4f4d5a05ad997ef5dd
43.237288
285
0.72682
5.612903
false
false
false
false
wenghengcong/Coderpursue
BeeFun/BeeFun/View/Trending/BFTrendingController.swift
1
14186
// // BFTrendingController.swift // BeeFun // // Created by wenghengcong on 15/12/30. // Copyright © 2015年 JungleSong. All rights reserved. // import UIKit import Moya import Foundation import MJRefresh import HMSegmentedControl import iCarousel public enum TrendingViewPageType: String { case user case repos } class BFTrendingController: BFBaseViewController, iCarouselDataSource, iCarouselDelegate { //view var segControl: HMSegmentedControl! = JSHMSegmentedBridge.segmentControl(titles: ["Repositories".localized, "Developers".localized]) var filterView: CPFilterTableView? let filterVHeight: CGFloat = ScreenSize.height-uiTopBarHeight-uiTabBarHeight-35 //filterview height // MARK: data var requesRepostModel: BFGithubTrendingRequsetModel? var requesDeveloperModel: BFGithubTrendingRequsetModel? var showcasePage: Int = 1 var reposData: [BFGithubTrengingModel] = [] var devesData: [BFGithubTrengingModel] = [] var showcasesData: [ObjShowcase] = [] var cityArr: [String]? var countryArr: [String]? var languageArr: [String]? // MARK: - request parameters var lastSegmentIndex = 0 var paraSince: String = "daily" var paraLanguage: String = "all" //carousel let tableTag = 5000 var carouselContent: iCarousel = iCarousel() var clickTag: Bool = false var currentIndex: Int { return carouselContent.currentItemIndex } var displayTableView: UITableView? { if let vw = carouselContent.currentItemView { if let table = vw.viewWithTag(tableTag) as? UITableView { return table } } return nil } // MARK: - view cycle override func viewDidLoad() { super.viewDidLoad() needLogin = false tvc_getDataFromPlist() tvc_initView() tvc_updateNetrokData() reloadViewClosure = { [weak self] (reachable) in self?.carouselContent.isHidden = !reachable } loginViewClosure = { [weak self] (login) in self?.carouselContent.isHidden = !login } //只有在首次启动时才弹窗,确保只弹一次窗 _ = checkCurrentNetworkState() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if segControl.selectedSegmentIndex == 0 && reposData.count == 0 { tvc_getReposRequest() } else if segControl.selectedSegmentIndex == 1 && devesData.count == 0 { tvc_getUserRequest() } else if segControl.selectedSegmentIndex == 2 && showcasesData.count == 0 { tvc_getShowcasesRequest(page: showcasePage) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) tvc_filterViewDisapper() } // MARK: - action override func leftItemAction(_ sender: UIButton?) { let btn = sender! btn.isSelected = !btn.isSelected if btn.isSelected { tvc_filterViewApper() } else { tvc_filterViewDisapper() } } func segmentControlChange(index: Int) { displayTableView?.reloadData() //请求 if index == 0 && reposData.isEmpty { tvc_getReposRequest() } else if index == 1 && devesData.isEmpty { tvc_getUserRequest() } else if index == 2 && showcasesData.isEmpty { tvc_getShowcasesRequest(page: showcasePage) } //筛选按钮是否显示 self.leftItem?.isHidden = index == 0 || index == 1 ? false : true self.clickTag = true self.carouselContent.scrollToItem(at: index, animated: true) } @objc func tvc_didClickSearchBar() { let searchVC = SESearchViewController() searchVC.hidesBottomBarWhenPushed = true navigationController?.pushViewController(searchVC, animated: true) } /// 加载数据 func tvc_updateNetrokData() { requesRepostModel = BFGithubTrendingRequsetModel() requesDeveloperModel = BFGithubTrendingRequsetModel() let source = 2 requesRepostModel?.type = 1 requesRepostModel?.source = source requesRepostModel?.time = BFGihubTrendingTimeEnum.daily requesRepostModel?.language = paraLanguage requesRepostModel?.page = 1 requesRepostModel?.perpage = 100 requesRepostModel?.sort = "up_star_num" requesRepostModel?.direction = "desc" requesDeveloperModel?.type = 2 requesDeveloperModel?.source = source requesDeveloperModel?.time = BFGihubTrendingTimeEnum.daily requesDeveloperModel?.language = paraLanguage requesDeveloperModel?.page = 1 requesDeveloperModel?.perpage = 100 requesDeveloperModel?.sort = "pos" requesDeveloperModel?.direction = "asc" if segControl.selectedSegmentIndex == 0 { tvc_getReposRequest() } else if segControl.selectedSegmentIndex == 1 { tvc_getUserRequest() } else { tvc_getShowcasesRequest(page: showcasePage) } } override func reconnect() { super.reconnect() tvc_updateNetrokData() } override func request() { super.request() tvc_updateNetrokData() } override func didAction(place: BFPlaceHolderView) { if place == placeEmptyView { request() } else if place == placeLoginView { login() } else if place == placeReloadView { self.request() } } } // MARK: - iCarousel extension BFTrendingController { func numberOfItems(in carousel: iCarousel) -> Int { return segControl.sectionTitles.count } //1. 先获取view func carousel(_ carousel: iCarousel, viewForItemAt index: Int, reusing view: UIView?) -> UIView { var reuseView: UIView var reuseTable: UITableView if let vw = view { reuseView = vw } else { reuseTable = UITableView() reuseTable.frame = CGRect.zero reuseTable.dataSource = self reuseTable.delegate = self reuseTable.separatorStyle = .none reuseTable.scrollsToTop = true reuseTable.backgroundColor = UIColor.bfViewBackgroundColor reuseTable.mj_header = refreshManager.header() reuseTable.mj_footer = refreshManager.footer() if #available(iOS 11, *) { reuseTable.estimatedRowHeight = 0 reuseTable.estimatedSectionHeaderHeight = 0 reuseTable.estimatedSectionFooterHeight = 0 } refreshManager.delegate = self reuseTable.frame = CGRect(x: 0, y: 0, w: carouselContent.width, h: carouselContent.height) reuseTable.tag = tableTag reuseView = UIView(frame: CGRect(x: 0, y: 0, w: carouselContent.width, h: carouselContent.height)) reuseView.addSubview(reuseTable) } return reuseView } //2. index change func carouselCurrentItemIndexDidChange(_ carousel: iCarousel) { if carouselContent == carousel { // 如果是点击segment控件,则不需要改变tag index if !clickTag { if !segControl.sectionTitles.isBeyond(index: currentIndex) { segControl.setSelectedSegmentIndex(UInt(currentIndex), animated: true) } } clickTag = false displayTableView?.reloadData() if segControl.selectedSegmentIndex == 0 { if reposData.isEmpty { tvc_getReposRequest() } leftItem?.isHidden = false } else if segControl.selectedSegmentIndex == 1 { leftItem?.isHidden = false if self.devesData.isEmpty { tvc_getUserRequest() } } else if segControl.selectedSegmentIndex == 2 { leftItem?.isHidden = true if showcasesData.isEmpty { tvc_getShowcasesRequest(page: showcasePage) } } } } //可循环滑动 // func carousel(_ carousel: iCarousel, valueFor option: iCarouselOption, withDefault value: CGFloat) -> CGFloat { // switch option { // case .wrap: // return 1 // default: // return value // } // } } // MARK: - 筛选视图的回调 extension BFTrendingController : CPFilterTableViewProtocol { //filter delegate func didSelectValueColoumn(_ row: Int, type: String, value: String) { if type == "Since" { paraSince = value } else if type == "Language" { if value == "All" { paraLanguage = "all" } else { paraLanguage = value.replacingOccurrences(of: " ", with: "-").lowercased() } } tvc_filterViewDisapper() tvc_updateNetrokData() displayTableView?.setContentOffset(CGPoint.zero, animated: true) } func didSelectTypeColoumn(_ row: Int, type: String) { } func didTapSinceTime(since: String) { paraSince = since tvc_filterViewDisapper() tvc_updateNetrokData() displayTableView?.setContentOffset(CGPoint.zero, animated: true) } } extension BFTrendingController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if segControl.selectedSegmentIndex == 0 { return self.reposData.count } else if segControl.selectedSegmentIndex == 1 { return self.devesData.count } return self.showcasesData.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let row = indexPath.row var cellId = "" if segControl.selectedSegmentIndex == 0 { cellId = "BFRepositoryTypeFourCellIdentifier" var cell = tableView.dequeueReusableCell(withIdentifier: cellId) as? BFRepositoryTypeFourCell if cell == nil { cell = (BFRepositoryTypeFourCell.cellFromNibNamed("BFRepositoryTypeFourCell") as? BFRepositoryTypeFourCell) } if self.reposData.isBeyond(index: row) { return cell! } let repos = self.reposData[row] cell!.objRepos = repos cell?.setBothEndsLines(row, all: reposData.count) return cell! } else if segControl.selectedSegmentIndex == 1 { cellId = "BFUserTypeOneCellIdentifier" var cell = tableView.dequeueReusableCell(withIdentifier: cellId) as? BFUserTypeOneCell if cell == nil { cell = (BFUserTypeOneCell.cellFromNibNamed("BFUserTypeOneCell") as? BFUserTypeOneCell) } if self.devesData.isBeyond(index: row) { return cell! } let user = self.devesData[row] cell!.user = user cell!.userNo = row cell?.setBothEndsLines(row, all: devesData.count) return cell! } cellId = "BFTrendingShowcaseCellIdentifier" var cell = tableView.dequeueReusableCell(withIdentifier: cellId) as? BFTrendingShowcaseCell if cell == nil { cell = (BFTrendingShowcaseCell.cellFromNibNamed("BFTrendingShowcaseCell") as? BFTrendingShowcaseCell) } if self.showcasesData.isBeyond(index: row) { return cell! } let showcase = showcasesData[row] cell!.showcase = showcase cell?.setBothEndsLines(row, all: showcasesData.count) return cell! } } extension BFTrendingController { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { if segControl.selectedSegmentIndex == 0 { return 85 } else if segControl.selectedSegmentIndex == 1 { return 71 } return 128 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) tvc_filterViewDisapper() if !UserManager.shared.needLoginAlert() { return } if segControl.selectedSegmentIndex == 0 { let repos = self.reposData[indexPath.row] let objRepos = ObjRepos() repos.full_name = repos.full_name?.replacing(" ", with: "") objRepos.name = repos.full_name objRepos.url = repos.repo_url JumpManager.shared.jumpReposDetailView(repos: objRepos, from: .other) } else if segControl.selectedSegmentIndex == 1 { let dev = self.devesData[indexPath.row] let objUser = ObjUser() objUser.login = dev.login JumpManager.shared.jumpUserDetailView(user: objUser) } else { let showcase = self.showcasesData[indexPath.row] let caseVC = BFShowcaseDetailController() caseVC.showcase = showcase caseVC.hidesBottomBarWhenPushed = true self.navigationController?.pushViewController(caseVC, animated: true) } } } extension BFTrendingController { /// 下拉刷新 override func headerRefresh() { self.displayTableView?.mj_header.endRefreshing() if segControl.selectedSegmentIndex == 2 { showcasePage = 1 } tvc_updateNetrokData() } /// 上拉加载 override func footerRefresh() { self.displayTableView?.mj_footer.endRefreshing() if segControl.selectedSegmentIndex == 2 { showcasePage += 1 tvc_updateNetrokData() } } }
mit
0967975640ff7c3a5ca65d6d6b053f54
31.061644
136
0.601367
4.770041
false
false
false
false
ResearchSuite/ResearchSuiteExtensions-iOS
source/Core/Classes/RSEnhancedMultipleChoiceResult.swift
1
1943
// // RSEnhancedMultipleChoiceResult.swift // Pods // // Created by James Kizer on 4/10/17. // // import UIKit import ResearchKit import Gloss public struct RSEnahncedMultipleChoiceSelection: JSONEncodable { public let identifier: String public let value: NSCoding & NSCopying & NSObjectProtocol public let auxiliaryResult: ORKResult? public var description: String { return "\(value)" } public func toJSON() -> JSON? { return jsonify([ "identifier" ~~> self.identifier, "value" ~~> self.value, "auxiliaryResult" ~~> self.auxiliaryResult ]) } } open class RSEnhancedMultipleChoiceResult: ORKResult { open var choiceAnswers: [RSEnahncedMultipleChoiceSelection]? open func choiceAnswer(for identifier: String) -> RSEnahncedMultipleChoiceSelection? { guard let choiceAnswers = self.choiceAnswers else { return nil } return choiceAnswers.filter({ $0.identifier == identifier }).first } override open func copy(with zone: NSZone? = nil) -> Any { let obj = super.copy(with: zone) if let choiceResult = obj as? RSEnhancedMultipleChoiceResult, let choiceAnswers = self.choiceAnswers { choiceResult.choiceAnswers = choiceAnswers return choiceResult } return obj } override open var description: String { //let answers: [String] = choiceAnswers!.map { $0.description } let answers: [String] = choiceAnswers != nil ? choiceAnswers!.map { $0.description } : [String]() if answers.count > 0 { return super.description + "[" + answers.reduce("\n", { (acc, answer) -> String in return acc + answer + "\n" }) + "]" } else { return super.description + "[]" } } }
apache-2.0
50f8ce311808a050912e372c3c12f992
27.15942
105
0.591354
4.739024
false
false
false
false
proversity-org/edx-app-ios
Source/ContainerNavigationController.swift
1
3970
// // ContainerNavigationController.swift // edX // // Created by Akiva Leffert on 6/29/15. // Copyright (c) 2015 edX. All rights reserved. // import UIKit /// A controller should implement this protocol to indicate that it wants to be responsible /// for its own status bar styling instead of leaving it up to its container, which is the default /// behavior. /// It is deliberately empty and just exists so controllers can declare they want this behavior. protocol StatusBarOverriding { } /// A controller should implement this protocol to indicate that it wants to be responsible /// for its own interface orientation instead of using the defaults. /// It is deliberately empty and just exists so controllers can declare they want this behavior. @objc protocol InterfaceOrientationOverriding { } /// A simple UINavigationController subclass that can forward status bar /// queries to its children should they opt into that by implementing the ContainedNavigationController protocol class ForwardingNavigationController: UINavigationController, StatusBarOverriding { override init(rootViewController: UIViewController) { super.init(rootViewController: rootViewController) view.handleDynamicTypeNotification() } override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override var childForStatusBarStyle: UIViewController? { if let controller = viewControllers.last as? StatusBarOverriding as? UIViewController { return controller } else { return super.childForStatusBarStyle } } override var childForStatusBarHidden: UIViewController? { if let controller = viewControllers.last as? StatusBarOverriding as? UIViewController { return controller } else { return super.childForStatusBarHidden } } override var shouldAutorotate: Bool { if let controller = viewControllers.last as? InterfaceOrientationOverriding as? UIViewController { return controller.shouldAutorotate } else { return super.shouldAutorotate } } override var supportedInterfaceOrientations: UIInterfaceOrientationMask { if let controller = viewControllers.last as? InterfaceOrientationOverriding as? UIViewController { return controller.supportedInterfaceOrientations } else { return .portrait } } override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation { if let controller = viewControllers.last as? InterfaceOrientationOverriding as? UIViewController { return controller.preferredInterfaceOrientationForPresentation } else { return .portrait } } override var preferredStatusBarStyle: UIStatusBarStyle { return UIStatusBarStyle(barStyle: .default) } } extension UINavigationController { struct AssociatedKeys { static var completionHandler = "completionHandletObject" } typealias Completion = ()->Void var completionHandler:Completion { get { guard let value = objc_getAssociatedObject(self, &AssociatedKeys.completionHandler) as? Completion else { return {} } return value } set(newValue) { objc_setAssociatedObject(self, &AssociatedKeys.completionHandler, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } func pushViewController(viewController: UIViewController, completion :@escaping Completion) { completionHandler = completion pushViewController(viewController, animated: true) } }
apache-2.0
8f2070709610d04cc1aaa8433d5e032d
34.132743
145
0.696977
6.051829
false
false
false
false
hzy87email/actor-platform
actor-apps/app-ios/ActorApp/Controllers Support/Executions.swift
2
5682
// // Copyright (c) 2014-2015 Actor LLC. <https://actor.im> // import Foundation enum ExecutionType { case Normal case Hidden case Safe } class Executions { class func execute(command: ACCommand) { execute(command, successBlock: nil, failureBlock: nil) } class func execute(command: ACCommand, type: ExecutionType = .Normal, ignore: [String] = [], successBlock: ((val: Any?) -> Void)?, failureBlock: ((val: Any?) -> Void)?) { var hud: MBProgressHUD? if type != .Hidden { hud = showProgress() } command.startWithCallback(CocoaCallback(result: { (val:Any?) -> () in dispatchOnUi { hud?.hide(true) successBlock?(val: val) } }, error: { (val) -> () in dispatchOnUi { hud?.hide(true) if type == .Safe { // If unknown error, just try again var tryAgain = true if let exception = val as? ACRpcException { // If is in ignore list, just return to UI if ignore.contains(exception.getTag()) { failureBlock?(val: val) return } // Get error from tryAgain = exception.isCanTryAgain() } // Showing alert if tryAgain { errorWithError(val, rep: { () -> () in Executions.execute(command, type: type, successBlock: successBlock, failureBlock: failureBlock) }, cancel: { () -> () in failureBlock?(val: val) }) } else { errorWithError(val, cancel: { () -> () in failureBlock?(val: val) }) } } else { failureBlock?(val: val) } } })) } class func errorWithError(e: AnyObject, rep:(()->())? = nil, cancel:(()->())? = nil) { error(Actor.getFormatter().formatErrorTextWithError(e), rep: rep, cancel: cancel) } class func errorWithTag(tag: String, rep:(()->())? = nil, cancel:(()->())? = nil) { error(Actor.getFormatter().formatErrorTextWithTag(tag), rep: rep, cancel: cancel) } class func error(message: String, rep:(()->())? = nil, cancel:(()->())? = nil) { if rep != nil { let d = UIAlertViewBlock(clickedClosure: { (index) -> () in if index > 0 { rep?() } else { cancel?() } }) let alert = UIAlertView(title: localized("AlertError"), message: message, delegate: d, cancelButtonTitle: localized("AlertCancel"), otherButtonTitles: localized("AlertTryAgain")) setAssociatedObject(alert, value: d, associativeKey: &alertViewBlockReference) alert.show() } else { let d = UIAlertViewBlock(clickedClosure: { (index) -> () in cancel?() }) let alert = UIAlertView(title: nil, message: message, delegate: d, cancelButtonTitle: localized("AlertOk")) setAssociatedObject(alert, value: d, associativeKey: &alertViewBlockReference) alert.show() } } class private func showProgress() -> MBProgressHUD { let window = UIApplication.sharedApplication().windows[1] let hud = MBProgressHUD(window: window) hud.mode = MBProgressHUDMode.Indeterminate hud.removeFromSuperViewOnHide = true window.addSubview(hud) window.bringSubviewToFront(hud) hud.show(true) return hud } } private var alertViewBlockReference = "_block_reference" @objc private class UIAlertViewBlock: NSObject, UIAlertViewDelegate { private let clickedClosure: ((index: Int) -> ()) init(clickedClosure: ((index: Int) -> ())) { self.clickedClosure = clickedClosure } @objc private func alertView(alertView: UIAlertView, clickedButtonAtIndex buttonIndex: Int) { clickedClosure(index: buttonIndex) } @objc private func alertViewCancel(alertView: UIAlertView) { clickedClosure(index: -1) } } extension UIViewController { func execute(command: ACCommand) { Executions.execute(command) } func execute(command: ACCommand, successBlock: ((val: Any?) -> Void)?, failureBlock: ((val: Any?) -> Void)?) { Executions.execute(command, successBlock: successBlock, failureBlock: failureBlock) } func executeSafe(command: ACCommand, ignore: [String] = [], successBlock: ((val: Any?) -> Void)? = nil) { Executions.execute(command, type: .Safe, ignore: ignore, successBlock: successBlock, failureBlock: { (val) -> () in successBlock?(val: nil) }) } func executeHidden(command: ACCommand, successBlock: ((val: Any?) -> Void)? = nil) { Executions.execute(command, type: .Hidden, successBlock: successBlock, failureBlock: nil) } }
mit
9c3ce4614a4634d2c76b86cd6c60d446
35.197452
174
0.495424
5.330206
false
false
false
false
hacktx/iOS-HackTX-2015
HackTX/EventFeedbackViewController.swift
1
3264
// // EventFeedbackViewController.swift // HackTX // // Created by Drew Romanyk on 9/8/15. // Copyright (c) 2015 HackTX. All rights reserved. // import UIKit import Alamofire class EventFeedbackViewController: UIViewController { @IBAction func cancelButton(sender: UIBarButtonItem) { dismissViewControllerAnimated(true, completion: nil) } @IBOutlet weak var star1: UIButton! @IBOutlet weak var star2: UIButton! @IBOutlet weak var star3: UIButton! @IBOutlet weak var star4: UIButton! @IBOutlet weak var star5: UIButton! @IBOutlet weak var submit: UIButton! var ratingScore = 5 var scheduleEvent = Event() override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func star1Clicked(sender: UIButton) { ratingScore = 1 star2.imageView?.image = UIImage(named: "partners") star3.imageView?.image = UIImage(named: "partners") star4.imageView?.image = UIImage(named: "partners") star5.imageView?.image = UIImage(named: "partners") } @IBAction func star2Clicked(sender: UIButton) { ratingScore = 2 star2.imageView?.image = UIImage(named: "partners-filled") star3.imageView?.image = UIImage(named: "partners") star4.imageView?.image = UIImage(named: "partners") star5.imageView?.image = UIImage(named: "partners") } @IBAction func star3Clicked(sender: UIButton) { ratingScore = 3 star2.imageView?.image = UIImage(named: "partners-filled") star3.imageView?.image = UIImage(named: "partners-filled") star4.imageView?.image = UIImage(named: "partners") star5.imageView?.image = UIImage(named: "partners") } @IBAction func star4Clicked(sender: UIButton) { ratingScore = 4 star2.imageView?.image = UIImage(named: "partners-filled") star3.imageView?.image = UIImage(named: "partners-filled") star4.imageView?.image = UIImage(named: "partners-filled") star5.imageView?.image = UIImage(named: "partners") } @IBAction func star5Clicked(sender: UIButton) { ratingScore = 5 star2.imageView?.image = UIImage(named: "partners-filled") star3.imageView?.image = UIImage(named: "partners-filled") star4.imageView?.image = UIImage(named: "partners-filled") star5.imageView?.image = UIImage(named: "partners-filled") } @IBAction func submitClicked(sender: UIButton) { let parameters = ["id": scheduleEvent.id!, "rating": ratingScore] Alamofire.request(Router.Feedback((parameters))) .responseJSON{ (request, response, data) in if data.isFailure { let errorAlert = UIAlertView() if errorAlert.title == "" { errorAlert.title = "Error" errorAlert.message = "Oops! Looks like there was a problem trying to send your feedback." errorAlert.addButtonWithTitle("Ok") errorAlert.show() } } else if let _: AnyObject = data.value { UserPrefs.shared().setFeedbackEventDone(self.scheduleEvent.id!) self.dismissViewControllerAnimated(true, completion: nil) } } } }
mit
4c86a25791cd7c6ade4e78e05abef749
34.107527
95
0.656556
4.01476
false
false
false
false
ul7290/realm-cocoa
RealmSwift-swift1.2/Optional.swift
2
3214
//////////////////////////////////////////////////////////////////////////// // // Copyright 2015 Realm Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // //////////////////////////////////////////////////////////////////////////// import Realm /// Types that can be represented in a `RealmOptional`. public protocol RealmOptionalType {} extension Int: RealmOptionalType {} extension Int8: RealmOptionalType {} extension Int16: RealmOptionalType {} extension Int32: RealmOptionalType {} extension Int64: RealmOptionalType {} extension Float: RealmOptionalType {} extension Double: RealmOptionalType {} extension Bool: RealmOptionalType {} // Not all RealmOptionalType's can be cast to AnyObject, so handle casting logic here. private func realmOptionalToAnyObject<T: RealmOptionalType>(value: T?) -> AnyObject? { if let anyObjectValue: AnyObject = value as? AnyObject { return anyObjectValue } else if let int8Value = value as? Int8 { return NSNumber(long: Int(int8Value)) } else if let int16Value = value as? Int16 { return NSNumber(long: Int(int16Value)) } else if let int32Value = value as? Int32 { return NSNumber(long: Int(int32Value)) } else if let int64Value = value as? Int64 { return NSNumber(longLong: int64Value) } return nil } // Not all RealmOptionalType's can be cast from AnyObject, so handle casting logic here. private func anyObjectToRealmOptional<T: RealmOptionalType>(anyObject: AnyObject?) -> T? { if T.self is Int8.Type { return ((anyObject as! NSNumber?)?.longValue).map { Int8($0) } as! T? } else if T.self is Int16.Type { return ((anyObject as! NSNumber?)?.longValue).map { Int16($0) } as! T? } else if T.self is Int32.Type { return ((anyObject as! NSNumber?)?.longValue).map { Int32($0) } as! T? } else if T.self is Int64.Type { return (anyObject as! NSNumber?)?.longLongValue as! T? } return anyObject as! T? } /** A `RealmOptional` represents a optional value for types that can't be directly declared as `dynamic` in Swift, such as `Int`s, `Float`, `Double`, and `Bool`. It encapsulates a value in its `value` property, which is the only way to mutate a `RealmOptional` property on an `Object`. */ public final class RealmOptional<T: RealmOptionalType>: RLMOptionalBase { /// The value this optional represents. public var value: T? { get { return anyObjectToRealmOptional(underlyingValue) } set { underlyingValue = realmOptionalToAnyObject(newValue) } } /// Creates a `RealmOptional` with a `nil` default value. public override init() { super.init() } }
apache-2.0
25aab49ed91380539b039401432547aa
37.261905
90
0.66117
4.308311
false
false
false
false
hsuanan/Mr-Ride-iOS
Mr-Ride/Controller/MapViewNavigationController.swift
1
573
// // MapViewNavigationController.swift // Mr-Ride // // Created by Hsin An Hsu on 6/20/16. // Copyright © 2016 AppWorks School HsinAn Hsu. All rights reserved. // import UIKit class MapViewNavigationController: UINavigationController { override func viewDidLoad() { super.viewDidLoad() navigationBar.barStyle = UIBarStyle.Black navigationBar.topItem?.title = "Map" navigationBar.tintColor = UIColor.whiteColor() navigationBar.barTintColor = UIColor.mrLightblueColor() navigationBar.translucent = false } }
mit
845d7d797d0d994ae244ed829a109b56
23.869565
69
0.699301
4.612903
false
false
false
false
brentdax/SQLKit
Sources/CorePostgreSQL/PGIntervalFormatter.swift
1
7014
// // PGIntervalFormatter.swift // LittlinkRouterPerfect // // Created by Brent Royal-Gordon on 12/1/16. // // import Foundation class PGIntervalFormatter: Formatter { override func getObjectValue(_ objectValue: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool { do { let value = try self.objectValue(for: string) if let objectValue = objectValue { objectValue.pointee = value as AnyObject? } return true } catch { if let errorDescription = errorDescription { errorDescription.pointee = error.localizedDescription as NSString } return false } } func objectValue(for string: String) throws -> Any? { return try interval(from: string) } override func string(for objectValue: Any?) -> String? { return (objectValue as? PGInterval).map(string(from:)) } } extension PGIntervalFormatter { func interval(from text: String) throws -> PGInterval { return try Parser().parse(text) } fileprivate struct Parser: StringParser { enum ParseState: PGConversionParsingState { case start(for: PGInterval) case expectingQuantity(in: PGInterval.Component.Section, for: PGInterval) case readingQuantity(ValueAccumulator, in: PGInterval.Component.Section, for: PGInterval) var localizedStateDescription: String { switch self { case .start: return NSLocalizedString("at the start of the text", comment: "") case .expectingQuantity(in: .date, for: _): return NSLocalizedString("while processing the date section", comment: "") case .expectingQuantity(in: .time, for: _): return NSLocalizedString("while processing the time section", comment: "") case .readingQuantity(_, in: .date, for: _): return NSLocalizedString("while reading a number in the date section", comment: "") case .readingQuantity(_, in: .time, for: _): return NSLocalizedString("while reading a number in the time section", comment: "") } } } let initialParseState = ParseState.start(for: PGInterval()) func continueParsing(_ char: Character, in state: ParseState) throws -> ParseState { switch (state, char) { case (.start(for: let interval), "P"): return .expectingQuantity(in: .date, for: interval) case (.start, _): throw PGError.unexpectedCharacter(char) case (.expectingQuantity(in: .date, for: let interval), "T"): return .expectingQuantity(in: .time, for: interval) case (.expectingQuantity(in: let section, for: let interval), AnyOf.digits): return .readingQuantity(ValueAccumulator(char), in: section, for: interval) case (.expectingQuantity, _): throw PGError.unexpectedCharacter(char) case (.readingQuantity(let accumulator, in: let section, for: let interval), AnyOf.digits): return .readingQuantity(accumulator.adding(char), in: section, for: interval) case (.readingQuantity(let accumulator, in: let section, for: var interval), _): guard let component = PGInterval.Component(section: section, unit: char) else { throw PGError.unexpectedCharacter(char) } let newValue = try accumulator.make() as Int let oldValue = interval[component] guard oldValue == 0 else { throw PGError.redundantQuantity(oldValue: oldValue, newValue: newValue, for: component) } interval[component] = newValue return .expectingQuantity(in: section, for: interval) } } func finishParsing(in state: ParseState) throws -> PGInterval { switch state { case .expectingQuantity(in: _, for: let interval): return interval case .start: throw PGError.earlyTermination case .readingQuantity(let accumulator, in: _, for: _): throw PGError.unitlessQuantity(try accumulator.make()) } } func wrapError(_ error: Error, at index: String.Index, in string: String, during state: ParseState) -> Error { return PGError.invalidInterval(error, at: index, in: string, during: state) } } } extension PGIntervalFormatter { func string(from interval: PGInterval) -> String { var result = "P" result += components(from: .date, in: interval) let times = components(from: .time, in: interval) if !times.isEmpty { result += "T" + times } return result } fileprivate func components(from section: PGInterval.Component.Section, in interval: PGInterval) -> String { return section.components.flatMap { component in let value = interval[component] guard value != 0 else { return nil } return "\(value)\(component.unit)" }.joined() } } fileprivate extension PGInterval.Component { enum Section { static let all: [Section] = [.date, .time] case date case time var components: [PGInterval.Component] { switch self { case .date: return [.year, .month, .week, .day] case .time: return [.hour, .minute, .second] } } } var section: Section { switch self { case .year, .month, .week, .day: return .date case .hour, .minute, .second: return .time } } init?(section: Section, unit: Character) { switch (section, unit) { case (.date, "Y"): self = .year case (.date, "M"): self = .month case (.date, "W"): self = .week case (.date, "D"): self = .day case (.time, "H"): self = .hour case (.time, "M"): self = .minute case (.time, "S"): self = .second default: return nil } } var unit: String { switch self { case .year: return "Y" case .month: return "M" case .week: return "W" case .day: return "D" case .hour: return "H" case .minute: return "M" case .second: return "S" } } }
mit
82e6b1b485d3af6f098c833839c88060
34.785714
190
0.543199
4.922105
false
false
false
false
kyouko-taiga/LogicKit
Sources/LogicKit/Sequence+Extensions.swift
1
652
extension Sequence { func concatenated<S>(with other: S) -> SequenceConcatenation<Self, S> where S: Sequence, S.Element == Element { return SequenceConcatenation(self, other) } } struct SequenceConcatenation<S1, S2>: Sequence where S1: Sequence, S2: Sequence, S1.Element == S2.Element { init(_ first: S1, _ second: S2) { self.first = first self.second = second } func makeIterator() -> AnyIterator<S1.Element> { var iter1 = first.makeIterator() var iter2 = second.makeIterator() return AnyIterator { return iter1.next() ?? iter2.next() } } private let first: S1 private let second: S2 }
mit
0ac2d6699d4c3af0b325d2955eb0e352
20.032258
71
0.657975
3.486631
false
false
false
false
vittoriom/NDHpple
NDHpple/AppDelegate.swift
1
3064
// // AppDelegate.swift // NDHpple // // Created by Nicolai on 24/06/14. // Copyright (c) 2014 Nicolai Davidsson. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func showNDHpple() { NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: "http://www.reddit.com/r/swift")!) { data, response, error in if let data = data { let html = NSString(data: data, encoding: NSUTF8StringEncoding) let parser = NDHpple(HTMLData: (html as? String) ?? "") let xpath = "//*[@id='siteTable']/div/div[2]/p[@class='title']/a" let titles = parser.searchWithXPathQuery(xpath) ?? [] for node in titles { print(node.firstChild?.content) } } }.resume() } func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool { self.window = UIWindow(frame: UIScreen.mainScreen().bounds) // Override point for customization after application launch. self.window!.rootViewController = UIViewController() self.window!.backgroundColor = UIColor.whiteColor() self.window!.makeKeyAndVisible() showNDHpple() 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
400f728634a6a489278d8220aa0ab2b9
44.058824
285
0.692232
5.301038
false
false
false
false
mohamede1945/quran-ios
UIKitExtension/UIView+AutoLayout.swift
2
11600
// // UIView+AutoLayout.swift // Quran // // Created by Mohamed Afifi on 4/29/16. // // Quran for iOS is a Quran reading application for iOS. // Copyright (C) 2017 Quran.com // // 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. // import UIKit extension UIView { public func addAutoLayoutSubview(_ subview: UIView) { subview.translatesAutoresizingMaskIntoConstraints = false addSubview(subview) } @discardableResult public func addParentLeadingConstraint(_ view: UIView, value: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: view, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func addParentTrailingConstraint(_ view: UIView, value: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func addParentTopConstraint(_ view: UIView, value: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: view, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.top, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func addParentBottomConstraint(_ view: UIView, value: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: view, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func addParentCenterXConstraint(_ view: UIView, value: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: view, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func addParentCenterYConstraint(_ view: UIView, value: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: view, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func addHeightConstraint(_ value: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func addWidthConstraint(_ value: CGFloat) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: self, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func pinParentHorizontal(_ view: UIView, leadingValue: CGFloat = 0, trailingValue: CGFloat = 0) -> [NSLayoutConstraint] { var array: [NSLayoutConstraint] = [] array.append(addParentLeadingConstraint(view, value: leadingValue)) array.append(addParentTrailingConstraint(view, value: trailingValue)) return array } @discardableResult public func pinParentVertical(_ view: UIView, topValue: CGFloat = 0, bottomValue: CGFloat = 0) -> [NSLayoutConstraint] { var array: [NSLayoutConstraint] = [] array.append(addParentTopConstraint(view, value: topValue)) array.append(addParentBottomConstraint(view, value: bottomValue)) return array } @discardableResult public func pinParentAllDirections(_ view: UIView, leadingValue: CGFloat = 0, trailingValue: CGFloat = 0, topValue: CGFloat = 0, bottomValue: CGFloat = 0) -> [NSLayoutConstraint] { var array: [NSLayoutConstraint] = [] array += pinParentHorizontal(view, leadingValue: leadingValue, trailingValue: trailingValue) array += pinParentVertical(view, topValue: topValue, bottomValue: bottomValue) return array } @discardableResult public func addParentCenter(_ view: UIView, centerX: CGFloat = 0, centerY: CGFloat = 0) -> [NSLayoutConstraint] { var array: [NSLayoutConstraint] = [] array.append(addParentCenterXConstraint(view, value: centerX)) array.append(addParentCenterYConstraint(view, value: centerY)) return array } @discardableResult public func addSiblingHorizontalContiguous(left: UIView, right: UIView, value: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: right, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: left, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func addSiblingVerticalContiguous(top: UIView, bottom: UIView, value: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: bottom, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: top, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func alignSiblingTop(first: UIView, second: UIView, value: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: first, attribute: NSLayoutAttribute.top, relatedBy: NSLayoutRelation.equal, toItem: second, attribute: NSLayoutAttribute.top, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func alignSiblingBottom(first: UIView, second: UIView, value: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: first, attribute: NSLayoutAttribute.bottom, relatedBy: NSLayoutRelation.equal, toItem: second, attribute: NSLayoutAttribute.bottom, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func alignSiblingLeading(first: UIView, second: UIView, value: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: first, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: second, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func alignSiblingTrailing(first: UIView, second: UIView, value: CGFloat = 0) -> NSLayoutConstraint { let constraint = NSLayoutConstraint( item: first, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: second, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: value) addConstraint(constraint) return constraint } @discardableResult public func addEqualWidth(views: [UIView], value: CGFloat = 0) -> [NSLayoutConstraint] { assert(views.count > 1, "should have at least 2 views") let view1 = views[0] var constraints = [NSLayoutConstraint]() for i in 1..<views.count { let view2 = views[i] let constraint = NSLayoutConstraint( item: view1, attribute: NSLayoutAttribute.width, relatedBy: NSLayoutRelation.equal, toItem: view2, attribute: NSLayoutAttribute.width, multiplier: 1, constant: value) constraints.append(constraint) addConstraint(constraint) } return constraints } @discardableResult public func addEqualHeight(views: [UIView], value: CGFloat = 0) -> [NSLayoutConstraint] { assert(views.count > 1, "should have at least 2 views") let view1 = views[0] var constraints = [NSLayoutConstraint]() for i in 1..<views.count { let view2 = views[i] let constraint = NSLayoutConstraint( item: view1, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: view2, attribute: NSLayoutAttribute.height, multiplier: 1, constant: value) constraints.append(constraint) addConstraint(constraint) } return constraints } @discardableResult public func addEqualSize(views: [UIView], width: CGFloat = 0, height: CGFloat = 0) -> [NSLayoutConstraint] { var array: [NSLayoutConstraint] = [] array.append(contentsOf: addEqualHeight(views: views, value: height)) array.append(contentsOf: addEqualWidth(views: views, value: width)) return array } @discardableResult public func addSizeConstraints(width: CGFloat, height: CGFloat) -> [NSLayoutConstraint] { var array: [NSLayoutConstraint] = [] array.append(addWidthConstraint(width)) array.append(addHeightConstraint(height)) return array } }
gpl-3.0
92e4ff46cb6473b0c117c8be3fd26743
35.024845
132
0.627586
5.508072
false
false
false
false
ChernyshenkoTaras/TimeIntervalPicker
TimeIntervalPicker/Classes/TimeIntervalPicker.swift
1
14968
// // TimeIntervalPicker.swift // TimeIntervalPicker // // Created by Taras Chernyshenko on 2/6/17. // Copyright © 2017 Taras Chernyshenko. All rights reserved. // import UIKit open class TimeIntervalPicker: UIView, UIPickerViewDelegate, UIPickerViewDataSource { private let grayColor = UIColor(red: 198/255, green: 198/255, blue: 198/255, alpha: 1) private let background = UIColor(red: 232/255, green: 232/255, blue: 232/255, alpha: 1.0) private let blueColor = UIColor(red: 22/255, green: 131/255, blue: 250/255, alpha: 1.0) private let font = UIFont(name: "Helvetica", size: 13.0) private let boldFont = UIFont(name: "Helvetica-Bold", size: 15.0) public typealias Completion = (TimeInterval) -> Void private enum Component: Int { case hours case minutes } open var completion: Completion? open var maxMinutes: Int = 60 { didSet { self.hours = 0 self.minutes = 0 self.pickerView?.reloadAllComponents() } } private lazy var maxHours: Int = { return self.maxMinutes <= 60 ? 0 : self.maxMinutes / 60 }() open var titleString: String = "Time Interval" { didSet { self.titleLabel?.text = self.titleString } } open var doneString: String = "Done" { didSet { self.doneButton?.setTitle(self.doneString, for: .normal) } } open var closeString: String = "Close" { didSet { self.closeButton?.setTitle(self.closeString, for: .normal) } } open var hourSuffix: String? open var minuteSuffix: String? private var hours: Int = 0 { didSet { if self.maxHours == self.hours { self.minutes = 0 } let minutes: Component = .minutes self.pickerView?.reloadComponent(minutes.rawValue) } } private var minutes: Int = 0 private var titleLabel: UILabel? private var doneButton: UIButton? private var closeButton: UIButton? private var pickerView: UIPickerView? private var containerView: UIView? public init() { let screenWidth: CGFloat = UIScreen.main.bounds.width let screenHeight: CGFloat = UIScreen.main.bounds.height let frame: CGRect = CGRect(x: 0, y: 0, width: screenWidth, height: screenHeight) super.init(frame: frame) self.initialize() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.initialize() } private func initialize() { let screenWidth: CGFloat = UIScreen.main.bounds.width let screenHeight: CGFloat = UIScreen.main.bounds.height let width: CGFloat = screenWidth - 64 let height: CGFloat = 250 let x: CGFloat = 32 let y: CGFloat = (screenHeight - height) / 2 let frame: CGRect = CGRect(x: x, y: y, width: width, height: height) self.containerView = UIView(frame: frame) self.pickerView = UIPickerView(frame: CGRect.zero) self.doneButton = UIButton(frame: CGRect.zero) self.closeButton = UIButton(frame: CGRect.zero) self.titleLabel = UILabel(frame: CGRect.zero) self.pickerView?.dataSource = self self.pickerView?.delegate = self self.doneButton?.addTarget(self, action: #selector(TimeIntervalPicker.done), for: .touchUpInside) self.closeButton?.addTarget(self, action: #selector(TimeIntervalPicker.close), for: .touchUpInside) self.setupUI() self.updateUI() } private func setupUI() { guard let containerView = self.containerView, let pickerView = self.pickerView, let doneButton = self.doneButton, let closeButton = self.closeButton, let titleLabel = self.titleLabel else { return } let topSeparator = UIView(frame: CGRect.zero) let bottomSeparator = UIView(frame: CGRect.zero) topSeparator.backgroundColor = self.grayColor bottomSeparator.backgroundColor = self.grayColor self.addSubview(containerView) containerView.addSubview(pickerView) containerView.addSubview(doneButton) containerView.addSubview(closeButton) containerView.addSubview(titleLabel) containerView.addSubview(topSeparator) containerView.addSubview(bottomSeparator) pickerView.translatesAutoresizingMaskIntoConstraints = false doneButton.translatesAutoresizingMaskIntoConstraints = false closeButton.translatesAutoresizingMaskIntoConstraints = false titleLabel.translatesAutoresizingMaskIntoConstraints = false topSeparator.translatesAutoresizingMaskIntoConstraints = false bottomSeparator.translatesAutoresizingMaskIntoConstraints = false //buttons containerView.addConstraint(NSLayoutConstraint(item: containerView, attribute: .trailing, relatedBy: .equal, toItem: doneButton, attribute: .trailing, multiplier: 1.0, constant: 0)) containerView.addConstraint(NSLayoutConstraint(item: containerView, attribute: .bottom, relatedBy: .equal, toItem: doneButton, attribute: .bottom, multiplier: 1.0, constant: 0)) containerView.addConstraint(NSLayoutConstraint(item: containerView, attribute: .leading, relatedBy: .equal, toItem: closeButton, attribute: .leading, multiplier: 1.0, constant: 0)) containerView.addConstraint(NSLayoutConstraint(item: containerView, attribute: .bottom, relatedBy: .equal, toItem: closeButton, attribute: .bottom, multiplier: 1.0, constant: 0)) containerView.addConstraint(NSLayoutConstraint(item: doneButton, attribute: .leading, relatedBy: .equal, toItem: closeButton, attribute: .trailing, multiplier: 1.0, constant: 0)) closeButton.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 40)) doneButton.addConstraint(NSLayoutConstraint(item: doneButton, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 40)) containerView.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .width, relatedBy: .equal, toItem: containerView, attribute: .width, multiplier: 0.5, constant: 0)) //titles containerView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .top, relatedBy: .equal, toItem: containerView, attribute: .top, multiplier: 1.0, constant: 0)) containerView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1.0, constant: 0)) containerView.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .trailing, relatedBy: .equal, toItem: containerView, attribute: .trailing, multiplier: 1.0, constant: 0)) titleLabel.addConstraint(NSLayoutConstraint(item: titleLabel, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 40)) //pickerView containerView.addConstraint(NSLayoutConstraint(item: pickerView, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1.0, constant: 0)) containerView.addConstraint(NSLayoutConstraint(item: pickerView, attribute: .trailing, relatedBy: .equal, toItem: containerView, attribute: .trailing, multiplier: 1.0, constant: 0)) containerView.addConstraint(NSLayoutConstraint(item: pickerView, attribute: .top, relatedBy: .equal, toItem: titleLabel, attribute: .bottom, multiplier: 1.0, constant: 0)) containerView.addConstraint(NSLayoutConstraint(item: pickerView, attribute: .bottom, relatedBy: .equal, toItem: closeButton, attribute: .top, multiplier: 1.0, constant: 0)) //separators containerView.addConstraint(NSLayoutConstraint(item: topSeparator, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1.0, constant: 0)) containerView.addConstraint(NSLayoutConstraint(item: topSeparator, attribute: .trailing, relatedBy: .equal, toItem: containerView, attribute: .trailing, multiplier: 1.0, constant: 0)) containerView.addConstraint(NSLayoutConstraint(item: topSeparator, attribute: .bottom, relatedBy: .equal, toItem: pickerView, attribute: .top, multiplier: 1.0, constant: 0)) topSeparator.addConstraint(NSLayoutConstraint(item: topSeparator, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 0.5)) containerView.addConstraint(NSLayoutConstraint(item: bottomSeparator, attribute: .leading, relatedBy: .equal, toItem: containerView, attribute: .leading, multiplier: 1.0, constant: 0)) containerView.addConstraint(NSLayoutConstraint(item: bottomSeparator, attribute: .trailing, relatedBy: .equal, toItem: containerView, attribute: .trailing, multiplier: 1.0, constant: 0)) containerView.addConstraint(NSLayoutConstraint(item: bottomSeparator, attribute: .bottom, relatedBy: .equal, toItem: pickerView, attribute: .bottom, multiplier: 1.0, constant: 0)) bottomSeparator.addConstraint(NSLayoutConstraint(item: bottomSeparator, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .height, multiplier: 1.0, constant: 0.5)) } private func updateUI() { self.backgroundColor = UIColor.clear self.titleLabel?.textAlignment = .center self.closeButton?.setTitle(self.closeString, for: .normal) self.doneButton?.setTitle(self.doneString, for: .normal) self.titleLabel?.text = self.titleString self.closeButton?.titleLabel?.font = self.font self.doneButton?.titleLabel?.font = self.font self.titleLabel?.font = self.boldFont self.closeButton?.setTitleColor(self.blueColor, for: .normal) self.doneButton?.setTitleColor(self.blueColor, for: .normal) self.containerView?.backgroundColor = self.background self.containerView?.layer.borderColor = self.grayColor.cgColor self.containerView?.layer.borderWidth = 0.5 self.containerView?.layer.cornerRadius = 10 self.pickerView?.layer.opacity = 0.5 } open func show(at selectedMinute: Int = 0) { guard let appDelegate = UIApplication.shared.delegate else { assertionFailure() return } guard let window = appDelegate.window else { assertionFailure() return } if selectedMinute <= self.maxMinutes { let modul = self.maxMinutes <= 60 ? 61 : 60 let minute = selectedMinute % modul let hour = selectedMinute < modul ? 0 : selectedMinute / 60 self.hours = hour self.minutes = minute self.pickerView?.reloadAllComponents() if hour > 0 { self.pickerView?.selectRow(hour, inComponent: 0, animated: true) self.pickerView?.selectRow(minute, inComponent: 1, animated: true) } else { self.pickerView?.selectRow(minute, inComponent: self.pickerView?.numberOfComponents == 1 ? 0 : 1, animated: true) } } window?.addSubview(self) window?.bringSubview(toFront: self) window?.endEditing(true) UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: { self.containerView?.backgroundColor = UIColor.groupTableViewBackground self.pickerView?.layer.opacity = 1 self.pickerView?.layer.transform = CATransform3DMakeScale(1, 1, 1) }) } @objc private func done() { let hours: Int = self.hours let minutes: Int = self.minutes let seconds: Int = hours * 3600 + minutes * 60 self.completion?(TimeInterval(seconds)) self.close() } @objc private func close() { UIView.animate(withDuration: 0.2, delay: 0, options: .curveEaseInOut, animations: { self.alpha = 0.0 }) { (isFinished) in self.removeFromSuperview() } } //MARK: UIPickerViewDataSource methods public func numberOfComponents(in pickerView: UIPickerView) -> Int { return self.maxHours > 0 ? 2 : 1 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { let comp = self.maxHours > 0 ? component : 1 switch Component(rawValue: comp)! { case .hours: return self.maxHours + 1 case .minutes: if self.maxMinutes == 60 { return 61 } if self.hours == self.maxHours { return (self.maxMinutes % 60) + 1} return self.maxHours > 0 ? 60 : self.maxMinutes + 1 } } //MARK: UIPickerViewDelegate methods public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let comp = self.maxHours > 0 ? component : 1 switch Component(rawValue: comp)! { case .hours: self.hours = row case .minutes: self.minutes = row } } public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { let isMinuteComponent = pickerView.numberOfComponents == 1 || component > 0 let suffixType:String? = isMinuteComponent ? self.minuteSuffix : self.hourSuffix if let existingSuffix = suffixType { return "\(row) \(existingSuffix)" } else { return "\(row)" } } public func pickerView(_ pickerView: UIPickerView, widthForComponent component: Int) -> CGFloat { return 80 } public func pickerView(_ pickerView: UIPickerView, rowHeightForComponent component: Int) -> CGFloat { return 30 } }
mit
84c53d3acc6bf2819959676666979410
39.671196
93
0.625242
4.997329
false
false
false
false
cathy810218/onebusaway-iphone
OneBusAway/ui/stops/NearbyStopsViewController.swift
1
10637
// // NearbyStopsViewController.swift // org.onebusaway.iphone // // Created by Aaron Brethorst on 11/6/16. // Copyright © 2016 OneBusAway. All rights reserved. // import UIKit import OBAKit import PromiseKit import SVProgressHUD typealias NearbyStopsCanceled = () -> Void class NearbyStopsViewController: OBAStaticTableViewController { var stop: OBAStopV2? var searchResult: OBASearchResult? var mapDataLoader: OBAMapDataLoader? var mapRegionManager: OBAMapRegionManager? @objc var presentedModally = false @objc var pushesResultsOntoStack = false @objc var canceled: NearbyStopsCanceled? @objc var closeButtonTitle = OBAStrings.close @objc lazy public var navigator: OBANavigator = { let navigator = UIApplication.shared.delegate as! OBAApplicationDelegate return navigator }() lazy var modelService: OBAModelService = { return OBAApplication.shared().modelService }() public var currentCoordinate: CLLocationCoordinate2D? @objc init(mapDataLoader: OBAMapDataLoader, mapRegionManager: OBAMapRegionManager) { super.init(nibName: nil, bundle: nil) self.pushesResultsOntoStack = true self.mapDataLoader = mapDataLoader self.mapDataLoader?.add(self) self.mapRegionManager = mapRegionManager self.mapRegionManager?.add(delegate: self) } @objc init(withStop stop: OBAStopV2) { self.stop = stop self.currentCoordinate = self.stop?.coordinate super.init(nibName: nil, bundle: nil) } @objc init(withSearchResult searchResult: OBASearchResult?) { self.searchResult = searchResult super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - View Controller override func viewDidLoad() { super.viewDidLoad() self.title = NSLocalizedString("msg_nearby_stops", comment: "Title of the Nearby Stops view controller") self.emptyDataSetTitle = NSLocalizedString("msg_mayus_no_stops_found", comment: "Empty data set title for the Nearby Stops controller") self.emptyDataSetDescription = NSLocalizedString("msg_coulnt_find_other_stops_on_radius", comment: "Empty data set description for the Nearby Stops controller") if self.presentedModally { self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: self.closeButtonTitle, style: .plain, target: self, action: #selector(closeButtonTapped)) } self.loadData() } } // MARK: - Map Data Loader extension NearbyStopsViewController: OBAMapDataLoaderDelegate { func mapDataLoader(_ mapDataLoader: OBAMapDataLoader, didReceiveError error: Error) { // noop? } func mapDataLoader(_ mapDataLoader: OBAMapDataLoader, didUpdate searchResult: OBASearchResult) { self.searchResult = searchResult self.loadData() } } // MARK: - Map Region Manager extension NearbyStopsViewController: OBAMapRegionDelegate { func mapRegionManager(_ manager: OBAMapRegionManager, setRegion region: MKCoordinateRegion, animated: Bool) { self.currentCoordinate = region.center loadData() } } // MARK: - Data Loading extension NearbyStopsViewController { func loadData() { if let searchResult = self.searchResult { self.populateTable(searchResult) } else if let stop = self.stop { SVProgressHUD.show() self.modelService.requestStopsNear(stop.coordinate).then { searchResult in self.populateTable(searchResult as! OBASearchResult) }.always { SVProgressHUD.dismiss() }.catch { error in AlertPresenter.showWarning(OBAStrings.error, body: error.localizedDescription) } } // otherwise, show nothing. If the data on the map // hasn't loaded yet, then there's nothing to show here. } /// Builds a list of table sections, sets the view controller's `sections` property /// to that built list, and reloads the table view. /// /// - Parameter searchResult: The `OBASearchResult` object used to populate the view controller func populateTable(_ searchResult: OBASearchResult) { var sections: [OBATableSection?] switch searchResult.searchType { case .region, .placemark, .stopId, .stops: sections = self.stopSectionsFromSearchResult(searchResult) case .route: sections = [self.routeSectionFromSearchResult(searchResult)] case .address: sections = [self.addressSectionFromSearchResult(searchResult)] default: sections = [] } self.sections = sections.flatMap { $0 } self.tableView.reloadData() } /// Creates an array of sections for the provided stops. /// Each stop is grouped according to its cardinal direction. /// e.g. N: [S1, S2], S: [S3, S4] /// /// - Parameter searchResult: A search result object containing a list of stops /// - Returns: An array of `OBATableSection`s containing stop rows func stopSectionsFromSearchResult(_ searchResult: OBASearchResult) -> [OBATableSection] { let stops = searchResult.values as! [OBAStopV2] var sections: [OBATableSection] = [] let filteredStops = stops.filter { $0 != self.stop } // If we have a coordinate, sort by that into a single section. // If not, group by cardinal direction and return multiple sections. if self.currentCoordinate != nil { let section = stopSectionFrom(title: nil, stops: stops) sections.append(section) } else { let grouped: [String: [OBAStopV2]] = filteredStops.categorize { $0.direction } for (direction, stopsForDirection) in grouped { let title = cardinalDirectionFromAbbreviation(direction) let section = stopSectionFrom(title: title, stops: stopsForDirection) sections.append(section) } } return sections } func stopSectionFrom(title: String?, stops: [OBAStopV2]) -> OBATableSection { let section = OBATableSection.init(title: title) var rows: [OBAStopV2] if let coordinate = self.currentCoordinate { rows = stops.sorted(by: { (s1, s2) -> Bool in let distance1 = OBAMapHelpers.getDistanceFrom(s1.coordinate, to: coordinate) let distance2 = OBAMapHelpers.getDistanceFrom(s2.coordinate, to: coordinate) return distance1 < distance2 }) } else { rows = stops } section.rows = rows.map { stop in let row = OBATableRow.init(title: stop.name) { _ in let target = OBANavigationTarget(forStopID: stop.stopId) self.navigateTo(target) } row.subtitle = String.localizedStringWithFormat(NSLocalizedString("text_only_routes_colon_param", comment: "e.g. Routes: 10, 12, 43"), stop.routeNamesAsString()) row.style = .subtitle row.accessoryType = .disclosureIndicator return row } return section } func routeSectionFromSearchResult(_ searchResult: OBASearchResult) -> OBATableSection? { guard let routes = searchResult.values as? [OBARouteV2] else { let error = OBAErrorMessages.buildError(forBadData: searchResult) Crashlytics.sharedInstance().recordError(error) return nil } let rows = routes.map { route -> OBATableRow in let row = OBATableRow.init(title: route.fullRouteName) { _ in let target = OBANavigationTarget(forRoute: route) self.navigateTo(target) } row.subtitle = route.agency.name row.style = .subtitle return row } return OBATableSection.init(title: NSLocalizedString("nearby_stops.routes_section_title", comment: "The section title on the 'Nearby' controller that says 'Routes'"), rows: rows) } func addressSectionFromSearchResult(_ searchResult: OBASearchResult) -> OBATableSection { let placemarks = searchResult.values as! [OBAPlacemark] let rows = placemarks.map { placemark -> OBATableRow in let row = OBATableRow.init(title: placemark.title!, action: { _ in let target = OBANavigationTarget(forSearch: placemark) self.navigateTo(target) }) return row } return OBATableSection.init(title: nil, rows: rows) } } // MARK: - Actions extension NearbyStopsViewController { @objc private func closeButtonTapped() { self.dismissModal { self.canceled?() } } } // MARK: - Private extension NearbyStopsViewController { private func navigateTo(_ target: OBANavigationTarget) { if self.pushesResultsOntoStack { // abxoxo - make this way better! I should be able to map from // an OBANavigationTarget -> UIViewController and push that. guard let stopID = target.searchArgument as? String else { return } let stopController = OBAStopViewController.init(stopID: stopID) self.navigationController?.pushViewController(stopController, animated: true) } else { self.dismissModal { self.navigator.navigate(to: target) } } } private func dismissModal(completion: (() -> Swift.Void)? = nil) { if self.presentedModally { self.dismiss(animated: true, completion: completion) } } func cardinalDirectionFromAbbreviation(_ abbreviation: String) -> String { switch abbreviation { case "N": return NSLocalizedString("msg_northbound", comment: "As in 'going to the north.'") case "E": return NSLocalizedString("msg_eastbound", comment: "As in 'going to the east.'") case "S": return NSLocalizedString("msg_southbound", comment: "As in 'going to the south.'") case "W": return NSLocalizedString("msg_westbound", comment: "As in 'going to the west.'") default: return NSLocalizedString("nearby_stops.stops_section_title", comment: "Title for a section that displays stops without a specified cardinal direction. Just 'Stops' in English.") } } }
apache-2.0
a71533dca9c0634a88df5bb88298e7b0
35.802768
189
0.643381
4.677221
false
false
false
false
GrandCentralBoard/GrandCentralBoard
Pods/Operations/Sources/Core/Shared/RetryOperation.swift
2
7259
// // RetryOperation.swift // Operations // // Created by Daniel Thorpe on 29/12/2015. // // import Foundation /** RetryFailureInfo is a value type which provides information related to a previously failed NSOperation which it is generic over. It is used in conjunction with RetryOperation. */ public struct RetryFailureInfo<T: NSOperation> { /// - returns: the failed operation public let operation: T /// - returns: the errors the operation finished with. public let errors: [ErrorType] /// - returns: all the aggregate errors of previous attempts public let aggregateErrors: [ErrorType] /// - returns: the number of attempts made so far public let count: Int /** This is a block which can be used to add operations to a queue. For example, perhaps it is necessary to retry the task, but only until another operation has completed. This can be done by creating the operation, setting the dependency and adding it using this block, before responding to the RetryOperation. - returns: a block which accects var arg NSOperation instances. */ public let addOperations: (NSOperation...) -> Void /// - returns: the `RetryOperation`'s log property. public let log: LoggerType /** - returns: the block which is used to configure operation instances before they are added to the queue */ public let configure: T -> Void } class RetryGenerator<T: NSOperation>: GeneratorType { typealias Payload = RetryOperation<T>.Payload typealias Handler = RetryOperation<T>.Handler internal let retry: Handler internal var info: RetryFailureInfo<T>? = .None private var generator: AnyGenerator<(Delay?, T)> init(generator: AnyGenerator<Payload>, retry: Handler) { self.generator = generator self.retry = retry } func next() -> Payload? { guard let payload = generator.next() else { return nil } guard let info = info else { return payload } return retry(info, payload) } } /** RetryOperation is a subclass of RepeatedOperation. Like RepeatedOperation it is generic over type T, an NSOperation subclass. It can be used to automatically retry another instance of operation T if the first operation finishes with errors. To support effective error recovery, in addition to a (Delay?, T) generator RetryOperation is initialized with a block. The block will receive failure info, in addition to the next result (if not nil) of the operation generator. The block must return (Delay?, T)?. Therefore consumers can inspect the failure info, and adjust the Delay, or operation before returning it. To finish, the block can return .None */ public class RetryOperation<T: NSOperation>: RepeatedOperation<T> { public typealias FailureInfo = RetryFailureInfo<T> public typealias Handler = (RetryFailureInfo<T>, Payload) -> Payload? let retry: RetryGenerator<T> /** A designated initializer Creates an operation which will retry executing operations in the face of errors. - parameter maxCount: an optional Int, which defaults to .None. If not nil, this is the maximum number of operations which will be executed. - parameter generator: the generator of (Delay?, T) values. - parameter retry: a Handler block type, can be used to inspect aggregated error to adjust the next delay and Operation. */ public init(maxCount max: Int? = .None, generator: AnyGenerator<Payload>, retry block: Handler) { retry = RetryGenerator(generator: generator, retry: block) super.init(maxCount: max, generator: AnyGenerator(retry)) name = "Retry Operation <\(T.self)>" } /** A designated initializer, which accepts two generators, one for the delay and another for the operation, in addition to a retry handler block - parameter maxCount: an optional Int, which defaults to .None. If not nil, this is the maximum number of operations which will be executed. - parameter delay: a generator with Delay element. - parameter generator: a generator with T element. - parameter retry: a Handler block type, can be used to inspect aggregated error to adjust the next delay and Operation. */ public init<D, G where D: GeneratorType, D.Element == Delay, G: GeneratorType, G.Element == T>(maxCount max: Int? = .None, delay: D, generator: G, retry block: Handler) { let tuple = TupleGenerator(primary: generator, secondary: delay) retry = RetryGenerator(generator: AnyGenerator(tuple), retry: block) super.init(maxCount: max, generator: AnyGenerator(retry)) name = "Retry Operation <\(T.self)>" } /** An initializer with wait strategy and generic operation generator. This is useful where another system can be responsible for vending instances of the custom operation. Typically there may be some state involved in such a Generator. e.g. The wait strategy is useful if say, you want to repeat the operations with random delays, or exponential backoff. These standard schemes and be easily expressed. ```swift class MyOperationGenerator: GeneratorType { func next() -> MyOperation? { // etc } } let operation = RetryOperation( maxCount: 3, strategy: .Random((0.1, 1.0)), generator: MyOperationGenerator() ) { info, delay, op in // inspect failure info return (delay, op) } ``` - parameter maxCount: an optional Int, which defaults to 5. - parameter strategy: a WaitStrategy which defaults to a 0.1 second fixed interval. - parameter [unnamed] generator: a generic generator which has an Element equal to T. - parameter retry: a Handler block type, can be used to inspect aggregated error to adjust the next delay and Operation. This defaults to pass through the delay and operation regardless of error info. */ public init<G where G: GeneratorType, G.Element == T>(maxCount max: Int? = 5, strategy: WaitStrategy = .Fixed(0.1), _ generator: G, retry block: Handler = { $1 }) { let delay = MapGenerator(strategy.generator()) { Delay.By($0) } let tuple = TupleGenerator(primary: generator, secondary: delay) retry = RetryGenerator(generator: AnyGenerator(tuple), retry: block) super.init(maxCount: max, generator: AnyGenerator(retry)) name = "Retry Operation <\(T.self)>" } public override func willFinishOperation(operation: NSOperation, withErrors errors: [ErrorType]) { if errors.isEmpty { retry.info = .None } else if let op = operation as? T { retry.info = createFailureInfo(op, errors: errors) addNextOperation() } } internal func createFailureInfo(operation: T, errors: [ErrorType]) -> RetryFailureInfo<T> { return RetryFailureInfo( operation: operation, errors: errors, aggregateErrors: aggregateErrors, count: count, addOperations: addOperations, log: log, configure: configure ) } }
gpl-3.0
84fed19080357062f06b39e15e397179
36.417526
174
0.678468
4.644274
false
false
false
false
TotalDigital/People-iOS
People at Total/FlowLayout.swift
1
1156
// // FlowLayout.swift // People at Total // // Created by Florian Letellier on 05/02/2017. // Copyright © 2017 Florian Letellier. All rights reserved. // import Foundation import UIKit class FlowLayout: UICollectionViewFlowLayout { override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? { let attributesForElementsInRect = super.layoutAttributesForElements(in: rect) var newAttributesForElementsInRect = [UICollectionViewLayoutAttributes]() var leftMargin: CGFloat = 0.0; for attributes in attributesForElementsInRect! { if (attributes.frame.origin.x == self.sectionInset.left) { leftMargin = self.sectionInset.left } else { var newLeftAlignedFrame = attributes.frame newLeftAlignedFrame.origin.x = leftMargin attributes.frame = newLeftAlignedFrame } leftMargin += attributes.frame.size.width + 8 newAttributesForElementsInRect.append(attributes) } return newAttributesForElementsInRect } }
apache-2.0
4cf211f55444194c73f1ce03899ceb6a
31.083333
103
0.657143
5.57971
false
false
false
false
FuckBoilerplate/RxCache
iOS/Pods/ObjectMapper/ObjectMapper/Core/MapError.swift
5
2424
// // MapError.swift // ObjectMapper // // Created by Tristan Himmelman on 2016-09-26. // // The MIT License (MIT) // // Copyright (c) 2014-2016 Hearst // // 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 struct MapError: Error { public var key: String? public var currentValue: Any? public var reason: String? public var file: StaticString? public var function: StaticString? public var line: UInt? init(key: String?, currentValue: Any?, reason: String?, file: StaticString? = nil, function: StaticString? = nil, line: UInt? = nil) { self.key = key self.currentValue = currentValue self.reason = reason self.file = file self.function = function self.line = line } } extension MapError: CustomStringConvertible { private var location: String? { guard let file = file, let function = function, let line = line else { return nil } let fileName = ((String(describing: file).components(separatedBy: "/").last ?? "").components(separatedBy: ".").first ?? "") return "\(fileName).\(function):\(line)" } public var description: String { let info: [(String, Any?)] = [ ("- reason", reason), ("- location", location), ("- key", key), ("- currentValue", currentValue), ] let infoString = info.map { "\($0): \($1 ?? "nil")" }.joined(separator: "\n") return "Got an error while mapping.\n\(infoString)" } }
mit
6abde3e248ad0b8267ff17a7ecb62089
34.647059
135
0.702558
3.928687
false
false
false
false
S-Shimotori/Chalcedony
Chalcedony/Chalcedony/CCDAboutAppViewController.swift
1
927
// // CCDAboutAppViewController.swift // Chalcedony // // Created by S-Shimotori on 6/19/15. // Copyright (c) 2015 S-Shimotori. All rights reserved. // import UIKit class CCDAboutAppViewController: UIViewController { private let pageTitle = "アプリについて" @IBOutlet private weak var textViewAboutApp: UITextView! private let aboutAppText = "AboutApp" private let aboutAppExtension = "txt" override func viewDidLoad() { super.viewDidLoad() navigationItem.title = pageTitle let filePath = NSBundle.mainBundle().pathForResource(aboutAppText, ofType: aboutAppExtension) if let filePath = filePath { let stringFromFile = NSString(contentsOfFile: filePath, encoding: NSUTF8StringEncoding, error: nil) if let stringFromFile = stringFromFile as? String { textViewAboutApp.text = stringFromFile } } } }
mit
57580c66613319b87880cb40ccc8d22d
30.482759
111
0.682366
4.497537
false
false
false
false
apple/swift-driver
Tests/TestUtilities/OutputFileMapCreator.swift
1
2560
//===--------------- OutputFileMapCreator.swift - Swift Testing -----------===// // // 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 TSCBasic import struct Foundation.Data import class Foundation.JSONEncoder public struct OutputFileMapCreator { private let module: String private let inputPaths: [AbsolutePath] private let derivedData: AbsolutePath // The main entry isn't required for some WMO builds private let excludeMainEntry: Bool private init(module: String, inputPaths: [AbsolutePath], derivedData: AbsolutePath, excludeMainEntry: Bool) { self.module = module self.inputPaths = inputPaths self.derivedData = derivedData self.excludeMainEntry = excludeMainEntry } public static func write(module: String, inputPaths: [AbsolutePath], derivedData: AbsolutePath, to dst: AbsolutePath, excludeMainEntry: Bool = false) { let creator = Self(module: module, inputPaths: inputPaths, derivedData: derivedData, excludeMainEntry: excludeMainEntry) try! localFileSystem.writeIfChanged(path: dst, bytes: ByteString(creator.generateData())) } private func generateDict() -> [String: [String: String]] { let master = ["swift-dependencies": derivedData.appending(component: "\(module)-master.swiftdeps").nativePathString(escaped: false)] let mainEntryDict = self.excludeMainEntry ? [:] : ["": master] func baseNameEntry(_ s: AbsolutePath) -> [String: String] { [ "dependencies": ".d", "diagnostics": ".dia", "llvm-bc": ".bc", "object": ".o", "swift-dependencies": ".swiftdeps", "swiftmodule": "-partial.swiftmodule" ] .mapValues {"\(derivedData.appending(component: s.basenameWithoutExt))\($0)"} } return Dictionary(uniqueKeysWithValues: inputPaths.map { ("\($0)", baseNameEntry($0)) } ) .merging(mainEntryDict) {_, _ in fatalError()} } private func generateData() -> Data { let d: [String: [String: String]] = generateDict() let enc = JSONEncoder() return try! enc.encode(d) } }
apache-2.0
32817e13ccfa138589cc82c2b1451562
37.208955
136
0.634375
4.629295
false
false
false
false
blockchain/My-Wallet-V3-iOS
Modules/CryptoAssets/Sources/StellarKit/Models/Accounts/StellarWalletAccount.swift
1
1212
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import PlatformKit public struct StellarWalletAccount: WalletAccount, Equatable, Codable { public var index: Int public var publicKey: String public var label: String? public var archived: Bool public init(index: Int, publicKey: String, label: String? = nil, archived: Bool = false) { self.index = index self.publicKey = publicKey self.label = label self.archived = archived } enum CodingKeys: String, CodingKey { case index case publicKey case label case archived } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) publicKey = try values.decode(String.self, forKey: .publicKey) label = try values.decodeIfPresent(String.self, forKey: .label) archived = try values.decode(Bool.self, forKey: .archived) index = 0 } public func encode(to encoder: Encoder) throws { var container = encoder.unkeyedContainer() try container.encode(publicKey) try container.encode(label) try container.encode(archived) } }
lgpl-3.0
0e418ca5f2d8d208015c64e27ddc529b
29.275
94
0.657308
4.604563
false
false
false
false
chicio/HackerRank
30DaysOfCode/Day17MoreExceptions.swift
1
1153
// // Day17MoreExceptions.swift // HackerRank // // Created by Fabrizio Duroni on 05/10/2016. // // https://www.hackerrank.com/challenges/30-more-exceptions import Darwin // Defining enum for throwing error // throw RangeError.NotInRange... is used to throw the error enum RangeError : Error { case NotInRange(String) } // Start of class Calculator class Calculator { // Start of function power func power(n: Int, p: Int) throws -> Int { guard n >= 0 && p >= 0 else { throw RangeError.NotInRange("n and p should be non-negative") } return Int(powf(Float(n), Float(p))) } } let myCalculator = Calculator() var t = Int(readLine()!)! while t > 0 { let np = readLine()!.characters.split(separator: " ", maxSplits: Int.max, omittingEmptySubsequences: true).map(String.init) do { let ans = try myCalculator.power(n: Int(np[0])!, p: Int(np[1])!) print(ans) } catch RangeError.NotInRange(let errorMsg) { print(errorMsg) } t = t - 1 }
mit
7d495758940aa98fa2e023bebf45d059
23.020833
91
0.565481
3.908475
false
false
false
false