repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
olkakusiak/SearchInGitHub | refs/heads/master | SearchInGitHub/RepoDetailsViewController.swift | mit | 1 | //
// RepoDetailsViewController.swift
// SearchInGitHub
//
// Created by Aleksandra Kusiak on 27.11.2016.
// Copyright © 2016 ola. All rights reserved.
//
import UIKit
class RepoDetailsViewController: UIViewController {
@IBOutlet weak var userAvatar: UIImageView!
@IBOutlet weak var userDetailsContainer: UIView!
@IBOutlet weak var fullNameLabel: UILabel!
@IBOutlet weak var languageLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var numberOfStarsLabel: UILabel!
@IBOutlet weak var numberOfForksLabel: UILabel!
@IBOutlet weak var numberOfIssuesLabel: UILabel!
@IBOutlet weak var numberOfWatchersLabel: UILabel!
@IBOutlet weak var starsLabel: UILabel!
@IBOutlet weak var forksLabel: UILabel!
@IBOutlet weak var issuesLabel: UILabel!
@IBOutlet weak var watchersLabel: UILabel!
var singleRepo: SingleRepoData?
var userLogin: String?
var repoName: String?
override func viewDidLoad() {
super.viewDidLoad()
setupView()
DataManager.instance.getSingleRepo(userLogin: userLogin!, repoName: repoName!, repoDownloaded: {repo in
self.singleRepo = repo
self.reloadLabels()
}, error: {error in
print("error with getting single repo")
})
}
func setupView(){
userDetailsContainer.backgroundColor = UIColor.forkMidnightBlue
userAvatar.layer.cornerRadius = 10.0
userAvatar.clipsToBounds = true
userAvatar.layer.borderWidth = 1
userAvatar.layer.borderColor = UIColor.cloudsGrey.cgColor
fullNameLabel.textColor = UIColor.cloudsGrey
languageLabel.textColor = UIColor.cloudsGrey
descriptionLabel.textColor = UIColor.cloudsGrey
starsLabel.textColor = UIColor.forkMidnightBlue
numberOfStarsLabel.textColor = UIColor.forkMidnightBlue
forksLabel.textColor = UIColor.forkMidnightBlue
numberOfForksLabel.textColor = UIColor.forkMidnightBlue
issuesLabel.textColor = UIColor.forkMidnightBlue
numberOfIssuesLabel.textColor = UIColor.forkMidnightBlue
watchersLabel.textColor = UIColor.forkMidnightBlue
numberOfWatchersLabel.textColor = UIColor.forkMidnightBlue
userAvatar.image = #imageLiteral(resourceName: "placeholder")
fullNameLabel.text = ""
languageLabel.text = ""
descriptionLabel.text = ""
numberOfStarsLabel.text = ""
numberOfForksLabel.text = ""
numberOfIssuesLabel.text = ""
numberOfWatchersLabel.text = ""
}
func reloadLabels(){
if let repo = singleRepo{
userAvatar.sd_setImage(with: URL(string: repo.avatarURL), placeholderImage: #imageLiteral(resourceName: "placeholder"))
fullNameLabel.text = repo.fullName
languageLabel.text = "language: \(repo.language)"
descriptionLabel.text = repo.description
numberOfStarsLabel.text = "\(repo.stars)"
numberOfForksLabel.text = "\(repo.forks)"
numberOfIssuesLabel.text = "\(repo.issues)"
numberOfWatchersLabel.text = "\(repo.watchers)"
}
}
}
| efba17af85b47613feae443048d07ceb | 31.689655 | 122 | 0.768284 | false | false | false | false |
Hendrik44/pi-weather-app | refs/heads/master | Carthage/Checkouts/Charts/ChartsDemo-macOS/ChartsDemo-macOS/Demos/BarDemoViewController.swift | apache-2.0 | 5 | //
// BarDemoViewController.swift
// ChartsDemo-OSX
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
import Foundation
import Cocoa
import Charts
open class BarDemoViewController: NSViewController
{
@IBOutlet var barChartView: BarChartView!
override open func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
let xArray = Array(1..<10)
let ys1 = xArray.map { x in return sin(Double(x) / 2.0 / 3.141 * 1.5) }
let ys2 = xArray.map { x in return cos(Double(x) / 2.0 / 3.141) }
let yse1 = ys1.enumerated().map { x, y in return BarChartDataEntry(x: Double(x), y: y) }
let yse2 = ys2.enumerated().map { x, y in return BarChartDataEntry(x: Double(x), y: y) }
let data = BarChartData()
let ds1 = BarChartDataSet(entries: yse1, label: "Hello")
ds1.colors = [NSUIColor.red]
data.addDataSet(ds1)
let ds2 = BarChartDataSet(entries: yse2, label: "World")
ds2.colors = [NSUIColor.blue]
data.addDataSet(ds2)
let barWidth = 0.4
let barSpace = 0.05
let groupSpace = 0.1
data.barWidth = barWidth
self.barChartView.xAxis.axisMinimum = Double(xArray[0])
self.barChartView.xAxis.axisMaximum = Double(xArray[0]) + data.groupWidth(groupSpace: groupSpace, barSpace: barSpace) * Double(xArray.count)
// (0.4 + 0.05) * 2 (data set count) + 0.1 = 1
data.groupBars(fromX: Double(xArray[0]), groupSpace: groupSpace, barSpace: barSpace)
self.barChartView.data = data
self.barChartView.gridBackgroundColor = NSUIColor.white
self.barChartView.chartDescription?.text = "Barchart Demo"
}
@IBAction func save(_ sender: Any)
{
let panel = NSSavePanel()
panel.allowedFileTypes = ["png"]
panel.beginSheetModal(for: self.view.window!) { (result) -> Void in
if result.rawValue == NSFileHandlingPanelOKButton
{
if let path = panel.url?.path
{
let _ = self.barChartView.save(to: path, format: .png, compressionQuality: 1.0)
}
}
}
}
override open func viewWillAppear()
{
self.barChartView.animate(xAxisDuration: 1.0, yAxisDuration: 1.0)
}
}
| ef07361795da98ba843c49a60f03e9a8 | 32.276316 | 148 | 0.601423 | false | false | false | false |
Mattmlm/codepath-twitter-redux | refs/heads/master | Codepath Twitter/Codepath Twitter/ComposeTweetViewController.swift | mit | 1 | //
// ComposeTweetViewController.swift
// Codepath Twitter
//
// Created by admin on 10/4/15.
// Copyright © 2015 mattmo. All rights reserved.
//
import UIKit
class ComposeTweetViewController: UIViewController {
@IBOutlet weak var tweetField: UITextField!
var replyToTweet: Tweet?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white]
self.navigationController?.navigationBar.barTintColor = UIColor(rgba: "#55ACEE");
self.navigationController?.navigationBar.isTranslucent = false;
self.navigationController?.navigationBar.tintColor = UIColor.white;
if replyToTweet != nil {
self.tweetField.text = "@\((replyToTweet!.user?.screenname)!) "
}
self.tweetField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func onCancelButtonPressed(sender: Any) {
dismiss(animated: true, completion: nil);
}
@IBAction func onTweetButtonPressed(sender: Any) {
// let dict = NSMutableDictionary()
// dict["status"] = tweetField.text!
// if replyToTweet != nil {
// dict["in_reply_to_status_id"] = replyToTweet!.idString!
// }
// TwitterClient.sharedInstance.composeTweetWithCompletion(dict) { (tweet, error) -> () in
// dispatch_async(dispatch_get_main_queue(), { () -> Void in
// self.dismiss(animated:true, completion: nil);
// })
// }
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 855779ccb3fa44b882a71c6afa34353d | 30.75 | 125 | 0.645206 | false | false | false | false |
jhurray/SQLiteModel-Example-Project | refs/heads/master | OSX+SQLiteModel/Pods/SQLiteModel/SQLiteModel/RelationshipModel.swift | mit | 3 | //
// SQLiteRelationshipModel.swift
// SQLiteModel
//
// Created by Jeff Hurray on 3/15/16.
// Copyright © 2016 jhurray. All rights reserved.
//
import Foundation
import SQLite
struct RelationshipColumns {
static let LeftID = Expression<SQLiteModelID>("left_id")
static let RightID = Expression<SQLiteModelID>("right_id")
}
internal protocol RelationshipModel : SQLiteModel {
associatedtype LeftModel: SQLiteModel
associatedtype RightModel: SQLiteModel
static func initialize() -> Void
static func removeLeft(leftID: SQLiteModelID) -> Void
static func removeRight(rightID: SQLiteModelID) -> Void
static func removeMultipleRight(rightIDs: [SQLiteModelID]) -> Void
static var unique: Bool {get}
}
extension RelationshipModel {
internal static var tableName: String {
let leftName = String(LeftModel).lowercaseString
let rightName = String(RightModel).lowercaseString
let addition = RelationshipReferenceTracker.currentTemplate((LeftModel.self, RightModel.self))
return "\(leftName)_rel_map_\(rightName)_\(addition)"
}
static var unique: Bool {
return false
}
final static func removeLeft(leftID: SQLiteModelID) -> Void {
let query = self.table.filter(RelationshipColumns.LeftID == leftID)
let _ = try? self.delete(query)
}
static func removeRight(rightID: SQLiteModelID) -> Void {
let query = self.table.filter(RelationshipColumns.RightID == rightID)
let _ = try? self.delete(query)
}
static func removeMultipleRight(rightIDs: [SQLiteModelID]) -> Void {
let query = self.table.filter(rightIDs.contains(RelationshipColumns.RightID))
let _ = try? self.delete(query)
}
private static func finishBuildTable(tableBuilder: TableBuilder) -> Void {
tableBuilder.unique([RelationshipColumns.LeftID, RelationshipColumns.RightID])
tableBuilder.foreignKey(RelationshipColumns.LeftID, references: LeftModel.table, LeftModel.localIDExpression, delete: TableBuilder.Dependency.Cascade)
tableBuilder.foreignKey(RelationshipColumns.RightID, references: RightModel.table, RightModel.localIDExpression, delete: TableBuilder.Dependency.Cascade)
}
}
protocol SingularRelationshipModel : RelationshipModel {
static func getRelationship(leftID: SQLiteModelID) -> RightModel?
static func setRelationship(left: LeftModel, right: RightModel)
}
extension SingularRelationshipModel {
static func getRelationship(leftID: SQLiteModelID) -> RightModel? {
guard let rightID = Meta.queryCachedValueForSingularRelationship(self, queryColumn: RelationshipColumns.LeftID, queryValue: leftID, returnColumn: RelationshipColumns.RightID) else {
if let result = try? self.fetch(self.table.filter(RelationshipColumns.LeftID == leftID)) where result.count == 1 {
guard let rightID = result.first?.get(RelationshipColumns.RightID),
let instance = try? RightModel.find(rightID)
else {
return nil
}
return instance
}
else {
return nil
}
}
return RightModel(localID: rightID)
}
final static func setRelationship(left: LeftModel, right: RightModel) {
if Meta.hasLocalInstanceContextForSingularRelationhip(self, leftID: left.localID) {
let setters = [
RelationshipColumns.RightID <- right.localID,
]
let query = self.query.filter(RelationshipColumns.LeftID == left.localID)
try! self.update(query, setters: setters)
}
else {
self.removeLeft(left.localID)
if self.unique {
self.removeRight(right.localID)
}
let setters = [
RelationshipColumns.LeftID <- left.localID,
RelationshipColumns.RightID <- right.localID,
]
let _ = try! self.new(setters)
}
}
static func initialize() -> Void {
let _ = try? self.createTable()
let _ = try? self.createIndex([RelationshipColumns.LeftID], unique: true)
}
}
internal struct SingularRelationship<Left : SQLiteModel, Right : SQLiteModel> : SingularRelationshipModel {
typealias LeftModel = Left
typealias RightModel = Right
var localID: SQLiteModelID = -1
static func buildTable(tableBuilder: TableBuilder) {
tableBuilder.column(RelationshipColumns.LeftID, unique: true)
tableBuilder.column(RelationshipColumns.RightID)
self.finishBuildTable(tableBuilder)
}
}
internal struct UniqueSingularRelationship<Left : SQLiteModel, Right : SQLiteModel> : SingularRelationshipModel {
typealias LeftModel = Left
typealias RightModel = Right
var localID: SQLiteModelID = -1
static var unique: Bool {
return true
}
static func buildTable(tableBuilder: TableBuilder) {
tableBuilder.column(RelationshipColumns.LeftID, unique: true)
tableBuilder.column(RelationshipColumns.RightID, unique: true)
self.finishBuildTable(tableBuilder)
}
}
protocol MultipleRelationshipModel : RelationshipModel {
static func getRelationship(leftID: SQLiteModelID) -> [RightModel]
static func setRelationship(left: LeftModel, right: [RightModel])
}
extension MultipleRelationshipModel {
static func getRelationship(leftID: SQLiteModelID) -> [RightModel] {
let rightIDs = Meta.queryCachedValueForRelationship(self, queryColumn: RelationshipColumns.LeftID, queryValue: leftID, returnColumn: RelationshipColumns.RightID)
if rightIDs.count == 0 { // No values have been cached thus far
let mapQuery = self.table.filter(RelationshipColumns.LeftID == leftID)
guard let fetchedMapping = try? self.fetch(mapQuery) else {
return []
}
let rightIDs = fetchedMapping.map({ $0.get(RelationshipColumns.RightID) })
let instanceQuery = RightModel.query.filter(rightIDs.contains(RightModel.localIDExpression))
guard let fetchedInstances = try? RightModel.fetch(instanceQuery) else {
return []
}
return fetchedInstances
}
else {
let cachedIDsSplit = Meta.queryCachedInstanceIDsFor(RightModel.self, hashes: rightIDs.sort{ $0 < $1})
var instances: [RightModel] = cachedIDsSplit.0.map { RightModel(localID: $0) }
if cachedIDsSplit.1.count > 0 {
let query = RightModel.table.filter(cachedIDsSplit.1.contains(RightModel.localIDExpression))
guard let fetchedInstances = try? RightModel.fetch(query) else {
return instances
}
instances += fetchedInstances
}
return instances
}
}
static func setRelationship(left: LeftModel, right: [RightModel]) {
self.removeLeft(left.localID)
if self.unique {
self.removeMultipleRight(right.map({ $0.localID }))
}
guard right.count > 0 else {
return
}
let now = NSDate()
let dateString = dateFormatter.stringFromDate(now)
var statement = "INSERT INTO \(self.tableName) (left_id, right_id, sqlmdl_localCreatedAt, sqlmdl_localUpdatedAt) VALUES"
for rightID in right.map({ $0.localID }) {
statement += " (\(left.localID), \(rightID), '\(dateString)', '\(dateString)'),"
}
statement.removeAtIndex(statement.characters.endIndex.predecessor())
statement += ";"
let _ = try? self.connect(error: SQLiteModelError.InsertError, connectionBlock: { connection in
try connection.execute(statement)
let query = self.query.filter(RelationshipColumns.LeftID == left.localID)
for row in try connection.prepare(query) {
Meta.createLocalInstanceContextFor(self, row: row)
}
})
}
static func initialize() -> Void {
let _ = try? self.createTable()
let _ = try? self.createIndex([RelationshipColumns.LeftID], unique: false)
}
}
internal struct MultipleRelationship<Left : SQLiteModel, Right : SQLiteModel> : MultipleRelationshipModel {
typealias LeftModel = Left
typealias RightModel = Right
var localID: SQLiteModelID = -1
static func buildTable(tableBuilder: TableBuilder) {
tableBuilder.column(RelationshipColumns.LeftID)
tableBuilder.column(RelationshipColumns.RightID)
self.finishBuildTable(tableBuilder)
}
static func initialize() {
let _ = try? self.createTable()
let _ = try? self.createIndex([RelationshipColumns.LeftID], unique: false)
}
}
internal struct UniqueMultipleRelationship<Left : SQLiteModel, Right : SQLiteModel> : MultipleRelationshipModel {
typealias LeftModel = Left
typealias RightModel = Right
var localID: SQLiteModelID = -1
static var unique: Bool {
return true
}
static func buildTable(tableBuilder: TableBuilder) {
tableBuilder.column(RelationshipColumns.LeftID)
tableBuilder.column(RelationshipColumns.RightID, unique: true)
self.finishBuildTable(tableBuilder)
}
static func initialize() {
let _ = try? self.createTable()
let _ = try? self.createIndex([RelationshipColumns.LeftID], unique: false)
}
}
| 3b041cd7e7891d4079ab43d4ee864995 | 36.449612 | 189 | 0.65297 | false | false | false | false |
slavapestov/swift | refs/heads/master | test/expr/closure/closures.swift | apache-2.0 | 1 | // RUN: %target-parse-verify-swift
var func6 : (fn : (Int,Int) -> Int) -> ()
var func6a : ((Int, Int) -> Int) -> ()
var func6b : (Int, (Int, Int) -> Int) -> ()
func func6c(f: (Int, Int) -> Int, _ n: Int = 0) {} // expected-warning{{prior to parameters}}
// Expressions can be auto-closurified, so that they can be evaluated separately
// from their definition.
var closure1 : () -> Int = {4} // Function producing 4 whenever it is called.
var closure2 : (Int,Int) -> Int = { 4 } // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{36-36= _,_ in}}
var closure3a : () -> () -> (Int,Int) = {{ (4, 2) }} // multi-level closing.
var closure3b : (Int,Int) -> (Int) -> (Int,Int) = {{ (4, 2) }} // expected-error{{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{52-52=_,_ in }}
var closure4 : (Int,Int) -> Int = { $0 + $1 }
var closure5 : (Double) -> Int = {
$0 + 1.0 // expected-error {{cannot convert value of type 'Double' to expected argument type 'Int'}}
}
var closure6 = $0 // expected-error {{anonymous closure argument not contained in a closure}}
var closure7 : Int =
{ 4 } // expected-error {{function produces expected type 'Int'; did you mean to call it with '()'?}} {{9-9=()}}
func funcdecl1(a: Int, _ y: Int) {}
func funcdecl3() -> Int {}
func funcdecl4(a: ((Int) -> Int), _ b: Int) {}
func funcdecl5(a: Int, _ y: Int) {
// Pass in a closure containing the call to funcdecl3.
funcdecl4({ funcdecl3() }, 12) // expected-error {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{14-14= _ in}}
func6(fn: {$0 + $1}) // Closure with two named anonymous arguments
func6(fn: {($0) + $1}) // Closure with sequence expr inferred type
func6(fn: {($0) + $0}) // expected-error{{cannot convert value of type '(Int, Int)' to expected argument type 'Int'}}
var testfunc : ((), Int) -> Int
testfunc({$0+1}) // expected-error {{missing argument for parameter #2 in call}}
funcdecl5(1, 2) // recursion.
// Element access from a tuple.
var a : (Int, f : Int, Int)
var b = a.1+a.f
// Tuple expressions with named elements.
var i : (y : Int, x : Int) = (x : 42, y : 11)
funcdecl1(123, 444)
// Calls.
4() // expected-error {{invalid use of '()' to call a value of non-function type 'Int'}} {{4-6=}}
// rdar://12017658 - Infer some argument types from func6.
func6(fn: { a, b -> Int in a+b})
// Return type inference.
func6(fn: { a,b in a+b })
// Infer incompatible type.
func6(fn: {a,b -> Float in 4.0 }) // expected-error {{declared closure result 'Float' is incompatible with contextual type 'Int'}} {{21-26=Int}} // Pattern doesn't need to name arguments.
func6(fn: { _,_ in 4 })
func6(fn: {a,b in 4.0 }) // expected-error {{cannot convert value of type 'Double' to closure result type 'Int'}}
// TODO: This diagnostic can be improved: rdar://22128205
func6(fn: {(a : Float, b) in 4 }) // expected-error {{cannot convert value of type '(Float, _) -> Int' to expected argument type '(Int, Int) -> Int'}}
var fn = {}
var fn2 = { 4 }
var c : Int = { a,b -> Int in a+b} // expected-error{{cannot convert value of type '(Int, Int) -> Int' to specified type 'Int'}}
}
func unlabeledClosureArgument() {
func add(x: Int, y: Int) -> Int { return x + y }
func6a({$0 + $1}) // single closure argument
func6a(add)
func6b(1, {$0 + $1}) // second arg is closure
func6b(1, add)
func6c({$0 + $1}) // second arg is default int
func6c(add)
}
// rdar://11935352 - closure with no body.
func closure_no_body(p: () -> ()) {
return closure_no_body({})
}
// rdar://12019415
func t() {
let u8 : UInt8 = 1
let x : Bool = true
if 0xA0..<0xBF ~= Int(u8) && x {
}
}
// <rdar://problem/11927184>
func f0(a: Any) -> Int { return 1 }
assert(f0(1) == 1)
var selfRef = { selfRef() } // expected-error {{variable used within its own initial value}}
var nestedSelfRef = {
var recursive = { nestedSelfRef() } // expected-error {{variable used within its own initial value}}
recursive()
}
var shadowed = { (shadowed: Int) -> Int in
let x = shadowed
return x
} // no-warning
var shadowedShort = { (shadowedShort: Int) -> Int in shadowedShort+1 } // no-warning
func anonymousClosureArgsInClosureWithArgs() {
var a1 = { () in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a2 = { () -> Int in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
var a3 = { (z: Int) in $0 } // expected-error {{anonymous closure arguments cannot be used inside a closure that has explicit arguments}}
}
func doStuff(fn : () -> Int) {}
func doVoidStuff(fn : () -> ()) {}
// <rdar://problem/16193162> Require specifying self for locations in code where strong reference cycles are likely
class ExplicitSelfRequiredTest {
var x = 42
func method() -> Int {
// explicit closure requires an explicit "self." base.
doVoidStuff({ self.x += 1 })
doStuff({ x+1 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{15-15=self.}}
doVoidStuff({ x += 1 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{19-19=self.}}
// Methods follow the same rules as properties, uses of 'self' must be marked with "self."
doStuff { method() } // expected-error {{call to method 'method' in closure requires explicit 'self.' to make capture semantics explicit}} {{15-15=self.}}
doVoidStuff { method() } // expected-error {{call to method 'method' in closure requires explicit 'self.' to make capture semantics explicit}} {{19-19=self.}}
doStuff { self.method() }
// <rdar://problem/18877391> "self." shouldn't be required in the initializer expression in a capture list
// This should not produce an error, "x" isn't being captured by the closure.
doStuff({ [myX = x] in myX })
// This should produce an error, since x is used within the inner closure.
doStuff({ [myX = {x}] in 4 }) // expected-error {{reference to property 'x' in closure requires explicit 'self.' to make capture semantics explicit}} {{23-23=self.}}
// expected-warning @-1 {{capture 'myX' was never used}}
return 42
}
}
class SomeClass {
var field : SomeClass?
func foo() -> Int {}
}
func testCaptureBehavior(ptr : SomeClass) {
// Test normal captures.
weak var wv : SomeClass? = ptr
unowned let uv : SomeClass = ptr
unowned(unsafe) let uv1 : SomeClass = ptr
unowned(safe) let uv2 : SomeClass = ptr
doStuff { wv!.foo() }
doStuff { uv.foo() }
doStuff { uv1.foo() }
doStuff { uv2.foo() }
// Capture list tests
let v1 : SomeClass? = ptr
let v2 : SomeClass = ptr
doStuff { [weak v1] in v1!.foo() }
// expected-warning @+2 {{variable 'v1' was written to, but never read}}
doStuff { [weak v1, // expected-note {{previous}}
weak v1] in v1!.foo() } // expected-error {{definition conflicts with previous value}}
doStuff { [unowned v2] in v2.foo() }
doStuff { [unowned(unsafe) v2] in v2.foo() }
doStuff { [unowned(safe) v2] in v2.foo() }
doStuff { [weak v1, weak v2] in v1!.foo() + v2!.foo() }
let i = 42
// expected-warning @+1 {{variable 'i' was never mutated}} {{19-20=let}}
doStuff { [weak i] in i! } // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}}
}
extension SomeClass {
func bar() {
doStuff { [unowned self] in self.foo() }
doStuff { [unowned xyz = self.field!] in xyz.foo() }
doStuff { [weak xyz = self.field] in xyz!.foo() }
// rdar://16889886 - Assert when trying to weak capture a property of self in a lazy closure
doStuff { [weak self.field] in field!.foo() } // expected-error {{fields may only be captured by assigning to a specific name}} expected-error {{reference to property 'field' in closure requires explicit 'self.' to make capture semantics explicit}} {{36-36=self.}}
// expected-warning @+1 {{variable 'self' was written to, but never read}}
doStuff { [weak self&field] in 42 } // expected-error {{expected ']' at end of capture list}}
}
func strong_in_capture_list() {
// <rdar://problem/18819742> QOI: "[strong self]" in capture list generates unhelpful error message
_ = {[strong self] () -> () in return } // expected-error {{expected 'weak', 'unowned', or no specifier in capture list}}
}
}
// <rdar://problem/16955318> Observed variable in a closure triggers an assertion
var closureWithObservedProperty: () -> () = {
var a: Int = 42 {
willSet {
_ = "Will set a to \(newValue)"
}
didSet {
_ = "Did set a with old value of \(oldValue)"
}
}
}
;
{}() // expected-error{{statement cannot begin with a closure expression}} expected-note{{explicitly discard the result of the closure by assigning to '_'}} {{1-1=_ = }}
// rdar://19179412 - Crash on valid code.
func rdar19179412() -> Int -> Int {
return { x in
class A {
let d : Int = 0
}
}
}
// Test coercion of single-expression closure return types to void.
func takesVoidFunc(f: () -> ()) {}
var i: Int = 1
takesVoidFunc({i})
var f1: () -> () = {i}
var x = {return $0}(1)
func returnsInt() -> Int { return 0 }
takesVoidFunc(returnsInt) // expected-error {{cannot convert value of type '() -> Int' to expected argument type '() -> ()'}}
takesVoidFunc({() -> Int in 0}) // expected-error {{declared closure result 'Int' is incompatible with contextual type '()'}} {{22-25=()}}
// These used to crash the compiler, but were fixed to support the implementation of rdar://problem/17228969
Void(0) // expected-error{{argument passed to call that takes no arguments}}
_ = {0}
// <rdar://problem/22086634> "multi-statement closures require an explicit return type" should be an error not a note
let samples = { // expected-error {{type of expression is ambiguous without more context}}
// FIXME: This diagnostic should be improved, we can infer a type for the closure expr from
// its body (by trying really hard in diagnostic generation) and say that we need an explicit
// contextual result specified because we don't do cross-statement type inference or something.
if (i > 10) { return true }
else { return false }
}()
// <rdar://problem/19756953> Swift error: cannot capture '$0' before it is declared
func f(fp : (Bool, Bool) -> Bool) {}
f { $0 && !$1 }
// <rdar://problem/18123596> unexpected error on self. capture inside class method
func TakesIntReturnsVoid(fp : (Int -> ())) {}
struct TestStructWithStaticMethod {
static func myClassMethod(count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
class TestClassWithStaticMethod {
class func myClassMethod(count: Int) {
// Shouldn't require "self."
TakesIntReturnsVoid { _ in myClassMethod(0) }
}
}
// Test that we can infer () as the result type of these closures.
func genericOne<T>(a: () -> T) {}
func genericTwo<T>(a: () -> T, _ b: () -> T) {}
genericOne {}
genericTwo({}, {})
// <rdar://problem/22344208> QoI: Warning for unused capture list variable should be customized
class r22344208 {
func f() {
let q = 42
let _: () -> Int = {
[unowned self, // expected-warning {{capture 'self' was never used}}
q] in // expected-warning {{capture 'q' was never used}}
1 }
}
}
var f = { (s: Undeclared) -> Int in 0 } // expected-error {{use of undeclared type 'Undeclared'}}
// <rdar://problem/21375863> Swift compiler crashes when using closure, declared to return illegal type.
func r21375863() {
var width = 0
var height = 0
var bufs: [[UInt8]] = (0..<4).map { _ -> [asdf] in // expected-error {{use of undeclared type 'asdf'}}
[UInt8](count: width*height, repeatedValue: 0)
}
}
| 49dbdfe2bb035636538759213662911a | 37.198738 | 270 | 0.639937 | false | false | false | false |
IAskWind/IAWExtensionTool | refs/heads/master | Demo/roadtrip/Pods/Kingfisher/Sources/Cache/Storage.swift | mit | 4 | //
// Storage.swift
// Kingfisher
//
// Created by Wei Wang on 2018/10/15.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
/// Constants for some time intervals
struct TimeConstants {
static let secondsInOneMinute = 60
static let minutesInOneHour = 60
static let hoursInOneDay = 24
static let secondsInOneDay = 86_400
}
/// Represents the expiration strategy used in storage.
///
/// - never: The item never expires.
/// - seconds: The item expires after a time duration of given seconds from now.
/// - days: The item expires after a time duration of given days from now.
/// - date: The item expires after a given date.
public enum StorageExpiration {
/// The item never expires.
case never
/// The item expires after a time duration of given seconds from now.
case seconds(TimeInterval)
/// The item expires after a time duration of given days from now.
case days(Int)
/// The item expires after a given date.
case date(Date)
/// Indicates the item is already expired. Use this to skip cache.
case expired
func estimatedExpirationSince(_ date: Date) -> Date {
switch self {
case .never: return .distantFuture
case .seconds(let seconds):
return date.addingTimeInterval(seconds)
case .days(let days):
let duration = TimeInterval(TimeConstants.secondsInOneDay) * TimeInterval(days)
return date.addingTimeInterval(duration)
case .date(let ref):
return ref
case .expired:
return .distantPast
}
}
var estimatedExpirationSinceNow: Date {
return estimatedExpirationSince(Date())
}
var isExpired: Bool {
return timeInterval <= 0
}
var timeInterval: TimeInterval {
switch self {
case .never: return .infinity
case .seconds(let seconds): return seconds
case .days(let days): return TimeInterval(TimeConstants.secondsInOneDay) * TimeInterval(days)
case .date(let ref): return ref.timeIntervalSinceNow
case .expired: return -(.infinity)
}
}
}
/// Represents the expiration extending strategy used in storage to after access.
///
/// - none: The item expires after the original time, without extending after access.
/// - cacheTime: The item expiration extends by the original cache time after each access.
/// - expirationTime: The item expiration extends by the provided time after each access.
public enum ExpirationExtending {
/// The item expires after the original time, without extending after access.
case none
/// The item expiration extends by the original cache time after each access.
case cacheTime
/// The item expiration extends by the provided time after each access.
case expirationTime(_ expiration: StorageExpiration)
}
/// Represents types which cost in memory can be calculated.
public protocol CacheCostCalculable {
var cacheCost: Int { get }
}
/// Represents types which can be converted to and from data.
public protocol DataTransformable {
func toData() throws -> Data
static func fromData(_ data: Data) throws -> Self
static var empty: Self { get }
}
| 5dc11266022562d3a52977b624d3eab4 | 37.212389 | 101 | 0.70264 | false | false | false | false |
fireunit/login | refs/heads/master | login/login.playground/Pages/password.xcplaygroundpage/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
import XCPlayground
import Material
struct Devices {
let iPhoneSE = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 568))
let iPhone6 = UIView(frame: CGRect(x: 0, y: 0, width: 375, height: 667))
let iPhone6Plus = UIView(frame: CGRect(x: 375, y: 0, width: 414, height: 736))
}
/// Live View
var iPhone6 = Devices().iPhone6
iPhone6.backgroundColor = MaterialColor.white
let view = UIView(frame: iPhone6.frame)
XCPlaygroundPage.currentPage.liveView = view
view.addSubview(iPhone6)
let size = CGFloat(40)
let margin = CGFloat(16)
let buttonSize = CGFloat(64)
let largeMargin = 96
// TextField
let textField: TextField = TextField()
textField.placeholder = "Password"
textField.font = RobotoFont.regularWithSize(16)
textField.textColor = MaterialColor.black
let clearButton: FlatButton = FlatButton()
clearButton.pulseColor = MaterialColor.grey.base
clearButton.tintColor = MaterialColor.grey.base
view.addSubview(textField)
let submitButton: RaisedButton = RaisedButton(frame: CGRectMake(107, 207, 100, 35))
submitButton.setTitle("Login", forState: .Normal)
submitButton.titleLabel!.font = RobotoFont.mediumWithSize(14)
submitButton.backgroundColor = MaterialColor.cyan.darken2
submitButton.pulseColor = MaterialColor.white
view.addSubview(submitButton)
textField.translatesAutoresizingMaskIntoConstraints = false
MaterialLayout.size(view, child: textField, width: view.frame.width - margin * 2, height: 25)
MaterialLayout.alignFromTopLeft(view, child: textField, top:160 , left: margin)
| 2b512a01fd163965bc0531ea25781463 | 31.875 | 93 | 0.775665 | false | false | false | false |
MartinOSix/DemoKit | refs/heads/master | dSwift/SwiftDemoKit/SwiftDemoKit/CollectionViewAnimationCell.swift | apache-2.0 | 1 | //
// CollectionViewAnimationCell.swift
// SwiftDemoKit
//
// Created by runo on 17/5/5.
// Copyright © 2017年 com.runo. All rights reserved.
//
import UIKit
class CollectionViewAnimationCell: UICollectionViewCell {
let imageV = UIImageView(frame: CGRect(x: 0, y: 0, width: kScreenWidth-20, height: 100))
let textV = UITextView(frame: CGRect(x: 0, y: 110, width: kScreenWidth-20, height: 30))
let backBtn = UIButton(frame: CGRect(x: 10, y: 10, width: 40, height: 40))
var backBtnClickBlock: (()->())?
override init(frame: CGRect) {
super.init(frame: frame)
imageV.contentMode = .center
imageV.clipsToBounds = true
textV.font = UIFont.systemFont(ofSize: 14)
textV.isUserInteractionEnabled = false
backBtn.setImage(#imageLiteral(resourceName: "Back-icon"), for: .normal)
backBtn.isHidden = true
backBtn.addTarget(self, action: #selector(backBtnClick), for: .touchUpInside)
backgroundColor = UIColor.gray
addSubview(imageV)
addSubview(textV)
addSubview(backBtn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func handleCellSelected() {
backBtn.isHidden = false
superview?.bringSubview(toFront: self)
}
func backBtnClick() {
backBtn.isHidden = true
backBtnClickBlock!()
}
func preparaCell(model : CellModel) {
imageV.frame = CGRect(x: 0, y: 0, width: kScreenWidth-20, height: 100)
textV.frame = CGRect(x: 0, y: 110, width: kScreenWidth-20, height: 30)
imageV.image = model.img
textV.text = model.title
}
}
| ab736b684a0a9409074957c59d06743f | 22.613333 | 92 | 0.614342 | false | false | false | false |
marta-rodriguez/swift-learning | refs/heads/master | FlickrSearch-Starter/FlickrSearch/MasterViewController.swift | mit | 1 | /*
* Copyright (c) 2014 Razeware LLC
*
* 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 MasterViewController: UIViewController {
@IBOutlet var tableView: UITableView!
@IBOutlet var searchBar: UISearchBar!
var searches = OrderedDictionary<String, [Flickr.Photo]>()
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow {
let (_, photos) = self.searches[indexPath.row]
(segue.destinationViewController as! DetailViewController).photos = photos
}
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let selectedIndexPath = self.tableView.indexPathForSelectedRow {
self.tableView.deselectRowAtIndexPath(selectedIndexPath, animated: true)
}
self.navigationItem.leftBarButtonItem = self.editButtonItem()
}
override func setEditing(editing: Bool, animated: Bool) {
super.setEditing(editing, animated: animated)
self.tableView.setEditing(editing, animated: animated)
}
}
extension MasterViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.searches.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let (term, photos) = self.searches[indexPath.row]
cell.textLabel?.text = "\(term) (\(photos.count))"
return cell
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
self.searches.removeAtIndex(indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
}
extension MasterViewController: UISearchBarDelegate {
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchBar.resignFirstResponder()
let searchTerm = searchBar.text
Flickr.search(searchTerm!) {
switch ($0) {
case .Error:
break
case .Results(let results):
self.searches.insert(results, forKey: searchTerm!, atIndex: 0)
self.tableView.reloadData()
}
}
}
}
| 87f479a97aadffc8f60ccfc73d0e62b3 | 35.881188 | 146 | 0.729933 | false | false | false | false |
josve05a/wikipedia-ios | refs/heads/develop | Wikipedia/Code/ArticleLocationCollectionViewController.swift | mit | 2 | import UIKit
class ArticleLocationCollectionViewController: ColumnarCollectionViewController, DetailPresentingFromContentGroup {
var articleURLs: [URL] {
didSet {
collectionView.reloadData()
}
}
let dataStore: MWKDataStore
fileprivate let locationManager = WMFLocationManager.fine()
private var feedFunnelContext: FeedFunnelContext?
private var previewedIndexPath: IndexPath?
let contentGroupIDURIString: String?
required init(articleURLs: [URL], dataStore: MWKDataStore, contentGroup: WMFContentGroup?, theme: Theme) {
self.articleURLs = articleURLs
self.dataStore = dataStore
contentGroupIDURIString = contentGroup?.objectID.uriRepresentation().absoluteString
super.init()
self.theme = theme
if contentGroup != nil {
self.feedFunnelContext = FeedFunnelContext(contentGroup)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
layoutManager.register(ArticleLocationCollectionViewCell.self, forCellWithReuseIdentifier: ArticleLocationCollectionViewCell.identifier, addPlaceholder: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
locationManager.delegate = self
if WMFLocationManager.isAuthorized() {
locationManager.startMonitoringLocation()
}
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
locationManager.delegate = nil
locationManager.stopMonitoringLocation()
if isMovingFromParent, let context = feedFunnelContext {
FeedFunnel.shared.logFeedCardClosed(for: context, maxViewed: maxViewed)
}
}
func articleURL(at indexPath: IndexPath) -> URL {
return articleURLs[indexPath.item]
}
override func collectionView(_ collectionView: UICollectionView, estimatedHeightForItemAt indexPath: IndexPath, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate {
var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 150)
guard let placeholderCell = layoutManager.placeholder(forCellWithReuseIdentifier: ArticleLocationCollectionViewCell.identifier) as? ArticleLocationCollectionViewCell else {
return estimate
}
placeholderCell.layoutMargins = layout.itemLayoutMargins
configure(cell: placeholderCell, forItemAt: indexPath, layoutOnly: true)
estimate.height = placeholderCell.sizeThatFits(CGSize(width: columnWidth, height: UIView.noIntrinsicMetric), apply: false).height
estimate.precalculated = true
return estimate
}
override func metrics(with size: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics {
return ColumnarCollectionViewLayoutMetrics.tableViewMetrics(with: size, readableWidth: readableWidth, layoutMargins: layoutMargins)
}
// MARK: - CollectionViewFooterDelegate
override func collectionViewFooterButtonWasPressed(_ collectionViewFooter: CollectionViewFooter) {
navigationController?.popViewController(animated: true)
}
}
// MARK: - UICollectionViewDataSource
extension ArticleLocationCollectionViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
var numberOfItems: Int {
return articleURLs.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return numberOfItems
}
private func configure(cell: UICollectionViewCell, forItemAt indexPath: IndexPath, layoutOnly: Bool) {
guard let cell = cell as? ArticleLocationCollectionViewCell else {
return
}
let url = articleURL(at: indexPath)
guard let article = dataStore.fetchArticle(with: url) else {
return
}
var userLocation: CLLocation?
var userHeading: CLHeading?
if locationManager.isUpdating {
userLocation = locationManager.location
userHeading = locationManager.heading
}
cell.articleLocation = article.location
cell.update(userLocation: userLocation, heading: userHeading)
cell.configure(article: article, displayType: .pageWithLocation, index: indexPath.row, theme: theme, layoutOnly: layoutOnly)
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ArticleLocationCollectionViewCell.identifier, for: indexPath)
configure(cell: cell, forItemAt: indexPath, layoutOnly: false)
return cell
}
}
// MARK: - WMFLocationManagerDelegate
extension ArticleLocationCollectionViewController: WMFLocationManagerDelegate {
func updateLocationOnVisibleCells() {
for cell in collectionView.visibleCells {
guard let locationCell = cell as? ArticleLocationCollectionViewCell else {
continue
}
locationCell.update(userLocation: locationManager.location, heading: locationManager.heading)
}
}
func locationManager(_ controller: WMFLocationManager, didUpdate location: CLLocation) {
updateLocationOnVisibleCells()
}
func locationManager(_ controller: WMFLocationManager, didUpdate heading: CLHeading) {
updateLocationOnVisibleCells()
}
func locationManager(_ controller: WMFLocationManager, didChangeEnabledState enabled: Bool) {
if enabled {
locationManager.startMonitoringLocation()
}
}
}
// MARK: - UICollectionViewDelegate
extension ArticleLocationCollectionViewController {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if let context = feedFunnelContext {
FeedFunnel.shared.logArticleInFeedDetailReadingStarted(for: context, index: indexPath.item, maxViewed: maxViewed)
}
navigate(to: articleURLs[indexPath.item])
}
}
// MARK: - UIViewControllerPreviewingDelegate
extension ArticleLocationCollectionViewController {
override func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = collectionViewIndexPathForPreviewingContext(previewingContext, location: location) else {
return nil
}
previewedIndexPath = indexPath
let articleURL = self.articleURL(at: indexPath)
let articleViewController = WMFArticleViewController(articleURL: articleURL, dataStore: dataStore, theme: self.theme)
articleViewController.articlePreviewingActionsDelegate = self
articleViewController.wmf_addPeekableChildViewController(for: articleURL, dataStore: dataStore, theme: theme)
if let context = feedFunnelContext {
FeedFunnel.shared.logArticleInFeedDetailPreviewed(for: context, index: indexPath.item)
}
return articleViewController
}
override func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
if let context = feedFunnelContext {
FeedFunnel.shared.logArticleInFeedDetailReadingStarted(for: context, index: previewedIndexPath?.item, maxViewed: maxViewed)
}
viewControllerToCommit.wmf_removePeekableChildViewControllers()
if let articleViewController = viewControllerToCommit as? WMFArticleViewController {
wmf_push(articleViewController, animated: true)
} else {
wmf_push(viewControllerToCommit, animated: true)
}
}
}
// MARK: - Reading lists event logging
extension ArticleLocationCollectionViewController: EventLoggingEventValuesProviding {
var eventLoggingCategory: EventLoggingCategory {
return .places
}
var eventLoggingLabel: EventLoggingLabel? {
return nil
}
}
// MARK: - WMFArticlePreviewingActionsDelegate
extension ArticleLocationCollectionViewController {
override func shareArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController, shareActivityController: UIActivityViewController) {
guard let context = feedFunnelContext else {
super.shareArticlePreviewActionSelected(withArticleController: articleController, shareActivityController: shareActivityController)
return
}
super.shareArticlePreviewActionSelected(withArticleController: articleController, shareActivityController: shareActivityController)
FeedFunnel.shared.logFeedDetailShareTapped(for: context, index: previewedIndexPath?.item, midnightUTCDate: context.midnightUTCDate)
}
override func readMoreArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController) {
guard let context = feedFunnelContext else {
super.readMoreArticlePreviewActionSelected(withArticleController: articleController)
return
}
articleController.wmf_removePeekableChildViewControllers()
wmf_push(articleController, context: context, index: previewedIndexPath?.item, animated: true)
}
override func saveArticlePreviewActionSelected(withArticleController articleController: WMFArticleViewController, didSave: Bool, articleURL: URL) {
guard let context = feedFunnelContext else {
super.saveArticlePreviewActionSelected(withArticleController: articleController, didSave: didSave, articleURL: articleURL)
return
}
if didSave {
ReadingListsFunnel.shared.logSaveInFeed(context: context, articleURL: articleURL, index: previewedIndexPath?.item)
} else {
ReadingListsFunnel.shared.logUnsaveInFeed(context: context, articleURL: articleURL, index: previewedIndexPath?.item)
}
}
}
| 182e741aaea556c8b47800b21d73b90e | 43.257511 | 200 | 0.726532 | false | false | false | false |
theScud/Lunch | refs/heads/wip | lunchPlanner/UI/SplashViewController.swift | apache-2.0 | 1 | //
// SplashViewController.swift
// lunchPlanner
//
// Created by Sudeep Kini on 04/11/16.
// Copyright © 2016 TestLabs. All rights reserved.
//
import UIKit
import CoreLocation
class SplashViewController: UIViewController,CLLocationManagerDelegate {
var locationManager: CLLocationManager = CLLocationManager()
var gotlocation = false
override func viewDidLoad() {
super.viewDidLoad()
self.locationManager.requestWhenInUseAuthorization()
// Getting user Location
//Location Manager Request for Locations
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
locationManager.stopUpdatingLocation()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if CLLocationManager.locationServicesEnabled() {
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let appDelegate = UIApplication.shared.delegate as! AppDelegate
if let location = locations.last {
if(gotlocation == false ){
appDelegate.appState?.updateUserLocation(location:location)
self.performSegue(withIdentifier:"gotoCategoriesPage", sender: self)
locationManager.stopUpdatingLocation()
gotlocation = true
}
}
}
}
| 7c2753828ef45aeca83a231332f71318 | 27.555556 | 100 | 0.652585 | false | false | false | false |
heigong/Shared | refs/heads/master | iOS/a_Playgrounds/Basic_Enum.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
// Declare a simple enum
enum Direction: Int {
case North = 0, East, South, West
}
class Road {
var direction: Direction
init(){
direction = .North
}
}
let road = Road()
road.direction.rawValue
// ** Important **
// Init with rawValue returns an optional value
road.direction = Direction(rawValue: 0)!
road.direction.rawValue
switch road.direction {
case .North:
println("North")
default:
println("Other directions")
}
// Associated values
// each member can have its own value, can be different type if needed
enum Barcode{
case UPCA(Int, Int, Int, Int)
case QRCode(String)
}
let barcode1 = Barcode.UPCA(1, 2, 3, 4)
let barcode2 = Barcode.QRCode("1234")
// Assorciated values can be extract by switch cases:
switch barcode1 {
case let .UPCA(a, b, c, d):
println("\(a)-\(b)-\(c)-\(d)")
case let .QRCode(a):
println("\(a)")
} | 98f0ed7d432a84328c8cca2011a4eaa5 | 18.583333 | 70 | 0.658147 | false | false | false | false |
edulpn/rxmoyatest | refs/heads/master | RxMoyaTest/RxMoyaTest/UserEntity.swift | mit | 1 | //
// UserEntity.swift
// RxMoyaTest
//
// Created by Eduardo Pinto on 8/30/17.
// Copyright © 2017 Eduardo Pinto. All rights reserved.
//
import Foundation
import ObjectMapper
struct UserEntity: ImmutableMappable {
let login: String
let id: Int
let avatarURL: String
let gravatarId: String
let URL: String
let htmlURL: String
let followersURL: String
let followingURL: String
let gistsURL: String
let starredURL: String
let subscriptionsURL: String
let organizationsURL: String
let reposURL: String
let eventsURL: String
let receivedEventsURL: String
let type: String
let isSiteAdmin: Bool
init(map: Map) throws {
login = try map.value("login")
id = try map.value("id")
avatarURL = try map.value("avatar_url")
gravatarId = try map.value("gravatar_id")
URL = try map.value("url")
htmlURL = try map.value("html_url")
followersURL = try map.value("followers_url")
followingURL = try map.value("following_url")
gistsURL = try map.value("gists_url")
starredURL = try map.value("starred_url")
subscriptionsURL = try map.value("subscriptions_url")
organizationsURL = try map.value("organizations_url")
reposURL = try map.value("repos_url")
eventsURL = try map.value("events_url")
receivedEventsURL = try map.value("received_events_url")
type = try map.value("type")
isSiteAdmin = try map.value("site_admin")
}
}
| 1e1269aedf0aa2bf31f1031c78926727 | 29.58 | 64 | 0.646174 | false | false | false | false |
yoonhg84/ModalPresenter | refs/heads/master | RxModalityStack/Transition/SlideTransition.swift | mit | 1 | //
// Created by Chope on 2018. 3. 15..
// Copyright (c) 2018 Chope Industry. All rights reserved.
//
import UIKit
public enum Direction: Equatable {
case up
case down
case left
case right
}
class SlideTransition: TransitionAnimatable {
let duration: TimeInterval = 0.3
let direction: Direction
init(direction: Direction) {
self.direction = direction
}
func animateTransition(to: TransitionInfo, animation: @escaping () -> Void, completion: @escaping () -> Void) {
var frame = to.finalFrame
switch direction {
case .up:
frame.origin.y = frame.height
case .down:
frame.origin.y = -frame.height
case .left:
frame.origin.x = frame.width
case .right:
frame.origin.x = -frame.width
}
to.view.frame = frame
UIView.animate(
withDuration: duration,
delay: 0,
options: .curveEaseInOut,
animations: {
to.view.frame = to.finalFrame
animation()
},
completion: { _ in
completion()
})
}
func animateTransition(from: TransitionInfo, animation: @escaping () -> Void, completion: @escaping () -> Void) {
var frame = from.initialFrame
switch direction {
case .up:
frame.origin.y = frame.height
case .down:
frame.origin.y = -frame.height
case .left:
frame.origin.x = frame.width
case .right:
frame.origin.x = -frame.width
}
UIView.animate(
withDuration: duration,
delay: 0,
options: .curveEaseInOut,
animations: {
from.view.frame = frame
animation()
},
completion: { _ in
completion()
})
}
}
| bbb214b63fc42af105acde0dd1495562 | 24.12987 | 117 | 0.518863 | false | false | false | false |
NghiaTranUIT/Unofficial-Uber-macOS | refs/heads/master | UberGo/UberGo/DriverAnnotation.swift | mit | 1 | //
// DriverAnnotation.swift
// UberGo
//
// Created by Nghia Tran on 9/7/17.
// Copyright © 2017 Nghia Tran. All rights reserved.
//
import Foundation
import Mapbox
import UberGoCore
class DriverAnnotation: MGLPointAnnotation {
// MARK: - Variable
public lazy var image: MGLAnnotationImage = {
let image = NSImage(imageLiteralResourceName: "driver_mark")
return MGLAnnotationImage(image: image,
reuseIdentifier: "driver_mark")
}()
// MARK: - Variable
fileprivate var driverObj: DriverObj!
fileprivate var vehicleObj: VehicleObj!
fileprivate var driverLocation: UberCoordinateObj!
fileprivate lazy var _calloutController: NSViewController = {
let controller = CalloutAnnotations(nibName: "CalloutAnnotations", bundle: nil)!
controller.setupCallout(mode: .noTimeEstimation, timeETA: nil, calloutTitle: self.title)
return controller
}()
// MARK: - Init
public init?(tripObj: TripObj) {
guard let driverObj = tripObj.driver else { return nil }
guard let driverLocation = tripObj.location else { return nil }
guard let vehicleObj = tripObj.vehicle else { return nil }
self.driverObj = driverObj
self.driverLocation = driverLocation
self.vehicleObj = vehicleObj
super.init()
self.coordinate = driverLocation.coordinate
self.title = "\(driverObj.name) - \(vehicleObj.model) \(vehicleObj.licensePlate)"
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
// MARK: - UberAnnotationType
extension DriverAnnotation: UberAnnotationType {
var imageAnnotation: MGLAnnotationImage? {
return image
}
var calloutViewController: NSViewController? {
return _calloutController
}
}
| f32861bcaea37ddc2e14d62dd118c21c | 27.828125 | 96 | 0.672087 | false | false | false | false |
groschovskiy/lerigos_music | refs/heads/master | Mobile/Dependencies/iOS/Projects/SwiftHTTP-1.0.3/Source/Operation.swift | apache-2.0 | 1 | //
// Operation.swift
// SwiftHTTP
//
// Created by Dalton Cherry on 8/2/15.
// Copyright © 2015 vluxe. All rights reserved.
//
import Foundation
enum HTTPOptError: ErrorType {
case InvalidRequest
}
/**
This protocol exist to allow easy and customizable swapping of a serializing format within an class methods of HTTP.
*/
public protocol HTTPSerializeProtocol {
/**
implement this protocol to support serializing parameters to the proper HTTP body or URL
-parameter request: The NSMutableURLRequest object you will modify to add the parameters to
-parameter parameters: The container (array or dictionary) to convert and append to the URL or Body
*/
func serialize(request: NSMutableURLRequest, parameters: HTTPParameterProtocol) throws
}
/**
Standard HTTP encoding
*/
public struct HTTPParameterSerializer: HTTPSerializeProtocol {
public init() { }
public func serialize(request: NSMutableURLRequest, parameters: HTTPParameterProtocol) throws {
try request.appendParameters(parameters)
}
}
/**
Send the data as a JSON body
*/
public struct JSONParameterSerializer: HTTPSerializeProtocol {
public init() { }
public func serialize(request: NSMutableURLRequest, parameters: HTTPParameterProtocol) throws {
try request.appendParametersAsJSON(parameters)
}
}
/**
All the things of an HTTP response
*/
public class Response {
/// The header values in HTTP response.
public var headers: Dictionary<String,String>?
/// The mime type of the HTTP response.
public var mimeType: String?
/// The suggested filename for a downloaded file.
public var suggestedFilename: String?
/// The body data of the HTTP response.
public var data: NSData {
return collectData
}
/// The status code of the HTTP response.
public var statusCode: Int?
/// The URL of the HTTP response.
public var URL: NSURL?
/// The Error of the HTTP response (if there was one).
public var error: NSError?
///Returns the response as a string
public var text: String? {
return NSString(data: data, encoding: NSUTF8StringEncoding) as? String
}
///get the description of the response
public var description: String {
var buffer = ""
if let u = URL {
buffer += "URL:\n\(u)\n\n"
}
if let code = self.statusCode {
buffer += "Status Code:\n\(code)\n\n"
}
if let heads = headers {
buffer += "Headers:\n"
for (key, value) in heads {
buffer += "\(key): \(value)\n"
}
buffer += "\n"
}
if let t = text {
buffer += "Payload:\n\(t)\n"
}
return buffer
}
///private things
///holds the collected data
var collectData = NSMutableData()
///finish closure
var completionHandler:((Response) -> Void)?
//progress closure. Progress is between 0 and 1.
var progressHandler:((Float) -> Void)?
///This gets called on auth challenges. If nil, default handling is use.
///Returning nil from this method will cause the request to be rejected and cancelled
var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)?
///This is for doing SSL pinning
var security: HTTPSecurity?
}
/**
The class that does the magic. Is a subclass of NSOperation so you can use it with operation queues or just a good ole HTTP request.
*/
public class HTTP: NSOperation {
/**
Get notified with a request finishes.
*/
public var onFinish:((Response) -> Void)? {
didSet {
if let handler = onFinish {
DelegateManager.sharedInstance.addTask(task, completionHandler: { (response: Response) in
self.finish()
handler(response)
})
}
}
}
///This is for handling authenication
public var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)? {
set {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }
resp.auth = newValue
}
get {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }
return resp.auth
}
}
///This is for doing SSL pinning
public var security: HTTPSecurity? {
set {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }
resp.security = newValue
}
get {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }
return resp.security
}
}
///This is for monitoring progress
public var progress: ((Float) -> Void)? {
set {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return }
resp.progressHandler = newValue
}
get {
guard let resp = DelegateManager.sharedInstance.responseForTask(task) else { return nil }
return resp.progressHandler
}
}
///the actual task
var task: NSURLSessionDataTask!
/// Reports if the task is currently running
private var running = false
/// Reports if the task is finished or not.
private var done = false
/// Reports if the task is cancelled
private var _cancelled = false
/**
creates a new HTTP request.
*/
public init(_ req: NSURLRequest, session: NSURLSession = SharedSession.defaultSession) {
super.init()
task = session.dataTaskWithRequest(req)
DelegateManager.sharedInstance.addResponseForTask(task)
}
//MARK: Subclassed NSOperation Methods
/// Returns if the task is asynchronous or not. NSURLSessionTask requests are asynchronous.
override public var asynchronous: Bool {
return true
}
/// Returns if the task is current running.
override public var executing: Bool {
return running
}
/// Returns if the task is finished.
override public var finished: Bool {
return done && !_cancelled
}
/**
start/sends the HTTP task with a completionHandler. Use this when *NOT* using an NSOperationQueue.
*/
public func start(completionHandler:((Response) -> Void)) {
onFinish = completionHandler
start()
}
/**
Start the HTTP task. Make sure to set the onFinish closure before calling this to get a response.
*/
override public func start() {
if cancelled {
self.willChangeValueForKey("isFinished")
done = true
self.didChangeValueForKey("isFinished")
return
}
self.willChangeValueForKey("isExecuting")
self.willChangeValueForKey("isFinished")
running = true
done = false
self.didChangeValueForKey("isExecuting")
self.didChangeValueForKey("isFinished")
task.resume()
}
/**
Cancel the running task
*/
override public func cancel() {
task.cancel()
_cancelled = true
finish()
}
/**
Sets the task to finished.
If you aren't using the DelegateManager, you will have to call this in your delegate's URLSession:dataTask:didCompleteWithError: method
*/
public func finish() {
self.willChangeValueForKey("isExecuting")
self.willChangeValueForKey("isFinished")
running = false
done = true
self.didChangeValueForKey("isExecuting")
self.didChangeValueForKey("isFinished")
}
/**
Class method to create a GET request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func GET(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil,
requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .GET, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a HEAD request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func HEAD(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .HEAD, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a DELETE request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func DELETE(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .DELETE, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a POST request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func POST(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .POST, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a PUT request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func PUT(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil,
requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .PUT, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a PUT request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func PATCH(url: String, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
return try HTTP.New(url, method: .PATCH, parameters: parameters, headers: headers, requestSerializer: requestSerializer)
}
/**
Class method to create a HTTP request that handles the NSMutableURLRequest and parameter encoding for you.
*/
public class func New(url: String, method: HTTPVerb, parameters: HTTPParameterProtocol? = nil, headers: [String:String]? = nil, requestSerializer: HTTPSerializeProtocol = HTTPParameterSerializer()) throws -> HTTP {
guard let req = NSMutableURLRequest(urlString: url) else { throw HTTPOptError.InvalidRequest }
if let handler = DelegateManager.sharedInstance.requestHandler {
handler(req)
}
req.verb = method
if let params = parameters {
try requestSerializer.serialize(req, parameters: params)
}
if let heads = headers {
for (key,value) in heads {
req.addValue(value, forHTTPHeaderField: key)
}
}
return HTTP(req)
}
/**
Set the global auth handler
*/
public class func globalAuth(handler: ((NSURLAuthenticationChallenge) -> NSURLCredential?)?) {
DelegateManager.sharedInstance.auth = handler
}
/**
Set the global security handler
*/
public class func globalSecurity(security: HTTPSecurity?) {
DelegateManager.sharedInstance.security = security
}
/**
Set the global request handler
*/
public class func globalRequest(handler: ((NSMutableURLRequest) -> Void)?) {
DelegateManager.sharedInstance.requestHandler = handler
}
}
/**
Absorb all the delegates methods of NSURLSession and forwards them to pretty closures.
This is basically the sin eater for NSURLSession.
*/
class DelegateManager: NSObject, NSURLSessionDataDelegate {
//the singleton to handle delegate needs of NSURLSession
static let sharedInstance = DelegateManager()
/// this is for global authenication handling
var auth:((NSURLAuthenticationChallenge) -> NSURLCredential?)?
///This is for global SSL pinning
var security: HTTPSecurity?
/// this is for global request handling
var requestHandler:((NSMutableURLRequest) -> Void)?
var taskMap = Dictionary<Int,Response>()
//"install" a task by adding the task to the map and setting the completion handler
func addTask(task: NSURLSessionTask, completionHandler:((Response) -> Void)) {
addResponseForTask(task)
if let resp = responseForTask(task) {
resp.completionHandler = completionHandler
}
}
//"remove" a task by removing the task from the map
func removeTask(task: NSURLSessionTask) {
taskMap.removeValueForKey(task.taskIdentifier)
}
//add the response task
func addResponseForTask(task: NSURLSessionTask) {
if taskMap[task.taskIdentifier] == nil {
taskMap[task.taskIdentifier] = Response()
}
}
//get the response object for the task
func responseForTask(task: NSURLSessionTask) -> Response? {
return taskMap[task.taskIdentifier]
}
//handle getting data
func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
addResponseForTask(dataTask)
guard let resp = responseForTask(dataTask) else { return }
resp.collectData.appendData(data)
if resp.progressHandler != nil { //don't want the extra cycles for no reason
guard let taskResp = dataTask.response else { return }
progressHandler(resp, expectedLength: taskResp.expectedContentLength, currentLength: Int64(resp.collectData.length))
}
}
//handle task finishing
func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
guard let resp = responseForTask(task) else { return }
resp.error = error
if let hresponse = task.response as? NSHTTPURLResponse {
resp.headers = hresponse.allHeaderFields as? Dictionary<String,String>
resp.mimeType = hresponse.MIMEType
resp.suggestedFilename = hresponse.suggestedFilename
resp.statusCode = hresponse.statusCode
resp.URL = hresponse.URL
}
if let code = resp.statusCode where resp.statusCode > 299 {
resp.error = createError(code)
}
if let handler = resp.completionHandler {
handler(resp)
}
removeTask(task)
}
//handle authenication
func URLSession(session: NSURLSession, task: NSURLSessionTask, didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
var sec = security
var au = auth
if let resp = responseForTask(task) {
if let s = resp.security {
sec = s
}
if let a = resp.auth {
au = a
}
}
if let sec = sec where challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
let space = challenge.protectionSpace
if let trust = space.serverTrust {
if sec.isValid(trust, domain: space.host) {
completionHandler(.UseCredential, NSURLCredential(trust: trust))
return
}
}
completionHandler(.CancelAuthenticationChallenge, nil)
return
} else if let a = au {
let cred = a(challenge)
if let c = cred {
completionHandler(.UseCredential, c)
return
}
completionHandler(.RejectProtectionSpace, nil)
return
}
completionHandler(.PerformDefaultHandling, nil)
}
//upload progress
func URLSession(session: NSURLSession, task: NSURLSessionTask, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
guard let resp = responseForTask(task) else { return }
progressHandler(resp, expectedLength: totalBytesExpectedToSend, currentLength: totalBytesSent)
}
//download progress
func URLSession(session: NSURLSession, downloadTask: NSURLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
guard let resp = responseForTask(downloadTask) else { return }
progressHandler(resp, expectedLength: totalBytesExpectedToWrite, currentLength: bytesWritten)
}
//handle progress
func progressHandler(response: Response, expectedLength: Int64, currentLength: Int64) {
guard let handler = response.progressHandler else { return }
let slice = 1/expectedLength
handler(Float(slice*currentLength))
}
/**
Create an error for response you probably don't want (400-500 HTTP responses for example).
-parameter code: Code for error.
-returns An NSError.
*/
private func createError(code: Int) -> NSError {
let text = HTTPStatusCode(statusCode: code).statusDescription
return NSError(domain: "HTTP", code: code, userInfo: [NSLocalizedDescriptionKey: text])
}
}
/**
Handles providing singletons of NSURLSession.
*/
class SharedSession {
static let defaultSession = NSURLSession(configuration: NSURLSessionConfiguration.defaultSessionConfiguration(),
delegate: DelegateManager.sharedInstance, delegateQueue: nil)
static let ephemeralSession = NSURLSession(configuration: NSURLSessionConfiguration.ephemeralSessionConfiguration(),
delegate: DelegateManager.sharedInstance, delegateQueue: nil)
} | 11a409434bea88e5b14e5de39540206c | 36.6 | 219 | 0.656485 | false | false | false | false |
mlilback/rc2SwiftClient | refs/heads/master | Rc2Common/themes/ThemeManager.swift | isc | 1 | //
// ThemeManager.swift
//
// Copyright ©2016 Mark Lilback. This file is licensed under the ISC license.
//
import Foundation
import ReactiveSwift
import SwiftyUserDefaults
import MJLLogger
fileprivate extension DefaultsKeys {
static let activeOutputTheme = DefaultsKey<OutputTheme?>("rc2.activeOutputTheme")
static let activeSyntaxTheme = DefaultsKey<SyntaxTheme?>("rc2.activeSyntaxTheme")
}
enum ThemeError: Error {
case notEditable
}
/// wraps the information about a type of theme to allow it to be used generically
public class ThemeWrapper<T: Theme> {
public var themes: [T] { return getThemes() }
public var selectedTheme: T { return getSelectedTheme() }
public var builtinThemes: [T] { return themes.filter { $0.isBuiltin } }
public var userThemes: [T] { return themes.filter { !$0.isBuiltin } }
private var getThemes: () -> [T]
private var getSelectedTheme: () -> T
public init() {
// swiftlint:disable force_cast
if T.self == OutputTheme.self {
getThemes = { return ThemeManager.shared.outputThemes as! [T] }
getSelectedTheme = { return ThemeManager.shared.activeOutputTheme.value as! T }
} else {
getThemes = { return ThemeManager.shared.syntaxThemes as! [T] }
getSelectedTheme = { return ThemeManager.shared.activeSyntaxTheme.value as! T }
}
// swiftlint:enable force_cast
}
}
public class ThemeManager {
public static let shared = ThemeManager()
public var outputThemes: [OutputTheme] { return _outputThemes }
public var syntaxThemes: [SyntaxTheme] { return _syntaxThemes }
private var _outputThemes = [OutputTheme]()
private var _syntaxThemes = [SyntaxTheme]()
public let activeOutputTheme: MutableProperty<OutputTheme>!
public let activeSyntaxTheme: MutableProperty<SyntaxTheme>!
/// sets the active theme based on the type of theme passed as an argument
public func setActive<T: Theme>(theme: T) {
if let otheme = theme as? OutputTheme {
activeOutputTheme.value = otheme
} else if let stheme = theme as? SyntaxTheme {
activeSyntaxTheme.value = stheme
} else {
fatalError("invalid theme")
}
}
@objc private func syntaxThemeChanged(_ note: Notification) {
guard let theme = note.object as? SyntaxTheme else { return }
if activeSyntaxTheme.value.dirty {
do {
try activeSyntaxTheme.value.save()
} catch {
Log.error("error saving theme: \(error)", .core)
}
}
activeSyntaxTheme.value = theme
}
@objc private func outputThemeChanged(_ note: Notification) {
guard let theme = note.object as? OutputTheme else { return }
if theme != activeOutputTheme.value, activeOutputTheme.value.dirty {
do {
try activeOutputTheme.value.save()
} catch {
Log.error("error saving theme: \(error)", .core)
}
}
activeOutputTheme.value = theme
}
/// returns a duplicate of theme with a unique name that has already been inserted in the correct array
public func duplicate<T: Theme>(theme: T) -> T {
let currentNames = existingNames(theme)
let baseName = "\(theme.name) copy"
var num = 0
var curName = baseName
while currentNames.contains(curName) {
num += 1
curName = baseName + " \(num)"
}
let newTheme = clone(theme: theme, name: curName)
setActive(theme: newTheme)
return newTheme
}
/// clone theme by force casting due to limitation in swift type system
private func clone<T: Theme>(theme: T, name: String) -> T {
// swiftlint:disable force_cast
if let outputTheme = theme as? OutputTheme {
let copy = outputTheme.duplicate(name: name) as! T
_outputThemes.append(copy as! OutputTheme)
return copy
} else if let syntaxTheme = theme as? SyntaxTheme {
let copy = syntaxTheme.duplicate(name: name) as! T
_syntaxThemes.append(copy as! SyntaxTheme)
return copy
}
// swiftlint:enable force_try
fatalError()
}
/// returns array of names of existing themes of the same type as instance
private func existingNames<T: Theme>(_ instance: T) -> [String] {
if instance is OutputTheme {
return _outputThemes.map { $0.name }
} else if instance is SyntaxTheme {
return _syntaxThemes.map { $0.name }
}
fatalError()
}
private init() {
_syntaxThemes = BaseTheme.loadThemes()
_outputThemes = BaseTheme.loadThemes()
let activeSyntax = ThemeManager.findDefaultSyntaxTheme(in: _syntaxThemes)
activeSyntaxTheme = MutableProperty(activeSyntax)
let activeOutput = ThemeManager.findDefaultOutputTheme(in: _outputThemes)
activeOutputTheme = MutableProperty(activeOutput)
NotificationCenter.default.addObserver(self, selector: #selector(syntaxThemeChanged(_:)), name: .SyntaxThemeModified, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(outputThemeChanged(_:)), name: .OutputThemeModified, object: nil)
}
private static func findDefaultOutputTheme(in array: [OutputTheme]) -> OutputTheme {
if let theme: OutputTheme = Defaults[.activeOutputTheme] {
return theme
}
//look for one named default
if let defaultTheme = array.first(where: { $0.name == "Default" }) {
return defaultTheme
}
return OutputTheme.defaultTheme as! OutputTheme
}
private static func findDefaultSyntaxTheme(in array: [SyntaxTheme]) -> SyntaxTheme {
if let theme: SyntaxTheme = Defaults[.activeSyntaxTheme] {
return theme
}
//look for one named default
if let defaultTheme = array.first(where: { $0.name == "Default" }) {
return defaultTheme
}
return SyntaxTheme.defaultTheme as! SyntaxTheme
}
}
| d4d1527c3797603dcbd8c41e700f9bf6 | 31.801205 | 132 | 0.722498 | false | false | false | false |
plivesey/SwiftGen | refs/heads/master | SwiftGen.playground/Pages/Fonts-Demo.xcplaygroundpage/Contents.swift | mit | 1 | //: #### Other pages
//: * [Demo for `swiftgen strings`](Colors-Demo)
//: * [Demo for `swiftgen images`](Images-Demo)
//: * [Demo for `swiftgen storyboards`](Storyboards-Demo)
//: * [Demo for `swiftgen colors`](Colors-Demo)
//: * Demo for `swiftgen fonts`
//: #### Example of code generated by swiftgen-fonts
import UIKit.UIFont
protocol FontConvertible {
func font(size: CGFloat) -> UIFont!
}
extension FontConvertible where Self: RawRepresentable, Self.RawValue == String {
func font(size: CGFloat) -> UIFont! {
return UIFont(font: self, size: size)
}
}
extension UIFont {
convenience init!<FontType: FontConvertible>
(font: FontType, size: CGFloat)
where FontType: RawRepresentable, FontType.RawValue == String {
self.init(name: font.rawValue, size: size)
}
}
struct FontFamily {
enum Helvetica: String, FontConvertible {
case regular = "Helvetica"
case bold = "Helvetica-Bold"
}
enum HelveticaNeue: String, FontConvertible {
case regular = "HelveticaNeue"
case bold = "HelveticaNeue-Bold"
}
}
//: #### Usage Example
// Using the UIFont constructor…
let helvetica = UIFont(font: FontFamily.Helvetica.regular, size: 20.0)
// Or using the enum value and its `font` method
let helveticaNeue = FontFamily.HelveticaNeue.regular.font(size: 20.0)
let helveticaBoldBig = FontFamily.Helvetica.bold.font(size: 100.0)
let helveticaNeueBoldSmall = UIFont(font: FontFamily.HelveticaNeue.bold, size: 8.0)
| 02a0f5b819302accbd72e2e6e80e5e1d | 30.375 | 83 | 0.683931 | false | false | false | false |
ukitaka/FPRealm | refs/heads/master | Tests/CompositionSpec.swift | mit | 2 | //
// CompositionSpec.swift
// RealmIO
//
// Created by ukitaka on 2017/04/25.
// Copyright © 2017年 waft. All rights reserved.
//
import RealmSwift
import RealmIO
import XCTest
import Quick
import Nimble
class CompositionSpec: QuickSpec {
let realm = try! Realm(configuration: Realm.Configuration(fileURL: nil, inMemoryIdentifier: "for test"))
override func spec() {
super.spec()
let readIO = RealmRO<Void> { _ in }
let writeIO = RealmRW<Void> { _ in }
let readAnyIO = AnyRealmIO<Void>(io: readIO)
let writeAnyIO = AnyRealmIO<Void>(io: writeIO)
it("should be `write` when compose `write` and `write`.") {
let io = writeIO.flatMap { _ in writeIO }
expect(io.isReadWrite).to(beTrue())
}
it("should be `write` when compose `read` and `write`.") {
let io = readIO.flatMap { _ in writeIO }
expect(io.isReadWrite).to(beTrue())
}
it("should be `write` when compose `write` and `read`.") {
let io = writeIO.flatMap { _ in readIO }
expect(io.isReadWrite).to(beTrue())
}
it("should be `read` when compose `read` and `read`.") {
let io = readIO.flatMap { _ in readIO }
expect(io.isReadOnly).to(beTrue())
}
it("should be `read` when compose `any(read)` and `read`.") {
let io = readAnyIO.flatMap { _ in readIO }
expect(io.isReadOnly).to(beTrue())
}
it("should be `write` when compose `any(read)` and `write`.") {
let io = readAnyIO.flatMap { _ in writeIO }
expect(io.isReadWrite).to(beTrue())
}
it("should be `write` when compose `any(write)` and `read`.") {
let io = writeAnyIO.flatMap { _ in readIO }
expect(io.isReadWrite).to(beTrue())
}
it("should be `write` when compose `any(write)` and `write`.") {
let io = writeAnyIO.flatMap { _ in writeIO }
expect(io.isReadWrite).to(beTrue())
}
}
}
| 80bacc1ba14c07d7b9d9379b4cb53781 | 30.348485 | 108 | 0.560174 | false | false | false | false |
umutbozkurt/10k | refs/heads/master | 10k/Delegates/AppDelegate.swift | mit | 2 | //
// AppDelegate.swift
// 10k
//
// Created by Umut Bozkurt on 03/09/15.
// Copyright (c) 2015 Umut Bozkurt. All rights reserved.
//
import Cocoa
import RealmSwift
import Fabric
import Crashlytics
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate
{
@IBOutlet weak var window: NSWindow!
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(-2)
let popover = NSPopover()
var eventMonitor: EventMonitor?
func applicationDidFinishLaunching(aNotification: NSNotification)
{
if let button = self.statusItem.button
{
button.image = NSImage(named: "10k")
button.action = Selector("togglePopover:")
}
self.eventMonitor = EventMonitor(mask: NSEventMask.LeftMouseDownMask | NSEventMask.RightMouseDownMask){
[unowned self] event in
if self.popover.shown
{
self.hidePopover(event)
}
}
// Run automatically at startup
let isStartupSet = NSUserDefaults.standardUserDefaults().boolForKey("isStartupSet")
if (!isStartupSet)
{
if (!LaunchStarter.applicationIsInStartUpItems())
{
LaunchStarter.toggleLaunchAtStartup()
}
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "isStartupSet")
}
let config = Realm.Configuration(
schemaVersion: 1,
migrationBlock: { migration, oldSchemaVersion in
})
Realm.Configuration.defaultConfiguration = config
// Realm().write { () -> Void in
// Realm().deleteAll()
// }
if (Realm().objects(Subject).count == 0)
{
self.popover.contentViewController = WelcomeViewController(nibName:"WelcomeViewController", bundle:nil)
}
else
{
self.popover.contentViewController = TrackerViewController(nibName:"TrackerViewController", bundle:nil)
}
Fabric.with([Crashlytics.self])
NSUserDefaults.standardUserDefaults().registerDefaults(["NSApplicationCrashOnExceptions": true])
}
func applicationWillTerminate(aNotification: NSNotification)
{
}
private func showPopover(sender: AnyObject?)
{
if let button = statusItem.button {
popover.showRelativeToRect(button.bounds, ofView: button, preferredEdge: NSMinYEdge)
}
self.eventMonitor?.start()
}
private func hidePopover(sender: AnyObject?)
{
popover.performClose(sender)
self.eventMonitor?.stop()
}
func togglePopover(sender: AnyObject?)
{
if self.popover.shown
{
self.hidePopover(sender)
}
else
{
self.showPopover(sender)
}
}
}
// MARK: NSUserNotificationCenter Delegate Methods
extension AppDelegate: NSUserNotificationCenterDelegate
{
func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool
{
return true
}
func userNotificationCenter(center: NSUserNotificationCenter, didActivateNotification notification: NSUserNotification)
{
if (notification.activationType == NSUserNotificationActivationType.ActionButtonClicked)
{
let subjects = notification.valueForKey("_alternateActionButtonTitles") as! NSArray
let index = notification.valueForKey("_alternateActionIndex") as! Int
// There will be multiple Records on userInfo, delete irrelevant ones and save current subject's Record
let realm = Realm()
realm.write{
let payload = notification.userInfo as! Dictionary<String, Array<String>>
for recordId in payload["recordIDs"]!
{
let record = realm.objectForPrimaryKey(Record.self, key: recordId)!
let relevant = record.subject!.name == (subjects[index] as! String)
if (relevant)
{
record.endedAt = NSDate()
realm.add(record, update: true)
NSLog("FLUSH DB")
}
else
{
realm.delete(record)
}
}
}
}
}
}
| 84837edd1f095a866f5dee05652a9370 | 29.569536 | 133 | 0.578423 | false | false | false | false |
RuiAAPeres/Nuke | refs/heads/master | Nuke/Source/Core/ImageRequest.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2015 Alexander Grebenyuk (github.com/kean).
import Foundation
#if os(OSX)
import Cocoa
#else
import UIKit
#endif
public enum ImageContentMode {
case AspectFill
case AspectFit
}
/* Size to pass when requesting the original image available for a request (image won't be resized).
*/
public let ImageMaximumSize = CGSizeMake(CGFloat.max, CGFloat.max)
public struct ImageRequest {
public var URLRequest: NSURLRequest
/** Target size in pixels.
*/
public var targetSize: CGSize = ImageMaximumSize
public var contentMode: ImageContentMode = .AspectFill
public var shouldDecompressImage = true
/** Filter to be applied to the image. Use ImageProcessorComposition to compose multiple filters.
*/
public var processor: ImageProcessing?
public var userInfo: Any?
public init(URL: NSURL, targetSize: CGSize = ImageMaximumSize, contentMode: ImageContentMode = .AspectFill) {
self.URLRequest = NSURLRequest(URL: URL)
self.targetSize = targetSize
self.contentMode = contentMode
}
public init(URLRequest: NSURLRequest, targetSize: CGSize = ImageMaximumSize, contentMode: ImageContentMode = .AspectFill) {
self.URLRequest = URLRequest
self.targetSize = targetSize
self.contentMode = contentMode
}
}
public extension ImageRequest {
public var allowsCaching: Bool {
switch self.URLRequest.cachePolicy {
case .UseProtocolCachePolicy, .ReturnCacheDataElseLoad, .ReturnCacheDataDontLoad: return true
default: return false
}
}
public func isLoadEquivalentToRequest(other: ImageRequest) -> Bool {
let lhs = self.URLRequest, rhs = other.URLRequest
return lhs.URL == rhs.URL &&
lhs.cachePolicy == rhs.cachePolicy &&
lhs.timeoutInterval == rhs.timeoutInterval &&
lhs.networkServiceType == rhs.networkServiceType &&
lhs.allowsCellularAccess == rhs.allowsCellularAccess
}
public func isCacheEquivalentToRequest(other: ImageRequest) -> Bool {
return self.URLRequest.URL == other.URLRequest.URL
}
}
| a9d22c9a0b8c836af6630575441e68a0 | 31.308824 | 127 | 0.690487 | false | false | false | false |
epaga/PenguinMath | refs/heads/master | PenguinRace/GameScene.swift | apache-2.0 | 1 | //
// GameScene.swift
// PenguinRace
//
// Created by John Goering on 21/06/15.
// Copyright (c) 2015 John Goering. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
var screen1: GameScreenNode?
var screen2: GameScreenNode?
var pos1: CGFloat = 0
var pos2: CGFloat = 0
let baseSpeed: CGFloat = 3
var speed1: CGFloat = 2
var speed2: CGFloat = 2
var lastTime: NSTimeInterval = 0
override init(size: CGSize) {
super.init(size:size)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMoveToView(view: SKView) {
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
screen1 = GameScreenNode(gameWindow:self.frame, pixelWindow:CGSize(width: 2*self.frame.size.width, height: 2 * self.frame.size.height))
screen2 = GameScreenNode(gameWindow:self.frame, pixelWindow:CGSize(width: 2*self.frame.size.width, height: 2 * self.frame.size.height))
screen2?.screenNode.position = CGPoint(x:self.frame.size.width, y:self.frame.size.height)
screen2?.screenNode.zRotation = CGFloat(M_PI)
self.addChild(screen1!.screenNode)
self.addChild(screen2!.screenNode)
}
override func update(currentTime: CFTimeInterval) {
if lastTime == 0 {
lastTime = currentTime-0.01
}
let elapsedTime = CGFloat(currentTime - lastTime)
if speed1 < baseSpeed {
speed1 *= 1.01
} else if speed1 > baseSpeed {
speed1 *= 0.999
}
if speed2 < baseSpeed {
speed2 *= 1.01
} else if speed2 > baseSpeed {
speed2 *= 0.999
}
pos1 += elapsedTime*speed1
pos2 += elapsedTime*speed2
if pos1 >= 100 {
pos1 = 100
}
if pos2 >= 100 {
pos2 = 100
}
screen1?.moveToPosition(pos1)
screen1?.moveOtherToPosition(pos2)
screen2?.moveToPosition(pos2)
screen2?.moveOtherToPosition(pos1)
lastTime = currentTime
}
}
| 7a088022641335fd2f63868fc925034e | 30.835821 | 143 | 0.60947 | false | false | false | false |
brentsimmons/Evergreen | refs/heads/ios-candidate | Shared/ExtensionPoints/ExtensionPointIdentifer.swift | mit | 1 | //
// ExtensionPointIdentifer.swift
// NetNewsWire
//
// Created by Maurice Parker on 4/8/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import Foundation
import Account
import RSCore
enum ExtensionPointIdentifer: Hashable {
#if os(macOS)
case marsEdit
case microblog
#endif
case twitter(String)
case reddit(String)
var extensionPointType: ExtensionPoint.Type {
switch self {
#if os(macOS)
case .marsEdit:
return SendToMarsEditCommand.self
case .microblog:
return SendToMicroBlogCommand.self
#endif
case .twitter:
return TwitterFeedProvider.self
case .reddit:
return RedditFeedProvider.self
}
}
public var userInfo: [AnyHashable: AnyHashable] {
switch self {
#if os(macOS)
case .marsEdit:
return [
"type": "marsEdit"
]
case .microblog:
return [
"type": "microblog"
]
#endif
case .twitter(let screenName):
return [
"type": "twitter",
"screenName": screenName
]
case .reddit(let username):
return [
"type": "reddit",
"username": username
]
}
}
public init?(userInfo: [AnyHashable: AnyHashable]) {
guard let type = userInfo["type"] as? String else { return nil }
switch type {
#if os(macOS)
case "marsEdit":
self = ExtensionPointIdentifer.marsEdit
case "microblog":
self = ExtensionPointIdentifer.microblog
#endif
case "twitter":
guard let screenName = userInfo["screenName"] as? String else { return nil }
self = ExtensionPointIdentifer.twitter(screenName)
case "reddit":
guard let username = userInfo["username"] as? String else { return nil }
self = ExtensionPointIdentifer.reddit(username)
default:
return nil
}
}
public func hash(into hasher: inout Hasher) {
switch self {
#if os(macOS)
case .marsEdit:
hasher.combine("marsEdit")
case .microblog:
hasher.combine("microblog")
#endif
case .twitter(let screenName):
hasher.combine("twitter")
hasher.combine(screenName)
case .reddit(let username):
hasher.combine("reddit")
hasher.combine(username)
}
}
}
| 495e28190a7f9b08d3a5c3cd8fc01555 | 19.919192 | 79 | 0.686142 | false | false | false | false |
ontouchstart/swift3-playground | refs/heads/playgroundbook | Learn to Code 1.playgroundbook/Contents/Chapters/Document7.playgroundchapter/Pages/Challenge5.playgroundpage/Sources/SetUp.swift | mit | 1 | //
// SetUp.swift
//
// Copyright (c) 2016 Apple Inc. All Rights Reserved.
//
import Foundation
// MARK: Globals
let world = loadGridWorld(named: "7.9")
public let actor = Actor()
public func playgroundPrologue() {
placeRandomItems()
placeActor()
placePortals()
// Must be called in `playgroundPrologue()` to update with the current page contents.
registerAssessment(world, assessment: assessmentPoint)
//// ----
// Any items added or removed after this call will be animated.
finalizeWorldBuilding(for: world) {
realizeRandomItems()
}
//// ----
}
// Called from LiveView.swift to initially set the LiveView.
public func presentWorld() {
setUpLiveViewWith(world)
}
// MARK: Epilogue
public func playgroundEpilogue() {
sendCommands(for: world)
}
func placeActor() {
world.place(actor, facing: north, at: Coordinate(column: 3, row: 1))
}
func realizeRandomItems() {
let switches = [
Coordinate(column: 0, row: 2),
Coordinate(column: 1, row: 0),
Coordinate(column: 1, row: 7),
Coordinate(column: 2, row: 7),
Coordinate(column: 3, row: 7),
Coordinate(column: 3, row: 5),
Coordinate(column: 3, row: 4),
Coordinate(column: 3, row: 3),
Coordinate(column: 3, row: 0),
Coordinate(column: 4, row: 7),
Coordinate(column: 5, row: 1),
Coordinate(column: 5, row: 3),
Coordinate(column: 5, row: 4),
Coordinate(column: 5, row: 5),
Coordinate(column: 5, row: 6),
]
let switchNodes = world.place(nodeOfType: Switch.self, at: switches)
for switchNode in switchNodes {
if arc4random_uniform(6) % 2 == 0 {
switchNode.isOn = true
} else {
switchNode.isOn = false
}
}
let item = [
Coordinate(column: 0, row: 4),
]
world.placeGems(at: item)
}
func placeRandomItems() {
let switches = [
Coordinate(column: 0, row: 2),
Coordinate(column: 1, row: 0),
Coordinate(column: 1, row: 7),
Coordinate(column: 2, row: 7),
Coordinate(column: 3, row: 7),
Coordinate(column: 3, row: 5),
Coordinate(column: 3, row: 4),
Coordinate(column: 3, row: 3),
Coordinate(column: 3, row: 0),
Coordinate(column: 4, row: 7),
Coordinate(column: 5, row: 1),
Coordinate(column: 5, row: 3),
Coordinate(column: 5, row: 4),
Coordinate(column: 5, row: 5),
Coordinate(column: 5, row: 6),
]
let switchNode = Switch()
for eachSwitch in switches {
world.place(RandomNode(resembling: switchNode), at: eachSwitch)
}
}
func placePortals() {
world.place(Portal(color: .blue), between: Coordinate(column: 0, row: 7), and: Coordinate(column: 4, row: 6))
}
func placeBlocks() {
let obstacles = [
Coordinate(column: 0, row: 5),
Coordinate(column: 0, row: 6),
Coordinate(column: 1, row: 5),
Coordinate(column: 1, row: 6),
Coordinate(column: 2, row: 5),
Coordinate(column: 2, row: 6),
]
world.removeNodes(at: obstacles)
world.placeWater(at: obstacles)
let tiers = [
Coordinate(column: 5, row: 0),
Coordinate(column: 5, row: 1),
Coordinate(column: 5, row: 2),
Coordinate(column: 5, row: 3),
Coordinate(column: 5, row: 4),
Coordinate(column: 5, row: 5),
Coordinate(column: 5, row: 6),
Coordinate(column: 5, row: 7),
Coordinate(column: 5, row: 3),
Coordinate(column: 5, row: 4),
Coordinate(column: 5, row: 5),
Coordinate(column: 5, row: 6),
Coordinate(column: 5, row: 7),
Coordinate(column: 4, row: 6),
Coordinate(column: 4, row: 7),
Coordinate(column: 4, row: 7),
Coordinate(column: 3, row: 3),
Coordinate(column: 3, row: 4),
Coordinate(column: 3, row: 5),
Coordinate(column: 3, row: 6),
Coordinate(column: 3, row: 7),
Coordinate(column: 3, row: 7),
Coordinate(column: 0, row: 7),
Coordinate(column: 1, row: 7),
Coordinate(column: 2, row: 7),
Coordinate(column: 0, row: 7),
Coordinate(column: 1, row: 7),
Coordinate(column: 2, row: 7),
Coordinate(column: 0, row: 0),
Coordinate(column: 1, row: 0),
Coordinate(column: 0, row: 1),
Coordinate(column: 0, row: 2),
Coordinate(column: 0, row: 2),
Coordinate(column: 0, row: 3),
Coordinate(column: 0, row: 3),
Coordinate(column: 0, row: 4),
Coordinate(column: 1, row: 4),
Coordinate(column: 2, row: 4),
Coordinate(column: 0, row: 4),
Coordinate(column: 1, row: 4),
Coordinate(column: 2, row: 4),
Coordinate(column: 0, row: 4),
Coordinate(column: 1, row: 4),
Coordinate(column: 2, row: 4),
]
world.placeBlocks(at: tiers)
world.place(Stair(), facing: south, at: Coordinate(column: 0, row: 3))
world.place(Stair(), facing: west, at: Coordinate(column: 4, row: 0))
world.place(Stair(), facing: south, at: Coordinate(column: 3, row: 2))
world.place(Stair(), facing: east, at: Coordinate(column: 2, row: 0))
world.place(Stair(), facing: south, at: Coordinate(column: 0, row: 1))
world.place(Stair(), facing: south, at: Coordinate(column: 5, row: 2))
}
| 5b71784f6775cdce6e821eed5a46fddc | 28.973118 | 113 | 0.563049 | false | false | false | false |
dooch/mySwiftStarterApp | refs/heads/master | SwiftWeather/Essentials.swift | mit | 1 | //
// Essentials.swift
// SwiftWeather
//
// Created by CB on 4/02/2016.
// Copyright © 2016 Jake Lin. All rights reserved.
//
import Foundation
import UIKit
public class ImageLoader {
var cache = NSCache()
class var sharedLoader : ImageLoader {
struct Static {
static let instance : ImageLoader = ImageLoader()
}
return Static.instance
}
func imageForUrl(urlString: String, completionHandler:(image: UIImage?, url: String) -> ()) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {()in
let data: NSData? = self.cache.objectForKey(urlString) as? NSData
if let goodData = data {
let image = UIImage(data: goodData)
dispatch_async(dispatch_get_main_queue(), {() in
completionHandler(image: image, url: urlString)
})
return
}
let downloadTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if (error != nil) {
completionHandler(image: nil, url: urlString)
return
}
if data != nil {
let image = UIImage(data: data!)
self.cache.setObject(data!, forKey: urlString)
dispatch_async(dispatch_get_main_queue(), {() in
completionHandler(image: image, url: urlString)
})
return
}
})
downloadTask.resume()
})
}
}
| b46bc46de85dce630479e5199b9dcbd8 | 31.482143 | 214 | 0.518417 | false | false | false | false |
alessioros/mobilecodegenerator3 | refs/heads/master | examples/BookShelf/ios/completed/BookShelf/BookShelf/AppDelegate.swift | gpl-3.0 | 1 | import UIKit
import CoreData
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
// Configure Firebase
FirebaseApp.configure()
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "BookShelf")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| 81380ef425659f23914d5ae690a349ac | 51.511905 | 285 | 0.682612 | false | false | false | false |
gokselkoksal/Core | refs/heads/master | Core/Sources/Subscription.swift | mit | 1 | //
// Subscription.swift
// Core
//
// Created by Göksel Köksal on 04/06/2017.
// Copyright © 2017 GK. All rights reserved.
//
import Foundation
public protocol AnySubscriber: class, NavigationPerformer {
func _update(with state: State)
}
public protocol Subscriber: AnySubscriber {
associatedtype StateType: State
func update(with state: StateType)
}
public extension Subscriber {
func _update(with state: State) {
guard let state = state as? StateType else { return }
update(with: state)
}
}
internal struct Subscription {
internal private(set) weak var subscriber: AnySubscriber?
private let queue: DispatchQueue
internal init(subscriber: AnySubscriber?, queue: DispatchQueue) {
self.subscriber = subscriber
self.queue = queue
}
internal func notify(with newState: State) {
execute {
self.subscriber?._update(with: newState)
}
}
internal func notify(with navigation: Navigation) {
execute {
self.subscriber?.perform(navigation)
}
}
private func execute(_ block: @escaping () -> Void) {
if queue == DispatchQueue.main && Thread.isMainThread {
block()
} else {
queue.async {
block()
}
}
}
}
| c6bc57cf73d30fdfb82a8a6eb69bd9e8 | 20.172414 | 67 | 0.666938 | false | false | false | false |
sarahspins/Loop | refs/heads/master | Loop/Models/Glucose.swift | apache-2.0 | 1 | //
// GlucoseRxMessage.swift
// Loop
//
// Created by Nathan Racklyeft on 5/30/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import Foundation
import xDripG5
extension Glucose: SensorDisplayable {
var stateDescription: String {
let status: String
switch self.status {
case .OK:
status = ""
case .LowBattery:
status = NSLocalizedString(" Low Battery", comment: "The description of a low G5 transmitter battery with a leading space")
case .Unknown(let value):
status = String(format: "%02x", value)
}
return String(format: "%1$@ %2$@", String(state), status)
}
var trendType: GlucoseTrend? {
guard trend < Int(Int8.max) else {
return nil
}
switch trend {
case let x where x <= -30:
return .DownDownDown
case let x where x <= -20:
return .DownDown
case let x where x <= -10:
return .Down
case let x where x < 10:
return .Flat
case let x where x < 20:
return .Up
case let x where x < 30:
return .UpUp
default:
return .UpUpUp
}
}
}
| e55d43512c2563162d4a2977ef63798b | 23.98 | 135 | 0.542034 | false | false | false | false |
nahive/spotify-notify | refs/heads/master | SpotifyNotify/Storage/UserPreferences.swift | unlicense | 1 | //
// UserPreferences.swift
// SpotifyNotify
//
// Created by 先生 on 22/02/2018.
// Copyright © 2018 Szymon Maślanka. All rights reserved.
//
import Foundation
import Magnet
enum StatusBarIcon: Int {
case `default` = 0
case monochromatic = 1
case none = 99
init(value: Int?) {
guard let value = value else { self = .none; return }
self = StatusBarIcon(rawValue: value) ?? .none
}
}
struct UserPreferences {
private struct Keys {
static let appAlreadySetup = "already.setup.key"
static let notificationsEnabled = "notifications.enabled.key"
static let notificationsPlayPause = "notifications.playpause.key"
static let notificationsSound = "notifications.sound.key"
static let notificationsDisableOnFocus = "notifications.focus.key"
static let notificationsLength = "notifications.length.key"
static let startOnLogin = "startonlogin.key"
static let showAlbumArt = "showalbumart.key"
static let roundAlbumArt = "roundalbumart.key"
static let showSongProgress = "songprogress.key"
static let menuIcon = "menuicon.key"
static let shortcutKeyCode = "shortcut.keycode.key"
static let shortcutModifiers = "shortcut.modifiers.key"
}
private let defaults = UserDefaults.standard
var appAlreadySetup: Bool {
get { return defaults.bool(forKey: Keys.appAlreadySetup) }
set { defaults.set(newValue, forKey: Keys.appAlreadySetup) }
}
var notificationsEnabled: Bool {
get { return defaults.bool(forKey: Keys.notificationsEnabled) }
set { defaults.set(newValue, forKey: Keys.notificationsEnabled) }
}
var notificationsPlayPause: Bool {
get { return defaults.bool(forKey: Keys.notificationsPlayPause) }
set { defaults.set(newValue, forKey: Keys.notificationsPlayPause) }
}
var notificationsSound: Bool {
get { return defaults.bool(forKey: Keys.notificationsSound) }
set { defaults.set(newValue, forKey: Keys.notificationsSound) }
}
var notificationsDisableOnFocus: Bool {
get { return defaults.bool(forKey: Keys.notificationsDisableOnFocus) }
set { defaults.set(newValue, forKey: Keys.notificationsDisableOnFocus) }
}
var notificationsLength: Int {
get { return defaults.integer(forKey: Keys.notificationsLength) }
set { defaults.set(newValue, forKey: Keys.notificationsLength) }
}
var startOnLogin: Bool {
get { return defaults.bool(forKey: Keys.startOnLogin) }
set { defaults.set(newValue, forKey: Keys.startOnLogin) }
}
var showAlbumArt: Bool {
get { return defaults.bool(forKey: Keys.showAlbumArt) }
set { defaults.set(newValue, forKey: Keys.showAlbumArt) }
}
var roundAlbumArt: Bool {
get { return defaults.bool(forKey: Keys.roundAlbumArt) }
set { defaults.set(newValue, forKey: Keys.roundAlbumArt) }
}
var showSongProgress: Bool {
get { return defaults.bool(forKey: Keys.showSongProgress) }
set { defaults.set(newValue, forKey: Keys.showSongProgress) }
}
var menuIcon: StatusBarIcon {
get { return StatusBarIcon(value: defaults.integer(forKey: Keys.menuIcon)) }
set { defaults.set(newValue.rawValue, forKey: Keys.menuIcon) }
}
var shortcut: KeyCombo? {
get {
let keycode = defaults.integer(forKey: Keys.shortcutKeyCode)
let modifiers = defaults.integer(forKey: Keys.shortcutModifiers)
guard keycode != 0 && modifiers != 0 else { return nil }
return KeyCombo(QWERTYKeyCode: keycode, carbonModifiers: modifiers)
}
set {
guard let keyCombo = newValue else {
defaults.set(0, forKey: Keys.shortcutKeyCode)
defaults.set(0, forKey: Keys.shortcutModifiers)
return
}
defaults.set(keyCombo.QWERTYKeyCode, forKey: Keys.shortcutKeyCode)
defaults.set(keyCombo.modifiers, forKey: Keys.shortcutModifiers)
}
}
}
| 4f01f1e4d408c2b222c3b535ed77ba2f | 30.92437 | 78 | 0.714135 | false | false | false | false |
mozilla-magnet/magnet-client | refs/heads/master | ios/NotificationsHelperIOS10.swift | mpl-2.0 | 1 | //
// NotificationsHelperIOS10.swift
// Magnet
//
// Created by Francisco Jordano on 04/11/2016.
// Copyright © 2016 Mozilla. All rights reserved.
//
import Foundation
import UserNotifications
import UserNotificationsUI
import SwiftyJSON
@available(iOS 10.0, *)
class NotificationsHelperIOS10: NSObject, UNUserNotificationCenterDelegate {
private static let CATEGORY = "magnet.notifications.category"
override init() {
super.init()
UNUserNotificationCenter.currentNotificationCenter().delegate = self
}
func processNotifications(toNotify: Dictionary<String, String>) {
toNotify.keys.forEach { (url) in
let channel = toNotify[url]
processNotification(url, channel: channel!)
}
}
private func processNotification(url: String, channel: String) {
Log.l("Processing notification for \(url)")
fetchData(url, callback: { (json) in
do {
guard json[0] != nil && json[0]["description"] != nil && json[0]["title"] != nil else {
return
}
try self.showRichNotification(json[0]["title"].string!,
subtitle: "by \(channel)",
body: json[0]["description"].string!,
image: json[0]["image"].string,
url: url)
Log.l("Dispatching rich notification for \(json.rawString())")
} catch {
Log.w("Could not launch notification for \(url) : \(channel)")
}
})
}
private func fetchData(url: String, callback: ((JSON) -> Void)) {
let api = ApiMetadata()
let urls: NSArray = [url]
api.post("metadata", data: urls, callback: ApiCallback(success: { json in
callback(json)
}, error: { (err) in
debugPrint("Could not get metadata for \(url): \(err)")
}))
}
private func showRichNotification(title: String, subtitle: String, body: String, image: String?, url: String) {
let content = UNMutableNotificationContent()
content.title = title
content.subtitle = subtitle
content.body = body
if let _image: String = image! {
content.launchImageName = _image
}
content.categoryIdentifier = NotificationsHelperIOS10.CATEGORY
let action = UNNotificationAction(identifier: "visit", title: "Visit", options: UNNotificationActionOptions.Foreground)
let category = UNNotificationCategory(identifier: NotificationsHelperIOS10.CATEGORY, actions: [action], intentIdentifiers: [], options: [])
UNUserNotificationCenter.currentNotificationCenter().setNotificationCategories([category])
// Trigger this notification in 1 second from now.
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 1, repeats: false)
let request = UNNotificationRequest(identifier: url, content: content, trigger: trigger)
UNUserNotificationCenter.currentNotificationCenter().addNotificationRequest(request, withCompletionHandler: {error in
guard let error = error else {
return
}
Log.w("Error while sending notification \(error)")
})
}
func userNotificationCenter(center: UNUserNotificationCenter, didReceiveNotificationResponse response: UNNotificationResponse, withCompletionHandler completionHandler: () -> Void) {
if (response.actionIdentifier == "visit") {
Log.l("Launching web page \(response.notification.request.identifier)")
let url = NSURL(string: response.notification.request.identifier)
UIApplication.sharedApplication().openURL(url!, options: [:], completionHandler: nil)
} else {
// We were clicked but not the visit (go to browser) action
// so we navigate to the deep link inside the app
let url = NSURL(string: "mozilla-magnet://item?url=\(response.notification.request.identifier)")
UIApplication.sharedApplication().openURL(url!, options: [:], completionHandler: nil)
}
}
}
| 57aa9cb8f2e3cbbcbcc68735d641bd7f | 37.5 | 183 | 0.682597 | false | false | false | false |
warumono-for-develop/SwiftPageViewController | refs/heads/master | SwiftPageViewController/SwiftPageViewController/IntroViewController.swift | mit | 1 | //
// IntroViewController.swift
// Maniau1
//
// Created by kevin on 2017. 2. 24..
// Copyright © 2017년 warumono. All rights reserved.
//
import UIKit
class IntroViewController: UIViewController
{
@IBOutlet weak var pageControl: UIPageControl!
@IBOutlet weak var containerView: UIView!
fileprivate var introPageViewController: IntroPageViewController?
{
didSet
{
introPageViewController?.introPageViewControllerDataSource = self
introPageViewController?.introPageViewControllerDelegate = self
}
}
override var preferredStatusBarStyle: UIStatusBarStyle
{
return .lightContent
}
override func viewDidLoad()
{
super.viewDidLoad()
// Do any additional setup after loading the view.
pageControl.addTarget(self, action: #selector(IntroViewController.didChangePage), for: .valueChanged)
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
if let introPageViewController = segue.destination as? IntroPageViewController
{
self.introPageViewController = introPageViewController
}
}
}
extension IntroViewController
{
@IBAction func didTouch(_ sender: UIButton)
{
if sender.tag == 0
{
if pageControl.numberOfPages <= pageControl.currentPage + 1
{
return
}
introPageViewController?.pageTo(at: pageControl.numberOfPages - 1)
}
else if sender.tag == 1
{
introPageViewController?.next()
}
}
@objc fileprivate func didChangePage()
{
introPageViewController?.pageTo(at: pageControl.currentPage)
}
}
extension IntroViewController: IntroPageViewControllerDataSource
{
func introPageViewController(_ pageViewController: IntroPageViewController, numberOfPages pages: Int)
{
pageControl.numberOfPages = pages
}
}
extension IntroViewController: IntroPageViewControllerDelegate
{
func introPageViewController(_ pageViewController: IntroPageViewController, didChangePageIndex index: Int)
{
pageControl.currentPage = index
}
}
| 2dddf7d357d54e30ad4f8ecaee123dd9 | 21.311828 | 107 | 0.760482 | false | false | false | false |
karivalkama/Agricola-Scripture-Editor | refs/heads/master | TranslationEditor/StatefulStackView.swift | mit | 1 | //
// StatefulStackView.swift
// TranslationEditor
//
// Created by Mikko Hilpinen on 16.6.2017.
// Copyright © 2017 SIL. All rights reserved.
//
import UIKit
enum DataState
{
// Data is not yet available, but is being retrieved
case loading
// No data was found
case empty
// An error occurred while retrieving data
case error
// Data was found and loaded successfully
case data
}
// This stack view is designed to change visible content based on program status
class StatefulStackView: UIStackView
{
// ATTRIBUTES -----------------
private var views = [DataState: Weak<UIView>]()
private var lastState: DataState?
// OTHER METHODS -------------
func dataLoaded(isEmpty: Bool = false)
{
setState(isEmpty ? .empty : .data)
}
func errorOccurred(title: String? = nil, description: String? = nil, canContinueWithData: Bool = true)
{
if !canContinueWithData || lastState != .data
{
if title != nil || description != nil
{
registerDefaultErrorView(heading: title, description: description)
}
setState(.error)
}
}
func setState(_ state: DataState)
{
if lastState == state
{
return
}
else
{
lastState = state
}
// Makes sure there exists a suitable view in the stack
if !views[state].exists({ $0.isDefined })
{
var defaultView: UIView?
switch state
{
case .loading: defaultView = DefaultLoadingView()
case .empty: defaultView = DefaultNoDataView()
case .error: defaultView = DefaultErrorView()
default: defaultView = nil
}
if let defaultView = defaultView
{
register(defaultView, for: state)
}
else
{
return
}
}
// Sets the view for the state visible and other views invisible
views.values.forEach { $0.value?.isHidden = true }
views[state]?.value?.isHidden = false
}
func register(_ view: UIView, for state: DataState)
{
// Removes any previous view for that state
if let previousView = views[state]?.value
{
removeArrangedSubview(previousView)
}
views[state] = Weak(view)
// Adds the view to this stack view if not already
if !view.isDescendant(of: self)
{
view.isHidden = true
addArrangedSubview(view)
}
}
func registerDefaultLoadingView(title: String? = nil)
{
let view = DefaultLoadingView()
if let title = title
{
view.title = title
}
register(view, for: .loading)
}
func registerDefaultErrorView(heading: String? = nil, description: String? = nil)
{
let view = DefaultErrorView()
if let heading = heading
{
view.title = heading
}
if let description = description
{
view.errorDescription = description
}
register(view, for: .error)
}
func registerDefaultNoDataView(heading: String? = nil, description: String? = nil)
{
let view = DefaultNoDataView()
if let heading = heading
{
view.title = heading
}
if let description = description
{
view.extraDescription = description
}
register(view, for: .empty)
}
}
| dcb1d289d167c68e0c34c2d04923b3ea | 18.81457 | 103 | 0.664104 | false | false | false | false |
AnthonyMDev/CrashlyticsRecorder | refs/heads/master | Pod/Classes/AnalyticsRecorder.swift | mit | 1 | //
// AnalyticsRecorder.swift
// CrashlyticsRecorder
//
// Created by David Whetstone on 1/7/19.
//
import Foundation
public protocol AnalyticsProtocol: class {
static func logEvent(_ name: String, parameters: [String: Any]?)
static func setUserProperty(_ value: String?, forName name: String)
static func setUserID(_ userID: String?)
static func setScreenName(_ screenName: String?, screenClass screenClassOverride: String?)
static func appInstanceID() -> String
static func resetAnalyticsData()
}
public class AnalyticsRecorder {
/// The `AnalyticsRecorder` shared instance to be used for recording Analytics events
public private(set) static var sharedInstance: AnalyticsRecorder?
private var analyticsClass: AnalyticsProtocol.Type
private init(analyticsClass: AnalyticsProtocol.Type) {
self.analyticsClass = analyticsClass
}
/**
Creates the `sharedInstance` with the `Analytics` class for the application. This method should be called in `application:didFinishLaunchingWithOptions:`.
- parameter analytics: The `Analytics` class from the `FirebaseCore` framework.
- returns: The created `FirebaseRecorder` shared instance
*/
public class func createSharedInstance(analytics analyticsClass: AnalyticsProtocol.Type) -> AnalyticsRecorder {
let recorder = AnalyticsRecorder(analyticsClass: analyticsClass)
sharedInstance = recorder
return recorder
}
public func logEvent(_ name: String, parameters: [String: Any]?) {
analyticsClass.logEvent(name, parameters: parameters)
}
public func setUserProperty(_ value: String?, forName name: String) {
analyticsClass.setUserProperty(value, forName: name)
}
public func setUserID(_ userID: String?) {
analyticsClass.setUserID(userID)
}
public func setScreenName(_ screenName: String?, screenClass screenClassOverride: String?) {
analyticsClass.setScreenName(screenName, screenClass: screenClassOverride)
}
public func appInstanceID() -> String {
return analyticsClass.appInstanceID()
}
public func resetAnalyticsData() {
analyticsClass.resetAnalyticsData()
}
}
public extension AnalyticsRecorder {
public func logEvent(_ name: AnalyticsEvent, parameters: [AnalyticsParameter: Any]? = nil) {
let parameters = parameters?.reduce(into: [:]) { result, x in result[x.key.rawValue] = x.value }
logEvent(name.rawValue, parameters: parameters)
}
public func setUserProperty(_ value: String?, forName name: AnalyticsUserProperty) {
analyticsClass.setUserProperty(value, forName: name.rawValue)
}
}
public enum AnalyticsEvent: String {
case addPaymentInfo = "add_payment_info"
case addToCart = "add_to_cart"
case addToWishlist = "add_to_wishlist"
case appOpen = "app_open"
case beginCheckout = "begin_checkout"
case campaignDetails = "campaign_details"
case checkoutProgress = "checkout_progress"
case earnVirtualCurrency = "earn_virtual_currency"
case ecommercePurchase = "ecommerce_purchase"
case generateLead = "generate_lead"
case joinGroup = "join_group"
case levelUp = "level_up"
case login = "login"
case postScore = "post_score"
case presentOffer = "present_offer"
case purchaseRefund = "purchase_refund"
case removeFromCart = "remove_from_cart"
case search = "search"
case selectContent = "select_content"
case setCheckoutOption = "set_checkout_option"
case share = "share"
case signUp = "sign_up"
case spendVirtualCurrency = "spend_virtual_currency"
case tutorialBegin = "tutorial_begin"
case tutorialComplete = "tutorial_complete"
case unlockAchievement = "unlock_achievement"
case viewItem = "view_item"
case viewItemList = "view_item_list"
case viewSearchResults = "view_search_results"
case levelStart = "level_start"
case levelEnd = "level_end"
}
public enum AnalyticsParameter: String {
case achievementID = "achievement_id"
case adNetworkClickID = "aclid"
case affiliation = "affiliation"
case campaign = "campaign"
case character = "character"
case checkoutStep = "checkout_step"
case checkoutOption = "checkout_option"
case content = "content"
case contentType = "content_type"
case coupon = "coupon"
case cP1 = "cp1"
case creativeName = "creative_name"
case creativeSlot = "creative_slot"
case currency = "currency"
case destination = "destination"
case endDate = "end_date"
case flightNumber = "flight_number"
case groupID = "group_id"
case index = "index"
case itemBrand = "item_brand"
case itemCategory = "item_category"
case itemID = "item_id"
case itemLocationID = "item_location_id"
case itemName = "item_name"
case itemList = "item_list"
case itemVariant = "item_variant"
case level = "level"
case location = "location"
case medium = "medium"
case numberOfNights = "number_of_nights"
case numberOfPassengers = "number_of_passengers"
case numberOfRooms = "number_of_rooms"
case origin = "origin"
case price = "price"
case quantity = "quantity"
case score = "score"
case searchTerm = "search_term"
case shipping = "shipping"
case signUpMethod = "sign_up_method"
case source = "source"
case startDate = "start_date"
case tax = "tax"
case term = "term"
case transactionID = "transaction_id"
case travelClass = "travel_class"
case value = "value"
case virtualCurrencyName = "virtual_currency_name"
case levelName = "level_name"
case success = "success"
}
public enum AnalyticsUserProperty: String {
case signUpMethod = "sign_up_method"
}
| ddcb3b8c3c1d61be95510af6eca79a05 | 36.624277 | 159 | 0.618682 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | refs/heads/master | Source/LoadStateViewController.swift | apache-2.0 | 2 | //
// LoadStateViewController.swift
// edX
//
// Created by Akiva Leffert on 5/13/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import Foundation
import edXCore
public enum LoadState {
case Initial
case Loaded
case Empty(icon : Icon?, message : String?, attributedMessage : NSAttributedString?, accessibilityMessage : String?, buttonInfo : MessageButtonInfo?)
// if attributed message is set then message is ignored
// if message is set then the error is ignored
case Failed(error : NSError?, icon : Icon?, message : String?, attributedMessage : NSAttributedString?, accessibilityMessage : String?, buttonInfo : MessageButtonInfo?)
var accessibilityMessage : String? {
switch self {
case Initial: return nil
case Loaded: return nil
case let Empty(info): return info.accessibilityMessage
case let Failed(info): return info.accessibilityMessage
}
}
var isInitial : Bool {
switch self {
case .Initial: return true
default: return false
}
}
var isLoaded : Bool {
switch self {
case .Loaded: return true
default: return false
}
}
var isError : Bool {
switch self {
case .Failed(_): return true
default: return false
}
}
static func failed(error : NSError? = nil, icon : Icon? = .UnknownError, message : String? = nil, attributedMessage : NSAttributedString? = nil, accessibilityMessage : String? = nil, buttonInfo : MessageButtonInfo? = nil) -> LoadState {
return LoadState.Failed(error : error, icon : icon, message : message, attributedMessage : attributedMessage, accessibilityMessage : accessibilityMessage, buttonInfo : buttonInfo)
}
static func empty(icon icon : Icon?, message : String? = nil, attributedMessage : NSAttributedString? = nil, accessibilityMessage : String? = nil, buttonInfo : MessageButtonInfo? = nil) -> LoadState {
return LoadState.Empty(icon: icon, message: message, attributedMessage: attributedMessage, accessibilityMessage : accessibilityMessage, buttonInfo : buttonInfo)
}
}
/// A controller should implement this protocol to support reloading with fullscreen errors for unknownErrors
@objc protocol LoadStateViewReloadSupport {
func loadStateViewReload()
}
class LoadStateViewController : UIViewController {
private let loadingView : UIView
private var contentView : UIView?
private let messageView : IconMessageView
private var delegate: LoadStateViewReloadSupport?
private var madeInitialAppearance : Bool = false
var state : LoadState = .Initial {
didSet {
// this sets a background color so when the view is pushed in it doesn't have a black or weird background
switch state {
case .Initial:
view.backgroundColor = OEXStyles.sharedStyles().standardBackgroundColor()
default:
view.backgroundColor = UIColor.clearColor()
}
updateAppearanceAnimated(madeInitialAppearance)
}
}
var insets : UIEdgeInsets = UIEdgeInsetsZero {
didSet {
self.view.setNeedsUpdateConstraints()
}
}
init() {
messageView = IconMessageView()
loadingView = SpinnerView(size: .Large, color: .Primary)
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var messageStyle : OEXTextStyle {
return messageView.messageStyle
}
override func loadView() {
self.view = PassthroughView()
}
func setupInController(controller : UIViewController, contentView : UIView) {
controller.addChildViewController(self)
didMoveToParentViewController(controller)
self.contentView = contentView
contentView.alpha = 0
controller.view.addSubview(loadingView)
controller.view.addSubview(messageView)
controller.view.addSubview(self.view)
if isSupportingReload() {
delegate = controller as? LoadStateViewReloadSupport
}
}
func loadStateViewReload() {
if isSupportingReload() {
delegate?.loadStateViewReload()
}
}
func isSupportingReload() -> Bool {
if let _ = self.parentViewController as? LoadStateViewReloadSupport as? UIViewController {
return true
}
return false
}
override func viewDidLoad() {
super.viewDidLoad()
messageView.alpha = 0
view.addSubview(messageView)
view.addSubview(loadingView)
state = .Initial
self.view.setNeedsUpdateConstraints()
self.view.userInteractionEnabled = false
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
madeInitialAppearance = true
}
override func updateViewConstraints() {
loadingView.snp_updateConstraints {make in
make.center.equalTo(view)
}
messageView.snp_updateConstraints {make in
make.center.equalTo(view)
}
view.snp_updateConstraints { make in
if let superview = view.superview {
make.edges.equalTo(superview).inset(insets)
}
}
super.updateViewConstraints()
}
private func updateAppearanceAnimated(animated : Bool) {
var alphas : (loading : CGFloat, message : CGFloat, content : CGFloat, touchable : Bool) = (loading : 0, message : 0, content : 0, touchable : false)
UIView.animateWithDuration(0.3 * NSTimeInterval(animated)) {
switch self.state {
case .Initial:
alphas = (loading : 1, message : 0, content : 0, touchable : false)
case .Loaded:
alphas = (loading : 0, message : 0, content : 1, touchable : false)
case let .Empty(info):
self.messageView.buttonInfo = info.buttonInfo
UIView.performWithoutAnimation {
if let message = info.attributedMessage {
self.messageView.attributedMessage = message
}
else {
self.messageView.message = info.message
}
self.messageView.icon = info.icon
}
alphas = (loading : 0, message : 1, content : 0, touchable : true)
case let .Failed(info):
self.messageView.buttonInfo = info.buttonInfo
UIView.performWithoutAnimation {
if let error = info.error where error.oex_isNoInternetConnectionError {
self.messageView.showError(Strings.networkNotAvailableMessageTrouble, icon: .InternetError)
}
else if let error = info.error as? OEXAttributedErrorMessageCarrying {
self.messageView.showError(error.attributedDescriptionWithBaseStyle(self.messageStyle), icon: info.icon)
}
else if let message = info.attributedMessage {
self.messageView.showError(message, icon: info.icon)
}
else if let message = info.message {
self.messageView.showError(message, icon: info.icon)
}
else if let error = info.error where error.errorIsThisType(NSError.oex_unknownNetworkError()) {
self.messageView.showError(Strings.unknownError, icon: info.icon)
}
else if let error = info.error where error.errorIsThisType(NSError.oex_outdatedVersionError()) {
self.messageView.setupForOutdatedVersionError()
}
else {
self.messageView.showError(info.error?.localizedDescription, icon: info.icon)
}
}
alphas = (loading : 0, message : 1, content : 0, touchable : true)
dispatch_async(dispatch_get_main_queue()) { [weak self] in
self?.parentViewController?.hideSnackBar()
}
}
self.messageView.accessibilityMessage = self.state.accessibilityMessage
self.loadingView.alpha = alphas.loading
self.messageView.alpha = alphas.message
self.contentView?.alpha = alphas.content
self.view.userInteractionEnabled = alphas.touchable
}
}
}
| e339dd0a69858d41e3fceec1b2742a49 | 36.512712 | 240 | 0.599232 | false | false | false | false |
guoc/excerptor | refs/heads/master | Excerptor/Preferences.swift | mit | 1 | //
// Preferences.swift
// Excerptor
//
// Created by Chen Guo on 23/05/2015.
// Copyright (c) 2015 guoc. All rights reserved.
//
import Foundation
private let sharedInstance = Preferences()
class Preferences: NSObject, PrefsPaneDelegate {
fileprivate var userDefaults: UserDefaults = {
var userDefaults = UserDefaults(suiteName: "name.guoc.excerptor")!
let defaultValuesFilePath = Bundle.main.path(forResource: "PreferencesDefaultValues", ofType: "plist")!
guard let defaultValues = NSDictionary(contentsOfFile: defaultValuesFilePath)! as? [String: AnyObject] else {
exitWithError("Fail to read preferences default values: \(NSDictionary(contentsOfFile: defaultValuesFilePath)!)")
}
userDefaults.register(defaults: defaultValues)
if Preferences.dntpIsInstalled() {
let defaultValuesForDNtpFilePath = Bundle.main.path(forResource: "PreferencesDefaultValues(DNtp)", ofType: "plist")!
guard let defaultValuesForDNtp = NSDictionary(contentsOfFile: defaultValuesForDNtpFilePath)! as? [String: AnyObject] else {
exitWithError("Fail to read preferences default values for DNtp: \(NSDictionary(contentsOfFile: defaultValuesForDNtpFilePath)!)")
}
userDefaults.register(defaults: defaultValuesForDNtp)
}
return userDefaults
}()
class var sharedPreferences: Preferences {
return sharedInstance
}
static func dntpIsInstalled() -> Bool {
return (LSCopyApplicationURLsForBundleIdentifier("com.devon-technologies.thinkpro2" as CFString, nil) != nil)
}
let boolForSelectionLinkIncludesBoundsInfo = false
// MARK: PrefsPaneDelegate
fileprivate struct Constants {
static let AppForOpenPDF = "AppForOpenPDF"
static let SelectionLinkPlainText = "SelectionLinkPlainText"
static let SelectionLinkRichTextSameAsPlainText = "SelectionLinkRichTextSameAsPlainText"
static let SelectionLinkRichText = "SelectionLinkRichText"
static let ShowNotificationWhenFileNotFoundInDNtpForSelectionLink = "ShowNotificationWhenFileNotFoundInDNtpForSelectionLink" // swiftlint:disable:this identifier_name
static let SelectionFilesLocation = "SelectionFilesLocation"
static let SelectionFileName = "SelectionFileName"
static let SelectionFileExtension = "SelectionFileExtension"
static let SelectionFileTags = "SelectionFileTags"
static let SelectionFileContent = "SelectionFileContent"
static let ShowNotificationWhenFileNotFoundInDNtpForSelectionFile = "ShowNotificationWhenFileNotFoundInDNtpForSelectionFile" // swiftlint:disable:this identifier_name
static let AnnotationFilesLocation = "AnnotationFilesLocation"
static let AnnotationFileName = "AnnotationFileName"
static let AnnotationFileExtension = "AnnotationFileExtension"
static let AnnotationFileTags = "AnnotationFileTags"
static let AnnotationFileContent = "AnnotationFileContent"
static let ShowNotificationWhenFileNotFoundInDNtpForAnnotationFile = "ShowNotificationWhenFileNotFoundInDNtpForAnnotationFile" // swiftlint:disable:this identifier_name
// Hidden preferences
static let PathVariables = "PathVariables"
static let PathSubstitutes = "PathSubstitutes"
}
// swiftlint:disable variable_name
struct CommonPlaceholders {
static let PDFFileLink_DEVONthinkUUIDType = "{{PDFFileLink_DEVONthinkUUID}}"
static let PDFFileLink_FilePathType = "{{PDFFileLink_FilePath}}"
static let PDFFilePath = "{{PDFFilePath}}"
static let PDFFileName = "{{PDFFileName}}"
static let PDFFileName_NoExtension = "{{PDFFileName_NoExtension}}"
static let PDFFileDEVONthinkUUID = "{{PDFFileDEVONthinkUUID}}"
static let Page = "{{Page}}"
}
struct SelectionPlaceholders {
static let SelectionText = "{{SelectionText}}"
static let UserName = "{{UserName}}"
static let CreationDate = "{{CreationDate}}"
static let SelectionLink_DEVONthinkUUIDType = "{{SelectionLink_DEVONthinkUUID}}"
static let SelectionLink_FilePathType = "{{SelectionLink_FilePath}}"
}
struct AnnotationPlaceholders {
static let AnnotationText = "{{AnnotationText}}"
static let NoteText = "{{NoteText}}"
static let annotationType = "{{Type}}"
static let Color = "{{Color}}"
static let Author = "{{Author}}"
static let AnnotationDate = "{{AnnotationDate}}"
static let ExportDate = "{{ExportDate}}"
static let AnnotationLink_DEVONthinkUUIDType = "{{AnnotationLink_DEVONthinkUUID}}"
static let AnnotationLink_FilePathType = "{{AnnotationLink_FilePath}}"
}
// swiftlint:enable variable_name
static let availablePlaceholders: [String] = { () -> [String] in
let selectionPlaceholders = Set(Preferences.availableSelectionPlaceholders)
let annotationPlaceholders = Set(Preferences.availableAnnotationPlaceholders)
return [String](selectionPlaceholders.union(annotationPlaceholders))
}()
static let availableSelectionPlaceholders = [
Preferences.CommonPlaceholders.PDFFileLink_DEVONthinkUUIDType,
Preferences.CommonPlaceholders.PDFFileLink_FilePathType,
Preferences.CommonPlaceholders.PDFFilePath,
Preferences.CommonPlaceholders.PDFFileName,
Preferences.CommonPlaceholders.PDFFileName_NoExtension,
Preferences.CommonPlaceholders.PDFFileDEVONthinkUUID,
Preferences.CommonPlaceholders.Page,
Preferences.SelectionPlaceholders.SelectionText,
Preferences.SelectionPlaceholders.UserName,
Preferences.SelectionPlaceholders.CreationDate,
Preferences.SelectionPlaceholders.SelectionLink_DEVONthinkUUIDType,
Preferences.SelectionPlaceholders.SelectionLink_FilePathType
]
static let availableAnnotationPlaceholders = [
Preferences.CommonPlaceholders.PDFFileLink_DEVONthinkUUIDType,
Preferences.CommonPlaceholders.PDFFileLink_FilePathType,
Preferences.CommonPlaceholders.PDFFilePath,
Preferences.CommonPlaceholders.PDFFileName,
Preferences.CommonPlaceholders.PDFFileName_NoExtension,
Preferences.CommonPlaceholders.PDFFileDEVONthinkUUID,
Preferences.CommonPlaceholders.Page,
Preferences.AnnotationPlaceholders.AnnotationText,
Preferences.AnnotationPlaceholders.NoteText,
Preferences.AnnotationPlaceholders.annotationType,
Preferences.AnnotationPlaceholders.Color,
Preferences.AnnotationPlaceholders.Author,
Preferences.AnnotationPlaceholders.AnnotationDate,
Preferences.AnnotationPlaceholders.ExportDate,
Preferences.AnnotationPlaceholders.AnnotationLink_DEVONthinkUUIDType,
Preferences.AnnotationPlaceholders.AnnotationLink_FilePathType
]
var availablePlaceholders: [Any] {
return Preferences.availablePlaceholders as [AnyObject]
}
var availableSelectionPlaceholders: [Any] {
return Preferences.availableSelectionPlaceholders as [AnyObject]
}
var availableAnnotationPlaceholders: [Any] {
return Preferences.availableAnnotationPlaceholders as [AnyObject]
}
var appForOpenPDF: PDFReaderApp {
get {
self.userDefaults.synchronize()
return PDFReaderApp(rawValue: self.userDefaults.integer(forKey: Constants.AppForOpenPDF))!
}
set {
self.userDefaults.set(newValue.rawValue, forKey: Constants.AppForOpenPDF)
self.userDefaults.synchronize()
}
}
var stringForSelectionLinkPlainText: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionLinkPlainText)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionLinkPlainText)
self.userDefaults.synchronize()
}
}
var boolForSelectionLinkRichTextSameAsPlainText: Bool { // swiftlint:disable:this identifier_name
get {
self.userDefaults.synchronize()
return self.userDefaults.bool(forKey: Constants.SelectionLinkRichTextSameAsPlainText)
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionLinkRichTextSameAsPlainText)
self.userDefaults.synchronize()
}
}
var stringForSelectionLinkRichText: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionLinkRichText)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionLinkRichText)
self.userDefaults.synchronize()
}
}
// swiftlint:disable identifier_name
var boolForShowNotificationWhenFileNotFoundInDNtpForSelectionLink: Bool {
get {
self.userDefaults.synchronize()
return self.userDefaults.bool(forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForSelectionLink)
}
set {
self.userDefaults.set(newValue, forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForSelectionLink)
self.userDefaults.synchronize()
}
}
var stringForSelectionFilesLocation: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionFilesLocation)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionFilesLocation)
self.userDefaults.synchronize()
}
}
var stringForSelectionFileName: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionFileName)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionFileName)
self.userDefaults.synchronize()
}
}
var stringForSelectionFileExtension: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionFileExtension)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionFileExtension)
self.userDefaults.synchronize()
}
}
var stringForSelectionFileTags: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionFileTags)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionFileTags)
self.userDefaults.synchronize()
}
}
var stringForSelectionFileContent: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.SelectionFileContent)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.SelectionFileContent)
self.userDefaults.synchronize()
}
}
var boolForShowNotificationWhenFileNotFoundInDNtpForSelectionFile: Bool {
get {
self.userDefaults.synchronize()
return self.userDefaults.bool(forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForSelectionFile)
}
set {
self.userDefaults.set(newValue, forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForSelectionFile)
self.userDefaults.synchronize()
}
}
var stringForAnnotationFilesLocation: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.AnnotationFilesLocation)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.AnnotationFilesLocation)
self.userDefaults.synchronize()
}
}
var stringForAnnotationFileName: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.AnnotationFileName)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.AnnotationFileName)
self.userDefaults.synchronize()
}
}
var stringForAnnotationFileExtension: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.AnnotationFileExtension)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.AnnotationFileExtension)
self.userDefaults.synchronize()
}
}
var stringForAnnotationFileTags: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.AnnotationFileTags)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.AnnotationFileTags)
self.userDefaults.synchronize()
}
}
var stringForAnnotationFileContent: String {
get {
self.userDefaults.synchronize()
return self.userDefaults.string(forKey: Constants.AnnotationFileContent)!
}
set {
self.userDefaults.set(newValue, forKey: Constants.AnnotationFileContent)
self.userDefaults.synchronize()
}
}
var boolForShowNotificationWhenFileNotFoundInDNtpForAnnotationFile: Bool {
get {
self.userDefaults.synchronize()
return self.userDefaults.bool(forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForAnnotationFile)
}
set {
self.userDefaults.set(newValue, forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForAnnotationFile)
self.userDefaults.synchronize()
}
}
// Hidden preferences
var dictionaryForPathVariables: [String: String] {
self.userDefaults.synchronize()
guard let dict = self.userDefaults.dictionary(forKey: Constants.PathVariables) as? [String: String] else {
return [String: String]()
}
return dict
}
var dictionaryForPathSubstitutes: [String: String] {
self.userDefaults.synchronize()
guard let dict = self.userDefaults.dictionary(forKey: Constants.PathSubstitutes) as? [String: String] else {
return [String: String]()
}
return dict
}
func resetSelectionLinkPreferences() {
self.userDefaults.removeObject(forKey: Constants.SelectionLinkPlainText)
self.userDefaults.removeObject(forKey: Constants.SelectionLinkRichTextSameAsPlainText)
self.userDefaults.removeObject(forKey: Constants.SelectionLinkRichText)
self.userDefaults.removeObject(forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForSelectionLink)
}
func resetSelectionFilePreferences() {
self.userDefaults.removeObject(forKey: Constants.SelectionFilesLocation)
self.userDefaults.removeObject(forKey: Constants.SelectionFileName)
self.userDefaults.removeObject(forKey: Constants.SelectionFileExtension)
self.userDefaults.removeObject(forKey: Constants.SelectionFileTags)
self.userDefaults.removeObject(forKey: Constants.SelectionFileContent)
self.userDefaults.removeObject(forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForSelectionFile)
}
func resetAnnotationFilePreferences() {
self.userDefaults.removeObject(forKey: Constants.AnnotationFilesLocation)
self.userDefaults.removeObject(forKey: Constants.AnnotationFileName)
self.userDefaults.removeObject(forKey: Constants.AnnotationFileExtension)
self.userDefaults.removeObject(forKey: Constants.AnnotationFileTags)
self.userDefaults.removeObject(forKey: Constants.AnnotationFileContent)
self.userDefaults.removeObject(forKey: Constants.ShowNotificationWhenFileNotFoundInDNtpForAnnotationFile)
}
}
| 9ebdc89679ac75ea318726fcccfbe47e | 38.553086 | 176 | 0.699045 | false | false | false | false |
alblue/swift | refs/heads/master | stdlib/public/core/ObjectIdentifier.swift | apache-2.0 | 6 | //===----------------------------------------------------------------------===//
//
// 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 unique identifier for a class instance or metatype.
///
/// In Swift, only class instances and metatypes have unique identities. There
/// is no notion of identity for structs, enums, functions, or tuples.
@_fixed_layout // trivial-implementation
public struct ObjectIdentifier {
@usableFromInline // trivial-implementation
internal let _value: Builtin.RawPointer
/// Creates an instance that uniquely identifies the given class instance.
///
/// The following example creates an example class `IntegerRef` and compares
/// instances of the class using their object identifiers and the identical-to
/// operator (`===`):
///
/// class IntegerRef {
/// let value: Int
/// init(_ value: Int) {
/// self.value = value
/// }
/// }
///
/// let x = IntegerRef(10)
/// let y = x
///
/// print(ObjectIdentifier(x) == ObjectIdentifier(y))
/// // Prints "true"
/// print(x === y)
/// // Prints "true"
///
/// let z = IntegerRef(10)
/// print(ObjectIdentifier(x) == ObjectIdentifier(z))
/// // Prints "false"
/// print(x === z)
/// // Prints "false"
///
/// - Parameter x: An instance of a class.
@inlinable // trivial-implementation
public init(_ x: AnyObject) {
self._value = Builtin.bridgeToRawPointer(x)
}
/// Creates an instance that uniquely identifies the given metatype.
///
/// - Parameter: A metatype.
@inlinable // trivial-implementation
public init(_ x: Any.Type) {
self._value = unsafeBitCast(x, to: Builtin.RawPointer.self)
}
}
extension ObjectIdentifier : CustomDebugStringConvertible {
/// A textual representation of the identifier, suitable for debugging.
public var debugDescription: String {
return "ObjectIdentifier(\(_rawPointerToString(_value)))"
}
}
extension ObjectIdentifier: Equatable {
@inlinable // trivial-implementation
public static func == (x: ObjectIdentifier, y: ObjectIdentifier) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(x._value, y._value))
}
}
extension ObjectIdentifier: Comparable {
@inlinable // trivial-implementation
public static func < (lhs: ObjectIdentifier, rhs: ObjectIdentifier) -> Bool {
return UInt(bitPattern: lhs) < UInt(bitPattern: rhs)
}
}
extension ObjectIdentifier: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(Int(Builtin.ptrtoint_Word(_value)))
}
}
extension UInt {
/// Creates an integer that captures the full value of the given object
/// identifier.
@inlinable // trivial-implementation
public init(bitPattern objectID: ObjectIdentifier) {
self.init(Builtin.ptrtoint_Word(objectID._value))
}
}
extension Int {
/// Creates an integer that captures the full value of the given object
/// identifier.
@inlinable // trivial-implementation
public init(bitPattern objectID: ObjectIdentifier) {
self.init(bitPattern: UInt(bitPattern: objectID))
}
}
| 004e437fbc0dfe1d5fe694809b63b7aa | 31.902655 | 80 | 0.645777 | false | false | false | false |
kdawgwilk/vapor | refs/heads/master | Tests/Vapor/SessionTests.swift | mit | 1 | @testable import Vapor
import XCTest
class SessionTests: XCTestCase {
static let allTests = [
("testDestroy_asksDriverToDestroy", testDestroy_asksDriverToDestroy),
("testSubscriptGet_asksDriverForValue", testSubscriptGet_asksDriverForValue),
("testSubscriptSet_asksDriverToSetValue", testSubscriptSet_asksDriverToSetValue),
("testIdentifierCreation", testIdentifierCreation)
]
func testDestroy_asksDriverToDestroy() {
let driver = TestDriver()
let subject = Session(identifier: "baz", sessions: driver)
subject.destroy()
guard let action = driver.actions.first, case .Destroy = action else {
XCTFail("No actions recorded or recorded action was not a destroy action")
return
}
}
func testSubscriptGet_asksDriverForValue() {
let driver = TestDriver()
let subject = Session(identifier: "baz", sessions: driver)
_ = subject["test"]
guard let action = driver.actions.first, case .ValueFor(let key) = action else {
XCTFail("No actions recorded or recorded action was not a value for action")
return
}
XCTAssertEqual(key.key, "test")
}
func testSubscriptSet_asksDriverToSetValue() {
let driver = TestDriver()
let subject = Session(identifier: "baz", sessions: driver)
subject["foo"] = "bar"
guard let action = driver.actions.first, case .SetValue(let key) = action else {
XCTFail("No actions recorded or recorded action was not a set value action")
return
}
XCTAssertEqual(key.value, "bar")
XCTAssertEqual(key.key, "foo")
}
func testIdentifierCreation() throws {
let drop = Droplet()
drop.get("cookie") { request in
request.session?["hi"] = "test"
return "hi"
}
let request = try Request(method: .get, path: "cookie")
request.headers["Cookie"] = "vapor-session=123"
let response = try drop.respond(to: request)
var sessionMiddleware: SessionMiddleware?
for middleware in drop.globalMiddleware {
if let middleware = middleware as? SessionMiddleware {
sessionMiddleware = middleware
}
}
XCTAssert(sessionMiddleware != nil, "Could not find session middleware")
XCTAssert(sessionMiddleware?.sessions.contains(identifier: "123") == false, "Session should not contain 123")
XCTAssert(response.cookies["vapor-session"] != nil, "No cookie was added")
let id = response.cookies["vapor-session"] ?? ""
XCTAssert(sessionMiddleware?.sessions.contains(identifier: id) == true, "Session did not contain cookie")
}
}
private class TestDriver: Sessions {
var drop = Droplet()
enum Action {
case ValueFor(key: String, identifier: String)
case SetValue(value: String?, key: String, identifier: String)
case Destroy(identifier: String)
}
var actions = [Action]()
func makeIdentifier() -> String {
return "Foo"
}
func value(for key: String, identifier: String) -> String? {
actions.append(.ValueFor(key: key, identifier: identifier))
return nil
}
private func contains(identifier: String) -> Bool {
return false
}
func set(_ value: String?, for key: String, identifier: String) {
actions.append(.SetValue(value: value, key: key, identifier: identifier))
}
func destroy(_ identifier: String) {
actions.append(.Destroy(identifier: identifier))
}
}
| 0b27873a30a75385769c80196bf36797 | 31.4375 | 117 | 0.63281 | false | true | false | false |
Legoless/Saystack | refs/heads/master | Code/Extensions/UIKit/UIViewController+Traverse.swift | mit | 1 | //
// UIViewController+Traverse.swift
// Saystack
//
// Created by Dal Rupnik on 4/5/20.
// Copyright © 2020 Unified Sense. All rights reserved.
//
import Foundation
import UIKit
public extension UIViewController {
func findController<T : UIViewController>(ofType: T.Type) -> T? {
let controller = self
if controller.isKind(of: T.self) {
return controller as? T
}
if let navigationController = controller as? UINavigationController {
for childController in navigationController.viewControllers {
if let child = childController.findController(ofType: T.self) {
return child
}
}
}
if let splitController = controller as? UISplitViewController {
for childController in splitController.viewControllers {
if let child = childController.findController(ofType: T.self) {
return child
}
}
}
if let tabBarController = controller as? UITabBarController {
for childController in tabBarController.viewControllers ?? [] {
if let child = childController.findController(ofType: T.self) {
return child
}
}
}
return nil
}
}
| 3b1002421be277882c224feb5aa2d10b | 29.130435 | 79 | 0.562771 | false | false | false | false |
voloshynslavik/MVx-Patterns-In-Swift | refs/heads/master | MVX Patterns In Swift/Patterns/MVVM/ViewModel.swift | mit | 1 | //
// ModelView.swift
// MVX Patterns In Swift
//
// Created by Yaroslav Voloshyn on 17/07/2017.
//
import Foundation
final class ViewModel: NSObject {
weak var delegate: ViewModelDelegate?
fileprivate let picsumPhotos = PicsumPhotosManager()
fileprivate var lastPageIndex: Int?
fileprivate var photos: [(PicsumPhoto, Data?)] = []
fileprivate var isLoading = false {
didSet {
self.delegate?.didLoadingStateChanged(in: self, from: oldValue, to: isLoading)
}
}
var photosCount: Int {
return photos.count
}
func getPhotoData(for index: Int, width: Int, height: Int) -> Data? {
guard let data = photos[index].1 else {
startLoadPhoto(for: index, width: width, height: height)
return nil
}
return data
}
func getPhotoAuthor(for index: Int) -> String {
return photos[index].0.author
}
}
// MARK: - Load items
extension ViewModel {
func loadMoreItems() {
guard !isLoading else {
return
}
var pageIndex = 1
if let lastPageIndex = lastPageIndex {
pageIndex = lastPageIndex + 1
}
loadItems(with: pageIndex)
}
private func loadItems(with pageIndex: Int) {
isLoading = true
picsumPhotos.getPhotos(pageIndex) { [weak self] (photos, error) in
defer {
self?.isLoading = false
}
guard let sself = self else {
return
}
sself.lastPageIndex = pageIndex
photos?.forEach {
sself.photos.append(($0, nil))
}
sself.delegate?.didUpdatedData(in: sself)
}
}
}
// MARK: - Load Photo
extension ViewModel {
func stopLoadPhoto(for index: Int, width: Int, height: Int) {
let url = photos[index].0.getResizedImageURL(width: width, height: height)
DataLoader.shared.stopDownload(with: url)
}
func startLoadPhoto(for index: Int, width: Int, height: Int) {
let url = photos[index].0.getResizedImageURL(width: width, height: height)
DataLoader.shared.downloadData(with: url) { [weak self] (data) in
guard let sself = self else {
return
}
sself.photos[index].1 = data
sself.delegate?.didDownloadPhoto(in: sself, with: index)
}
}
}
protocol ViewModelDelegate: class {
func didLoadingStateChanged(in viewModel: ViewModel, from oldState: Bool, to newState:Bool)
func didUpdatedData(in viewModel: ViewModel)
func didDownloadPhoto(in viewMode: ViewModel, with index: Int)
}
| 118d8d678530489e0948eedceae72d55 | 24.790476 | 95 | 0.589734 | false | false | false | false |
keyeMyria/edx-app-ios | refs/heads/master | Source/CourseDashboardCourseInfoView.swift | apache-2.0 | 2 | //
// CourseDashboardCourseInfoView.swift
// edX
//
// Created by Jianfeng Qiu on 13/05/2015.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
/** The Course Card View */
@IBDesignable
class CourseDashboardCourseInfoView: UIView {
//TODO: all these should be adjusted once the final UI is ready
private let LABEL_SIZE_HEIGHT = 20.0
private let CONTAINER_SIZE_HEIGHT = 60.0
private let CONTAINER_MARGIN_BOTTOM = 15.0
private let TEXT_MARGIN = 10.0
private let SEPARATORLINE_SIZE_HEIGHT = 1.0
var course: OEXCourse?
private let coverImage = UIImageView()
private let container = UIView()
private let titleLabel = UILabel()
private let detailLabel = UILabel()
private let bottomLine = UIView()
private let bannerLabel = OEXBannerLabel()
var titleTextStyle : OEXTextStyle {
return OEXTextStyle(weight : .Normal, size: .Large, color: OEXStyles.sharedStyles().neutralBlack())
}
var detailTextStyle : OEXTextStyle {
return OEXTextStyle(weight : .Normal, size: .XXXSmall, color: OEXStyles.sharedStyles().neutralDark())
}
var bannerTextStyle : OEXTextStyle {
return OEXTextStyle(weight : .Normal, size: .XXXSmall, color: UIColor.whiteColor())
}
func _setup() {
configureViews()
accessibilityTraits = UIAccessibilityTraitStaticText
accessibilityHint = OEXLocalizedString("ACCESSIBILITY_SHOWS_COURSE_CONTENT", nil)
NSNotificationCenter.defaultCenter().oex_addObserver(self, name: OEXImageDownloadCompleteNotification) { [weak self] (notification, observer, _) -> Void in
observer.setImageForImageView(notification)
}
}
override init(frame : CGRect) {
super.init(frame : frame)
_setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
_setup()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
let bundle = NSBundle(forClass: self.dynamicType)
coverImage.image = UIImage(named:"Splash_map", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection)
titleLabel.attributedText = titleTextStyle.attributedStringWithText("Demo Course")
detailLabel.attributedText = detailTextStyle.attributedStringWithText("edx | DemoX")
bannerLabel.attributedText = bannerTextStyle.attributedStringWithText("ENDED - SEPTEMBER 24")
bannerLabel.hidden = false
}
func configureViews() {
self.backgroundColor = OEXStyles.sharedStyles().neutralXLight()
self.clipsToBounds = true
self.bottomLine.backgroundColor = OEXStyles.sharedStyles().neutralXLight()
self.container.backgroundColor = OEXStyles.sharedStyles().neutralWhite().colorWithAlphaComponent(0.85)
self.coverImage.backgroundColor = OEXStyles.sharedStyles().neutralWhiteT()
self.coverImage.contentMode = UIViewContentMode.ScaleAspectFill
self.coverImage.clipsToBounds = true
self.container.accessibilityIdentifier = "Title Bar"
self.container.addSubview(titleLabel)
self.container.addSubview(detailLabel)
self.container.addSubview(bannerLabel)
self.addSubview(coverImage)
self.addSubview(container)
self.insertSubview(bottomLine, aboveSubview: coverImage)
bannerLabel.hidden = true
bannerLabel.adjustsFontSizeToFitWidth = true
bannerLabel.setContentCompressionResistancePriority(500, forAxis: UILayoutConstraintAxis.Horizontal)
detailLabel.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
self.container.snp_makeConstraints { make -> Void in
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.bottom.equalTo(self).offset(-CONTAINER_MARGIN_BOTTOM)
make.height.equalTo(CONTAINER_SIZE_HEIGHT)
}
self.coverImage.snp_makeConstraints { (make) -> Void in
make.top.equalTo(self)
make.leading.equalTo(self)
make.trailing.equalTo(self)
}
self.titleLabel.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(self.container).offset(TEXT_MARGIN)
make.trailing.equalTo(self.container).offset(TEXT_MARGIN)
make.top.equalTo(self.container).offset(TEXT_MARGIN)
make.height.equalTo(LABEL_SIZE_HEIGHT)
}
self.detailLabel.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(self.container).offset(TEXT_MARGIN)
make.top.equalTo(self.titleLabel.snp_bottom)
make.height.equalTo(LABEL_SIZE_HEIGHT)
}
self.bannerLabel.snp_makeConstraints { (make) -> Void in
make.width.greaterThanOrEqualTo(0).priority(1000)
make.width.equalTo(self.container.snp_width).multipliedBy(0.5).offset(-2 * TEXT_MARGIN).priority(900)
make.leading.greaterThanOrEqualTo(self.detailLabel.snp_trailing).offset(TEXT_MARGIN)
make.trailing.equalTo(self.container).offset(-TEXT_MARGIN).priorityHigh()
make.top.equalTo(self.detailLabel)
make.height.equalTo(self.detailLabel)
}
self.bottomLine.snp_makeConstraints { (make) -> Void in
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.bottom.equalTo(self)
make.top.equalTo(self.container.snp_bottom)
}
}
var titleText : String? {
get {
return self.titleLabel.text
}
set {
self.titleLabel.attributedText = titleTextStyle.attributedStringWithText(newValue)
updateAcessibilityLabel()
}
}
var detailText : String? {
get {
return self.detailLabel.text
}
set {
self.detailLabel.attributedText = detailTextStyle.attributedStringWithText(newValue)
updateAcessibilityLabel()
}
}
var bannerText : String? {
get {
return self.bannerLabel.text
}
set {
self.bannerLabel.attributedText = bannerTextStyle.attributedStringWithText(newValue)
self.bannerLabel.hidden = !(newValue != nil && !newValue!.isEmpty)
updateAcessibilityLabel()
}
}
func updateAcessibilityLabel() {
accessibilityLabel = "\(titleText),\(detailText),\(bannerText)"
}
private func imageURL() -> String? {
if let courseInCell = self.course, relativeURLString = courseInCell.course_image_url {
let baseURL = NSURL(string:OEXConfig.sharedConfig().apiHostURL() ?? "")
return NSURL(string: relativeURLString, relativeToURL: baseURL)?.absoluteString
}
return nil
}
func setCoverImage() {
setImage(UIImage(named: "Splash_map"))
if let imageURL = imageURL() where !imageURL.isEmpty {
OEXImageCache.sharedInstance().getImage(imageURL)
}
}
private func setImage(image: UIImage?) {
coverImage.image = image
if let image = image {
let ar = image.size.height / image.size.width
coverImage.snp_remakeConstraints({ (make) -> Void in
make.top.equalTo(self)
make.leading.equalTo(self)
make.trailing.equalTo(self)
make.height.equalTo(self.coverImage.snp_width).multipliedBy(ar)
})
}
}
func setImageForImageView(notification: NSNotification) {
let dictObj = notification.object as! NSDictionary
let image: UIImage? = dictObj.objectForKey("image") as? UIImage
let downloadImageUrl: String? = dictObj.objectForKey("image_url") as? String
if let downloadedImage = image, courseInCell = self.course, imageURL = imageURL() {
if imageURL == downloadImageUrl {
setImage(downloadedImage)
}
}
}
}
| 42cf88c690125aa4f305a38adf858373 | 37.771429 | 163 | 0.644313 | false | false | false | false |
shlyren/ONE-Swift | refs/heads/master | ONE_Swift/Classes/Reading-阅读/View/Detail/JENReadToolBarView.swift | mit | 1 | //
// JENReadToolBarView.swift
// ONE_Swift
//
// Created by 任玉祥 on 16/5/4.
// Copyright © 2016年 任玉祥. All rights reserved.
//
import UIKit
class JENReadToolBarView: UIView {
@IBOutlet private weak var praiseBtn: UIButton!
@IBOutlet private weak var commentBtn: UIButton!
@IBOutlet private weak var shareBtn: UIButton!
private var readType = JENReadType.Unknow
private var detail_id = ""
class func toolBarView(type: JENReadType, detail_id: String) -> JENReadToolBarView {
let toolBar = NSBundle.mainBundle().loadNibNamed("JENReadToolBarView", owner: nil, options: nil).first as! JENReadToolBarView
toolBar.frame = CGRectMake(0, JENScreenHeight - 44, JENScreenWidth, 44)
toolBar.readType = type
toolBar.detail_id = detail_id
return toolBar
}
func setToolBarTitle(praisenum: Int, commentnum: Int, sharenum: Int) {
praiseBtn.setTitle("\(praisenum)", forState: .Normal)
praiseBtn.setTitle("\(praisenum)", forState: .Selected)
commentBtn.setTitle("\(commentnum)", forState: .Normal)
commentBtn.setTitle("\(commentnum)", forState: .Highlighted)
shareBtn.setTitle("\(sharenum)", forState: .Normal)
shareBtn.setTitle("\(sharenum)", forState: .Highlighted)
}
}
| f23a0275dcb1ce056ab9db034caada60 | 34.324324 | 133 | 0.672533 | false | false | false | false |
donnywdavis/Word-Jive | refs/heads/master | WordJive/WordJive/WordsViewController.swift | cc0-1.0 | 1 | //
// WordsViewController.swift
// WordJive
//
// Created by Allen Spicer on 7/16/16.
// Copyright © 2016 Donny Davis. All rights reserved.
//
import UIKit
class WordsViewController: UIViewController {
var solutionsArray = [String]()
override func viewDidLoad() {
super.viewDidLoad()
placeSolutionsFromArrayOnView()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func placeSolutionsFromArrayOnView(){
solutionsArray = ["FED", "ON", "AT", "OH"]
var i = 0
while i < solutionsArray.count{
let width = view.frame.width
let rect = CGRectMake(0, CGFloat(20*i+100), width, 20)
let newLabel = UILabel.init(frame: rect)
newLabel.text = solutionsArray[i]
newLabel.textAlignment = .Center
self.view.addSubview(newLabel)
i = i + 1
}
}
} | 774f2e6edefeb7dea9225827d05b403f | 19 | 62 | 0.569405 | false | false | false | false |
farion/eloquence | refs/heads/master | Eloquence/EloquenceIOS/EMAccountsViewController.swift | apache-2.0 | 1 | import Foundation
import UIKit
import XMPPFramework
protocol EMAccountsViewControllerDelegate:NSObjectProtocol {
func didClickDoneInAccountsViewController();
}
class EMAccountsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource, EMAddAccountViewControllerDelegate {
var delegate:EMAccountsViewControllerDelegate?;
var addController: EMAddAccountViewController?;
var data = [EloAccount]();
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
tableView.delegate = self;
tableView.dataSource = self;
self.prepareData();
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent;
}
func prepareData(){
self.data = DataController.sharedInstance.getAccounts();
tableView.reloadData();
}
@IBAction func doneClicked(sender: AnyObject) {
if(delegate != nil){
delegate!.didClickDoneInAccountsViewController()
}
}
@IBAction func addClicked(sender: AnyObject) {
addController = UIStoryboard.init(name: "Shared", bundle: nil).instantiateViewControllerWithIdentifier("AddAccount") as? EMAddAccountViewController;
addController!.delegate = self;
self.presentViewController(addController!, animated: true, completion: {})
}
func doCloseAddAccountView(){
if(addController != nil){
addController!.dismissViewControllerAnimated(true, completion: nil)
addController!.delegate = nil;
addController = nil;
}
}
//pragma mark - UITableViewDataSource
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("AccountCell", forIndexPath: indexPath) as? EMAccountCell;
if(cell == nil) {
cell = EMAccountCell(style: UITableViewCellStyle.Default, reuseIdentifier: "AccountCell");
}
cell!.jidLabel.text = data[indexPath.row].getJid().jid;
cell!.disableSwitch.on = data[indexPath.row].isAutoConnect()
cell!.account = data[indexPath.row];
return cell!;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
//pragma mark - UITableViewDelegate
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
addController = UIStoryboard.init(name: "Shared", bundle: nil).instantiateViewControllerWithIdentifier("AddAccount") as? EMAddAccountViewController;
addController!.delegate = self;
addController!.account = data[indexPath.row];
self.presentViewController(addController!, animated: true, completion: {})
}
} | f447bacd0d215464ef46ec357a06cdd6 | 31.75 | 156 | 0.660359 | false | false | false | false |
Mrwerdo/QuickShare | refs/heads/master | LibQuickShare/Sources/Communication/SyncMessage+Actions.swift | mit | 1 | //
// SyncMessage+Actions.swift
// QuickShare
//
// Copyright (c) 2016 Andrew Thompson
//
// 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 Core
extension SyncMessage : Consumable {
public func consume(group: ShareGroup, message: ControlMessage, center: MessageCenter) {
/*
* Sync Message has this method, which will be called once it's decoded
* inside Message Center.
* It might be better to shift any synchronisation logic into this method
* as it might reduce the size of MessageCenter.
*
* However, the code works at present, and it's probably easier to just
* leave it be for a while.
*/
switch self.type {
case .Sync: /* Request for User Information */
let info = SyncState.Info(didStart: false, detectedUsers: [])
group.syncState = .Syncing(info)
sendUserInformation(group)
updateUserInformation(group, signature: self.signature, shouldReset: true )
case .Info: /* Response for User Information */
updateUserInformation(group, signature: self.signature)
case .Confirm: /* Check everybody's on the same page */
// This means that the originating host wants to
// finish the synchronization.
confirmStatus(group, matching: self.signature, center: center)
}
}
private func sendUserInformation(group: ShareGroup) {
let signature = group.signature
let info = SyncMessage(type: .Info, signature: signature)
group.add(message: info)
}
func updateUserInformation(group: ShareGroup, signature: Signature, shouldReset: Bool = false) {
if let info = group.syncState.syncInfo {
let newFoundPeers: [Signature]
if shouldReset {
newFoundPeers = [signature]
} else {
newFoundPeers = info.detectedUsers + [signature]
}
let newInfo = SyncState.Info(didStart: info.didStart, detectedUsers: newFoundPeers)
group.syncState = .Syncing(newInfo)
} else {
show("warning: \(#function) called when group.transferState.state != .Syncing")
}
}
func confirmStatus(group: ShareGroup, matching signature: Signature, center: MessageCenter) {
if let info = group.syncState.syncInfo {
if !info.didStart {
group.peers = info.detectedUsers.map { $0.user }
}
print("Are the signatures equal? \(group.signature.hash == signature.hash)")
if group.signature.hash == signature.hash {
group.packetCounter = 0
var users = group.peers + [group.user]
users.sortInPlace { $0.time < $1.time }
let controllers = users.filter { $0.isController }
if controllers.count != 1 {
show("resolving conflict in share group controllers")
if let user = users.first {
user.isController = true
show("\(user) is now the controller")
}
for user in users.dropFirst() {
user.isController = false
}
}
if let controller = center.groups[group], let c = controller {
center.update(controller: c, using: group)
}
group.syncState = .Ready
} else {
dump(group)
dump(group.signature)
dump(signature)
}
} else {
show("warning: \(#function) called when group.transferState.state != .Syncing")
}
}
}
| aef68d83214593a47d6f65179c464eac | 42.300885 | 100 | 0.596771 | false | false | false | false |
alexandrehcdc/dejavi | refs/heads/master | dejavi/Movies.swift | mit | 1 | import Foundation
import RealmSwift
let realm = try! Realm()
class MovieModel: Object {
dynamic var title, year, poster, genre, plot: String?
dynamic var isAlreadyWatched: Bool = false
dynamic var isAlreadySaved: Bool = false
dynamic var imageData: NSData?
func persistMovie(movie: Object) {
try! realm!.write {
realm!.add(movie)
}
}
func removeMovie (movie: Object) {
try! realm!.write {
realm!.delete(movie)
}
}
func setimageData (imageData : NSData?) {
guard imageData != nil else {
return
}
self.imageData = imageData
}
func setMovieValues (title: String, year: String, poster: String, genre: String, plot: String, isAlreadyWatched: Bool, isAlreadySaved: Bool) {
self.title = title
self.year = year
self.poster = poster
self.genre = genre
self.plot = plot
self.isAlreadyWatched = isAlreadyWatched
self.isAlreadySaved = isAlreadySaved
}
} | 1820bc89356a85f0d008d7fa428259a2 | 24.97561 | 146 | 0.597744 | false | false | false | false |
rui4u/weibo | refs/heads/master | Rui微博/Rui微博/Classes/Module/Home/StatusCell/StatusForwardCell.swift | mit | 1 | //
// StatusForwardCell.swift
// Rui微博
//
// Created by 沙睿 on 15/10/15.
// Copyright © 2015年 沙睿. All rights reserved.
//
import UIKit
class StatusForwardCell: StatusCell {
override var status: Status? {
didSet {
let name = status?.retweeted_status?.user?.name ?? ""
let text = status?.retweeted_status?.text ?? ""
forwardLabel.text = "@" + name + ":" + text
}
}
/// 设置界面
override func setupUI() {
super.setupUI()
// 1. 添加控件
contentView.insertSubview(backButton, belowSubview:pictureView)
contentView.insertSubview(forwardLabel, aboveSubview: backButton)
// 2. 设置布局
// 1> 背景按钮
backButton.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: LabelText, size: nil, offset: CGPoint(x: -8, y: 8))
backButton.ff_AlignVertical(type: ff_AlignType.TopRight, referView: bottomView, size: nil)
// 2> 转发文本
forwardLabel.ff_AlignInner(type: ff_AlignType.TopLeft, referView: backButton, size: nil, offset: CGPoint(x: 8, y: 8))
// 3> 配图视图
let cons = pictureView.ff_AlignVertical(type: ff_AlignType.BottomLeft, referView: forwardLabel, size: CGSize(width: 290, height: 290), offset: CGPoint(x: 0, y: 8))
pictureWidthCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Width)
pictureHeightCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Height)
pictureTopCons = pictureView.ff_Constraint(cons, attribute: NSLayoutAttribute.Top)
}
private lazy var forwardLabel: UILabel = {
let label = UILabel(color: UIColor.darkGrayColor(), fontSize: 14)
label.numberOfLines = 0
label.preferredMaxLayoutWidth = UIScreen.mainScreen().bounds.width - 2 * 8
return label
}()
private lazy var backButton: UIButton = {
let btn = UIButton()
btn.backgroundColor = UIColor(white: 0.9, alpha: 0.9)
return btn
}()
}
| 4010331c27bfa2348be79a08ec355a85 | 33.163934 | 171 | 0.615163 | false | false | false | false |
eurofurence/ef-app_ios | refs/heads/release/4.0.0 | Packages/EurofurenceApplication/Sources/EurofurenceApplication/Content Router/Routes/Embedded Event/EmbeddedEventRoute.swift | mit | 1 | import ComponentBase
import EurofurenceModel
import EventDetailComponent
import RouterCore
public struct EmbeddedEventRoute {
private let eventModuleFactory: EventDetailComponentFactory
private let eventDetailDelegate: EventDetailComponentDelegate
private let contentWireframe: ContentWireframe
public init(
eventModuleFactory: EventDetailComponentFactory,
eventDetailDelegate: EventDetailComponentDelegate,
contentWireframe: ContentWireframe
) {
self.eventModuleFactory = eventModuleFactory
self.eventDetailDelegate = eventDetailDelegate
self.contentWireframe = contentWireframe
}
}
// MARK: - Route
extension EmbeddedEventRoute: Route {
public typealias Parameter = EmbeddedEventRouteable
public func route(_ content: EmbeddedEventRouteable) {
let contentController = eventModuleFactory.makeEventDetailComponent(
for: content.identifier,
delegate: eventDetailDelegate
)
contentWireframe.replaceDetailContentController(contentController)
}
}
| 01aea76df08f61d60117acac25fd78ac | 27.641026 | 76 | 0.7359 | false | false | false | false |
yajeka/PS | refs/heads/master | PS/UIViewController+UIAlert.swift | lgpl-3.0 | 1 | //
// UIViewController+UIAlert.swift
// PS
//
// Created by Yauheni Yarotski on 20.03.16.
// Copyright © 2016 hackathon. All rights reserved.
//
import Foundation
import UIKit
extension UIViewController {
// MARK: - Alerts
public func showAlert(title title: String? = nil, message: String? = nil, error: NSError? = nil, okActionHandler: ((UIAlertAction) -> Void)? = nil)
{
let actions = [UIAlertAction(title: ActionTitle.Ok(), style: .Default, handler: okActionHandler)]
var composedMessage = message
#if DEBUG
if let error = error {
composedMessage += "\n\nDiagnostics: \(error.localizedDescription)"
}
#endif
presentAlert(title: title, message: composedMessage, actions: actions)
}
public func showAlertForNetworkError(error: NSError? = nil, okActionHandler:((UIAlertAction) -> Void)? = nil)
{
showAlert(
title: NSLocalizedString("Network Error", comment: "Network Error title"),
message: NSLocalizedString("There was an error connecting to the server. Please try again later when you have an Internet connection.", comment:"Network Error message"),
error: error,
okActionHandler: okActionHandler
)
}
// MARK: - Dialogs (like alert but with actions > 1)
public func showDialog(title title: String? = nil, message: String? = nil, actions: [UIAlertAction]){
presentAlert(title: title, message: message, actions: actions)
}
public func showDialogForConfirmation(
title title: String? = nil,
message: String? = nil,
cancelActionHandler: ((UIAlertAction) -> Void)? = nil,
confirmActionHandler: ((UIAlertAction) -> Void)? = nil)
{
let actions = [
UIAlertAction(title: ActionTitle.Cancel(), style: .Cancel, handler: cancelActionHandler),
UIAlertAction(title: ActionTitle.Ok(), style: .Default, handler: confirmActionHandler)
]
presentAlert(title: title, message: message, actions: actions)
}
// MARK: - ActionSheets (for iPad automatically convertes into dialog)
public func showActionSheet(title title: String? = nil, message: String? = nil, actions: [UIAlertAction])
{
let isIpad = UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad
presentAlert(title: title, message: message, style: isIpad ? .Alert : .ActionSheet, actions: actions)
}
public func showActionSheetDestructive(
title title: String? = nil,
message: String? = nil,
showTitleAndMessageOnIphone: Bool = true,
cancelActionHandler: ((UIAlertAction) -> Void)? = nil,
destructiveActionHandler: ((UIAlertAction) -> Void)? = nil)
{
let actions = [
UIAlertAction(title: ActionTitle.Cancel(), style: .Cancel, handler: cancelActionHandler),
UIAlertAction(title: ActionTitle.Remove(), style: .Destructive, handler: destructiveActionHandler)
]
let isIpad = UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad
let title = (!showTitleAndMessageOnIphone && !isIpad) ? nil : title
let message = (!showTitleAndMessageOnIphone && !isIpad) ? nil : message
presentAlert(title: title, message: message, style: isIpad ? .Alert : .ActionSheet, actions: actions)
}
// MARK: - Privite methods
private func presentAlert(
title title: String? = nil,
message: String? = nil,
style: UIAlertControllerStyle = .Alert,
actions: [UIAlertAction])
{
let alert = UIAlertController(title: title, message: message, preferredStyle: style)
if !actions.isEmpty {
for action in actions {
alert.addAction(action)
}
}
else {//defaul action if nobody will set at least one action
alert.addAction(UIAlertAction(title: ActionTitle.Ok(), style: .Default, handler: nil))
}
presentViewController(alert, animated: true, completion: nil)
}
}
struct ActionTitle {
static func Ok() -> String {
return NSLocalizedString("OK", comment:"OK button title")
}
static func Cancel() -> String {
return NSLocalizedString("Cancel", comment: "")
}
static func Remove() -> String {
return NSLocalizedString("Remove", comment: "")
}
} | 4e9021cd23413ef483c352b39e865039 | 35.830645 | 182 | 0.621989 | false | false | false | false |
peferron/algo | refs/heads/master | EPI/Sorting/Render a calendar/swift/main.swift | mit | 1 | public typealias Event = (start: Int, end: Int)
typealias Boundary = (time: Int, type: BoundaryType)
enum BoundaryType {
case Start
case End
}
public func maxConcurrentEvents(_ events: [Event]) -> Int {
let boundaries = events
.flatMap { event -> [Boundary] in [
(time: event.start, type: .Start),
(time: event.end, type: .End)
]}
.sorted {
// If multiple boundaries share the same time, process Start boundaries before End
// boundaries. That's because if one event ends at the same time another event starts,
// we consider these two events to overlap each other.
$0.time < $1.time || $0.time == $1.time && $0.type == .Start
}
var currentOverlap = 0
var maxOverlap = 0
for boundary in boundaries {
currentOverlap += boundary.type == .Start ? 1 : -1
maxOverlap = max(currentOverlap, maxOverlap)
}
return maxOverlap
}
| 2187638f05f4acf0d7f44bb3a7d32f51 | 29.5 | 98 | 0.599385 | false | false | false | false |
ahoppen/swift | refs/heads/main | SwiftCompilerSources/Sources/SIL/ApplySite.swift | apache-2.0 | 1 | //===--- ApplySite.swift - Defines the ApplySite protocols ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 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 SILBridging
public struct ApplyOperands {
public static let calleeOperandIndex: Int = 0
public static let firstArgumentIndex = 1
}
public protocol ApplySite : Instruction {
var operands: OperandArray { get }
var numArguments: Int { get }
var substitutionMap: SubstitutionMap { get }
func calleeArgIndex(callerArgIndex: Int) -> Int
func callerArgIndex(calleeArgIndex: Int) -> Int?
func getArgumentConvention(calleeArgIndex: Int) -> ArgumentConvention
}
extension ApplySite {
public var callee: Value { operands[ApplyOperands.calleeOperandIndex].value }
public var arguments: LazyMapSequence<OperandArray, Value> {
operands[1..<operands.count].lazy.map { $0.value }
}
public var substitutionMap: SubstitutionMap {
SubstitutionMap(ApplySite_getSubstitutionMap(bridged))
}
public func argumentIndex(of operand: Operand) -> Int? {
let opIdx = operand.index
if opIdx >= ApplyOperands.firstArgumentIndex &&
opIdx <= ApplyOperands.firstArgumentIndex + numArguments {
return opIdx - ApplyOperands.firstArgumentIndex
}
return nil
}
public func getArgumentConvention(calleeArgIndex: Int) -> ArgumentConvention {
return ApplySite_getArgumentConvention(bridged, calleeArgIndex).convention
}
public var referencedFunction: Function? {
if let fri = callee as? FunctionRefInst {
return fri.referencedFunction
}
return nil
}
}
public protocol FullApplySite : ApplySite {
var singleDirectResult: Value? { get }
}
extension FullApplySite {
public func calleeArgIndex(callerArgIndex: Int) -> Int { callerArgIndex }
public func callerArgIndex(calleeArgIndex: Int) -> Int? { calleeArgIndex }
}
| 9ce9d18a8ca3d49f5f3b696ad89c9a61 | 31.558824 | 80 | 0.707317 | false | false | false | false |
Alexzhxy/swift-2048 | refs/heads/master | swift-2048/NumberTileGame.swift | mit | 9 | //
// NumberTileGame.swift
// swift-2048
//
// Created by Austin Zheng on 6/3/14.
// Copyright (c) 2014 Austin Zheng. All rights reserved.
//
import UIKit
/// A view controller representing the swift-2048 game. It serves mostly to tie a GameModel and a GameboardView
/// together. Data flow works as follows: user input reaches the view controller and is forwarded to the model. Move
/// orders calculated by the model are returned to the view controller and forwarded to the gameboard view, which
/// performs any animations to update its state.
class NumberTileGameViewController : UIViewController, GameModelProtocol {
// How many tiles in both directions the gameboard contains
var dimension: Int
// The value of the winning tile
var threshold: Int
var board: GameboardView?
var model: GameModel?
var scoreView: ScoreViewProtocol?
// Width of the gameboard
let boardWidth: CGFloat = 230.0
// How much padding to place between the tiles
let thinPadding: CGFloat = 3.0
let thickPadding: CGFloat = 6.0
// Amount of space to place between the different component views (gameboard, score view, etc)
let viewPadding: CGFloat = 10.0
// Amount that the vertical alignment of the component views should differ from if they were centered
let verticalViewOffset: CGFloat = 0.0
init(dimension d: Int, threshold t: Int) {
dimension = d > 2 ? d : 2
threshold = t > 8 ? t : 8
super.init(nibName: nil, bundle: nil)
model = GameModel(dimension: dimension, threshold: threshold, delegate: self)
view.backgroundColor = UIColor.whiteColor()
setupSwipeControls()
}
required init(coder aDecoder: NSCoder) {
fatalError("NSCoding not supported")
}
func setupSwipeControls() {
let upSwipe = UISwipeGestureRecognizer(target: self, action: Selector("up:"))
upSwipe.numberOfTouchesRequired = 1
upSwipe.direction = UISwipeGestureRecognizerDirection.Up
view.addGestureRecognizer(upSwipe)
let downSwipe = UISwipeGestureRecognizer(target: self, action: Selector("down:"))
downSwipe.numberOfTouchesRequired = 1
downSwipe.direction = UISwipeGestureRecognizerDirection.Down
view.addGestureRecognizer(downSwipe)
let leftSwipe = UISwipeGestureRecognizer(target: self, action: Selector("left:"))
leftSwipe.numberOfTouchesRequired = 1
leftSwipe.direction = UISwipeGestureRecognizerDirection.Left
view.addGestureRecognizer(leftSwipe)
let rightSwipe = UISwipeGestureRecognizer(target: self, action: Selector("right:"))
rightSwipe.numberOfTouchesRequired = 1
rightSwipe.direction = UISwipeGestureRecognizerDirection.Right
view.addGestureRecognizer(rightSwipe)
}
// View Controller
override func viewDidLoad() {
super.viewDidLoad()
setupGame()
}
func reset() {
assert(board != nil && model != nil)
let b = board!
let m = model!
b.reset()
m.reset()
m.insertTileAtRandomLocation(2)
m.insertTileAtRandomLocation(2)
}
func setupGame() {
let vcHeight = view.bounds.size.height
let vcWidth = view.bounds.size.width
// This nested function provides the x-position for a component view
func xPositionToCenterView(v: UIView) -> CGFloat {
let viewWidth = v.bounds.size.width
let tentativeX = 0.5*(vcWidth - viewWidth)
return tentativeX >= 0 ? tentativeX : 0
}
// This nested function provides the y-position for a component view
func yPositionForViewAtPosition(order: Int, views: [UIView]) -> CGFloat {
assert(views.count > 0)
assert(order >= 0 && order < views.count)
let viewHeight = views[order].bounds.size.height
let totalHeight = CGFloat(views.count - 1)*viewPadding + views.map({ $0.bounds.size.height }).reduce(verticalViewOffset, combine: { $0 + $1 })
let viewsTop = 0.5*(vcHeight - totalHeight) >= 0 ? 0.5*(vcHeight - totalHeight) : 0
// Not sure how to slice an array yet
var acc: CGFloat = 0
for i in 0..<order {
acc += viewPadding + views[i].bounds.size.height
}
return viewsTop + acc
}
// Create the score view
let scoreView = ScoreView(backgroundColor: UIColor.blackColor(),
textColor: UIColor.whiteColor(),
font: UIFont(name: "HelveticaNeue-Bold", size: 16.0) ?? UIFont.systemFontOfSize(16.0),
radius: 6)
scoreView.score = 0
// Create the gameboard
let padding: CGFloat = dimension > 5 ? thinPadding : thickPadding
let v1 = boardWidth - padding*(CGFloat(dimension + 1))
let width: CGFloat = CGFloat(floorf(CFloat(v1)))/CGFloat(dimension)
let gameboard = GameboardView(dimension: dimension,
tileWidth: width,
tilePadding: padding,
cornerRadius: 6,
backgroundColor: UIColor.blackColor(),
foregroundColor: UIColor.darkGrayColor())
// Set up the frames
let views = [scoreView, gameboard]
var f = scoreView.frame
f.origin.x = xPositionToCenterView(scoreView)
f.origin.y = yPositionForViewAtPosition(0, views)
scoreView.frame = f
f = gameboard.frame
f.origin.x = xPositionToCenterView(gameboard)
f.origin.y = yPositionForViewAtPosition(1, views)
gameboard.frame = f
// Add to game state
view.addSubview(gameboard)
board = gameboard
view.addSubview(scoreView)
self.scoreView = scoreView
assert(model != nil)
let m = model!
m.insertTileAtRandomLocation(2)
m.insertTileAtRandomLocation(2)
}
// Misc
func followUp() {
assert(model != nil)
let m = model!
let (userWon, winningCoords) = m.userHasWon()
if userWon {
// TODO: alert delegate we won
let alertView = UIAlertView()
alertView.title = "Victory"
alertView.message = "You won!"
alertView.addButtonWithTitle("Cancel")
alertView.show()
// TODO: At this point we should stall the game until the user taps 'New Game' (which hasn't been implemented yet)
return
}
// Now, insert more tiles
let randomVal = Int(arc4random_uniform(10))
m.insertTileAtRandomLocation(randomVal == 1 ? 4 : 2)
// At this point, the user may lose
if m.userHasLost() {
// TODO: alert delegate we lost
NSLog("You lost...")
let alertView = UIAlertView()
alertView.title = "Defeat"
alertView.message = "You lost..."
alertView.addButtonWithTitle("Cancel")
alertView.show()
}
}
// Commands
@objc(up:)
func upCommand(r: UIGestureRecognizer!) {
assert(model != nil)
let m = model!
m.queueMove(MoveDirection.Up,
completion: { (changed: Bool) -> () in
if changed {
self.followUp()
}
})
}
@objc(down:)
func downCommand(r: UIGestureRecognizer!) {
assert(model != nil)
let m = model!
m.queueMove(MoveDirection.Down,
completion: { (changed: Bool) -> () in
if changed {
self.followUp()
}
})
}
@objc(left:)
func leftCommand(r: UIGestureRecognizer!) {
assert(model != nil)
let m = model!
m.queueMove(MoveDirection.Left,
completion: { (changed: Bool) -> () in
if changed {
self.followUp()
}
})
}
@objc(right:)
func rightCommand(r: UIGestureRecognizer!) {
assert(model != nil)
let m = model!
m.queueMove(MoveDirection.Right,
completion: { (changed: Bool) -> () in
if changed {
self.followUp()
}
})
}
// Protocol
func scoreChanged(score: Int) {
if scoreView == nil {
return
}
let s = scoreView!
s.scoreChanged(newScore: score)
}
func moveOneTile(from: (Int, Int), to: (Int, Int), value: Int) {
assert(board != nil)
let b = board!
b.moveOneTile(from, to: to, value: value)
}
func moveTwoTiles(from: ((Int, Int), (Int, Int)), to: (Int, Int), value: Int) {
assert(board != nil)
let b = board!
b.moveTwoTiles(from, to: to, value: value)
}
func insertTile(location: (Int, Int), value: Int) {
assert(board != nil)
let b = board!
b.insertTile(location, value: value)
}
}
| 9ea4f0ebd1eb99333224a75dbb93744c | 29.228464 | 148 | 0.661256 | false | false | false | false |
mrdepth/EVEUniverse | refs/heads/master | Neocom/Neocom/Killboard/zKillboard/ShipPicker.swift | lgpl-2.1 | 2 | //
// ShipPicker.swift
// Neocom
//
// Created by Artem Shimanski on 4/2/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import Expressible
import CoreData
struct ShipPicker: View {
var completion: (NSManagedObject) -> Void
@Environment(\.managedObjectContext) private var managedObjectContext
@Environment(\.self) private var environment
@State private var selectedType: SDEInvType?
@EnvironmentObject private var sharedState: SharedState
private func getCategories() -> FetchedResultsController<SDEInvCategory> {
let controller = managedObjectContext.from(SDEInvCategory.self)
.filter((/\SDEInvCategory.categoryID).in([SDECategoryID.ship.rawValue, SDECategoryID.structure.rawValue]))
.sort(by: \SDEInvCategory.categoryName, ascending: true)
.fetchedResultsController(sectionName: /\SDEInvCategory.published)
return FetchedResultsController(controller)
}
private let categories = Lazy<FetchedResultsController<SDEInvCategory>, Never>()
@State private var searchString: String = ""
@State private var searchResults: [FetchedResultsController<SDEInvType>.Section]? = nil
var body: some View {
let categories = self.categories.get(initial: getCategories())
return TypesSearch(searchString: $searchString, searchResults: $searchResults) {
if self.searchResults != nil {
TypePickerTypesContent(types: self.searchResults!, selectedType: self.$selectedType, completion: self.completion)
}
else {
ShipPickerCategoriesContent(categories: categories, completion: self.completion)
}
}
.navigationBarTitle(Text("Categories"))
.sheet(item: $selectedType) { type in
NavigationView {
TypeInfo(type: type).navigationBarItems(leading: BarButtonItems.close {self.selectedType = nil})
}
.modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState))
.navigationViewStyle(StackNavigationViewStyle())
}
}
}
struct ShipPickerCategoriesContent: View {
var categories: FetchedResultsController<SDEInvCategory>
var completion: (NSManagedObject) -> Void
var body: some View {
ForEach(categories.sections, id: \.name) { section in
Section(header: section.name == "0" ? Text("UNPUBLISHED") : Text("PUBLISHED")) {
ForEach(section.objects, id: \.objectID) { category in
NavigationLink(destination: ShipPickerGroups(category: category, completion: self.completion)) {
CategoryCell(category: category)
}
}
}
}
}
}
#if DEBUG
struct ShipPicker_Previews: PreviewProvider {
static var previews: some View {
NavigationView {
ShipPicker { _ in
}
}.modifier(ServicesViewModifier.testModifier())
}
}
#endif
| 39e21f1541c5ed40a8809239040833db | 36.938272 | 129 | 0.654735 | false | false | false | false |
aclissold/Blocker | refs/heads/master | Blocker.swift | mit | 1 | import Foundation
let runLoop = NSRunLoop.currentRunLoop()
let distantFuture = NSDate.distantFuture()
var blocking = false
public func block() {
blocking = true
while blocking &&
runLoop.runMode(NSDefaultRunLoopMode, beforeDate: distantFuture) {}
}
public func unblock() {
blocking = false
}
| f10e831b1dc79f18f61c998e3844ed6c | 18.75 | 75 | 0.718354 | false | false | false | false |
playbasis/native-sdk-ios | refs/heads/master | PlaybasisSDK/Classes/PBForm/PBDeviceForm.swift | mit | 1 | //
// PBDeviceForm.swift
// Playbook
//
// Created by Médéric Petit on 8/15/2559 BE.
// Copyright © 2559 smartsoftasia. All rights reserved.
//
import UIKit
public final class PBDeviceForm: PBForm {
//Required
public var playerId:String!
public var deviceToken:String!
public var deviceDescription:String!
public var deviceName:String!
override public func params() -> [String:String] {
var params:[String:String] = [:]
params["player_id"] = playerId
params["device_token"] = deviceToken
params["device_description"] = deviceDescription
params["device_name"] = deviceName
params["os_type"] = "iOS"
return params
}
}
| 39fc4d86e32764d97ceda055be8db363 | 23.724138 | 56 | 0.640167 | false | false | false | false |
creatubbles/ctb-api-swift | refs/heads/develop | CreatubblesAPIClientIntegrationTests/Spec/Content/ContentResponseHandlerSpec.swift | mit | 1 | //
// ContentResponseHandlerSpec.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Quick
import Nimble
@testable import CreatubblesAPIClient
class ContentResponseHandlerSpec: QuickSpec {
override func spec() {
describe("Content response handler") {
it("Should return recent content after login") {
let request = ContentRequest(type: .Recent, page: 1, perPage: 20, userId: nil)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
expect(responseData.pagingInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return trending content after login") {
let request = ContentRequest(type: .Trending, page: 1, perPage: 20, userId: nil)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
expect(responseData.pagingInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return Connected contents after login") {
let request = ContentRequest(type: .Connected, page: 1, perPage: 20, userId: nil)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutMedium) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
expect(responseData.pagingInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
}
it("Should return User Bubbled Contents after login") {
let request = ContentRequest(type: .BubbledContents, page: 1, perPage: 20, userId: TestConfiguration.testUserIdentifier)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutMedium) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler: ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
expect(responseData.pagingInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return Contents By A User after login") {
let request = ContentRequest(type: .ContentsByAUser, page: 1, perPage: 20, userId: TestConfiguration.testUserIdentifier)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutMedium) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler: ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
expect(responseData.pagingInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return Contents based on Followed Users after login") {
let request = ContentRequest(type: .Followed, page: 1, perPage: 20, userId: nil)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutMedium) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler: ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
expect(responseData.pagingInfo).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return trending creations") {
let request = FetchTrendingCreationsRequest()
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return trending users") {
let request = FetchTrendingUsersRequest()
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
sender.logout()
done()
})
}
}
}
it("Should return hashtag contents") {
let request = HashtagContentRequest(hashtagName:"lego", page: 1, perPage: 20)
let sender = TestComponentsFactory.requestSender
waitUntil(timeout: TestConfiguration.timeoutShort) {
done in
sender.login(TestConfiguration.username, password: TestConfiguration.password) {
(error: Error?) -> Void in
expect(error).to(beNil())
sender.send(request, withResponseHandler:ContentResponseHandler {
(responseData) -> (Void) in
expect(responseData.error).to(beNil())
expect(responseData.objects).notTo(beNil())
sender.logout()
done()
})
}
}
}
}
}
| 7d5978582b5da90df18f040c4f173eb9 | 45.958716 | 132 | 0.524763 | false | true | false | false |
RocketChat/Rocket.Chat.iOS | refs/heads/develop | Rocket.Chat/Models/Mapping/MessageModelMapping.swift | mit | 1 | //
// MessageModelMapping.swift
// Rocket.Chat
//
// Created by Rafael Kellermann Streit on 16/01/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import Foundation
import SwiftyJSON
import RealmSwift
extension Message: ModelMappeable {
//swiftlint:disable cyclomatic_complexity function_body_length
func map(_ values: JSON, realm: Realm?) {
if self.identifier == nil {
self.identifier = values["_id"].stringValue
}
self.rid = values["rid"].stringValue
self.text = values["msg"].stringValue
self.avatar = values["avatar"].string
self.emoji = values["emoji"].string
self.alias = values["alias"].stringValue
self.internalType = values["t"].string ?? "t"
self.role = values["role"].stringValue
self.pinned = values["pinned"].bool ?? false
self.unread = values["unread"].bool ?? false
self.groupable = values["groupable"].bool ?? true
self.snippetName = values["snippetName"].string
self.snippetId = values["snippetId"].string
if let createdAt = values["ts"]["$date"].double {
self.createdAt = Date.dateFromInterval(createdAt)
}
if let createdAt = values["ts"].string {
self.createdAt = Date.dateFromString(createdAt)
}
if let updatedAt = values["_updatedAt"]["$date"].double {
self.updatedAt = Date.dateFromInterval(updatedAt)
}
if let updatedAt = values["_updatedAt"].string {
self.updatedAt = Date.dateFromString(updatedAt)
}
if let userIdentifier = values["u"]["_id"].string {
self.userIdentifier = userIdentifier
if let realm = realm {
if let user = realm.object(ofType: User.self, forPrimaryKey: userIdentifier as AnyObject) {
user.map(values["u"], realm: realm)
realm.add(user, update: true)
} else {
let user = User()
user.map(values["u"], realm: realm)
realm.add(user, update: true)
}
}
}
// Starred
if let starred = values["starred"].array {
self.starred.removeAll()
starred.compactMap({ $0["_id"].string }).forEach(self.starred.append)
}
// Attachments
if let attachments = values["attachments"].array {
self.attachments.removeAll()
attachments.forEach {
guard var attachmentValue = try? $0.merged(with: JSON(dictionaryLiteral: ("messageIdentifier", values["_id"].stringValue))) else {
return
}
if let realm = realm {
var obj: Attachment!
// FA NOTE: We are not using Object.getOrCreate method here on purpose since
// we have to map the local modifications before mapping the current JSON on the object.
if let primaryKey = attachmentValue.rawString()?.md5(), let existingObj = realm.object(ofType: Attachment.self, forPrimaryKey: primaryKey) {
obj = existingObj
attachmentValue["collapsed"] = JSON(existingObj.collapsed)
} else {
obj = Attachment()
}
obj.map(attachmentValue, realm: realm)
realm.add(obj, update: true)
self.attachments.append(obj)
} else {
let obj = Attachment()
obj.map(attachmentValue, realm: realm)
self.attachments.append(obj)
}
}
}
// URLs
if let urls = values["urls"].array {
self.urls.removeAll()
for url in urls {
let obj = MessageURL()
obj.map(url, realm: realm)
self.urls.append(obj)
}
}
// Mentions
if let mentions = values["mentions"].array {
self.mentions.removeAll()
for mention in mentions {
let obj = Mention()
obj.map(mention, realm: realm)
self.mentions.append(obj)
}
}
// Channels
if let channels = values["channels"].array {
self.channels.removeAll()
for channel in channels {
let obj = Channel()
obj.map(channel, realm: realm)
self.channels.append(obj)
}
}
// Reactions
self.reactions.removeAll()
if let reactions = values["reactions"].dictionary {
reactions.enumerated().compactMap {
let reaction = MessageReaction()
reaction.map(emoji: $1.key, json: $1.value)
return reaction
}.forEach(self.reactions.append)
}
// Threads
if let threadMessageId = values["tmid"].string {
self.threadMessageId = threadMessageId
}
if let threadLastMessage = values["tlm"]["$date"].double {
self.threadLastMessage = Date.dateFromInterval(threadLastMessage)
}
if let threadLastMessage = values["tlm"].string {
self.threadLastMessage = Date.dateFromString(threadLastMessage)
}
if let threadMessagesCount = values["tcount"].int {
self.threadMessagesCount = threadMessagesCount
}
if let threadFollowers = values["replies"].arrayObject as? [String] {
if let currentUserId = AuthManager.currentUser()?.identifier {
self.threadIsFollowing = threadFollowers.contains(currentUserId)
}
}
// Discussions
if let discussionRid = values["drid"].string {
self.discussionRid = discussionRid
}
if let discussionLastMessage = values["dlm"]["$date"].double {
self.discussionLastMessage = Date.dateFromInterval(discussionLastMessage)
}
if let discussionLastMessage = values["dlm"].string {
self.discussionLastMessage = Date.dateFromString(discussionLastMessage)
}
if let discussionMessagesCount = values["dcount"].int {
self.discussionMessagesCount = discussionMessagesCount
}
}
}
| cb7d55dbfc753f17ebdec58713296dde | 33.751351 | 160 | 0.548608 | false | false | false | false |
alecananian/osx-coin-ticker | refs/heads/develop | CoinTicker/Source/Exchanges/OKExExchange.swift | mit | 1 | //
// OKExExchange.swift
// CoinTicker
//
// Created by Alec Ananian on 1/15/18.
// Copyright © 2018 Alec Ananian.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import SwiftyJSON
import PromiseKit
class OKExExchange: Exchange {
private struct Constants {
static let ProductListAPIPath = "https://www.okex.com/api/spot/v3/instruments"
static let TickerAPIPathFormat = "https://www.okex.com/api/spot/v3/instruments/%@/ticker"
}
init(delegate: ExchangeDelegate? = nil) {
super.init(site: .okex, delegate: delegate)
}
override func load() {
super.load(from: Constants.ProductListAPIPath) {
$0.json.arrayValue.compactMap { result in
return CurrencyPair(
baseCurrency: result["base_currency"].stringValue,
quoteCurrency: result["quote_currency"].stringValue,
customCode: result["instrument_id"].stringValue
)
}
}
}
override internal func fetch() {
_ = when(resolved: selectedCurrencyPairs.map({ currencyPair -> Promise<ExchangeAPIResponse> in
let apiRequestPath = String(format: Constants.TickerAPIPathFormat, currencyPair.customCode)
return requestAPI(apiRequestPath, for: currencyPair)
})).map { [weak self] results in
results.forEach({ result in
switch result {
case .fulfilled(let value):
if let currencyPair = value.representedObject as? CurrencyPair {
let price = value.json["last"].doubleValue
self?.setPrice(price, for: currencyPair)
}
default: break
}
})
self?.onFetchComplete()
}
}
}
| e40d6d7b2706ea1448bb7a28cf91b8d1 | 38.040541 | 103 | 0.647975 | false | false | false | false |
sendyhalim/Yomu | refs/heads/master | Yomu/Screens/ChapterList/ChapterItem.swift | mit | 1 | //
// MangaChapterCollectionViewItem.swift
// Yomu
//
// Created by Sendy Halim on 6/16/16.
// Copyright © 2016 Sendy Halim. All rights reserved.
//
import AppKit
import RxSwift
class ChapterItem: NSCollectionViewItem {
@IBOutlet weak var chapterTitle: NSTextField!
@IBOutlet weak var chapterNumber: NSTextField!
@IBOutlet weak var chapterPreview: NSImageView!
var disposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
chapterPreview.kf.indicatorType = .activity
}
func didEndDisplaying() {
chapterPreview.image = .none
disposeBag = DisposeBag()
}
func setup(withViewModel viewModel: ChapterViewModel) {
disposeBag = DisposeBag()
// Show activity indicator right now because fetch preview will
// fetch chapter pages first, after the pages are loaded, the first image of the pages
// will be fetched. Activity indicator will be removed automatically by kingfisher
// after image preview is fetched.
chapterPreview.kf.indicator?.startAnimatingView()
viewModel
.fetchPreview() ==> disposeBag
viewModel.title
.drive(chapterTitle.rx.text.orEmpty) ==> disposeBag
viewModel.title
.drive(chapterTitle.rx.text.orEmpty) ==> disposeBag
viewModel
.previewUrl
.drive(onNext: { [weak self] url in
self?.chapterPreview.setImageWithUrl(url)
self?.chapterPreview.kf.indicator?.stopAnimatingView()
}) ==> disposeBag
viewModel.number
.drive(chapterNumber.rx.text.orEmpty) ==> disposeBag
}
override func viewWillLayout() {
let border = Border(position: .bottom, width: 1.0, color: Config.style.borderColor)
view.drawBorder(border)
}
}
| 857bc9a7270a104a65ae6799b6147724 | 25.276923 | 90 | 0.706674 | false | false | false | false |
karstengresch/rw_studies | refs/heads/master | PaintCode/StopwatchPaintCode/PaintCodeTutorial.swift | unlicense | 1 | //
// PaintCodeTutorial.swift
// PaintCodeTutorial
//
// Created by Karsten Gresch on 02.10.15.
// Copyright (c) 2015 Closure One. All rights reserved.
//
// Generated by PaintCode (www.paintcodeapp.com)
//
import UIKit
public class PaintCodeTutorial : NSObject {
//// Cache
private struct Cache {
static let color: UIColor = UIColor(red: 0.481, green: 0.631, blue: 0.860, alpha: 1.000)
static var imageOfStopwatch: UIImage?
static var stopwatchTargets: [AnyObject]?
}
//// Colors
public class var color: UIColor { return Cache.color }
//// Drawing Methods
public class func drawStopwatch() {
//// Oval Drawing
let ovalPath = UIBezierPath(ovalInRect: CGRectMake(15, 30, 220, 220))
PaintCodeTutorial.color.setFill()
ovalPath.fill()
//// Rectangle Drawing
let rectanglePath = UIBezierPath(rect: CGRectMake(114, 7, 22, 29))
PaintCodeTutorial.color.setFill()
rectanglePath.fill()
//// Bezier Drawing
let bezierPath = UIBezierPath()
bezierPath.moveToPoint(CGPointMake(214.14, 30))
bezierPath.addLineToPoint(CGPointMake(235.36, 51.21))
bezierPath.addLineToPoint(CGPointMake(221.21, 65.35))
bezierPath.addCurveToPoint(CGPointMake(216.21, 60.35), controlPoint1: CGPointMake(221.21, 65.35), controlPoint2: CGPointMake(219.1, 63.24))
bezierPath.addLineToPoint(CGPointMake(204, 60.35))
bezierPath.addCurveToPoint(CGPointMake(204, 48.14), controlPoint1: CGPointMake(204, 60.35), controlPoint2: CGPointMake(204, 53.76))
bezierPath.addCurveToPoint(CGPointMake(200, 44.14), controlPoint1: CGPointMake(201.64, 45.78), controlPoint2: CGPointMake(200, 44.14))
bezierPath.addLineToPoint(CGPointMake(214.14, 30))
bezierPath.closePath()
PaintCodeTutorial.color.setFill()
bezierPath.fill()
}
public class func drawStopwatch_Hand() {
//// General Declarations
let context = UIGraphicsGetCurrentContext()
//// Bezier 2 Drawing
CGContextSaveGState(context)
CGContextTranslateCTM(context, 125, 110)
let bezier2Path = UIBezierPath()
bezier2Path.moveToPoint(CGPointMake(4, -84))
bezier2Path.addCurveToPoint(CGPointMake(4, -14.46), controlPoint1: CGPointMake(4, -84), controlPoint2: CGPointMake(4, -46.6))
bezier2Path.addCurveToPoint(CGPointMake(15, 0), controlPoint1: CGPointMake(10.34, -12.71), controlPoint2: CGPointMake(15, -6.9))
bezier2Path.addCurveToPoint(CGPointMake(4, 14.46), controlPoint1: CGPointMake(15, 6.9), controlPoint2: CGPointMake(10.34, 12.71))
bezier2Path.addCurveToPoint(CGPointMake(4, 31), controlPoint1: CGPointMake(4, 24.44), controlPoint2: CGPointMake(4, 31))
bezier2Path.addLineToPoint(CGPointMake(-4, 31))
bezier2Path.addCurveToPoint(CGPointMake(-4, 14.46), controlPoint1: CGPointMake(-4, 31), controlPoint2: CGPointMake(-4, 24.44))
bezier2Path.addCurveToPoint(CGPointMake(-15, 0), controlPoint1: CGPointMake(-10.34, 12.71), controlPoint2: CGPointMake(-15, 6.9))
bezier2Path.addCurveToPoint(CGPointMake(-4, -14.46), controlPoint1: CGPointMake(-15, -6.9), controlPoint2: CGPointMake(-10.34, -12.71))
bezier2Path.addCurveToPoint(CGPointMake(-4, -84), controlPoint1: CGPointMake(-4, -46.6), controlPoint2: CGPointMake(-4, -84))
bezier2Path.addLineToPoint(CGPointMake(4, -84))
bezier2Path.addLineToPoint(CGPointMake(4, -84))
bezier2Path.closePath()
UIColor.whiteColor().setFill()
bezier2Path.fill()
CGContextRestoreGState(context)
}
//// Generated Images
public class var imageOfStopwatch: UIImage {
if Cache.imageOfStopwatch != nil {
return Cache.imageOfStopwatch!
}
UIGraphicsBeginImageContextWithOptions(CGSizeMake(250, 250), false, 0)
PaintCodeTutorial.drawStopwatch()
Cache.imageOfStopwatch = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return Cache.imageOfStopwatch!
}
//// Customization Infrastructure
@IBOutlet var stopwatchTargets: [AnyObject]! {
get { return Cache.stopwatchTargets }
set {
Cache.stopwatchTargets = newValue
for target: AnyObject in newValue {
target.performSelector("setImage:", withObject: PaintCodeTutorial.imageOfStopwatch)
}
}
}
}
| 60ad062ec2bdcd88df84f26a00d57a03 | 37.767241 | 147 | 0.675561 | false | false | false | false |
aclissold/the-oakland-post | refs/heads/master | The Oakland Post/PostTableViewController.swift | bsd-3-clause | 2 | //
// PostTableViewController.swift
// The Oakland Post
//
// The main feature of the app: a table view of posts.
//
// Created by Andrew Clissold on 6/13/14.
// Copyright (c) 2014 Andrew Clissold. All rights reserved.
//
import UIKit
class PostTableViewController: BugFixTableViewController, MWFeedParserDelegate, StarButtonDelegate {
var baseURL: String!
var feedParser: FeedParser!
var parsedItems = [MWFeedItem]()
var finishedParsing = false
override func viewDidLoad() {
super.viewDidLoad()
// Pull to refresh.
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: "refresh", forControlEvents: UIControlEvents.ValueChanged)
self.refreshControl = refreshControl
feedParser = FeedParser(baseURL: baseURL, length: 15, delegate: self)
feedParser.parseInitial()
tableView.addInfiniteScrollingWithActionHandler(loadMorePosts)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if !finishedParsing {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
SVProgressHUD.show()
}
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
SVProgressHUD.dismiss()
}
func refresh() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
tableView.userInteractionEnabled = false
parsedItems.removeAll()
feedParser.parseInitial()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
func loadMorePosts() {
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
tableView.userInteractionEnabled = false
feedParser.parseMore()
}
// MARK: StarButtonDelegate
func didSelectStarButton(starButton: UIButton, forItem item: MWFeedItem) {
starButton.selected = !starButton.selected
if starButton.selected {
// Persist the new favorite.
let object = PFObject(item: item)
object.saveEventually()
BugFixWrapper.starredPosts.append(object)
} else {
deleteStarredPostWithIdentifier(item.identifier)
}
}
// MARK: MWFeedParserDelegate
func feedParser(parser: MWFeedParser!, didParseFeedItem item: MWFeedItem!) {
parsedItems.append(item)
}
func feedParserDidFinish(parser: MWFeedParser!) {
finishedParsing = true
reloadData()
}
func feedParser(parser: MWFeedParser!, didFailWithError error: NSError!) {
showAlertForErrorCode(feedParserDidFailErrorCode)
finishedParsing = true
reloadData()
}
func reloadData() {
tableView.reloadData()
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
SVProgressHUD.dismiss()
refreshControl!.endRefreshing()
tableView.infiniteScrollingView.stopAnimating()
tableView.userInteractionEnabled = true
}
// MARK: Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) {
if segue.identifier == readPostID {
let indexPath = self.tableView.indexPathForSelectedRow!
let item = parsedItems[indexPath.row] as MWFeedItem
(segue.destinationViewController as! PostViewController).URL = item.link
}
}
// MARK: Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return parsedItems.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(cellID, forIndexPath: indexPath) as! PostCell
cell.delegate = self
if indexPath.row <= parsedItems.count {
cell.item = parsedItems[indexPath.row] as MWFeedItem
cell.starButton.hidden = PFUser.currentUser() == nil
if !cell.starButton.hidden {
cell.starButton.selected = starredPostIdentifiers.contains(cell.item.identifier)
}
}
return cell
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return tableViewRowHeight
}
}
| 2a25c743f7b8e943dddb84e7a2489f37 | 30.903448 | 118 | 0.680285 | false | false | false | false |
tadasz/MistikA | refs/heads/master | MistikA/Classes/CountdownViewController.swift | mit | 1 | //
// CountdownViewController.swift
// MistikA
//
// Created by Tadas Ziemys on 18/08/14.
// Copyright (c) 2014 Tadas. All rights reserved.
//
import UIKit
class CountdownViewController: BaseViewController {
@IBOutlet weak var textLabel: LTMorphingLabel?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var timer: NSTimer?
func updateTimer() {
let dateFormater = NSDateFormatter()
dateFormater.dateFormat = ("dd:MM:yyyy HH:mm:ss")
let date = dateFormater.dateFromString("28:11:2014 19:36:36")
let now = NSDate()
let timeLeft = date!.timeIntervalSinceDate(now)
if timeLeft < 0 {
textLabel?.text = "Išaušo mistinė valanda..."
timer?.invalidate()
timer = nil
GameController.sharedInstance.currentGameStage = GameStage.FinalPuzzle
finishStage()
} else {
textLabel?.text = "\(timeLeft)"
}
// println("time left: \(timeLeft)")
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
timer = NSTimer.scheduledTimerWithTimeInterval(1.5, target: self, selector: "updateTimer", userInfo: nil, repeats: true)
// timer = NSTimer(timeInterval: 1.0, target: nil, selector: "updateTimer", userInfo: nil, repeats: true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func finishStage() {
let button: UIButton = UIButton(type: UIButtonType.Custom)
button.frame = self.view.bounds
button.addTarget(self, action: Selector("bringMeBack"), forControlEvents: UIControlEvents.TouchUpInside)
view.addSubview(button)
playSoundWin()
}
func bringMeBack() {
dismissViewControllerAnimated(true, completion: nil)
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| a82441c34bb587e4f8d0454fdea5a462 | 27.125 | 128 | 0.611717 | false | false | false | false |
SwiftDialog/SwiftDialog | refs/heads/master | SwiftDialog/RootElement.swift | apache-2.0 | 2 | // Copyright 2014 Thomas K. Dyas
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
protocol BooleanValuedElement {
var value: Bool { get }
}
public enum SummarizeBy {
case none
case radioGroup(group: String)
case count
}
public class RootElement : BaseElement {
public var sections: ArrayRef<SectionElement>
public var title: String
public var groups: [String: Int]
public var onRefresh: ((RootElement) -> ())?
public var summary: SummarizeBy
public var style: UITableViewStyle
public weak var dialogController: DialogController?
public init(
title: String,
sections: ArrayRef<SectionElement>,
groups: [String: Int] = [:],
onRefresh: ((RootElement) -> ())? = nil,
summary: SummarizeBy = .none,
style: UITableViewStyle = .grouped
) {
self.title = title
self.sections = sections
self.groups = groups
self.onRefresh = onRefresh
self.summary = summary
self.style = style
super.init()
for section in self.sections {
section.parent = self
}
}
public convenience init(
title: String,
elements: ArrayRef<Element>,
groups: [String: Int] = [:],
onRefresh: ((RootElement) -> ())? = nil,
summary: SummarizeBy = .none,
style: UITableViewStyle = .grouped
) {
self.init(
title: title,
sections: [SectionElement(elements: elements)],
groups: groups,
onRefresh: onRefresh,
summary: summary,
style: style
)
}
func indexForRadioElement(_ radioElement: RadioElement) -> Int? {
var index = 0
for section in sections {
for element in section.elements {
if let currentRadioElement = element as? RadioElement {
if currentRadioElement.group == radioElement.group {
if currentRadioElement == radioElement {
return index
}
index += 1
}
}
}
}
return nil
}
public override func getCell(_ tableView: UITableView) -> UITableViewCell! {
let cellKey = "root"
var cell = tableView.dequeueReusableCell(withIdentifier: cellKey) as UITableViewCell!
if cell == nil {
cell = UITableViewCell(style: .value1, reuseIdentifier: cellKey)
cell?.selectionStyle = .default
cell?.accessoryType = .disclosureIndicator
}
cell?.textLabel!.text = title
switch summary {
case .radioGroup(let group):
if let selectedIndex = groups[group] {
var currentIndex = 0
for section in sections {
for element in section.elements {
if let currentRadioElement = element as? RadioElement {
if currentRadioElement.group == group {
if currentIndex == selectedIndex {
cell?.detailTextLabel?.text = currentRadioElement.text
}
currentIndex += 1
}
}
}
}
}
case .count:
var count = 0
for section in sections {
for element in section.elements {
if let boolElement = element as? BooleanValuedElement {
if boolElement.value {
count += 1
}
}
}
}
cell?.detailTextLabel?.text = count.description
case .none:
cell?.detailTextLabel?.text = ""
}
return cell
}
public override func elementSelected(_ dialogController: DialogController, tableView: UITableView, atPath indexPath: IndexPath) {
let vc = DialogViewController(root: self)
dialogController.viewController?.navigationController?.pushViewController(vc, animated: true)
}
func invalidateAll() {
self.dialogController?.viewController?.tableView.reloadData()
}
func invalidateElements(_ invalidatedElements: [Element]) {
var rowsToReload: [IndexPath] = []
outer: for invalidatedElement in invalidatedElements {
guard let sectionOfInvalidatedElement = invalidatedElement.parent as? SectionElement else { continue }
guard let rootOfInvalidatedElement = sectionOfInvalidatedElement.parent as? RootElement else { continue }
if rootOfInvalidatedElement !== self { continue }
for (sectionIndex, section) in sections.enumerated() {
if section !== sectionOfInvalidatedElement { continue }
for (elementIndex, element) in section.elements.enumerated() {
if element === invalidatedElement {
rowsToReload.append(IndexPath(row: elementIndex, section: sectionIndex))
continue outer;
}
}
}
}
self.dialogController?.viewController?.tableView.reloadRows(at: rowsToReload, with: .none)
}
public func sectionIndexForElement(_ element: Element) -> Int? {
guard let sectionOfElement = element.parent as? SectionElement else { return nil }
guard let rootOfElement = sectionOfElement.parent as? RootElement else { return nil }
if rootOfElement !== self { return nil }
for (sectionIndex, section) in sections.enumerated() {
if section === sectionOfElement {
return sectionIndex
}
}
return nil
}
func insert(section: SectionElement, at index: Int) {
sections.insert(newElement: section, at: index)
dialogController?.viewController?.tableView.insertSections(IndexSet(integer: index), with: .none)
}
func remove(section: SectionElement) {
guard let index = sections.index(of: section) else { return }
let _ = sections.remove(at: index)
dialogController?.viewController?.tableView.deleteSections(IndexSet(integer: index), with: .none)
}
}
extension RootElement {
public static func invalidateSummarizedRootOf(element: Element) {
guard let root = element.root else { return }
switch (root.summary) {
case .none:
return
default:
root.root?.invalidateElements([root])
}
}
}
public protocol RootElementBuilder {
func title(_ title: String) -> RootElementBuilder
func sections(_ sections: ArrayRef<SectionElement>) -> RootElementBuilder
func section(_ section: SectionElement) -> RootElementBuilder
func groups(_ groups: [String: Int]) -> RootElementBuilder
func onRefresh(_ closure: @escaping (RootElement) -> ()) -> RootElementBuilder
func summary(_ summary: SummarizeBy) -> RootElementBuilder
func style(_ style: UITableViewStyle) -> RootElementBuilder
func build() -> RootElement
}
extension RootElement {
public static func builder() -> RootElementBuilder {
return BuilderImpl()
}
class BuilderImpl : RootElementBuilder {
private var _title: String = ""
private var _sections: ArrayRef<SectionElement> = ArrayRef<SectionElement>()
private var _groups: [String: Int] = [:]
private var _onRefresh: ((RootElement) -> ())?
private var _summary: SummarizeBy = .none
private var _style: UITableViewStyle = .grouped
func title(_ title: String) -> RootElementBuilder {
_title = title
return self
}
func sections(_ sections: ArrayRef<SectionElement>) -> RootElementBuilder {
_sections = sections
return self
}
func section(_ section: SectionElement) -> RootElementBuilder {
_sections.append(section)
return self
}
func groups(_ groups: [String: Int]) -> RootElementBuilder {
_groups = groups
return self
}
func onRefresh(_ closure: @escaping (RootElement) -> ()) -> RootElementBuilder {
_onRefresh = closure
return self
}
func summary(_ summary: SummarizeBy) -> RootElementBuilder {
_summary = summary
return self
}
func style(_ style: UITableViewStyle) -> RootElementBuilder {
_style = style
return self
}
func build() -> RootElement {
return RootElement(
title: _title,
sections: _sections,
groups: _groups,
onRefresh: _onRefresh,
summary: _summary,
style: _style
)
}
}
}
| 4ed3507efc8e8efaf88512bc8207cbd6 | 32.948097 | 133 | 0.561105 | false | false | false | false |
CatchChat/Yep | refs/heads/master | Yep/Views/Cells/FeedSkillUsers/FeedSkillUsersCell.swift | mit | 1 | //
// FeedSkillUsersCell.swift
// Yep
//
// Created by nixzhu on 15/10/23.
// Copyright © 2015年 Catch Inc. All rights reserved.
//
import UIKit
import YepKit
final class FeedSkillUsersCell: UITableViewCell {
@IBOutlet weak var promptLabel: UILabel!
@IBOutlet weak var avatarImageView1: UIImageView!
@IBOutlet weak var avatarImageView2: UIImageView!
@IBOutlet weak var avatarImageView3: UIImageView!
@IBOutlet weak var accessoryImageView: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
promptLabel.text = NSLocalizedString("People with this skill", comment: "")
accessoryImageView.tintColor = UIColor.yepCellAccessoryImageViewTintColor()
}
func configureWithFeeds(feeds: [DiscoveredFeed]) {
let feedCreators = Array(Set(feeds.map({ $0.creator }))).sort { $0.lastSignInUnixTime > $1.lastSignInUnixTime }
if let creator = feedCreators[safe: 0] {
let plainAvatar = PlainAvatar(avatarURLString: creator.avatarURLString, avatarStyle: nanoAvatarStyle)
avatarImageView1.navi_setAvatar(plainAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
} else {
avatarImageView1.image = nil
}
if let creator = feedCreators[safe: 1] {
let plainAvatar = PlainAvatar(avatarURLString: creator.avatarURLString, avatarStyle: nanoAvatarStyle)
avatarImageView2.navi_setAvatar(plainAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
} else {
avatarImageView2.image = nil
}
if let creator = feedCreators[safe: 2] {
let plainAvatar = PlainAvatar(avatarURLString: creator.avatarURLString, avatarStyle: nanoAvatarStyle)
avatarImageView3.navi_setAvatar(plainAvatar, withFadeTransitionDuration: avatarFadeTransitionDuration)
} else {
avatarImageView3.image = nil
}
}
}
| 0d5f6b127db6e0752a22e37818ece8cf | 33.857143 | 119 | 0.698258 | false | false | false | false |
Snowgan/WeiboDemo | refs/heads/master | WeiboDemo/XLTabBar.swift | mit | 1 | //
// XLTabBar.swift
// WeiboDemo
//
// Created by Jennifer on 18/11/15.
// Copyright © 2015 Snowgan. All rights reserved.
//
import UIKit
class XLTabBar: UITabBar {
var composeButton: UIButton!
override init(frame: CGRect) {
super.init(frame: frame)
// self.backgroundImage = UIImage(named: "tabbar_backgroud")
self.backgroundColor = UIColor.whiteColor()
composeButton = UIButton()
composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: .Normal)
composeButton.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: .Highlighted)
composeButton.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: .Normal)
composeButton.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: .Highlighted)
self.addSubview(composeButton)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
let tabbarCount = items!.count
print(tabbarCount)
let tabbarItemW = bounds.width / CGFloat(tabbarCount + 1)
let tabbarItamH = bounds.height
composeButton.bounds.size = composeButton.currentBackgroundImage!.size
composeButton.center = CGPoint(x: tabbarItemW*2.5, y: tabbarItamH*0.5)
print(subviews.count)
if subviews[2].isKindOfClass(NSClassFromString("UITabBarButton")!) {
print("tabbaritem")
}
for i in 2..<(subviews.count-1) {
var indexW = i - 2
if i > 3 {
indexW += 1
}
subviews[i].center = CGPoint(x: tabbarItemW*(CGFloat(indexW)+0.5), y: tabbarItamH*0.5)
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| fa19e13765d80ce862374fac60e8fdcc | 30.313433 | 117 | 0.618684 | false | false | false | false |
amraboelela/swift | refs/heads/master | stdlib/public/core/StringObject.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// StringObject abstracts the bit-level interpretation and creation of the
// String struct.
//
// TODO(String docs): Word-level diagram
/*
On 64-bit platforms, the discriminator is the most significant 4 bits of the
bridge object.
┌─────────────────────╥─────┬─────┬─────┬─────┐
│ Form ║ b63 │ b62 │ b61 │ b60 │
╞═════════════════════╬═════╪═════╪═════╪═════╡
│ Immortal, Small ║ 1 │ASCII│ 1 │ 0 │
├─────────────────────╫─────┼─────┼─────┼─────┤
│ Immortal, Large ║ 1 │ 0 │ 0 │ 0 │
╞═════════════════════╬═════╪═════╪═════╪═════╡
│ Native ║ 0 │ 0 │ 0 │ 0 │
├─────────────────────╫─────┼─────┼─────┼─────┤
│ Shared ║ x │ 0 │ 0 │ 0 │
├─────────────────────╫─────┼─────┼─────┼─────┤
│ Shared, Bridged ║ 0 │ 1 │ 0 │ 0 │
╞═════════════════════╬═════╪═════╪═════╪═════╡
│ Foreign ║ x │ 0 │ 0 │ 1 │
├─────────────────────╫─────┼─────┼─────┼─────┤
│ Foreign, Bridged ║ 0 │ 1 │ 0 │ 1 │
└─────────────────────╨─────┴─────┴─────┴─────┘
b63: isImmortal: Should the Swift runtime skip ARC
- Small strings are just values, always immortal
- Large strings can sometimes be immortal, e.g. literals
b62: (large) isBridged / (small) isASCII
- For large strings, this means lazily-bridged NSString: perform ObjC ARC
- Small strings repurpose this as a dedicated bit to remember ASCII-ness
b61: isSmall: Dedicated bit to denote small strings
b60: isForeign: aka isSlow, cannot provide access to contiguous UTF-8
The canonical empty string is the zero-sized small string. It has a leading
nibble of 1110, and all other bits are 0.
A "dedicated" bit is used for the most frequent fast-path queries so that they
can compile to a fused check-and-branch, even if that burns part of the
encoding space.
On 32-bit platforms, we store an explicit discriminator (as a UInt8) with the
same encoding as above, placed in the high bits. E.g. `b62` above is in
`_discriminator`'s `b6`.
*/
@_fixed_layout @usableFromInline
internal struct _StringObject {
// Namespace to hold magic numbers
@usableFromInline @_frozen
enum Nibbles {}
// Abstract the count and performance-flags containing word
@_fixed_layout @usableFromInline
struct CountAndFlags {
@usableFromInline
var _storage: UInt64
@inlinable @inline(__always)
internal init(zero: ()) { self._storage = 0 }
}
#if arch(i386) || arch(arm)
@usableFromInline @_frozen
internal enum Variant {
case immortal(UInt)
case native(AnyObject)
case bridged(_CocoaString)
@inlinable @inline(__always)
internal static func immortal(start: UnsafePointer<UInt8>) -> Variant {
let biased = UInt(bitPattern: start) &- _StringObject.nativeBias
return .immortal(biased)
}
@inlinable
internal var isImmortal: Bool {
@inline(__always) get {
if case .immortal = self { return true }
return false
}
}
}
@usableFromInline
internal var _count: Int
@usableFromInline
internal var _variant: Variant
@usableFromInline
internal var _discriminator: UInt8
@usableFromInline
internal var _flags: UInt16
@inlinable @inline(__always)
init(count: Int, variant: Variant, discriminator: UInt64, flags: UInt16) {
_internalInvariant(discriminator & 0xFF00_0000_0000_0000 == discriminator,
"only the top byte can carry the discriminator and small count")
self._count = count
self._variant = variant
self._discriminator = UInt8(truncatingIfNeeded: discriminator &>> 56)
self._flags = flags
self._invariantCheck()
}
@inlinable @inline(__always)
init(variant: Variant, discriminator: UInt64, countAndFlags: CountAndFlags) {
self.init(
count: countAndFlags.count,
variant: variant,
discriminator: discriminator,
flags: countAndFlags.flags)
}
@inlinable @inline(__always)
internal var _countAndFlagsBits: UInt64 {
let rawBits = UInt64(truncatingIfNeeded: _flags) &<< 48
| UInt64(truncatingIfNeeded: _count)
return rawBits
}
#else
//
// Laid out as (_countAndFlags, _object), which allows small string contents
// to naturally start on vector-alignment.
//
@usableFromInline
internal var _countAndFlagsBits: UInt64
@usableFromInline
internal var _object: Builtin.BridgeObject
@inlinable @inline(__always)
internal init(zero: ()) {
self._countAndFlagsBits = 0
self._object = Builtin.valueToBridgeObject(UInt64(0)._value)
}
#endif
@inlinable @inline(__always)
internal var _countAndFlags: CountAndFlags {
_internalInvariant(!isSmall)
return CountAndFlags(rawUnchecked: _countAndFlagsBits)
}
}
// Raw
extension _StringObject {
@usableFromInline
internal typealias RawBitPattern = (UInt64, UInt64)
#if arch(i386) || arch(arm)
// On 32-bit platforms, raw bit conversion is one-way only and uses the same
// layout as on 64-bit platforms.
@usableFromInline
internal var rawBits: RawBitPattern {
@inline(__always) get {
let count = UInt64(truncatingIfNeeded: UInt(bitPattern: _count))
let payload = UInt64(truncatingIfNeeded: discriminatedObjectRawBits)
& _StringObject.Nibbles.largeAddressMask
let flags = UInt64(truncatingIfNeeded: _flags)
let discr = UInt64(truncatingIfNeeded: _discriminator)
if isSmall {
// Rearrange small strings in a different way, compacting bytes into a
// contiguous sequence. See comment on small string layout below.
return (count | (payload &<< 32), flags | (discr &<< 56))
}
return (count | (flags &<< 48), payload | (discr &<< 56))
}
}
#else
@inlinable
internal var rawBits: RawBitPattern {
@inline(__always) get {
return (_countAndFlagsBits, discriminatedObjectRawBits)
}
}
@inlinable @inline(__always)
internal init(
bridgeObject: Builtin.BridgeObject, countAndFlags: CountAndFlags
) {
self._object = bridgeObject
self._countAndFlagsBits = countAndFlags._storage
_invariantCheck()
}
@inlinable @inline(__always)
internal init(
object: AnyObject, discriminator: UInt64, countAndFlags: CountAndFlags
) {
let builtinRawObject: Builtin.Int64 = Builtin.reinterpretCast(object)
let builtinDiscrim: Builtin.Int64 = discriminator._value
self.init(
bridgeObject: Builtin.reinterpretCast(
Builtin.stringObjectOr_Int64(builtinRawObject, builtinDiscrim)),
countAndFlags: countAndFlags)
}
// Initializer to use for tagged (unmanaged) values
@inlinable @inline(__always)
internal init(
pointerBits: UInt64, discriminator: UInt64, countAndFlags: CountAndFlags
) {
let builtinValueBits: Builtin.Int64 = pointerBits._value
let builtinDiscrim: Builtin.Int64 = discriminator._value
self.init(
bridgeObject: Builtin.valueToBridgeObject(Builtin.stringObjectOr_Int64(
builtinValueBits, builtinDiscrim)),
countAndFlags: countAndFlags)
}
@inlinable @inline(__always)
internal init(rawUncheckedValue bits: RawBitPattern) {
self.init(zero:())
self._countAndFlagsBits = bits.0
self._object = Builtin.valueToBridgeObject(bits.1._value)
_internalInvariant(self.rawBits == bits)
}
@inlinable @inline(__always)
internal init(rawValue bits: RawBitPattern) {
self.init(rawUncheckedValue: bits)
_invariantCheck()
}
#endif
@inlinable @_transparent
internal var discriminatedObjectRawBits: UInt64 {
#if arch(i386) || arch(arm)
let low32: UInt
switch _variant {
case .immortal(let bitPattern):
low32 = bitPattern
case .native(let storage):
low32 = Builtin.reinterpretCast(storage)
case .bridged(let object):
low32 = Builtin.reinterpretCast(object)
}
return UInt64(truncatingIfNeeded: _discriminator) &<< 56
| UInt64(truncatingIfNeeded: low32)
#else
return Builtin.reinterpretCast(_object)
#endif
}
}
// From/to raw bits for CountAndFlags
extension _StringObject.CountAndFlags {
@usableFromInline
internal typealias RawBitPattern = UInt64
@inlinable @inline(__always)
internal var rawBits: RawBitPattern {
return _storage
}
@inlinable @inline(__always)
internal init(rawUnchecked bits: RawBitPattern) {
self._storage = bits
}
@inlinable @inline(__always)
internal init(raw bits: RawBitPattern) {
self.init(rawUnchecked: bits)
_invariantCheck()
}
}
/*
Encoding is optimized for common fast creation. The canonical empty string,
ASCII small strings, as well as most literals, have all consecutive 1s in their
high nibble mask, and thus can all be encoded as a logical immediate operand
on arm64.
*/
extension _StringObject.Nibbles {
// The canonical empty sting is an empty small string
@inlinable
internal static var emptyString: UInt64 {
@inline(__always) get { return _StringObject.Nibbles.small(isASCII: true) }
}
}
/*
Large strings can either be "native", "shared", or "foreign".
Native strings have tail-allocated storage, which begins at an offset of
`nativeBias` from the storage object's address. String literals, which reside
in the constant section, are encoded as their start address minus `nativeBias`,
unifying code paths for both literals ("immortal native") and native strings.
Native Strings are always managed by the Swift runtime.
Shared strings do not have tail-allocated storage, but can provide access
upon query to contiguous UTF-8 code units. Lazily-bridged NSStrings capable of
providing access to contiguous ASCII/UTF-8 set the ObjC bit. Accessing shared
string's pointer should always be behind a resilience barrier, permitting
future evolution.
Foreign strings cannot provide access to contiguous UTF-8. Currently, this only
encompasses lazily-bridged NSStrings that cannot be treated as "shared". Such
strings may provide access to contiguous UTF-16, or may be discontiguous in
storage. Accessing foreign strings should remain behind a resilience barrier
for future evolution. Other foreign forms are reserved for the future.
Shared and foreign strings are always created and accessed behind a resilience
barrier, providing flexibility for the future.
┌────────────┐
│ nativeBias │
├────────────┤
│ 32 │
└────────────┘
┌───────────────┬────────────┐
│ b63:b60 │ b60:b0 │
├───────────────┼────────────┤
│ discriminator │ objectAddr │
└───────────────┴────────────┘
discriminator: See comment for _StringObject.Discriminator
objectAddr: The address of the beginning of the potentially-managed object.
TODO(Future): For Foreign strings, consider allocating a bit for whether they
can provide contiguous UTF-16 code units, which would allow us to avoid doing
the full call for non-contiguous NSString.
*/
extension _StringObject.Nibbles {
// Mask for address bits, i.e. non-discriminator and non-extra high bits
@inlinable @inline(__always)
static internal var largeAddressMask: UInt64 { return 0x0FFF_FFFF_FFFF_FFFF }
// Mask for address bits, i.e. non-discriminator and non-extra high bits
@inlinable @inline(__always)
static internal var discriminatorMask: UInt64 { return ~largeAddressMask }
}
extension _StringObject.Nibbles {
// Discriminator for small strings
@inlinable @inline(__always)
internal static func small(isASCII: Bool) -> UInt64 {
return isASCII ? 0xE000_0000_0000_0000 : 0xA000_0000_0000_0000
}
// Discriminator for small strings
@inlinable @inline(__always)
internal static func small(withCount count: Int, isASCII: Bool) -> UInt64 {
_internalInvariant(count <= _SmallString.capacity)
return small(isASCII: isASCII) | UInt64(truncatingIfNeeded: count) &<< 56
}
// Discriminator for large, immortal, swift-native strings
@inlinable @inline(__always)
internal static func largeImmortal() -> UInt64 {
return 0x8000_0000_0000_0000
}
// Discriminator for large, mortal (i.e. managed), swift-native strings
@inlinable @inline(__always)
internal static func largeMortal() -> UInt64 {
return 0x0000_0000_0000_0000
}
internal static func largeCocoa(providesFastUTF8: Bool) -> UInt64 {
return providesFastUTF8 ? 0x4000_0000_0000_0000 : 0x5000_0000_0000_0000
}
}
extension _StringObject {
@inlinable
internal static var nativeBias: UInt {
@inline(__always) get {
#if arch(i386) || arch(arm)
return 20
#else
return 32
#endif
}
}
@inlinable
internal var isImmortal: Bool {
@inline(__always) get {
return (discriminatedObjectRawBits & 0x8000_0000_0000_0000) != 0
}
}
@inlinable
internal var isMortal: Bool {
@inline(__always) get { return !isImmortal }
}
@inlinable
internal var isSmall: Bool {
@inline(__always) get {
return (discriminatedObjectRawBits & 0x2000_0000_0000_0000) != 0
}
}
@inlinable
internal var isLarge: Bool { @inline(__always) get { return !isSmall } }
// Whether this string can provide access to contiguous UTF-8 code units:
// - Small strings can by spilling to the stack
// - Large native strings can through an offset
// - Shared strings can:
// - Cocoa strings which respond to e.g. CFStringGetCStringPtr()
// - Non-Cocoa shared strings
@inlinable
internal var providesFastUTF8: Bool {
@inline(__always) get {
return (discriminatedObjectRawBits & 0x1000_0000_0000_0000) == 0
}
}
@inlinable
internal var isForeign: Bool {
@inline(__always) get { return !providesFastUTF8 }
}
// Whether we are native or shared, i.e. we have a backing class which
// conforms to `_AbstractStringStorage`
@inline(__always)
internal var hasStorage: Bool {
return (discriminatedObjectRawBits & 0xF000_0000_0000_0000) == 0
}
// Whether we are a mortal, native (tail-allocated) string
@inline(__always)
internal var hasNativeStorage: Bool {
// b61 on the object means isSmall, and on countAndFlags means
// isNativelyStored. We just need to check that b61 is 0 on the object and 1
// on countAndFlags.
let bits = ~discriminatedObjectRawBits & self._countAndFlagsBits
let result = bits & 0x2000_0000_0000_0000 != 0
_internalInvariant(!result || hasStorage, "native storage needs storage")
return result
}
// Whether we are a mortal, shared string (managed by Swift runtime)
internal var hasSharedStorage: Bool { return hasStorage && !hasNativeStorage }
}
// Queries conditional on being in a large or fast form.
extension _StringObject {
// Whether this string is native, i.e. tail-allocated and nul-terminated,
// presupposing it is both large and fast
@inlinable @inline(__always)
internal var largeFastIsTailAllocated: Bool {
_internalInvariant(isLarge && providesFastUTF8)
return _countAndFlags.isTailAllocated
}
// Whether this string is shared, presupposing it is both large and fast
@inline(__always)
internal var largeFastIsShared: Bool { return !largeFastIsTailAllocated }
// Whether this string is a lazily-bridged NSString, presupposing it is large
@inline(__always)
internal var largeIsCocoa: Bool {
_internalInvariant(isLarge)
return (discriminatedObjectRawBits & 0x4000_0000_0000_0000) != 0
}
}
/*
On 64-bit platforms, small strings have the following per-byte layout. When
stored in memory (little-endian), their first character ('a') is in the lowest
address and their top-nibble and count is in the highest address.
┌───────────────────────────────┬─────────────────────────────────────────────┐
│ _countAndFlags │ _object │
├───┬───┬───┬───┬───┬───┬───┬───┼───┬───┬────┬────┬────┬────┬────┬────────────┤
│ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │ 9 │ 10 │ 11 │ 12 │ 13 │ 14 │ 15 │
├───┼───┼───┼───┼───┼───┼───┼───┼───┼───┼────┼────┼────┼────┼────┼────────────┤
│ a │ b │ c │ d │ e │ f │ g │ h │ i │ j │ k │ l │ m │ n │ o │ 1x10 count │
└───┴───┴───┴───┴───┴───┴───┴───┴───┴───┴────┴────┴────┴────┴────┴────────────┘
On 32-bit platforms, we have less space to store code units, and it isn't
contiguous. However, we still use the above layout for the RawBitPattern
representation.
┌───────────────┬───────────────────┬────────┬─────────┐
│ _count │_variant .immortal │ _discr │ _flags │
├───┬───┬───┬───┼───┬───┬───┬───┬───┼────────┼────┬────┤
│ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │ 7 │ 8 │ 9 │ 10 │ 11 │
├───┼───┼───┼───┼───┴───┴───┴───┴───┼────────┼────┼────┤
│ a │ b │ c │ d │ e f g h │1x10 cnt│ i │ j │
└───┴───┴───┴───┴───────────────────┴────────┴────┴────┘
*/
extension _StringObject {
@inlinable @inline(__always)
internal init(_ small: _SmallString) {
// Small strings are encoded as _StringObjects in reverse byte order
// on big-endian platforms. This is to match the discriminator to the
// spare bits (the most significant nibble) in a pointer.
let word1 = small.rawBits.0.littleEndian
let word2 = small.rawBits.1.littleEndian
#if arch(i386) || arch(arm)
// On 32-bit, we need to unpack the small string.
let smallStringDiscriminatorAndCount: UInt64 = 0xFF00_0000_0000_0000
let leadingFour = Int(truncatingIfNeeded: word1)
let nextFour = UInt(truncatingIfNeeded: word1 &>> 32)
let smallDiscriminatorAndCount = word2 & smallStringDiscriminatorAndCount
let trailingTwo = UInt16(truncatingIfNeeded: word2)
self.init(
count: leadingFour,
variant: .immortal(nextFour),
discriminator: smallDiscriminatorAndCount,
flags: trailingTwo)
#else
// On 64-bit, we copy the raw bits (to host byte order).
self.init(rawValue: (word1, word2))
#endif
_internalInvariant(isSmall)
}
@inlinable
internal static func getSmallCount(fromRaw x: UInt64) -> Int {
return Int(truncatingIfNeeded: (x & 0x0F00_0000_0000_0000) &>> 56)
}
@inlinable
internal var smallCount: Int {
@inline(__always)
get {
_internalInvariant(isSmall)
return _StringObject.getSmallCount(fromRaw: discriminatedObjectRawBits)
}
}
@inlinable
internal static func getSmallIsASCII(fromRaw x: UInt64) -> Bool {
return x & 0x4000_0000_0000_0000 != 0
}
@inlinable
internal var smallIsASCII: Bool {
@inline(__always)
get {
_internalInvariant(isSmall)
return _StringObject.getSmallIsASCII(fromRaw: discriminatedObjectRawBits)
}
}
@inlinable @inline(__always)
internal init(empty:()) {
// Canonical empty pattern: small zero-length string
#if arch(i386) || arch(arm)
self.init(
count: 0,
variant: .immortal(0),
discriminator: Nibbles.emptyString,
flags: 0)
#else
self._countAndFlagsBits = 0
self._object = Builtin.valueToBridgeObject(Nibbles.emptyString._value)
#endif
_internalInvariant(self.smallCount == 0)
_invariantCheck()
}
}
/*
// TODO(String docs): Combine this with Nibbles table, and perhaps small string
// table, into something that describes the higher-level structure of
// _StringObject.
All non-small forms share the same structure for the other half of the bits
(i.e. non-object bits) as a word containing code unit count and various
performance flags. The top 16 bits are for performance flags, which are not
semantically relevant but communicate that some operations can be done more
efficiently on this particular string, and the lower 48 are the code unit
count (aka endIndex).
┌─────────┬───────┬──────────────────┬─────────────────┬────────┬───────┐
│ b63 │ b62 │ b61 │ b60 │ b59:48 │ b47:0 │
├─────────┼───────┼──────────────────┼─────────────────┼────────┼───────┤
│ isASCII │ isNFC │ isNativelyStored │ isTailAllocated │ TBD │ count │
└─────────┴───────┴──────────────────┴─────────────────┴────────┴───────┘
isASCII: set when all code units are known to be ASCII, enabling:
- Trivial Unicode scalars, they're just the code units
- Trivial UTF-16 transcoding (just bit-extend)
- Also, isASCII always implies isNFC
isNFC: set when the contents are in normal form C
- Enables trivial lexicographical comparisons: just memcmp
- `isASCII` always implies `isNFC`, but not vice versa
isNativelyStored: set for native stored strings
- `largeAddressBits` holds an instance of `_StringStorage`.
- I.e. the start of the code units is at the stored address + `nativeBias`
isTailAllocated: start of the code units is at the stored address + `nativeBias`
- `isNativelyStored` always implies `isTailAllocated`, but not vice versa
(e.g. literals)
TBD: Reserved for future usage
- Setting a TBD bit to 1 must be semantically equivalent to 0
- I.e. it can only be used to "cache" fast-path information in the future
count: stores the number of code units, corresponds to `endIndex`.
NOTE: isNativelyStored is *specifically* allocated to b61 to align with the
bit-position of isSmall on the BridgeObject. This allows us to check for
native storage without an extra branch guarding against smallness. See
`_StringObject.hasNativeStorage` for this usage.
*/
extension _StringObject.CountAndFlags {
@inlinable @inline(__always)
internal static var countMask: UInt64 { return 0x0000_FFFF_FFFF_FFFF }
@inlinable @inline(__always)
internal static var flagsMask: UInt64 { return ~countMask }
@inlinable @inline(__always)
internal static var isASCIIMask: UInt64 { return 0x8000_0000_0000_0000 }
@inlinable @inline(__always)
internal static var isNFCMask: UInt64 { return 0x4000_0000_0000_0000 }
@inlinable @inline(__always)
internal static var isNativelyStoredMask: UInt64 {
return 0x2000_0000_0000_0000
}
@inlinable @inline(__always)
internal static var isTailAllocatedMask: UInt64 {
return 0x1000_0000_0000_0000
}
// General purpose bottom initializer
@inlinable @inline(__always)
internal init(
count: Int,
isASCII: Bool,
isNFC: Bool,
isNativelyStored: Bool,
isTailAllocated: Bool
) {
var rawBits = UInt64(truncatingIfNeeded: count)
_internalInvariant(rawBits <= _StringObject.CountAndFlags.countMask)
if isASCII {
_internalInvariant(isNFC)
rawBits |= _StringObject.CountAndFlags.isASCIIMask
}
if isNFC {
rawBits |= _StringObject.CountAndFlags.isNFCMask
}
if isNativelyStored {
_internalInvariant(isTailAllocated)
rawBits |= _StringObject.CountAndFlags.isNativelyStoredMask
}
if isTailAllocated {
rawBits |= _StringObject.CountAndFlags.isTailAllocatedMask
}
self.init(raw: rawBits)
_internalInvariant(count == self.count)
_internalInvariant(isASCII == self.isASCII)
_internalInvariant(isNFC == self.isNFC)
_internalInvariant(isNativelyStored == self.isNativelyStored)
_internalInvariant(isTailAllocated == self.isTailAllocated)
}
@inlinable @inline(__always)
internal init(count: Int, flags: UInt16) {
// Currently, we only use top 4 flags
_internalInvariant(flags & 0xF000 == flags)
let rawBits = UInt64(truncatingIfNeeded: flags) &<< 48
| UInt64(truncatingIfNeeded: count)
self.init(raw: rawBits)
_internalInvariant(self.count == count && self.flags == flags)
}
//
// Specialized initializers
//
@inlinable @inline(__always)
internal init(immortalCount: Int, isASCII: Bool) {
self.init(
count: immortalCount,
isASCII: isASCII,
isNFC: isASCII,
isNativelyStored: false,
isTailAllocated: true)
}
@inline(__always)
internal init(mortalCount: Int, isASCII: Bool) {
self.init(
count: mortalCount,
isASCII: isASCII,
isNFC: isASCII,
isNativelyStored: true,
isTailAllocated: true)
}
@inline(__always)
internal init(sharedCount: Int, isASCII: Bool) {
self.init(
count: sharedCount,
isASCII: isASCII,
isNFC: isASCII,
isNativelyStored: false,
isTailAllocated: false)
}
//
// Queries and accessors
//
@inlinable @inline(__always)
internal var count: Int {
return Int(
truncatingIfNeeded: _storage & _StringObject.CountAndFlags.countMask)
}
@inlinable @inline(__always)
internal var flags: UInt16 {
return UInt16(truncatingIfNeeded: _storage &>> 48)
}
@inlinable @inline(__always)
internal var isASCII: Bool {
return 0 != _storage & _StringObject.CountAndFlags.isASCIIMask
}
@inlinable @inline(__always)
internal var isNFC: Bool {
return 0 != _storage & _StringObject.CountAndFlags.isNFCMask
}
@inlinable @inline(__always)
internal var isNativelyStored: Bool {
return 0 != _storage & _StringObject.CountAndFlags.isNativelyStoredMask
}
@inlinable @inline(__always)
internal var isTailAllocated: Bool {
return 0 != _storage & _StringObject.CountAndFlags.isTailAllocatedMask
}
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
if isASCII {
_internalInvariant(isNFC)
}
if isNativelyStored {
_internalInvariant(isTailAllocated)
}
}
#endif // INTERNAL_CHECKS_ENABLED
}
// Extract
extension _StringObject {
@inlinable @inline(__always)
internal var largeCount: Int {
_internalInvariant(isLarge)
return _countAndFlags.count
}
@inlinable
internal var largeAddressBits: UInt {
@inline(__always) get {
_internalInvariant(isLarge)
return UInt(truncatingIfNeeded:
discriminatedObjectRawBits & Nibbles.largeAddressMask)
}
}
@inlinable
internal var nativeUTF8Start: UnsafePointer<UInt8> {
@inline(__always) get {
_internalInvariant(largeFastIsTailAllocated)
return UnsafePointer(
bitPattern: largeAddressBits &+ _StringObject.nativeBias
)._unsafelyUnwrappedUnchecked
}
}
@inlinable
internal var nativeUTF8: UnsafeBufferPointer<UInt8> {
@inline(__always) get {
_internalInvariant(largeFastIsTailAllocated)
return UnsafeBufferPointer(start: nativeUTF8Start, count: largeCount)
}
}
// Resilient way to fetch a pointer
@usableFromInline @inline(never)
@_effects(releasenone)
internal func getSharedUTF8Start() -> UnsafePointer<UInt8> {
_internalInvariant(largeFastIsShared)
#if _runtime(_ObjC)
if largeIsCocoa {
return _cocoaUTF8Pointer(cocoaObject)._unsafelyUnwrappedUnchecked
}
#endif
return sharedStorage.start
}
@usableFromInline
internal var sharedUTF8: UnsafeBufferPointer<UInt8> {
@_effects(releasenone) @inline(never) get {
_internalInvariant(largeFastIsShared)
let start = self.getSharedUTF8Start()
return UnsafeBufferPointer(start: start, count: largeCount)
}
}
internal var nativeStorage: __StringStorage {
@inline(__always) get {
#if arch(i386) || arch(arm)
guard case .native(let storage) = _variant else {
_internalInvariantFailure()
}
return _unsafeUncheckedDowncast(storage, to: __StringStorage.self)
#else
_internalInvariant(hasNativeStorage)
return Builtin.reinterpretCast(largeAddressBits)
#endif
}
}
internal var sharedStorage: __SharedStringStorage {
@inline(__always) get {
#if arch(i386) || arch(arm)
guard case .native(let storage) = _variant else {
_internalInvariantFailure()
}
return _unsafeUncheckedDowncast(storage, to: __SharedStringStorage.self)
#else
_internalInvariant(largeFastIsShared && !largeIsCocoa)
_internalInvariant(hasSharedStorage)
return Builtin.reinterpretCast(largeAddressBits)
#endif
}
}
internal var cocoaObject: AnyObject {
@inline(__always) get {
#if arch(i386) || arch(arm)
guard case .bridged(let object) = _variant else {
_internalInvariantFailure()
}
return object
#else
_internalInvariant(largeIsCocoa && !isImmortal)
return Builtin.reinterpretCast(largeAddressBits)
#endif
}
}
}
// Aggregate queries / abstractions
extension _StringObject {
// The number of code units stored
//
// TODO(String micro-performance): Check generated code
@inlinable
internal var count: Int {
@inline(__always) get { return isSmall ? smallCount : largeCount }
}
//
// Whether the string is all ASCII
//
@inlinable
internal var isASCII: Bool {
@inline(__always) get {
if isSmall { return smallIsASCII }
return _countAndFlags.isASCII
}
}
@inline(__always)
internal var isNFC: Bool {
if isSmall {
// TODO(String performance): Worth implementing more sophisiticated
// check, or else performing normalization on- construction. For now,
// approximate it with isASCII
return smallIsASCII
}
return _countAndFlags.isNFC
}
// Get access to fast UTF-8 contents for large strings which provide it.
@inlinable @inline(__always)
internal var fastUTF8: UnsafeBufferPointer<UInt8> {
_internalInvariant(self.isLarge && self.providesFastUTF8)
guard _fastPath(self.largeFastIsTailAllocated) else {
return sharedUTF8
}
return UnsafeBufferPointer(
start: self.nativeUTF8Start, count: self.largeCount)
}
// Whether the object stored can be bridged directly as a NSString
@usableFromInline // @opaque
internal var hasObjCBridgeableObject: Bool {
@_effects(releasenone) get {
// Currently, all mortal objects can zero-cost bridge
return !self.isImmortal
}
}
// Fetch the stored subclass of NSString for bridging
@inline(__always)
internal var objCBridgeableObject: AnyObject {
_internalInvariant(hasObjCBridgeableObject)
return Builtin.reinterpretCast(largeAddressBits)
}
// Whether the object provides fast UTF-8 contents that are nul-terminated
@inlinable
internal var isFastZeroTerminated: Bool {
if _slowPath(!providesFastUTF8) { return false }
// Small strings nul-terminate when spilling for contiguous access
if isSmall { return true }
// TODO(String performance): Use performance flag, which could be more
// inclusive. For now, we only know native strings and small strings (when
// accessed) are. We could also know about some shared strings.
return largeFastIsTailAllocated
}
}
// Object creation
extension _StringObject {
@inlinable @inline(__always)
internal init(immortal bufPtr: UnsafeBufferPointer<UInt8>, isASCII: Bool) {
let countAndFlags = CountAndFlags(
immortalCount: bufPtr.count, isASCII: isASCII)
#if arch(i386) || arch(arm)
self.init(
variant: .immortal(start: bufPtr.baseAddress._unsafelyUnwrappedUnchecked),
discriminator: Nibbles.largeImmortal(),
countAndFlags: countAndFlags)
#else
// We bias to align code paths for mortal and immortal strings
let biasedAddress = UInt(
bitPattern: bufPtr.baseAddress._unsafelyUnwrappedUnchecked
) &- _StringObject.nativeBias
self.init(
pointerBits: UInt64(truncatingIfNeeded: biasedAddress),
discriminator: Nibbles.largeImmortal(),
countAndFlags: countAndFlags)
#endif
}
@inline(__always)
internal init(_ storage: __StringStorage) {
#if arch(i386) || arch(arm)
self.init(
variant: .native(storage),
discriminator: Nibbles.largeMortal(),
countAndFlags: storage._countAndFlags)
#else
self.init(
object: storage,
discriminator: Nibbles.largeMortal(),
countAndFlags: storage._countAndFlags)
#endif
}
internal init(_ storage: __SharedStringStorage) {
#if arch(i386) || arch(arm)
self.init(
variant: .native(storage),
discriminator: Nibbles.largeMortal(),
countAndFlags: storage._countAndFlags)
#else
self.init(
object: storage,
discriminator: Nibbles.largeMortal(),
countAndFlags: storage._countAndFlags)
#endif
}
internal init(
cocoa: AnyObject, providesFastUTF8: Bool, isASCII: Bool, length: Int
) {
let countAndFlags = CountAndFlags(sharedCount: length, isASCII: isASCII)
let discriminator = Nibbles.largeCocoa(providesFastUTF8: providesFastUTF8)
#if arch(i386) || arch(arm)
self.init(
variant: .bridged(cocoa),
discriminator: discriminator,
countAndFlags: countAndFlags)
#else
self.init(
object: cocoa, discriminator: discriminator, countAndFlags: countAndFlags)
_internalInvariant(self.largeAddressBits == Builtin.reinterpretCast(cocoa))
_internalInvariant(self.providesFastUTF8 == providesFastUTF8)
_internalInvariant(self.largeCount == length)
#endif
}
}
// Internal invariants
extension _StringObject {
#if !INTERNAL_CHECKS_ENABLED
@inlinable @inline(__always) internal func _invariantCheck() {}
#else
@usableFromInline @inline(never) @_effects(releasenone)
internal func _invariantCheck() {
#if arch(i386) || arch(arm)
_internalInvariant(MemoryLayout<_StringObject>.size == 12)
_internalInvariant(MemoryLayout<_StringObject>.stride == 12)
_internalInvariant(MemoryLayout<_StringObject>.alignment == 4)
_internalInvariant(MemoryLayout<_StringObject?>.size == 12)
_internalInvariant(MemoryLayout<_StringObject?>.stride == 12)
_internalInvariant(MemoryLayout<_StringObject?>.alignment == 4)
// Non-small-string discriminators are 4 high bits only. Small strings use
// the next 4 for count.
if isSmall {
_internalInvariant(_discriminator & 0xA0 == 0xA0)
} else {
_internalInvariant(_discriminator & 0x0F == 0)
}
#else
_internalInvariant(MemoryLayout<_StringObject>.size == 16)
_internalInvariant(MemoryLayout<_StringObject?>.size == 16)
#endif
if isForeign {
_internalInvariant(largeIsCocoa, "No other foreign forms yet")
}
if isSmall {
_internalInvariant(isImmortal)
_internalInvariant(smallCount <= 15)
_internalInvariant(smallCount == count)
_internalInvariant(!hasObjCBridgeableObject)
} else {
_internalInvariant(isLarge)
_internalInvariant(largeCount == count)
if providesFastUTF8 && largeFastIsTailAllocated {
_internalInvariant(!isSmall)
_internalInvariant(!largeIsCocoa)
_internalInvariant(_countAndFlags.isTailAllocated)
if isImmortal {
_internalInvariant(!hasNativeStorage)
_internalInvariant(!hasObjCBridgeableObject)
_internalInvariant(!_countAndFlags.isNativelyStored)
} else {
_internalInvariant(hasNativeStorage)
_internalInvariant(_countAndFlags.isNativelyStored)
_internalInvariant(hasObjCBridgeableObject)
_internalInvariant(nativeStorage.count == self.count)
}
}
if largeIsCocoa {
_internalInvariant(hasObjCBridgeableObject)
_internalInvariant(!isSmall)
_internalInvariant(!_countAndFlags.isNativelyStored)
_internalInvariant(!_countAndFlags.isTailAllocated)
if isForeign {
} else {
_internalInvariant(largeFastIsShared)
}
}
if _countAndFlags.isNativelyStored {
let anyObj = Builtin.reinterpretCast(largeAddressBits) as AnyObject
_internalInvariant(anyObj is __StringStorage)
}
}
#if arch(i386) || arch(arm)
switch _variant {
case .immortal:
_internalInvariant(isImmortal)
case .native:
_internalInvariant(hasNativeStorage || hasSharedStorage)
case .bridged:
_internalInvariant(isLarge)
_internalInvariant(largeIsCocoa)
}
#endif
}
#endif // INTERNAL_CHECKS_ENABLED
@inline(never)
internal func _dump() {
#if INTERNAL_CHECKS_ENABLED
let raw = self.rawBits
let word0 = ("0000000000000000" + String(raw.0, radix: 16)).suffix(16)
let word1 = ("0000000000000000" + String(raw.1, radix: 16)).suffix(16)
#if arch(i386) || arch(arm)
print("""
StringObject(\
<\(word0) \(word1)> \
count: \(String(_count, radix: 16)), \
variant: \(_variant), \
discriminator: \(_discriminator), \
flags: \(_flags))
""")
#else
print("StringObject(<\(word0) \(word1)>)")
#endif
let repr = _StringGuts(self)._classify()
switch repr._form {
case ._small:
_SmallString(self)._dump()
case ._immortal(address: let address):
print("""
Immortal(\
start: \(UnsafeRawPointer(bitPattern: address)!), \
count: \(repr._count))
""")
case ._native(_):
print("""
Native(\
owner: \(repr._objectIdentifier!), \
count: \(repr._count), \
capacity: \(repr._capacity))
""")
case ._cocoa(object: let object):
let address: UnsafeRawPointer = Builtin.reinterpretCast(object)
print("Cocoa(address: \(address))")
}
#endif // INTERNAL_CHECKS_ENABLED
}
}
| 3e681c9e3e2a6f77b916dec05ad9b24b | 31.096303 | 81 | 0.663229 | false | false | false | false |
gustavoavena/BandecoUnicamp | refs/heads/master | BandecoUnicamp/ConfiguracoesTableViewController.swift | mit | 1 | //
// ConfuiguracoesTableViewController.swift
// BandecoUnicamp
//
// Created by Gustavo Avena on 10/06/17.
// Copyright © 2017 Gustavo Avena. All rights reserved.
//
import UIKit
import UserNotifications
class ConfiguracoesTableViewController: UITableViewController {
@IBOutlet weak var dietaSwitch: UISwitch!
@IBOutlet weak var veggieTableViewCell: UITableViewCell!
@IBOutlet weak var notificationSwitch: UISwitch!
@IBOutlet weak var almocoNotificationCell: UITableViewCell!
@IBOutlet weak var jantarNotificationCell: UITableViewCell!
/// Responsavel por atualizar todo o UI relacionado as notificacoes. Toda vez que alguma opcao de notificacao for alterada, esse metodo deve ser chamado para
// garantir que os textos dos horarios estejamo corretos e as linhas das notificacoes das refeicoes aparecam somente se ativadas.
func loadNotificationOptions() {
notificationSwitch.isOn = UserDefaults.standard.bool(forKey: NOTIFICATION_KEY_STRING)
// TODO: setar o numero de linhas e as opcoes de notificacoes (ativadas ou nao, horario, etc) baseadp no User Defaults.
// e.g. notificacao_almoco = "12:00" e notificacao_jantar = nil
if let hora_almoco = UserDefaults.standard.string(forKey: ALMOCO_TIME_KEY_STRING) {
print("Setando horario da notificacao do almoco: \(hora_almoco)")
almocoNotificationCell.detailTextLabel?.text = hora_almoco
} else {
print("Horario pra notificacao do almoco nao encontrado.")
// nao colocar linhas a mais na table view...
}
if let hora_jantar = UserDefaults.standard.string(forKey: JANTAR_TIME_KEY_STRING) {
print("Setando horario da notificacao do jantar: \(hora_jantar)")
jantarNotificationCell.detailTextLabel?.text = hora_jantar
} else {
// nao colocar linhas a mais na table view...
print("Horario pra notificacao do jantar nao encontrado.")
}
}
override func viewDidLoad() {
super.viewDidLoad()
dietaSwitch.isOn = UserDefaults(suiteName: "group.bandex.shared")!.bool(forKey: VEGETARIANO_KEY_STRING)
// back button color
self.navigationController?.navigationBar.tintColor = UIColor(red:0.96, green:0.42, blue:0.38, alpha:1.0)
// disable highlight on veggie's cell. its only possible to click on switch
self.veggieTableViewCell.selectionStyle = .none;
tableView.reloadData()
loadNotificationOptions()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
trackScreenView()
}
@IBAction func dietaValueChanged(_ sender: UISwitch) {
UserDefaults(suiteName: "group.bandex.shared")!.set(sender.isOn, forKey: VEGETARIANO_KEY_STRING)
CardapioServices.shared.registerDeviceToken()
}
// Abre o feedback form no Safari
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if indexPath.section == 2 && indexPath.row == 0 {
UIApplication.shared.openURL(URL(string: "https://docs.google.com/forms/d/e/1FAIpQLSekvO0HnnfGnk0-FLTX86mVxAOB5Uajq8MPmB0Sv1pXPuQiCg/viewform")!)
tableView.deselectRow(at: indexPath, animated: true)
}
}
// - MARK: notifications
@IBAction func notificationSwitchToggled(_ sender: UISwitch) {
UserDefaults.standard.set(sender.isOn, forKey: NOTIFICATION_KEY_STRING)
if(sender.isOn) {
if #available(iOS 10.0, *) {
registerForPushNotifications()
} else {
// Fallback on earlier versions
}
} else { // Desabilitar notificacao
if #available(iOS 10.0, *) {
if let token = UserDefaults.standard.object(forKey: "deviceToken") as? String {
CardapioServices.shared.unregisterDeviceToken(token: token)
UserDefaults.standard.set(nil, forKey: ALMOCO_TIME_KEY_STRING)
UserDefaults.standard.set(nil, forKey: JANTAR_TIME_KEY_STRING)
self.loadNotificationOptions()
} else {
print("Device token nao encontrado para ser removido")
}
} else {
// Fallback on earlier versions
}
}
tableView.reloadData()
}
@available(iOS 10.0, *)
func registerForPushNotifications() {
UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound]) {
(granted, error) in
// print("Permission granted: \(granted)")
guard granted else { return }
self.getNotificationSettings()
}
}
@available(iOS 10.0, *)
func getNotificationSettings() {
UNUserNotificationCenter.current().getNotificationSettings { (settings) in
// print("Notification settings: \(settings)")
guard settings.authorizationStatus == .authorized else { return }
// Executing is main queue because of warning from XCode 9 thread sanitizer.
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
// TODO: atualizar opcoes de notificacoes no User Defaults.
if UserDefaults.standard.string(forKey: ALMOCO_TIME_KEY_STRING) == nil {
print("Configurando horario para notificacao do almoco pela primeira vez")
UserDefaults.standard.set("11:00", forKey: ALMOCO_TIME_KEY_STRING)
}
if UserDefaults.standard.string(forKey: JANTAR_TIME_KEY_STRING) == nil{
print("Configurando horario para notificacao do jantar pela primeira vez")
UserDefaults.standard.set("17:00", forKey: JANTAR_TIME_KEY_STRING)
}
// atualizar UI.
self.loadNotificationOptions()
}
}
}
// MARK: Time of notifications
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let destiny = segue.destination as? NotificationTimeViewController {
destiny.notificationTimeDisplayDelegate = self
if segue.identifier == "SegueAlmocoTime" {
destiny.refeicao = TipoRefeicao.almoco
destiny.pickerTimeOptions = destiny.ALMOCO_TIME_OPTIONS
//destiny.selectedTime =
}
if segue.identifier == "SegueJantarTime" {
destiny.refeicao = TipoRefeicao.jantar
destiny.pickerTimeOptions = destiny.JANTAR_TIME_OPTIONS
}
}
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if #available(iOS 10, *)
{
} else {
// ios 9 only
if(section == 1){
return 0.01
}
}
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if #available(iOS 9, *)
{
if #available(iOS 10, *)
{
} else {
// ios 9 only
if(section == 1){
return 0.01
}
}
}
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rows = [1,notificationSwitch.isOn ? 3 : 1,2]
if #available(iOS 9, *)
{
if #available(iOS 10, *)
{
} else {
// ios 9 only
if(section == 1){
rows[section] = 0
}
}
}
return rows[section]
}
override func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
var title = super.tableView(tableView, titleForFooterInSection: section)
if #available(iOS 9, *)
{
if #available(iOS 10, *)
{
} else {
// ios 9 only
if section == 1 {
title = ""
}
}
}
return title
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
var title = super.tableView(tableView, titleForHeaderInSection: section)
if #available(iOS 9, *)
{
if #available(iOS 10, *)
{
} else {
// ios 9 only
if section == 1 {
title = ""
}
}
}
return title
}
}
extension ConfiguracoesTableViewController: NotificationTimeDisplayDelegate {
func updateTimeString(time: String, refeicao: TipoRefeicao) {
let cell = refeicao == .almoco ? almocoNotificationCell : jantarNotificationCell
cell?.detailTextLabel?.text = time
}
}
| 10445774a509ef6b139d45ec729a7277 | 32.509868 | 161 | 0.558751 | false | false | false | false |
bitboylabs/selluv-ios | refs/heads/master | selluv-ios/selluv-ios/Classes/Controller/UI/Seller/SLV_822_UserFollower.swift | mit | 1 | //
// SLV_822_UserFollower.swift
// selluv-ios
//
// Created by 조백근 on 2017. 2. 2..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import Foundation
import UIKit
import SwifterSwift
import PullToRefresh
class SLV_822_UserFollower: SLVBaseStatusShowController {
let refresher = PullToRefresh()
var itemInfo: IndicatorInfo = IndicatorInfo(title: "팔로워")//tab 정보
weak var delegate: SLVButtonBarDelegate?// 델리게이트.
weak var myNavigationDelegate: SLVNavigationControllerDelegate?// push를 위한 네비게이션
weak var userInfo: SLVUserSimpleInfo?
var followers: [SLVSellerFollower] = []
var moveBlock: ((_ path: IndexPath, _ photo: UIImage, _ productId: String) -> ())?
@IBOutlet weak var collectView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
self.prepare()
self.loadFollowers()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func linkDelegate(controller: AnyObject) {
self.delegate = controller as? SLVButtonBarDelegate
self.myNavigationDelegate = controller as? SLVNavigationControllerDelegate
if self.delegate != nil {
let parent = self.delegate as! SLV_821_UserFollowController
self.userInfo = parent.sellerInfo
}
}
func prepare() {
self.view.backgroundColor = UIColor.clear
self.automaticallyAdjustsScrollViewInsets = false
self.collectView.remembersLastFocusedIndexPath = true
self.collectView.backgroundColor = UIColor.clear
self.collectView.delegate = self
self.collectView.dataSource = self
self.collectView.contentInset = UIEdgeInsetsMake(0, 0, 52, 0)
self.collectView.reloadData()
refresher.position = .bottom
self.collectView.addPullToRefresh(refresher) {
// action to be performed (pull data from some source)
}
}
deinit {
self.collectView?.removePullToRefresh((self.collectView?.bottomPullToRefresh!)!)
}
func loadFollowers() {
let userId = self.userInfo?.id
MyInfoDataModel.shared.userFollowersProducts(anyUserId: userId!) { (success, list) in
if success == true {
self.followers = list!
self.collectView.reloadData()
}
}
}
func setupMover(block: @escaping ((_ path: IndexPath, _ photo: UIImage, _ productId: String) -> ()) ) {
self.moveBlock = block
}
}
// MARK: - IndicatorInfoProvider
extension SLV_822_UserFollower: IndicatorInfoProvider {
func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo {
return itemInfo
}
}
// MARK: - Collection View
extension SLV_822_UserFollower: UICollectionViewDataSource, UICollectionViewDelegate {
public func scrollViewDidScroll(_ scrollView: UIScrollView) {
if scrollView == self.collectView {
let off = scrollView.contentOffset
if off.y > 0 {
// hide
self.delegate?.hideByScroll()
} else {
//show
self.delegate?.showByScroll()
}
}
}
public func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.followers.count
}
public func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let cell = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier:"SLVUserFollowSectionView", for: indexPath) as! SLVUserFollowSectionView
let item = self.followers[indexPath.section]
cell.setupData(follower: item)
return cell
}
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let collectionCell: SLVUserFollowProductsView = collectionView.dequeueReusableCell(withReuseIdentifier: "SLVUserFollowProductsView", for: indexPath as IndexPath) as! SLVUserFollowProductsView
let item = self.followers[indexPath.section]
let cellInfo = item.products //FollowerProductSimpleInfo
collectionCell.setupData(type: .sellerItem, items: cellInfo!)
collectionCell.setupViewer { (path, image, productId) in
if self.moveBlock != nil {
self.moveBlock!(path, image, productId)
}
}
return collectionCell
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int{
return 1
}
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
collectionView.setToIndexPath(indexPath: indexPath as NSIndexPath)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
let w = UIScreen.main.bounds.width
return CGSize(width: w, height: 54)
}
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: self.view.bounds.width, height: 120)
}
// func pageViewControllerLayout () -> UICollectionViewFlowLayout {
// let flowLayout = UICollectionViewFlowLayout()
// let itemSize = self.navigationController!.isNavigationBarHidden ?
// CGSize(width: screenWidth, height: screenHeight+20) : CGSize(width: screenWidth, height: screenHeight-navigationHeaderAndStatusbarHeight)
// flowLayout.itemSize = itemSize
// flowLayout.minimumLineSpacing = 0
// flowLayout.minimumInteritemSpacing = 0
// flowLayout.scrollDirection = .horizontal
// return flowLayout
// }
}
| b7fc5858d73602b4077fd0df596f1b60 | 36.487654 | 199 | 0.673473 | false | false | false | false |
adrfer/swift | refs/heads/master | test/SILGen/enum_resilience.swift | apache-2.0 | 4 | // RUN: %target-swift-frontend -I %S/../Inputs -enable-source-import -emit-silgen -enable-resilience %s | FileCheck %s
import resilient_enum
// Resilient enums are always address-only, and switches must include
// a default case
// CHECK-LABEL: sil hidden @_TF15enum_resilience15resilientSwitchFO14resilient_enum6MediumT_ : $@convention(thin) (@in Medium) -> ()
// CHECK: [[BOX:%.*]] = alloc_stack $Medium
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX]]
// CHECK-NEXT: switch_enum_addr [[BOX]] : $*Medium, case #Medium.Paper!enumelt: bb1, case #Medium.Canvas!enumelt: bb2, case #Medium.Pamphlet!enumelt.1: bb3, case #Medium.Postcard!enumelt.1: bb4, default bb5
// CHECK: bb1:
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb2:
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb3:
// CHECK-NEXT: [[INDIRECT_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]]
// CHECK-NEXT: [[INDIRECT:%.*]] = load [[INDIRECT_ADDR]]
// CHECK-NEXT: [[PAYLOAD:%.*]] = project_box [[INDIRECT]]
// CHECK-NEXT: strong_release [[INDIRECT]]
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb4:
// CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = unchecked_take_enum_data_addr [[BOX]]
// CHECK-NEXT: destroy_addr [[PAYLOAD_ADDR]]
// CHECK-NEXT: dealloc_stack [[BOX]]
// CHECK-NEXT: br bb6
// CHECK: bb5:
// CHECK-NEXT: unreachable
// CHECK: bb6:
// CHECK-NEXT: destroy_addr %0
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]]
func resilientSwitch(m: Medium) {
switch m {
case .Paper: ()
case .Canvas: ()
case .Pamphlet: ()
case .Postcard: ()
}
}
// Indirect enums are still address-only, because the discriminator is stored
// as part of the value, so we cannot resiliently make assumptions about the
// enum's size
// CHECK-LABEL: sil hidden @_TF15enum_resilience21indirectResilientEnumFO14resilient_enum16IndirectApproachT_ : $@convention(thin) (@in IndirectApproach) -> ()
func indirectResilientEnum(ia: IndirectApproach) {}
| 70bfb0d6d37f439d2f715e2e713947ea | 40.470588 | 209 | 0.648227 | false | false | false | false |
dsay/POPDataSource | refs/heads/master | DataSources/DataSource/EditableCellDataSource.swift | mit | 1 | import UIKit
public struct EditAction {
let action: DataSource.Action
let title: String
let color: UIColor
}
public protocol EditableCellDataSource {
func editActions() -> [EditAction]
}
extension TableViewDataSource where
Self: EditableCellDataSource & DataContainable & CellContainable,
Self.Configurator: CellSelectable,
Self.Configurator.Item == Self.Item
{
func canEditRow(for tableView: UITableView, at indexPath: IndexPath) -> Bool {
return true
}
func editActions(for tableView: UITableView, at indexPath: IndexPath) -> [UITableViewRowAction]? {
return self.editActions().map { retrive($0, tableView) }
}
private func retrive(_ editAction: EditAction,_ tableView: UITableView) -> UITableViewRowAction {
let action = UITableViewRowAction(style: .normal, title: editAction.title)
{ (action, indexPath) in
let attributes = self.attributes(in: tableView, at: indexPath)
if let selector = self.cellConfigurator?.selectors[editAction.action] {
selector(attributes.cell, indexPath, attributes.item)
}
}
action.backgroundColor = editAction.color
return action
}
private func attributes(in tableView: UITableView, at indexPath: IndexPath) -> (cell: Cell, item: Item) {
let item = self.item(at: indexPath.row)
guard let cell = tableView.cellForRow(at: indexPath) as? Cell else {
fatalError("cell no found")
}
return (cell, item)
}
}
| f42777e640d5464cb1e4a91fae16fad1 | 32.574468 | 109 | 0.655894 | false | true | false | false |
donnywals/StoryboardsAndXibs | refs/heads/master | StoryboardsAndXibs/TableViewDataSource.swift | mit | 1 | //
// TableViewDataSource.swift
// StoryboardsAndXibs
//
// Created by Donny Wals on 10-07-15.
// Copyright (c) 2015 Donny Wals. All rights reserved.
//
import UIKit
class TableViewDataSource: NSObject, UITableViewDataSource {
let items = ["item_1", "item_2", "item_3", "item_4", "item_5"]
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell!
if let c = tableView.dequeueReusableCellWithIdentifier("myCell") as? UITableViewCell {
cell = c
} else {
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "myCell")
}
cell.textLabel?.text = items[indexPath.row]
return cell
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return items.count
}
}
| 9d90d3365621dae5a8c03ccde679852d | 30.125 | 109 | 0.658635 | false | false | false | false |
SwiftStudies/OysterKit | refs/heads/master | Sources/stlrc/Options/LanguageOption.swift | bsd-2-clause | 1 | //
// StlrOptions.swift
// OysterKitPackageDescription
//
// Created by Swift Studies on 08/12/2017.
//
import Foundation
import OysterKit
import STLR
class LanguageOption : Option, IndexableParameterized {
typealias ParameterIndexType = Parameters
/**
Parameters
*/
public enum Parameters : Int, ParameterIndex {
case language = 0
public var parameter: Parameter{
switch self {
case .language:
return Language().one(optional: false)
}
}
public static var all: [Parameter]{
return [
Parameters.language.parameter
]
}
}
public struct Language : ParameterType{
enum Supported : String{
case swift
case swiftIR
case swiftPM
var fileExtension : String? {
switch self {
case .swift:
return rawValue
default:
return nil
}
}
func operations(in scope:STLR, for grammarName:String) throws ->[STLROperation]? {
switch self {
case .swift:
return nil
case .swiftIR:
return try SwiftStructure.generate(for: scope, grammar: grammarName, accessLevel: "public")
case .swiftPM:
return try SwiftPackageManager.generate(for: scope, grammar: grammarName, accessLevel: "public")
}
}
func generate(grammarName: String, from stlr:STLR, optimize:Bool, outputTo:String) throws {
if optimize {
STLR.register(optimizer: InlineIdentifierOptimization())
STLR.register(optimizer: CharacterSetOnlyChoiceOptimizer())
} else {
STLR.removeAllOptimizations()
}
stlr.grammar.optimize()
/// Use operation based generators
if let operations = try operations(in: stlr, for: grammarName) {
let workingDirectory = URL(fileURLWithPath: outputTo).deletingLastPathComponent().path
let context = OperationContext(with: URL(fileURLWithPath: workingDirectory)){
print($0)
}
do {
try operations.perform(in: context)
} catch OperationError.error(let message){
print(message.color(.red))
exit(EXIT_FAILURE)
} catch {
print(error.localizedDescription.color(.red))
exit(EXIT_FAILURE)
}
} else {
switch self {
case .swift:
let file = TextFile(grammarName+".swift")
stlr.swift(in: file)
let workingDirectory = URL(fileURLWithPath: outputTo).deletingLastPathComponent().path
let context = OperationContext(with: URL(fileURLWithPath: workingDirectory)) { (message) in
print(message)
}
try file.perform(in: context)
default:
throw OperationError.error(message: "Language did not produce operations")
}
}
}
}
public var name = "Language"
public func transform(_ argumentValue: String) -> Any? {
return Supported(rawValue: argumentValue)
}
}
init(){
super.init(shortForm: "l", longForm: "language", description: "The language to generate", parameterDefinition: Parameters.all, required: false)
}
}
| 70ec67d65e8a4a2c1788c3e0bbab94ad | 32.467213 | 151 | 0.480774 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | RiotSwiftUI/Modules/Common/ViewModel/StateStoreViewModel.swift | apache-2.0 | 1 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import Combine
import Foundation
import Combine
/// A constrained and concise interface for interacting with the ViewModel.
///
/// This class is closely bound to`StateStoreViewModel`. It provides the exact interface the view should need to interact
/// ViewModel (as modelled on our previous template architecture with the addition of two-way binding):
/// - The ability read/observe view state
/// - The ability to send view events
/// - The ability to bind state to a specific portion of the view state safely.
/// This class was brought about a little bit by necessity. The most idiomatic way of interacting with SwiftUI is via `@Published`
/// properties which which are property wrappers and therefore can't be defined within protocols.
/// A similar approach is taken in libraries like [CombineFeedback](https://github.com/sergdort/CombineFeedback).
/// It provides a nice layer of consistency and also safety. As we are not passing the `ViewModel` to the view directly, shortcuts/hacks
/// can't be made into the `ViewModel`.
@available(iOS 14, *)
@dynamicMemberLookup
class ViewModelContext<ViewState:BindableState, ViewAction>: ObservableObject {
// MARK: - Properties
// MARK: Private
fileprivate let viewActions: PassthroughSubject<ViewAction, Never>
// MARK: Public
/// Get-able/Observable `Published` property for the `ViewState`
@Published fileprivate(set) var viewState: ViewState
/// Set-able/Bindable access to the bindable state.
subscript<T>(dynamicMember keyPath: WritableKeyPath<ViewState.BindStateType, T>) -> T {
get { viewState.bindings[keyPath: keyPath] }
set { viewState.bindings[keyPath: keyPath] = newValue }
}
// MARK: Setup
init(initialViewState: ViewState) {
self.viewActions = PassthroughSubject()
self.viewState = initialViewState
}
// MARK: Public
/// Send a `ViewAction` to the `ViewModel` for processing.
/// - Parameter viewAction: The `ViewAction` to send to the `ViewModel`.
func send(viewAction: ViewAction) {
viewActions.send(viewAction)
}
}
/// A common ViewModel implementation for handling of `State`, `StateAction`s and `ViewAction`s
///
/// Generic type State is constrained to the BindableState protocol in that it may contain (but doesn't have to)
/// a specific portion of state that can be safely bound to.
/// If we decide to add more features to our state management (like doing state processing off the main thread)
/// we can do it in this centralised place.
@available(iOS 14, *)
class StateStoreViewModel<State: BindableState, StateAction, ViewAction> {
typealias Context = ViewModelContext<State, ViewAction>
// MARK: - Properties
// MARK: Public
/// For storing subscription references.
///
/// Left as public for `ViewModel` implementations convenience.
var cancellables = Set<AnyCancellable>()
/// Constrained interface for passing to Views.
var context: Context
var state: State {
get { context.viewState }
set { context.viewState = newValue }
}
// MARK: Setup
init(initialViewState: State) {
self.context = Context(initialViewState: initialViewState)
self.context.viewActions.sink { [weak self] action in
guard let self = self else { return }
self.process(viewAction: action)
}
.store(in: &cancellables)
}
/// Send state actions to modify the state within the reducer.
/// - Parameter action: The state action to send to the reducer.
@available(*, deprecated, message: "Mutate state directly instead")
func dispatch(action: StateAction) {
Self.reducer(state: &context.viewState, action: action)
}
/// Send state actions from a publisher to modify the state within the reducer.
/// - Parameter actionPublisher: The publisher that produces actions to be sent to the reducer
@available(*, deprecated, message: "Mutate state directly instead")
func dispatch(actionPublisher: AnyPublisher<StateAction, Never>) {
actionPublisher.sink { [weak self] action in
guard let self = self else { return }
Self.reducer(state: &self.context.viewState, action: action)
}
.store(in: &cancellables)
}
/// Override to handle mutations to the `State`
///
/// A redux style reducer, all modifications to state happen here.
/// - Parameters:
/// - state: The `inout` state to be modified,
/// - action: The action that defines which state modification should take place.
class func reducer(state: inout State, action: StateAction) {
//Default implementation, -no-op
}
/// Override to handles incoming `ViewAction`s from the `ViewModel`.
/// - Parameter viewAction: The `ViewAction` to be processed in `ViewModel` implementation.
func process(viewAction: ViewAction) {
//Default implementation, -no-op
}
}
| e210d6dd139ac2b70a5f3ee5e413ba9d | 37.868056 | 136 | 0.699839 | false | false | false | false |
koscida/Kos_AMAD_Spring2015 | refs/heads/master | Spring_16/GRADE_projects/Project_2/Project2/Girl_Game/Girl_Game/GameViewController.swift | gpl-3.0 | 1 | //
// GameViewController.swift
// Girl_Game
//
// Created by Brittany Kos on 4/6/16.
// Copyright (c) 2016 Kode Studios. All rights reserved.
//
import UIKit
import SpriteKit
/*
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file as String, ofType: "sks") {
do {
let sceneData = try NSData(contentsOfFile: path, options: NSDataReadingOptions.DataReadingMappedIfSafe)
//var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
let archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as! GameLevelScene
archiver.finishDecoding()
return scene
} catch {
print(error)
}
} else {
return nil
}
return nil
}
}
*/
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// create notifications for application resign and active. This will call those
// functions (inside of this class) then the app is exited an started again. This
// persists throughout the app, no matter the scene
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "applicationWillResignActive:",
name: UIApplicationWillResignActiveNotification,
object: UIApplication.sharedApplication())
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "applicationDidBecomeActive:",
name: UIApplicationDidBecomeActiveNotification,
object: UIApplication.sharedApplication())
/*
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
// Sprite Kit applies additional optimizations to improve rendering performance
skView.ignoresSiblingOrder = true
// get scene file
//let scene = GameIntroScene.unarchiveFromFile("GameIntroScene") as? GameIntroScene // intro
// Set the scale mode to scale to fit the window
scene!.scaleMode = .AspectFill
//scene!.scaleMode = .ResizeFill
skView.presentScene(scene)
*/
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews();
// Configure the view
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
// Sprite Kit applies additional optimizations to improve rendering performance
skView.ignoresSiblingOrder = true
// get scene file
//let scene = GameIntroScene(size: view.frame.size)
let scene = GameCharacterCreationScene(size: view.frame.size)
//let scene = GameLevel1Scene(size: view.frame.size, bodyFileName: "sil_latina", armorFileName: "sil_armor_warrior_trans", weaponFileName: "")
// get scaling factor
let scale:CGFloat = UIScreen.mainScreen().scale;
let size = CGSizeMake(skView.frame.size.width*scale, skView.frame.size.height*scale)
// Configure the scene
scene.scaleMode = .AspectFill
scene.size = size
// final present scene
skView.presentScene(scene)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
func applicationWillResignActive(notification: NSNotification) {
}
func applicationDidBecomeActive(notification: NSNotification) {
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return UIInterfaceOrientationMask.Landscape
//return .AllButUpsideDown
} else {
return UIInterfaceOrientationMask.Landscape
}
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| a99c6cd98a211f7ccebc3007ecf048d3 | 29.313725 | 150 | 0.607158 | false | false | false | false |
Alexandre-Georges/Filterer | refs/heads/master | Filterer/AGImageProcessor.swift | mit | 1 | import UIKit
protocol AGFilter {
func applyFilter(image: RGBAImage)
func changePixel(inout pixel: Pixel)
}
class AGColourFilter : AGFilter {
var intensity: Float
var colourFilterFunction: ((inout Pixel) -> Void)? = nil
init (colourToFilter: String, intensity: Float) {
self.intensity = intensity
switch colourToFilter {
case "red": colourFilterFunction = { pixel in
pixel.green = pixel.green - UInt8(Double(pixel.green) * Double(self.intensity) / 100.0)
pixel.blue = pixel.blue - UInt8(Double(pixel.blue) * Double(self.intensity) / 100.0)
}
case "green": colourFilterFunction = { pixel in
pixel.red = pixel.red - UInt8(Double(pixel.red) * Double(self.intensity) / 100.0)
pixel.blue = pixel.blue - UInt8(Double(pixel.blue) * Double(self.intensity) / 100.0)
}
case "blue": colourFilterFunction = { pixel in
pixel.red = pixel.red - UInt8(Double(pixel.red) * Double(self.intensity) / 100.0)
pixel.green = pixel.green - UInt8(Double(pixel.green) * Double(self.intensity) / 100.0)
}
default: colourFilterFunction = { pixel in
}
}
}
func applyFilter(image: RGBAImage) {
for heightIndex in 0..<image.height {
for widthIndex in 0..<image.width {
let index = heightIndex * image.width + widthIndex
self.changePixel(&image.pixels[index])
}
}
}
func changePixel(inout pixel: Pixel) {
self.colourFilterFunction!(&pixel)
}
}
class AGBlackAndWhiteFilter : AGFilter {
var intensity: Float
init (intensity: Float) {
self.intensity = intensity
}
func applyFilter(image: RGBAImage) {
for heightIndex in 0..<image.height {
for widthIndex in 0..<image.width {
let index = heightIndex * image.width + widthIndex
self.changePixel(&image.pixels[index])
}
}
}
func changePixel(inout pixel: Pixel) {
let medianValue = (UInt32(pixel.red) + UInt32(pixel.green) + UInt32(pixel.blue)) / 3
let filteredValue = Pixel(value: (UInt32(medianValue) | (UInt32(medianValue) << 8) | (UInt32(medianValue) << 16) | (UInt32(pixel.alpha) << 24)))
pixel.red = UInt8(Double(pixel.red) + Double(Int(filteredValue.red) - Int(pixel.red)) * Double(self.intensity) / 100)
pixel.green = UInt8(Double(pixel.green) + Double(Int(filteredValue.green) - Int(pixel.green)) * Double(self.intensity) / 100)
pixel.blue = UInt8(Double(pixel.blue) + Double(Int(filteredValue.blue) - Int(pixel.blue)) * Double(self.intensity) / 100)
}
}
class AGSepiaFilter : AGFilter {
var intensity: Float
init (intensity: Float) {
self.intensity = intensity
}
func applyFilter(image: RGBAImage) {
for heightIndex in 0..<image.height {
for widthIndex in 0..<image.width {
let index = heightIndex * image.width + widthIndex
self.changePixel(&image.pixels[index])
}
}
}
func changePixel(inout pixel: Pixel) {
pixel.red = UInt8(min(255,
Double(pixel.red) - (Double(pixel.red) - Double(pixel.red) * 0.393) * Double(self.intensity) / 100 +
Double(pixel.green) - (Double(pixel.green) - Double(pixel.green) * 0.769) * Double(self.intensity) / 100 +
Double(pixel.blue) - (Double(pixel.blue) - Double(pixel.blue) * 0.189) * Double(self.intensity) / 100))
pixel.green = UInt8(min(255,
Double(pixel.red) - (Double(pixel.red) - Double(pixel.red) * 0.349) * Double(self.intensity) / 100 +
Double(pixel.green) - (Double(pixel.green) - Double(pixel.green) * 0.686) * Double(self.intensity) / 100 +
Double(pixel.blue) - (Double(pixel.blue) - Double(pixel.blue) * 0.168) * Double(self.intensity) / 100))
pixel.blue = UInt8(min(255,
Double(pixel.red) - (Double(pixel.red) - Double(pixel.red) * 0.272) * Double(self.intensity) / 100 +
Double(pixel.green) - (Double(pixel.green) - Double(pixel.green) * 0.534) * Double(self.intensity) / 100 +
Double(pixel.blue) - (Double(pixel.blue) - Double(pixel.blue) * 0.131) * Double(self.intensity) / 100))
}
}
class AGBrightnessFilter : AGFilter {
var brightnessDelta: Int = 0
init (intensity: Float) {
self.brightnessDelta = Int(255 * (intensity * 2 - 100) / 100)
}
func applyFilter(image: RGBAImage) {
for heightIndex in 0..<image.height {
for widthIndex in 0..<image.width {
let index = heightIndex * image.width + widthIndex
self.changePixel(&image.pixels[index])
}
}
}
func changePixel(inout pixel: Pixel) {
pixel.red = UInt8(max(0, min(255, Int(pixel.red) + brightnessDelta)))
pixel.green = UInt8(max(0, min(255, Int(pixel.green) + brightnessDelta)))
pixel.blue = UInt8(max(0, min(255, Int(pixel.blue) + brightnessDelta)))
}
}
/*
class AGContrastFilter : AGFilterOld {
var averageRed: Int = 0
var averageGreen: Int = 0
var averageBlue: Int = 0
var deltaCoefficient: Double = 1.0
init (deltaCoefficient: Double) {
self.deltaCoefficient = deltaCoefficient
}
func applyFilter(image: RGBAImage) {
for heightIndex in 0..<image.height {
for widthIndex in 0..<image.width {
let index = heightIndex * image.width + widthIndex
let pixel = image.pixels[index]
self.averageRed += Int(pixel.red)
self.averageGreen += Int(pixel.green)
self.averageBlue += Int(pixel.blue)
}
}
self.averageRed /= (image.width * image.height)
self.averageGreen /= (image.width * image.height)
self.averageBlue /= (image.width * image.height)
for heightIndex in 0..<image.height {
for widthIndex in 0..<image.width {
let index = heightIndex * image.width + widthIndex
self.changePixel(&image.pixels[index])
}
}
}
func changePixel(inout pixel: Pixel) {
pixel.red = self.getDelta(UInt8(self.averageRed), value: pixel.red)
pixel.green = self.getDelta(UInt8(self.averageGreen), value: pixel.green)
pixel.blue = self.getDelta(UInt8(self.averageBlue), value: pixel.blue)
}
func getDelta(average: UInt8, value: UInt8) -> UInt8 {
let delta: Int = Int(value) - Int(average)
let theoreticalValue: Int = Int(value) + Int(Double(delta) * self.deltaCoefficient)
return UInt8(max(min(theoreticalValue, 255), 0))
}
}*/
enum AGFilterNames : String {
case Brightness
case ColourRed
case ColourGreen
case ColourBlue
case BlackAndWhite
}
class AGImageProcessor {
var image: RGBAImage? = nil
var filter: AGFilter? = nil
func addFilter(filterName: AGFilterNames, intensity: Float) {
var filter: AGFilter? = nil
switch filterName {
case AGFilterNames.Brightness : filter = AGBrightnessFilter(intensity: intensity)
case AGFilterNames.ColourRed : filter = AGColourFilter(colourToFilter: "red", intensity: intensity)
case AGFilterNames.ColourGreen : filter = AGColourFilter(colourToFilter: "green", intensity: intensity)
case AGFilterNames.ColourBlue : filter = AGColourFilter(colourToFilter: "blue", intensity: intensity)
case AGFilterNames.BlackAndWhite : filter = AGBlackAndWhiteFilter(intensity: intensity)
}
self.filter = filter!
}
func applyFilter() {
self.filter!.applyFilter(self.image!)
}
func getImage() -> UIImage {
return self.image!.toUIImage()!
}
func setImage(image: UIImage) {
self.image = RGBAImage(image: image)!
}
}
| 74ed1bea4954f155cf422841e1aeeea8 | 35.58296 | 152 | 0.596837 | false | false | false | false |
Sherlouk/IGListKit | refs/heads/master | Carthage/Checkouts/IGListKit/Examples/Examples-tvOS/IGListKitExamples/SectionControllers/DemoSectionController.swift | bsd-3-clause | 4 | /**
Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
The examples provided by Facebook are for non-commercial testing and evaluation
purposes only. Facebook reserves all rights not expressly granted.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
import IGListKit
final class DemoItem: NSObject {
let name: String
let controllerClass: UIViewController.Type
let controllerIdentifier: String?
init(name: String,
controllerClass: UIViewController.Type,
controllerIdentifier: String? = nil) {
self.name = name
self.controllerClass = controllerClass
self.controllerIdentifier = controllerIdentifier
}
}
final class DemoSectionController: IGListSectionController, IGListSectionType {
var object: DemoItem?
override init() {
super.init()
inset = UIEdgeInsets(top: 0, left: 50, bottom: 10, right: 0)
}
func numberOfItems() -> Int {
return 1
}
func sizeForItem(at index: Int) -> CGSize {
let itemWidth = (collectionContext!.containerSize.width / 2) - inset.left
return CGSize(width: itemWidth, height: 100)
}
func cellForItem(at index: Int) -> UICollectionViewCell {
let cell = collectionContext!.dequeueReusableCell(of: DemoCell.self, for: self, at: index) as! DemoCell
cell.label.text = object?.name
return cell
}
func didUpdate(to object: Any) {
self.object = object as? DemoItem
}
func didSelectItem(at index: Int) {
if let identifier = object?.controllerIdentifier {
let storyboard = UIStoryboard(name: "Demo", bundle: nil)
let controller = storyboard.instantiateViewController(withIdentifier: identifier)
controller.title = object?.name
viewController?.navigationController?.pushViewController(controller, animated: true)
} else if let controller = object?.controllerClass.init() {
controller.title = object?.name
viewController?.navigationController?.pushViewController(controller, animated: true)
}
}
}
| de12e34fcaa1e9c058cb644785f78b22 | 33.743243 | 111 | 0.683781 | false | false | false | false |
ccrama/Slide-iOS | refs/heads/master | Slide for Reddit/Reachability.swift | apache-2.0 | 1 | import Foundation
import SystemConfiguration
import UIKit
public let ReachabilityStatusChangedNotification = "ReachabilityStatusChangedNotification"
public enum ReachabilityType: CustomStringConvertible {
case WWAN
case WiFi
public var description: String {
switch self {
case .WWAN: return "WWAN"
case .WiFi: return "WiFi"
}
}
}
public enum ReachabilityStatus: CustomStringConvertible {
case Offline
case Online(ReachabilityType)
case Unknown
public var description: String {
switch self {
case .Offline: return "Offline"
case .Online(let type): return "Online (\(type))"
case .Unknown: return "Unknown"
}
}
}
public class Reachability {
func connectionStatus() -> ReachabilityStatus {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let defaultRouteReachability = (withUnsafePointer(to: &zeroAddress) {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) { zeroSockAddress in
SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
}
}) else {
return .Unknown
}
var flags: SCNetworkReachabilityFlags = []
if !SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) {
return .Unknown
}
return ReachabilityStatus(reachabilityFlags: flags)
}
func monitorReachabilityChanges() {
let host = "google.com"
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
let reachability = SCNetworkReachabilityCreateWithName(nil, host)!
SCNetworkReachabilitySetCallback(reachability, { (_, flags, _) in
let status = ReachabilityStatus(reachabilityFlags: flags)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: ReachabilityStatusChangedNotification), object: nil, userInfo: ["Status": status.description])}, &context)
SCNetworkReachabilityScheduleWithRunLoop(reachability, CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue)
}
}
extension ReachabilityStatus {
public init(reachabilityFlags flags: SCNetworkReachabilityFlags) {
let connectionRequired = flags.contains(.connectionRequired)
let isReachable = flags.contains(.reachable)
let isWWAN = flags.contains(.isWWAN)
if !connectionRequired && isReachable {
if isWWAN {
self = .Online(.WWAN)
} else {
self = .Online(.WiFi)
}
} else {
self = .Offline
}
}
}
| 272919feb1736930f92a076f53981589 | 31.522727 | 186 | 0.640461 | false | false | false | false |
Urinx/SublimeCode | refs/heads/master | Sublime/Sublime/SSHServerListTableViewController.swift | gpl-3.0 | 1 | //
// SSHServerListTableViewController.swift
// Sublime
//
// Created by Eular on 3/28/16.
// Copyright © 2016 Eular. All rights reserved.
//
import UIKit
class SSHServerListTableViewController: UITableViewController {
let serverPlist = Plist(path: Constant.SublimeRoot+"/etc/ssh_list.plist")
var serverList: [[String: String]] = []
override func viewDidLoad() {
super.viewDidLoad()
title = "Servers"
tableView.backgroundColor = Constant.CapeCod
tableView.separatorColor = Constant.NavigationBarAndTabBarColor
tableView.tableFooterView = UIView()
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(self.addNewServer))
}
override func viewWillAppear(animated: Bool) {
if let arr = serverPlist.getArrayInPlistFile() {
serverList = arr as! [[String : String]]
tableView.reloadData()
}
}
func addNewServer() {
let addnew = SSHAddNewServerViewController()
navigationController?.pushViewController(addnew, animated: true)
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return serverList.count
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return Constant.SSHServerListCellHeight
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: nil)
cell.backgroundColor = Constant.NavigationBarAndTabBarColor
cell.selectedBackgroundView = UIView(frame: cell.frame)
cell.selectedBackgroundView?.backgroundColor = Constant.TableCellSelectedColor
cell.accessoryType = .DisclosureIndicator
cell.textLabel?.text = serverList[indexPath.row]["host"]
cell.textLabel?.textColor = UIColor.whiteColor()
cell.detailTextLabel?.text = serverList[indexPath.row]["username"]
cell.detailTextLabel?.textColor = RGB(190, 190, 190)
cell.imageView?.image = UIImage(named: "ssh_server")
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
serverList.removeAtIndex(indexPath.row)
do {
try serverPlist.saveToPlistFile(serverList)
} catch {}
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let terminal = SSHTerminalViewController()
terminal.server = serverList[indexPath.row]
navigationController?.pushViewController(terminal, animated: true)
}
}
| 1cddf624ec93dd56122f6a19cf66522c | 36.444444 | 157 | 0.683086 | false | false | false | false |
quangvu1994/Exchange | refs/heads/master | Exchange/View/CollectionTableViewCell.swift | mit | 1 | //
// CollectionTableViewCell.swift
// Exchange
//
// Created by Quang Vu on 7/20/17.
// Copyright © 2017 Quang Vu. All rights reserved.
//
import UIKit
import FirebaseDatabase
class CollectionTableViewCell: UITableViewCell {
var status: String?
var itemList = [String: Any]() {
didSet {
collectionView.reloadData()
}
}
var cashAmount: String?
var controller: DisplayItemDetailHandler?
@IBOutlet weak var collectionView: UICollectionView!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
collectionView.delegate = self
collectionView.dataSource = self
}
}
extension CollectionTableViewCell: UICollectionViewDataSource, UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
var numOfItems = itemList.count
if let _ = cashAmount {
numOfItems += 1
}
if numOfItems == 0 {
let emptyLabel = UILabel(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: self.bounds.height))
emptyLabel.textAlignment = .center
emptyLabel.font = UIFont(name: "Futura", size: 14)
emptyLabel.textColor = UIColor(red: 44/255, green: 62/255, blue: 80/255, alpha: 1.0)
emptyLabel.numberOfLines = 2
emptyLabel.text = "No items offered "
collectionView.backgroundView = emptyLabel
}
return numOfItems
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Item Cell", for: indexPath) as! MyItemPostImageCell
// If there is cash
if let cashAmount = cashAmount {
// if this is the last cell
if indexPath.row == itemList.count {
cell.imageLabel.text = cashAmount
cell.imageLabel.isHidden = false
return cell
}
}
if let controller = controller {
cell.delegate = controller
cell.gestureDisplayingItemDetailWithInfo()
}
let key = Array(itemList.keys)[indexPath.row]
if let itemDataDict = itemList[key] as? [String : Any],
let url = itemDataDict["image_url"] as? String,
let itemTitle = itemDataDict["post_title"] as? String,
let itemDescription = itemDataDict["post_description"] as? String {
let imageURL = URL(string: url)
cell.postImage.kf.setImage(with: imageURL)
cell.itemImageURL = url
cell.itemTitle = itemTitle
cell.itemDescription = itemDescription
}
// Observe the availability of the item
let itemRef = Database.database().reference().child("allItems/\(key)/availability")
itemRef.observe(.value, with: { (snapshot) in
guard let availability = snapshot.value as? Bool else {
return
}
if !availability && self.status != "Confirmed"{
cell.soldLabel.isHidden = false
} else {
cell.soldLabel.isHidden = true
}
})
return cell
}
}
extension CollectionTableViewCell: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: collectionView.bounds.height, height: collectionView.bounds.height)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 1
}
}
| b3d3d91efc2797323051def4040d29cf | 35.537037 | 170 | 0.622402 | false | false | false | false |
TheNounProject/CollectionView | refs/heads/main | CollectionView/DataStructures/SortDescriptor.swift | mit | 1 | //
// SortDescriptor.swift
// CollectionView
//
// Created by Wesley Byrne on 2/16/18.
// Copyright © 2018 Noun Project. All rights reserved.
//
import Foundation
/// Sort Descriptor Result
///
/// - same: The two objects are equally compared
/// - ascending: The first object is before the second (ordered)
/// - descending: The second object precedes the first (reversed)
public enum SortDescriptorResult: ExpressibleByBooleanLiteral {
case same
case ascending
case descending
public typealias BooleanLiteralType = Bool
public init(booleanLiteral value: Bool) {
self = value ? .ascending : .descending
}
}
/// a comparator used to compare two objects
public struct SortDescriptor<T> {
public let ascending: Bool
private let comparator: (T, T) -> SortDescriptorResult
/// Initialize a sort descriptor with a custom comparator
///
/// - Parameter keyPath: A keypath for the type being sorted
/// - Parameter ascending: If the comparison should order ascending
public init<V: Comparable>(_ keyPath: KeyPath<T, V>, ascending: Bool = true) {
self.comparator = {
let v1 = $0[keyPath: keyPath]
let v2 = $1[keyPath: keyPath]
if v1 < v2 { return ascending ? .ascending : .descending }
if v1 > v2 { return ascending ? .descending : .ascending }
return .same
}
self.ascending = ascending
}
/// Initialize a sort descriptor with a custom comparator
///
/// - Parameter comparator: A comparator returning a comparison result
public init(_ comparator: @escaping ((T, T) -> SortDescriptorResult)) {
self.comparator = comparator
self.ascending = true
}
/// Compare two objects
///
/// - Parameters:
/// - a: The first object
/// - b: The second object
/// - Returns: A SortDescriptorResult for the two objects.
public func compare(_ a: T, to b: T) -> SortDescriptorResult {
return comparator(a, b)
}
}
extension SortDescriptor where T: Comparable {
public static var ascending: SortDescriptor<T> {
return SortDescriptor({ (a, b) -> SortDescriptorResult in
if a == b { return .same }
if a > b { return .descending }
return .ascending
})
}
public static var descending: SortDescriptor<T> {
return SortDescriptor({ (a, b) -> SortDescriptorResult in
if a == b { return .same }
if a > b { return .descending }
return .ascending
})
}
}
protocol Comparer {
associatedtype Compared
func compare(_ a: Compared, to b: Compared) -> SortDescriptorResult
}
extension SortDescriptor: Comparer { }
extension Sequence where Element: Comparer {
func compare(_ element: Element.Compared, _ other: Element.Compared) -> SortDescriptorResult {
for comparer in self {
switch comparer.compare(element, to: other) {
case .same: break
case .descending: return .descending
case .ascending: return .ascending
}
}
return .same
}
func element(_ element: Element.Compared, isBefore other: Element.Compared) -> Bool {
return self.compare(element, other) == .ascending
}
}
public extension Array {
mutating func sort(using sortDescriptor: SortDescriptor<Element>) {
self.sort { (a, b) -> Bool in
return sortDescriptor.compare(a, to: b) == .ascending
}
}
mutating func sort(using sortDescriptors: [SortDescriptor<Element>]) {
guard !sortDescriptors.isEmpty else { return }
if sortDescriptors.count == 1 {
return self.sort(using: sortDescriptors[0])
}
self.sort { (a, b) -> Bool in
for desc in sortDescriptors {
switch desc.compare(a, to: b) {
case .same: break
case .descending: return false
case .ascending: return true
}
}
return false
}
}
mutating func insert(_ element: Element, using sortDescriptors: [SortDescriptor<Element>]) -> Int {
if !sortDescriptors.isEmpty, let idx = (self.firstIndex { return sortDescriptors.compare(element, $0) != .ascending }) {
self.insert(element, at: idx)
return idx
}
self.append(element)
return self.count - 1
}
// public mutating func insert(_ element: Element, using sortDescriptors: [SortDescriptor<Element>]) -> Int {
// if sortDescriptors.count > 0 {
// for (idx, existing) in self.enumerated() {
// if sortDescriptors.compare(element, existing) != .ascending {
// self.insert(element, at: idx)
// return idx
// }
// }
// }
// self.append(element)
// return self.count - 1
// }
}
extension Sequence {
public func sorted(using sortDescriptor: SortDescriptor<Element>) -> [Element] {
return self.sorted(by: { (a, b) -> Bool in
return sortDescriptor.compare(a, to: b) == .ascending
})
}
public func sorted(using sortDescriptors: [SortDescriptor<Element>]) -> [Element] {
guard !sortDescriptors.isEmpty else { return Array(self) }
if sortDescriptors.count == 1 {
return self.sorted(using: sortDescriptors[0])
}
return self.sorted { (a, b) -> Bool in
return sortDescriptors.element(a, isBefore: b)
}
}
}
| 10f3172035442a10202787d6d215e570 | 31.953216 | 128 | 0.593434 | false | false | false | false |
HTWDD/HTWDresden-iOS-Temp | refs/heads/master | HTWDresden/HTWDresden/Dictionary.swift | gpl-2.0 | 1 | //
// Dictionary.swift
// HTWDresden
//
// Created by Benjamin Herzog on 19/04/16.
// Copyright © 2016 HTW Dresden. All rights reserved.
//
import Foundation
public extension Dictionary {
init < S: SequenceType where S.Generator.Element == (Key, Value) > (_ seq: S) {
self = [:]
self.merge(seq)
}
mutating func merge < S: SequenceType where S.Generator.Element == (Key, Value) > (other: S) {
for (k, v) in other {
self[k] = v
}
}
func mapValues<T>(op: Value -> T) -> [Key: T] {
return [Key: T](flatMap { return ($0, op($1)) })
}
var urlParameterRepresentation: String {
return reduce("") {
"\($0)\($0.isEmpty ? "" : "&")\($1.0)=\($1.1)"
}
}
}
| 537490728c449f827cc6eead546e4796 | 20.25 | 95 | 0.589706 | false | false | false | false |
jvivas/OraChallenge | refs/heads/master | OraChallenge/OraChallenge/API/UsersManager.swift | apache-2.0 | 1 | //
// UsersManager.swift
// OraChallenge
//
// Created by Jorge Vivas on 3/5/17.
// Copyright © 2017 JorgeVivas. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
@objc protocol UsersDelegate {
@objc optional func onCreateUserResponse(user:User?, errorMessage:String?)
@objc optional func onGetCurrentUser(user:User?, errorMessage:String?)
@objc optional func onUpdateCurrentUser(user:User?, errorMessage:String?)
}
class UsersManager: APIManager {
var delegate:UsersDelegate?
let pathUsers = "users"
let pathCurrentUser = "users/current"
func requestCreate(name:String, email:String, password:String, passwordConfirmation:String) {
let parameters: Parameters = ["name" : name, "email": email, "password": password, "password_confirmation" : passwordConfirmation]
request(path: pathUsers, method: .post, parameters: parameters, onSuccess: { (response: SwiftyJSON.JSON) in
let user = User(json: response["data"])
DefaultsManager.saveUserId(userId: (user?.id)!)
self.delegate?.onCreateUserResponse!(user: user, errorMessage: nil)
}, onFailed: { (response: String, statusCode:Int) in
self.delegate?.onCreateUserResponse!(user: nil, errorMessage: response)
})
}
func requestCurrentUser() {
request(path: pathCurrentUser, method: .get, parameters: nil, onSuccess: { (response: SwiftyJSON.JSON) in
let user = User(json: response["data"])
self.delegate?.onGetCurrentUser!(user: user, errorMessage: nil)
}, onFailed: { (response: String, statusCode:Int) in
self.delegate?.onGetCurrentUser!(user: nil, errorMessage: response)
})
}
func requestUpdateCurrentUser(name:String, email:String) {
let parameters: Parameters = ["name" : name, "email": email]
request(path: pathCurrentUser, method: .patch, parameters: parameters, onSuccess: { (response: SwiftyJSON.JSON) in
let user = User(json: response["data"])
self.delegate?.onUpdateCurrentUser!(user: user, errorMessage: nil)
}, onFailed: { (response: String, statusCode:Int) in
self.delegate?.onUpdateCurrentUser!(user: nil, errorMessage: response)
})
}
}
| 8bf7efa986b22899c46c05a55004c757 | 42.377358 | 138 | 0.670726 | false | false | false | false |
orta/SignalKit | refs/heads/master | SignalKit/Extensions/UIKit/UIView+Signal.swift | mit | 1 | //
// UIView+Signal.swift
// SignalKit
//
// Created by Yanko Dimitrov on 8/16/15.
// Copyright © 2015 Yanko Dimitrov. All rights reserved.
//
import UIKit
public extension SignalType where Item == UIColor {
/**
Bind a UIColor to the background color of UIView
*/
public func bindTo(backgroundColorIn view: UIView) -> Self {
addObserver { [weak view] in
view?.backgroundColor = $0
}
return self
}
}
public extension SignalType where Item == CGFloat {
/**
Bind a CGFloat value to the alpha property of UIView
*/
public func bindTo(alphaIn view: UIView) -> Self {
addObserver { [weak view] in
view?.alpha = $0
}
return self
}
}
public extension SignalType where Item == Bool {
/**
Bind a Boolean value to the hidden property of UIView
*/
public func bindTo(hiddenStateIn view: UIView) -> Self {
addObserver { [weak view] in
view?.hidden = $0
}
return self
}
}
| f97ece9fabbea708bebbfccf0e07520c | 18.466667 | 64 | 0.528253 | false | false | false | false |
parkera/swift-corelibs-foundation | refs/heads/master | Foundation/UUID.swift | apache-2.0 | 1 | //===----------------------------------------------------------------------===//
//
// 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 http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import CoreFoundation
public typealias uuid_t = (UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8, UInt8)
public typealias uuid_string_t = (Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8, Int8)
/// Represents UUID strings, which can be used to uniquely identify types, interfaces, and other items.
public struct UUID : ReferenceConvertible, Hashable, Equatable, CustomStringConvertible {
public typealias ReferenceType = NSUUID
public private(set) var uuid: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
/* Create a new UUID with RFC 4122 version 4 random bytes */
public init() {
withUnsafeMutablePointer(to: &uuid) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) {
_cf_uuid_generate_random($0)
}
}
}
fileprivate init(reference: NSUUID) {
var bytes: uuid_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
withUnsafeMutablePointer(to: &bytes) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) {
reference.getBytes($0)
}
}
uuid = bytes
}
/// Create a UUID from a string such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F".
///
/// Returns nil for invalid strings.
public init?(uuidString string: String) {
let res = withUnsafeMutablePointer(to: &uuid) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) {
return _cf_uuid_parse(string, $0)
}
}
if res != 0 {
return nil
}
}
/// Create a UUID from a `uuid_t`.
public init(uuid: uuid_t) {
self.uuid = uuid
}
/// Returns a string created from the UUID, such as "E621E1F8-C36C-495A-93FC-0C247A3E6E5F"
public var uuidString: String {
var bytes: uuid_string_t = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0)
return withUnsafePointer(to: uuid) { valPtr in
valPtr.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) { val in
withUnsafeMutablePointer(to: &bytes) { strPtr in
strPtr.withMemoryRebound(to: CChar.self, capacity: MemoryLayout<uuid_string_t>.size) { str in
_cf_uuid_unparse_upper(val, str)
return String(cString: str, encoding: .utf8)!
}
}
}
}
}
public var hashValue: Int {
return withUnsafePointer(to: uuid) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) {
return Int(bitPattern: CFHashBytes(UnsafeMutablePointer(mutating: $0), CFIndex(MemoryLayout<uuid_t>.size)))
}
}
}
public var description: String {
return uuidString
}
public var debugDescription: String {
return description
}
// MARK: - Bridging Support
fileprivate var reference: NSUUID {
return withUnsafePointer(to: uuid) {
$0.withMemoryRebound(to: UInt8.self, capacity: MemoryLayout<uuid_t>.size) {
return NSUUID(uuidBytes: $0)
}
}
}
public static func ==(lhs: UUID, rhs: UUID) -> Bool {
return lhs.uuid.0 == rhs.uuid.0 &&
lhs.uuid.1 == rhs.uuid.1 &&
lhs.uuid.2 == rhs.uuid.2 &&
lhs.uuid.3 == rhs.uuid.3 &&
lhs.uuid.4 == rhs.uuid.4 &&
lhs.uuid.5 == rhs.uuid.5 &&
lhs.uuid.6 == rhs.uuid.6 &&
lhs.uuid.7 == rhs.uuid.7 &&
lhs.uuid.8 == rhs.uuid.8 &&
lhs.uuid.9 == rhs.uuid.9 &&
lhs.uuid.10 == rhs.uuid.10 &&
lhs.uuid.11 == rhs.uuid.11 &&
lhs.uuid.12 == rhs.uuid.12 &&
lhs.uuid.13 == rhs.uuid.13 &&
lhs.uuid.14 == rhs.uuid.14 &&
lhs.uuid.15 == rhs.uuid.15
}
}
extension UUID : CustomReflectable {
public var customMirror: Mirror {
let c : [(label: String?, value: Any)] = []
let m = Mirror(self, children:c, displayStyle: .struct)
return m
}
}
extension UUID : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSUUID {
return reference
}
public static func _forceBridgeFromObjectiveC(_ x: NSUUID, result: inout UUID?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge \(NSUUID.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ input: NSUUID, result: inout UUID?) -> Bool {
result = UUID(reference: input)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSUUID?) -> UUID {
var result: UUID? = nil
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension NSUUID : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(UUID._unconditionallyBridgeFromObjectiveC(self))
}
}
extension UUID : Codable {
public init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
let uuidString = try container.decode(String.self)
guard let uuid = UUID(uuidString: uuidString) else {
throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath,
debugDescription: "Attempted to decode UUID from invalid UUID string."))
}
self = uuid
}
public func encode(to encoder: Encoder) throws {
var container = encoder.singleValueContainer()
try container.encode(self.uuidString)
}
}
| 1f7a5ffa18b28f99597002cad2092836 | 36.838889 | 255 | 0.570988 | false | false | false | false |
AlwaysRightInstitute/SwiftySecurity | refs/heads/develop | SwiftySecurity/PEM.swift | mit | 1 | //
// PEM.swift
// TestSwiftyDocker
//
// Created by Helge Hess on 08/05/15.
// Copyright (c) 2015 Helge Hess. All rights reserved.
//
import Foundation
// Note: Security.framework really wants certificates, not raw keys
public func GetDataFromPEM(s: String, type: String = "CERTIFICATE") -> NSData? {
// FIXME: lame implementation ;-)
let keyBegin = "-----BEGIN \(type)-----"
let keyEnd = "-----END \(type)-----"
let scanner = NSScanner(string: s)
scanner.scanUpToString(keyBegin, intoString: nil)
scanner.scanString (keyBegin, intoString: nil)
var base64 : NSString?
scanner.scanUpToString(keyEnd, intoString: &base64)
if base64 == nil || base64!.length < 1 { return nil }
let opts = NSDataBase64DecodingOptions.IgnoreUnknownCharacters
return NSData(base64EncodedString: base64! as String, options: opts)
}
public func GetDataFromPEMFile(path: String, type: String = "CERTIFICATE")
-> NSData?
{
let s: NSString?
do {
s = try NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
} catch _ {
s = nil
};
return s != nil ? GetDataFromPEM(s! as String, type: type) : nil
}
| d5b8c1cb9e49cfaec638e033c0f65435 | 27.775 | 80 | 0.676803 | false | false | false | false |
ReSwift/ReSwift-Router | refs/heads/master | ReSwiftRouter/Router.swift | mit | 2 | //
// Router.swift
// Meet
//
// Created by Benjamin Encz on 11/11/15.
// Copyright © 2015 ReSwift Community. All rights reserved.
//
import Foundation
import ReSwift
open class Router<State>: StoreSubscriber {
public typealias NavigationStateTransform = (Subscription<State>) -> Subscription<NavigationState>
var store: Store<State>
var lastNavigationState = NavigationState()
var routables: [Routable] = []
let waitForRoutingCompletionQueue = DispatchQueue(label: "WaitForRoutingCompletionQueue", attributes: [])
public init(store: Store<State>, rootRoutable: Routable, stateTransform: @escaping NavigationStateTransform) {
self.store = store
self.routables.append(rootRoutable)
self.store.subscribe(self, transform: stateTransform)
}
open func newState(state: NavigationState) {
let routingActions = Router.routingActionsForTransition(from: lastNavigationState.route,
to: state.route)
routingActions.forEach { routingAction in
let semaphore = DispatchSemaphore(value: 0)
// Dispatch all routing actions onto this dedicated queue. This will ensure that
// only one routing action can run at any given time. This is important for using this
// Router with UI frameworks. Whenever a navigation action is triggered, this queue will
// block (using semaphore_wait) until it receives a callback from the Routable
// indicating that the navigation action has completed
waitForRoutingCompletionQueue.async {
switch routingAction {
case let .pop(responsibleRoutableIndex, elementToBePopped):
DispatchQueue.main.async {
self.routables[responsibleRoutableIndex]
.pop(
elementToBePopped,
animated: state.changeRouteAnimated) {
semaphore.signal()
}
self.routables.remove(at: responsibleRoutableIndex + 1)
}
case let .change(responsibleRoutableIndex, elementToBeReplaced, newElement):
DispatchQueue.main.async {
self.routables[responsibleRoutableIndex + 1] =
self.routables[responsibleRoutableIndex]
.change(
elementToBeReplaced,
to: newElement,
animated: state.changeRouteAnimated) {
semaphore.signal()
}
}
case let .push(responsibleRoutableIndex, elementToBePushed):
DispatchQueue.main.async {
self.routables.append(
self.routables[responsibleRoutableIndex]
.push(
elementToBePushed,
animated: state.changeRouteAnimated) {
semaphore.signal()
}
)
}
}
let waitUntil = DispatchTime.now() + Double(Int64(3 * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
let result = semaphore.wait(timeout: waitUntil)
if case .timedOut = result {
print("[ReSwiftRouter]: Router is stuck waiting for a" +
" completion handler to be called. Ensure that you have called the" +
" completion handler in each Routable element.")
print("Set a symbolic breakpoint for the `ReSwiftRouterStuck` symbol in order" +
" to halt the program when this happens")
ReSwiftRouterStuck()
}
}
}
lastNavigationState = state
}
// MARK: Route Transformation Logic
static func largestCommonSubroute(_ oldRoute: Route, newRoute: Route) -> Int {
var largestCommonSubroute = -1
while largestCommonSubroute + 1 < newRoute.count &&
largestCommonSubroute + 1 < oldRoute.count &&
newRoute[largestCommonSubroute + 1] == oldRoute[largestCommonSubroute + 1] {
largestCommonSubroute += 1
}
return largestCommonSubroute
}
// Maps Route index to Routable index. Routable index is offset by 1 because the root Routable
// is not represented in the route, e.g.
// route = ["tabBar"]
// routables = [RootRoutable, TabBarRoutable]
static func routableIndex(for element: Int) -> Int {
return element + 1
}
static func routingActionsForTransition(
from oldRoute: Route,
to newRoute: Route) -> [RoutingActions] {
var routingActions: [RoutingActions] = []
// Find the last common subroute between two routes
let commonSubroute = largestCommonSubroute(oldRoute, newRoute: newRoute)
if commonSubroute == oldRoute.count - 1 && commonSubroute == newRoute.count - 1 {
return []
}
// Keeps track which element of the routes we are working on
// We start at the end of the old route
var routeBuildingIndex = oldRoute.count - 1
// Pop all route elements of the old route that are no longer in the new route
// Stop one element ahead of the commonSubroute. When we are one element ahead of the
// commmon subroute we have three options:
//
// 1. The old route had an element after the commonSubroute and the new route does not
// we need to pop the route element after the commonSubroute
// 2. The old route had no element after the commonSubroute and the new route does, we
// we need to push the route element(s) after the commonSubroute
// 3. The new route has a different element after the commonSubroute, we need to replace
// the old route element with the new one
while routeBuildingIndex > commonSubroute + 1 {
let routeElementToPop = oldRoute[routeBuildingIndex]
let popAction = RoutingActions.pop(
responsibleRoutableIndex: routableIndex(for: routeBuildingIndex - 1),
elementToBePopped: routeElementToPop
)
routingActions.append(popAction)
routeBuildingIndex -= 1
}
// This is the 3. case:
// "The new route has a different element after the commonSubroute, we need to replace
// the old route element with the new one"
if oldRoute.count > (commonSubroute + 1) && newRoute.count > (commonSubroute + 1) {
let changeAction = RoutingActions.change(
responsibleRoutableIndex: routableIndex(for: commonSubroute),
elementToBeReplaced: oldRoute[commonSubroute + 1],
newElement: newRoute[commonSubroute + 1])
routingActions.append(changeAction)
}
// This is the 1. case:
// "The old route had an element after the commonSubroute and the new route does not
// we need to pop the route element after the commonSubroute"
else if oldRoute.count > newRoute.count {
let popAction = RoutingActions.pop(
responsibleRoutableIndex: routableIndex(for: routeBuildingIndex - 1),
elementToBePopped: oldRoute[routeBuildingIndex]
)
routingActions.append(popAction)
routeBuildingIndex -= 1
}
// Push remainder of elements in new Route that weren't in old Route, this covers
// the 2. case:
// "The old route had no element after the commonSubroute and the new route does,
// we need to push the route element(s) after the commonSubroute"
let newRouteIndex = newRoute.count - 1
while routeBuildingIndex < newRouteIndex {
let routeElementToPush = newRoute[routeBuildingIndex + 1]
let pushAction = RoutingActions.push(
responsibleRoutableIndex: routableIndex(for: routeBuildingIndex),
elementToBePushed: routeElementToPush
)
routingActions.append(pushAction)
routeBuildingIndex += 1
}
return routingActions
}
}
func ReSwiftRouterStuck() {}
enum RoutingActions {
case push(responsibleRoutableIndex: Int, elementToBePushed: RouteElement)
case pop(responsibleRoutableIndex: Int, elementToBePopped: RouteElement)
case change(responsibleRoutableIndex: Int, elementToBeReplaced: RouteElement,
newElement: RouteElement)
}
| 58a7ca4794c28833cd973f1e9470b386 | 42.242991 | 115 | 0.572509 | false | false | false | false |
burningmantech/ranger-ims-mac | refs/heads/master | Incidents/Ranger.swift | apache-2.0 | 1 | //
// Ranger.swift
// Incidents
//
// © 2015 Burning Man and its contributors. All rights reserved.
// See the file COPYRIGHT.md for terms.
//
struct Ranger: CustomStringConvertible, Hashable, Comparable {
var handle: String
var name: String?
var status: String?
var hashValue: Int {
// Only handle matters for equality
return handle.hashValue
}
var description: String {
var result = handle
if name != nil { result += " (\(name!))" }
if status == "vintage" { result += "*" }
return result
}
init(
handle: String,
name : String? = nil,
status: String? = nil
) {
self.handle = handle
self.name = name
self.status = status
}
}
func ==(lhs: Ranger, rhs: Ranger) -> Bool {
// Only handle matters for equality
return lhs.handle == rhs.handle
}
func <(lhs: Ranger, rhs: Ranger) -> Bool {
if lhs.handle < rhs.handle {
return true
} else {
return false
}
}
| 6d700c01ac198a91e3bcaf1cae8b102f | 18.472727 | 65 | 0.543417 | false | false | false | false |
Derek-Chiu/Mr-Ride-iOS | refs/heads/master | Mr-Ride-iOS/Mr-Ride-iOS/HttpHelper.swift | mit | 1 | //
// HttpHelper.swift
// Mr-Ride-iOS
//
// Created by Derek on 6/16/16.
// Copyright © 2016 AppWorks School Derek. All rights reserved.
//
import Foundation
import Alamofire
class HttpHelper {
typealias CompletionHandler = () -> Void
var stationList = [Station]()
func getToilet(completion: CompletionHandler) {
Alamofire.request(.GET,
"http://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=008ed7cf-2340-4bc4-89b0-e258a5573be2", parameters: nil).responseJSON { reponse in
// print(reponse.request)
print(reponse.response?.statusCode) //status is here (200...etc)
print(reponse.data)
print(reponse.result.isSuccess) //SUCCESS
guard let JSON = reponse.result.value as? [String: AnyObject] else {
// error handling
print("JSON failed")
return
}
print("JSON done")
guard let result = JSON["result"] as? [String: AnyObject] else {
// error handling
print("result failed")
return
}
print("result done")
guard let results = result["results"] as? [[String: String]] else {
// error handling
print("results failed")
return
}
print("results done")
for data in results {
guard let name = data["單位名稱"] else {
// error handleing
print("單位名稱")
continue
}
guard let address = data["地址"] else {
// error handleing
print("地址")
continue
}
guard let lat = data["緯度"] else {
//error handling
print("緯度")
continue
}
guard let latitude = Double(lat) else {
//error handling
print("casting")
continue
}
guard let lng = data["經度"] else {
// error handleing
print("經度")
continue
}
guard let longitude = Double(lng) else {
//error handling
print("casting")
continue
}
guard let cate = data["類別"] else {
// error handleing
print("類別")
continue
}
// let toilet = Toilet(name: name, category: "ddddd", address: address, latitude: latitude, longitude: longitude)
// self.toiletList.append(toilet)
ToiletRecorder.getInstance().writeData(category: cate, name: name, address: address, lat: latitude, lng: longitude)
}
dispatch_async(dispatch_get_main_queue()){
//
// completion()
self.getToiletRiverSide(completion)
}
}
}
func getToiletRiverSide(completion: CompletionHandler) {
Alamofire.request(.GET,
"http://data.taipei/opendata/datalist/apiAccess?scope=resourceAquire&rid=fe49c753-9358-49dd-8235-1fcadf5bfd3f", parameters: nil).responseJSON { reponse in
// print(reponse.request)
print(reponse.response?.statusCode) //status is here (200...etc)
// print(reponse.data)
// print(reponse.result.isSuccess) //SUCCESS
guard let JSON = reponse.result.value as? [String: AnyObject] else {
// error handling
print("JSON failed")
return
}
print("JSON done")
guard let result = JSON["result"] as? [String: AnyObject] else {
// error handling
print("result failed")
return
}
print("result done")
guard let results = result["results"] as? [[String: String]] else {
// error handling
print("results failed")
return
}
print("results done")
for data in results {
guard let name = data["Location"] else {
// error handleing
print("Location")
continue
}
guard let lat = data["Latitude"] else {
//error handling
print("Latitude")
continue
}
guard let latitude = Double(lat) else {
//error handling
print("casting")
continue
}
guard let lng = data["Longitude"] else {
// error handleing
print("Longitude")
continue
}
guard let longitude = Double(lng) else {
//error handling
print("casting")
continue
}
// let toilet = Toilet(name: name, category: "River Side", address: "", latitude: latitude, longitude: longitude)
// self.toiletList.append(toilet)
ToiletRecorder.getInstance().writeData(category: "河濱", name: name, address: "", lat: latitude, lng: longitude)
}
dispatch_async(dispatch_get_main_queue()){
completion()
}
}
}
func getStations(completion: CompletionHandler) {
Alamofire.request(.GET,
"http://data.taipei/youbike", parameters: nil).validate().responseJSON { reponse in
// print(reponse.request)
// TODO: error handling
print(reponse.response?.statusCode) //status is here (200...etc)
// print(reponse.data)
print(reponse.result.isSuccess) //SUCCESS
// print(reponse.result.value)
guard let JSON = reponse.result.value as? [String: AnyObject] else {
// error handling
print("JSON failed")
return
}
guard let results = JSON["retVal"] as? [String: [String: String]] else {
// error handling
print("result failed")
return
}
for data in results
{
// station name
guard let name = data.1["sna"] else {
// error handleing
print("站名")
continue
}
guard let nameEN = data.1["snaen"] else {
// error handleing
print("站名EN")
continue
}
// loaction around
guard let location = data.1["ar"] else {
// error handleing
print("位置")
continue
}
guard let locationEN = data.1["aren"] else {
// error handleing
print("位置EN")
continue
}
// area around
guard let area = data.1["sarea"] else {
// error handleing
print("區")
continue
}
guard let areaEN = data.1["sareaen"] else {
// error handleing
print("區EN")
continue
}
// latitude
guard let lat = data.1["lat"] else {
//error handling
print("lat")
continue
}
guard let latitude = Double(lat) else {
//error handling
print("casting")
continue
}
// longitude
guard let lng = data.1["lng"] else {
// error handling
print("lng")
continue
}
guard let longitude = Double(lng) else {
//error handling
print("casting")
continue
}
// bike left
guard let bikeL = data.1["sbi"] else {
// error handling
print("bike left")
continue
}
guard let bikeLeft = Int(bikeL) else {
// error handling
print("casting")
continue
}
// parking space
guard let bikeS = data.1["bemp"] else {
//error handling
print("bike space")
continue
}
guard let bikeSpace = Int(bikeS) else {
// error handling
print("casting")
continue
}
// station available
guard let stationAvailability = data.1["act"] else {
//error handling
print("stationAvailability")
continue
}
guard let act = Int(stationAvailability) else {
continue
}
var isAvailable = true
switch act
{
case 0: isAvailable = false
case 1: isAvailable = true
default: isAvailable = true
}
let station = Station( name: name, nameEN: nameEN,
location: location, locarionEN: locationEN,
area: area, areaEN: areaEN,
latitude: latitude,
longitude: longitude,
bikeleft: bikeLeft,
bikeSpace: bikeSpace,
isAvailable: isAvailable)
self.stationList.append(station)
}
dispatch_async(dispatch_get_main_queue()){
completion()
}
}
}
func getStationList() -> [Station] {
return stationList
}
// get stations here
}
extension HttpHelper {
private static var sharedInstance: HttpHelper?
static func getInstance() -> HttpHelper {
if sharedInstance == nil {
sharedInstance = HttpHelper()
}
return sharedInstance!
}
} | a9199b649b8bbeac7b138913850c6717 | 35.267606 | 166 | 0.363756 | false | false | false | false |
jhend11/Coinvert | refs/heads/master | Coinvert/QRCodeReader/ReaderView.swift | lgpl-3.0 | 1 | /*
* 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 UIKit
class ReaderView: UIView {
private var overlay: CAShapeLayer = {
var overlay = CAShapeLayer()
overlay.backgroundColor = UIColor.clearColor().CGColor
overlay.fillColor = UIColor.clearColor().CGColor
overlay.strokeColor = UIColor.whiteColor().CGColor
overlay.lineWidth = 3
overlay.lineDashPattern = [7.0, 7.0]
overlay.lineDashPhase = 0
return overlay
}()
override init() {
super.init()
layer.addSublayer(overlay)
}
override init(frame: CGRect) {
super.init(frame: frame)
layer.addSublayer(overlay)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
layer.addSublayer(overlay)
}
override func drawRect(rect: CGRect) {
var innerRect = CGRectInset(rect, 50, 50)
let minSize = min(innerRect.width, innerRect.height)
if innerRect.width != minSize {
innerRect.origin.x += (innerRect.width - minSize) / 2
innerRect.size.width = minSize
}
else if innerRect.height != minSize {
innerRect.origin.y += (innerRect.height - minSize) / 2
innerRect.size.height = minSize
}
let offsetRect = CGRectOffset(innerRect, 0, 15)
overlay.path = UIBezierPath(roundedRect: offsetRect
, cornerRadius: 5).CGPath
}
}
| 4ba630ea6d6907098ea2900f0f0d9728 | 30.506329 | 79 | 0.703897 | false | false | false | false |
radazzouz/firefox-ios | refs/heads/master | StorageTests/TestTableTable.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
@testable import Storage
import XCTest
class TestSchemaTable: XCTestCase {
// This is a very basic test. Adds an entry. Retrieves it, and then clears the database
func testTable() {
let files = MockFiles()
let db = BrowserDB(filename: "browser.db", files: files)
// Test creating a table
var testTable = getCreateTable()
db.createOrUpdate(testTable)
// Now make sure the item is in the table-table
var err: NSError? = nil
let table = SchemaTable()
var cursor = db.withReadableConnection(&err) { (connection, err) -> Cursor<TableInfo> in
return table.query(connection, options: QueryOptions(filter: testTable.name))
}
verifyTable(cursor, table: testTable)
// We have to close this cursor to ensure we don't get results from a sqlite memory cache below when
// we requery the table.
cursor.close()
// Now test updating the table
testTable = getUpgradeTable()
db.createOrUpdate(testTable)
cursor = db.withReadableConnection(&err) { (connection, err) -> Cursor<TableInfo> in
return table.query(connection, options: QueryOptions(filter: testTable.name))
}
verifyTable(cursor, table: testTable)
// We have to close this cursor to ensure we don't get results from a sqlite memory cache below when
// we requery the table.
cursor.close()
// Now try updating it again to the same version. This shouldn't call create or upgrade
testTable = getNoOpTable()
db.createOrUpdate(testTable)
do {
// Cleanup
try files.remove("browser.db")
} catch _ {
}
}
// Helper for verifying that the data in a cursor matches whats in a table
fileprivate func verifyTable(_ cursor: Cursor<TableInfo>, table: TestTable) {
XCTAssertEqual(cursor.count, 1, "Cursor is the right size")
let data = cursor[0] as! TableInfoWrapper
XCTAssertNotNil(data, "Found an object of the right type")
XCTAssertEqual(data.name, table.name, "Table info has the right name")
XCTAssertEqual(data.version, table.version, "Table info has the right version")
}
// A test class for fake table creation/upgrades
class TestTable: Table {
var name: String { return "testName" }
var _version: Int = -1
var version: Int { return _version }
typealias `Type` = Int
// Called if the table is created.
let createCallback: () -> Bool
// Called if the table is upgraded.
let updateCallback: (_ from: Int) -> Bool
let dropCallback: (() -> Void)?
init(version: Int, createCallback: @escaping () -> Bool, updateCallback: @escaping (_ from: Int) -> Bool, dropCallback: (() -> Void)? = nil) {
self._version = version
self.createCallback = createCallback
self.updateCallback = updateCallback
self.dropCallback = dropCallback
}
func exists(_ db: SQLiteDBConnection) -> Bool {
let res = db.executeQuery("SELECT name FROM sqlite_master WHERE type = 'table' AND name=?", factory: StringFactory, withArgs: [name])
return res.count > 0
}
func drop(_ db: SQLiteDBConnection) -> Bool {
if let dropCallback = dropCallback {
dropCallback()
}
let sqlStr = "DROP TABLE IF EXISTS \(name)"
let err = db.executeChange(sqlStr, withArgs: [])
return err == nil
}
func create(_ db: SQLiteDBConnection) -> Bool {
// BrowserDB uses a different query to determine if a table exists, so we need to ensure it actually happens
db.executeChange("CREATE TABLE IF NOT EXISTS \(name) (ID INTEGER PRIMARY KEY AUTOINCREMENT)")
return createCallback()
}
func updateTable(_ db: SQLiteDBConnection, from: Int) -> Bool {
return updateCallback(from)
}
// These are all no-ops for testing
func insert(_ db: SQLiteDBConnection, item: Type?, err: inout NSError?) -> Int { return -1 }
func update(_ db: SQLiteDBConnection, item: Type?, err: inout NSError?) -> Int { return -1 }
func delete(_ db: SQLiteDBConnection, item: Type?, err: inout NSError?) -> Int { return -1 }
func query(_ db: SQLiteDBConnection, options: QueryOptions?) -> Cursor<Type> { return Cursor(status: .failure, msg: "Shouldn't hit this") }
}
// This function will create a table with appropriate callbacks set. Pass "create" if you expect the table to
// be created. Pass "update" if it should be updated. Pass anythign else if neither callback should be called.
func getCreateTable() -> TestTable {
let t = TestTable(version: 1, createCallback: { _ -> Bool in
XCTAssert(true, "Should have created table")
return true
}, updateCallback: { from -> Bool in
XCTFail("Should not try to update table")
return false
})
return t
}
func getUpgradeTable() -> TestTable {
var upgraded = false
var dropped = false
let t = TestTable(version: 2, createCallback: { _ -> Bool in
XCTAssertTrue(dropped, "Create should be called after upgrade attempt")
return true
}, updateCallback: { from -> Bool in
XCTAssert(true, "Should try to update table")
XCTAssertEqual(from, 1, "From is correct")
// We'll return false here. The db will take that as a sign to drop and recreate our table.
upgraded = true
return false
}, dropCallback: { () -> Void in
XCTAssertTrue(upgraded, "Should try to drop table")
dropped = true
})
return t
}
func getNoOpTable() -> TestTable {
let t = TestTable(version: 2, createCallback: { _ -> Bool in
XCTFail("Should not try to create table")
return false
}, updateCallback: { from -> Bool in
XCTFail("Should not try to update table")
return false
})
return t
}
}
| 5e837304dce1db9501556f1ebf71b533 | 39.41875 | 150 | 0.608938 | false | true | false | false |
icylydia/PlayWithLeetCode | refs/heads/master | 95. Unique Binary Search Trees II/solution.swift | mit | 1 | /**
* Definition for a binary tree node.
* public class TreeNode {
* public var val: Int
* public var left: TreeNode?
* public var right: TreeNode?
* public init(_ val: Int) {
* self.val = val
* self.left = nil
* self.right = nil
* }
* }
*/
class Solution {
func generateTrees(n: Int) -> [TreeNode?] {
if n == 0 {
return Array<TreeNode?>()
}
let root: TreeNode? = TreeNode(1)
var dp = Array<Array<TreeNode?>>()
let dp0 = Array<TreeNode?>()
dp.append(dp0)
let dp1 = [root]
dp.append(dp1)
if n == 1 {
return dp[1]
}
for i in 2...n {
var tp = Array<TreeNode?>()
// left nil
for right in dp[i-1] {
var mr = TreeNode(1)
mr.left = nil
mr.right = right?.copy()
tp.append(mr)
}
// right nil
for left in dp[i-1] {
var mr = TreeNode(1)
mr.left = left?.copy()
mr.right = nil
tp.append(mr)
}
// left + right
for j in 1..<i-1 {
for left in dp[j] {
for right in dp[i-1-j] {
var mr = TreeNode(1)
mr.left = left?.copy()
mr.right = right?.copy()
tp.append(mr)
}
}
}
dp.append(tp)
}
for tree in dp[n] {
dfs(0, tree)
}
return dp[n]
}
func dfs(base: Int, _ root: TreeNode?) -> Int {
if let root = root {
let left = dfs(base, root.left)
root.val = left + 1
let right = dfs(left + 1, root.right)
return right
} else {
return base
}
}
}
extension TreeNode {
func copy() -> TreeNode {
var root = TreeNode(self.val)
root.left = self.left?.copy()
root.right = self.right?.copy()
return root
}
} | 287e694575c12094b2bdb5c1b66f045e | 21.225 | 51 | 0.487338 | false | false | false | false |
ilhanadiyaman/firefox-ios | refs/heads/master | Storage/SQL/SQLiteHistory.swift | mpl-2.0 | 3 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
private let log = Logger.syncLogger
class NoSuchRecordError: MaybeErrorType {
let guid: GUID
init(guid: GUID) {
self.guid = guid
}
var description: String {
return "No such record: \(guid)."
}
}
func failOrSucceed<T>(err: NSError?, op: String, val: T) -> Deferred<Maybe<T>> {
if let err = err {
log.debug("\(op) failed: \(err.localizedDescription)")
return deferMaybe(DatabaseError(err: err))
}
return deferMaybe(val)
}
func failOrSucceed(err: NSError?, op: String) -> Success {
return failOrSucceed(err, op: op, val: ())
}
private var ignoredSchemes = ["about"]
public func isIgnoredURL(url: NSURL) -> Bool {
let scheme = url.scheme
if let _ = ignoredSchemes.indexOf(scheme) {
return true
}
if url.host == "localhost" {
return true
}
return false
}
public func isIgnoredURL(url: String) -> Bool {
if let url = NSURL(string: url) {
return isIgnoredURL(url)
}
return false
}
/*
// Here's the Swift equivalent of the below.
func simulatedFrecency(now: MicrosecondTimestamp, then: MicrosecondTimestamp, visitCount: Int) -> Double {
let ageMicroseconds = (now - then)
let ageDays = Double(ageMicroseconds) / 86400000000.0 // In SQL the .0 does the coercion.
let f = 100 * 225 / ((ageSeconds * ageSeconds) + 225)
return Double(visitCount) * max(1.0, f)
}
*/
// The constants in these functions were arrived at by utterly unscientific experimentation.
func getRemoteFrecencySQL() -> String {
let visitCountExpression = "remoteVisitCount"
let now = NSDate.nowMicroseconds()
let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24
let ageDays = "((\(now) - remoteVisitDate) / \(microsecondsPerDay))"
return "\(visitCountExpression) * max(1, 100 * 110 / (\(ageDays) * \(ageDays) + 110))"
}
func getLocalFrecencySQL() -> String {
let visitCountExpression = "((2 + localVisitCount) * (2 + localVisitCount))"
let now = NSDate.nowMicroseconds()
let microsecondsPerDay = 86_400_000_000.0 // 1000 * 1000 * 60 * 60 * 24
let ageDays = "((\(now) - localVisitDate) / \(microsecondsPerDay))"
return "\(visitCountExpression) * max(2, 100 * 225 / (\(ageDays) * \(ageDays) + 225))"
}
extension SDRow {
func getTimestamp(column: String) -> Timestamp? {
return (self[column] as? NSNumber)?.unsignedLongLongValue
}
func getBoolean(column: String) -> Bool {
if let val = self[column] as? Int {
return val != 0
}
return false
}
}
/**
* The sqlite-backed implementation of the history protocol.
*/
public class SQLiteHistory {
let db: BrowserDB
let favicons: FaviconsTable<Favicon>
let prefs: Prefs
required public init?(db: BrowserDB, prefs: Prefs) {
self.db = db
self.favicons = FaviconsTable<Favicon>()
self.prefs = prefs
// BrowserTable exists only to perform create/update etc. operations -- it's not
// a queryable thing that needs to stick around.
if !db.createOrUpdate(BrowserTable()) {
return nil
}
}
}
extension SQLiteHistory: BrowserHistory {
public func removeSiteFromTopSites(site: Site) -> Success {
if let host = site.url.asURL?.normalizedHost() {
return db.run([("UPDATE \(TableDomains) set showOnTopSites = 0 WHERE domain = ?", [host])])
}
return deferMaybe(DatabaseError(description: "Invalid url for site \(site.url)"))
}
public func removeHistoryForURL(url: String) -> Success {
let visitArgs: Args = [url]
let deleteVisits = "DELETE FROM \(TableVisits) WHERE siteID = (SELECT id FROM \(TableHistory) WHERE url = ?)"
let markArgs: Args = [NSDate.nowNumber(), url]
let markDeleted = "UPDATE \(TableHistory) SET url = NULL, is_deleted = 1, should_upload = 1, local_modified = ? WHERE url = ?"
return db.run([(deleteVisits, visitArgs),
(markDeleted, markArgs),
favicons.getCleanupCommands()])
}
// Note: clearing history isn't really a sane concept in the presence of Sync.
// This method should be split to do something else.
// Bug 1162778.
public func clearHistory() -> Success {
return self.db.run([
("DELETE FROM \(TableVisits)", nil),
("DELETE FROM \(TableHistory)", nil),
("DELETE FROM \(TableDomains)", nil),
self.favicons.getCleanupCommands(),
])
// We've probably deleted a lot of stuff. Vacuum now to recover the space.
>>> effect(self.db.vacuum)
}
func recordVisitedSite(site: Site) -> Success {
var error: NSError? = nil
// Don't store visits to sites with about: protocols
if isIgnoredURL(site.url) {
return deferMaybe(IgnoredSiteError())
}
db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in
let now = NSDate.nowNumber()
let i = self.updateSite(site, atTime: now, withConnection: conn)
if i > 0 {
return i
}
// Insert instead.
return self.insertSite(site, atTime: now, withConnection: conn)
}
return failOrSucceed(error, op: "Record site")
}
func updateSite(site: Site, atTime time: NSNumber, withConnection conn: SQLiteDBConnection) -> Int {
// We know we're adding a new visit, so we'll need to upload this record.
// If we ever switch to per-visit change flags, this should turn into a CASE statement like
// CASE WHEN title IS ? THEN max(should_upload, 1) ELSE should_upload END
// so that we don't flag this as changed unless the title changed.
//
// Note that we will never match against a deleted item, because deleted items have no URL,
// so we don't need to unset is_deleted here.
if let host = site.url.asURL?.normalizedHost() {
let update = "UPDATE \(TableHistory) SET title = ?, local_modified = ?, should_upload = 1, domain_id = (SELECT id FROM \(TableDomains) where domain = ?) WHERE url = ?"
let updateArgs: Args? = [site.title, time, host, site.url]
if Logger.logPII {
log.debug("Setting title to \(site.title) for URL \(site.url)")
}
let error = conn.executeChange(update, withArgs: updateArgs)
if error != nil {
log.warning("Update failed with \(error?.localizedDescription)")
return 0
}
return conn.numberOfRowsModified
}
return 0
}
private func insertSite(site: Site, atTime time: NSNumber, withConnection conn: SQLiteDBConnection) -> Int {
if let host = site.url.asURL?.normalizedHost() {
if let error = conn.executeChange("INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)", withArgs: [host]) {
log.warning("Domain insertion failed with \(error.localizedDescription)")
return 0
}
let insert = "INSERT INTO \(TableHistory) " +
"(guid, url, title, local_modified, is_deleted, should_upload, domain_id) " +
"SELECT ?, ?, ?, ?, 0, 1, id FROM \(TableDomains) WHERE domain = ?"
let insertArgs: Args? = [site.guid ?? Bytes.generateGUID(), site.url, site.title, time, host]
if let error = conn.executeChange(insert, withArgs: insertArgs) {
log.warning("Site insertion failed with \(error.localizedDescription)")
return 0
}
return 1
}
if Logger.logPII {
log.warning("Invalid URL \(site.url). Not stored in history.")
}
return 0
}
// TODO: thread siteID into this to avoid the need to do the lookup.
func addLocalVisitForExistingSite(visit: SiteVisit) -> Success {
var error: NSError? = nil
db.withWritableConnection(&error) { (conn, inout err: NSError?) -> Int in
// INSERT OR IGNORE because we *might* have a clock error that causes a timestamp
// collision with an existing visit, and it would really suck to error out for that reason.
let insert = "INSERT OR IGNORE INTO \(TableVisits) (siteID, date, type, is_local) VALUES (" +
"(SELECT id FROM \(TableHistory) WHERE url = ?), ?, ?, 1)"
let realDate = NSNumber(unsignedLongLong: visit.date)
let insertArgs: Args? = [visit.site.url, realDate, visit.type.rawValue]
error = conn.executeChange(insert, withArgs: insertArgs)
if error != nil {
log.warning("Visit insertion failed with \(err?.localizedDescription)")
return 0
}
return 1
}
return failOrSucceed(error, op: "Record visit")
}
public func addLocalVisit(visit: SiteVisit) -> Success {
return recordVisitedSite(visit.site)
>>> { self.addLocalVisitForExistingSite(visit) }
}
public func getSitesByFrecencyWithLimit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> {
return self.getSitesByFrecencyWithLimit(limit, includeIcon: true)
}
public func getSitesByFrecencyWithLimit(limit: Int, includeIcon: Bool) -> Deferred<Maybe<Cursor<Site>>> {
// Exclude redirect domains. Bug 1194852.
let (whereData, groupBy) = self.topSiteClauses()
return self.getFilteredSitesByFrecencyWithLimit(limit, groupClause: groupBy, whereData: whereData, includeIcon: includeIcon)
}
public func getTopSitesWithLimit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> {
let topSitesQuery = "SELECT * FROM \(TableCachedTopSites) ORDER BY frecencies DESC LIMIT (?)"
let factory = SQLiteHistory.iconHistoryColumnFactory
return self.db.runQuery(topSitesQuery, args: [limit], factory: factory)
}
public func setTopSitesNeedsInvalidation() {
prefs.setBool(false, forKey: PrefsKeys.KeyTopSitesCacheIsValid)
}
public func updateTopSitesCacheIfInvalidated() -> Deferred<Maybe<Bool>> {
if prefs.boolForKey(PrefsKeys.KeyTopSitesCacheIsValid) ?? false {
return deferMaybe(false)
}
return refreshTopSitesCache() >>> always(true)
}
public func setTopSitesCacheSize(size: Int32) {
let oldValue = prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0
if oldValue != size {
prefs.setInt(size, forKey: PrefsKeys.KeyTopSitesCacheSize)
setTopSitesNeedsInvalidation()
}
}
public func refreshTopSitesCache() -> Success {
let cacheSize = Int(prefs.intForKey(PrefsKeys.KeyTopSitesCacheSize) ?? 0)
return self.clearTopSitesCache()
>>> { self.updateTopSitesCacheWithLimit(cacheSize) }
}
private func updateTopSitesCacheWithLimit(limit : Int) -> Success {
let (whereData, groupBy) = self.topSiteClauses()
let (query, args) = self.filteredSitesByFrecencyQueryWithLimit(limit, groupClause: groupBy, whereData: whereData)
let insertQuery = "INSERT INTO \(TableCachedTopSites) \(query)"
return self.clearTopSitesCache() >>> {
self.db.run(insertQuery, withArgs: args) >>> {
self.prefs.setBool(true, forKey: PrefsKeys.KeyTopSitesCacheIsValid)
return succeed()
}
}
}
public func clearTopSitesCache() -> Success {
let deleteQuery = "DELETE FROM \(TableCachedTopSites)"
return self.db.run(deleteQuery, withArgs: nil) >>> {
self.prefs.removeObjectForKey(PrefsKeys.KeyTopSitesCacheIsValid)
return succeed()
}
}
public func getSitesByFrecencyWithLimit(limit: Int, whereURLContains filter: String) -> Deferred<Maybe<Cursor<Site>>> {
return self.getFilteredSitesByFrecencyWithLimit(limit, whereURLContains: filter)
}
public func getSitesByLastVisit(limit: Int) -> Deferred<Maybe<Cursor<Site>>> {
return self.getFilteredSitesByVisitDateWithLimit(limit, whereURLContains: nil, includeIcon: true)
}
private class func basicHistoryColumnFactory(row: SDRow) -> Site {
let id = row["historyID"] as! Int
let url = row["url"] as! String
let title = row["title"] as! String
let guid = row["guid"] as! String
let site = Site(url: url, title: title)
site.guid = guid
site.id = id
// Find the most recent visit, regardless of which column it might be in.
let local = row.getTimestamp("localVisitDate") ?? 0
let remote = row.getTimestamp("remoteVisitDate") ?? 0
let either = row.getTimestamp("visitDate") ?? 0
let latest = max(local, remote, either)
if latest > 0 {
site.latestVisit = Visit(date: latest, type: VisitType.Unknown)
}
return site
}
private class func iconColumnFactory(row: SDRow) -> Favicon? {
if let iconType = row["iconType"] as? Int,
let iconURL = row["iconURL"] as? String,
let iconDate = row["iconDate"] as? Double,
let _ = row["iconID"] as? Int {
let date = NSDate(timeIntervalSince1970: iconDate)
return Favicon(url: iconURL, date: date, type: IconType(rawValue: iconType)!)
}
return nil
}
private class func iconHistoryColumnFactory(row: SDRow) -> Site {
let site = basicHistoryColumnFactory(row)
site.icon = iconColumnFactory(row)
return site
}
private func topSiteClauses() -> (String, String) {
let whereData = "(\(TableDomains).showOnTopSites IS 1) AND (\(TableDomains).domain NOT LIKE 'r.%') "
let groupBy = "GROUP BY domain_id "
return (whereData, groupBy)
}
private func getFilteredSitesByVisitDateWithLimit(limit: Int,
whereURLContains filter: String? = nil,
includeIcon: Bool = true) -> Deferred<Maybe<Cursor<Site>>> {
let args: Args?
let whereClause: String
if let filter = filter {
args = ["%\(filter)%", "%\(filter)%"]
// No deleted item has a URL, so there is no need to explicitly add that here.
whereClause = "WHERE ((\(TableHistory).url LIKE ?) OR (\(TableHistory).title LIKE ?)) " +
"AND (\(TableHistory).is_deleted = 0)"
} else {
args = []
whereClause = "WHERE (\(TableHistory).is_deleted = 0)"
}
let ungroupedSQL =
"SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, domain_id, domain, " +
"COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate, " +
"COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate, " +
"COALESCE(count(\(TableVisits).is_local), 0) AS visitCount " +
"FROM \(TableHistory) " +
"INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id " +
"INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id " +
whereClause + " GROUP BY historyID"
let historySQL =
"SELECT historyID, url, title, guid, domain_id, domain, visitCount, " +
"max(localVisitDate) AS localVisitDate, " +
"max(remoteVisitDate) AS remoteVisitDate " +
"FROM (" + ungroupedSQL + ") " +
"WHERE (visitCount > 0) " + // Eliminate dead rows from coalescing.
"GROUP BY historyID " +
"ORDER BY max(localVisitDate, remoteVisitDate) DESC " +
"LIMIT \(limit) "
if includeIcon {
// We select the history items then immediately join to get the largest icon.
// We do this so that we limit and filter *before* joining against icons.
let sql = "SELECT " +
"historyID, url, title, guid, domain_id, domain, " +
"localVisitDate, remoteVisitDate, visitCount, " +
"iconID, iconURL, iconDate, iconType, iconWidth " +
"FROM (\(historySQL)) LEFT OUTER JOIN " +
"view_history_id_favicon ON historyID = view_history_id_favicon.id"
let factory = SQLiteHistory.iconHistoryColumnFactory
return db.runQuery(sql, args: args, factory: factory)
}
let factory = SQLiteHistory.basicHistoryColumnFactory
return db.runQuery(historySQL, args: args, factory: factory)
}
private func getFilteredSitesByFrecencyWithLimit(limit: Int,
whereURLContains filter: String? = nil,
groupClause: String = "GROUP BY historyID ",
whereData: String? = nil,
includeIcon: Bool = true) -> Deferred<Maybe<Cursor<Site>>> {
let factory: (SDRow) -> Site
if includeIcon {
factory = SQLiteHistory.iconHistoryColumnFactory
} else {
factory = SQLiteHistory.basicHistoryColumnFactory
}
let (query, args) = filteredSitesByFrecencyQueryWithLimit(limit,
whereURLContains: filter,
groupClause: groupClause,
whereData: whereData,
includeIcon: includeIcon
)
return db.runQuery(query, args: args, factory: factory)
}
private func filteredSitesByFrecencyQueryWithLimit(limit: Int,
whereURLContains filter: String? = nil,
groupClause: String = "GROUP BY historyID ",
whereData: String? = nil,
includeIcon: Bool = true) -> (String, Args?) {
let localFrecencySQL = getLocalFrecencySQL()
let remoteFrecencySQL = getRemoteFrecencySQL()
let sixMonthsInMicroseconds: UInt64 = 15_724_800_000_000 // 182 * 1000 * 1000 * 60 * 60 * 24
let sixMonthsAgo = NSDate.nowMicroseconds() - sixMonthsInMicroseconds
let args: Args?
let whereClause: String
let whereFragment = (whereData == nil) ? "" : " AND (\(whereData!))"
if let filter = filter {
args = ["%\(filter)%", "%\(filter)%"]
// No deleted item has a URL, so there is no need to explicitly add that here.
whereClause = " WHERE ((\(TableHistory).url LIKE ?) OR (\(TableHistory).title LIKE ?)) \(whereFragment)"
} else {
args = []
whereClause = " WHERE (\(TableHistory).is_deleted = 0) \(whereFragment)"
}
// Innermost: grab history items and basic visit/domain metadata.
let ungroupedSQL =
"SELECT \(TableHistory).id AS historyID, \(TableHistory).url AS url, title, guid, domain_id, domain" +
", COALESCE(max(case \(TableVisits).is_local when 1 then \(TableVisits).date else 0 end), 0) AS localVisitDate" +
", COALESCE(max(case \(TableVisits).is_local when 0 then \(TableVisits).date else 0 end), 0) AS remoteVisitDate" +
", COALESCE(sum(\(TableVisits).is_local), 0) AS localVisitCount" +
", COALESCE(sum(case \(TableVisits).is_local when 1 then 0 else 1 end), 0) AS remoteVisitCount" +
" FROM \(TableHistory) " +
"INNER JOIN \(TableDomains) ON \(TableDomains).id = \(TableHistory).domain_id " +
"INNER JOIN \(TableVisits) ON \(TableVisits).siteID = \(TableHistory).id " +
whereClause + " GROUP BY historyID"
// Next: limit to only those that have been visited at all within the last six months.
// (Don't do that in the innermost: we want to get the full count, even if some visits are older.)
// Discard all but the 1000 most frecent.
// Compute and return the frecency for all 1000 URLs.
let frecenciedSQL =
"SELECT *, (\(localFrecencySQL) + \(remoteFrecencySQL)) AS frecency" +
" FROM (" + ungroupedSQL + ")" +
" WHERE (" +
"((localVisitCount > 0) OR (remoteVisitCount > 0)) AND " + // Eliminate dead rows from coalescing.
"((localVisitDate > \(sixMonthsAgo)) OR (remoteVisitDate > \(sixMonthsAgo)))" + // Exclude really old items.
") ORDER BY frecency DESC" +
" LIMIT 1000" // Don't even look at a huge set. This avoids work.
// Next: merge by domain and sum frecency, ordering by that sum and reducing to a (typically much lower) limit.
let historySQL =
"SELECT historyID, url, title, guid, domain_id, domain" +
", max(localVisitDate) AS localVisitDate" +
", max(remoteVisitDate) AS remoteVisitDate" +
", sum(localVisitCount) AS localVisitCount" +
", sum(remoteVisitCount) AS remoteVisitCount" +
", sum(frecency) AS frecencies" +
" FROM (" + frecenciedSQL + ") " +
groupClause + " " +
"ORDER BY frecencies DESC " +
"LIMIT \(limit) "
// Finally: join this small list to the favicon data.
if includeIcon {
// We select the history items then immediately join to get the largest icon.
// We do this so that we limit and filter *before* joining against icons.
let sql = "SELECT" +
" historyID, url, title, guid, domain_id, domain" +
", localVisitDate, remoteVisitDate, localVisitCount, remoteVisitCount" +
", iconID, iconURL, iconDate, iconType, iconWidth, frecencies" +
" FROM (\(historySQL)) LEFT OUTER JOIN " +
"view_history_id_favicon ON historyID = view_history_id_favicon.id"
return (sql, args)
}
return (historySQL, args)
}
}
extension SQLiteHistory: Favicons {
// These two getter functions are only exposed for testing purposes (and aren't part of the public interface).
func getFaviconsForURL(url: String) -> Deferred<Maybe<Cursor<Favicon?>>> {
let sql = "SELECT iconID AS id, iconURL AS url, iconDate AS date, iconType AS type, iconWidth AS width FROM " +
"\(ViewWidestFaviconsForSites), \(TableHistory) WHERE " +
"\(TableHistory).id = siteID AND \(TableHistory).url = ?"
let args: Args = [url]
return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory)
}
func getFaviconsForBookmarkedURL(url: String) -> Deferred<Maybe<Cursor<Favicon?>>> {
let sql = "SELECT \(TableFavicons).id AS id, \(TableFavicons).url AS url, \(TableFavicons).date AS date, \(TableFavicons).type AS type, \(TableFavicons).width AS width FROM \(TableFavicons), \(TableBookmarks) WHERE \(TableBookmarks).faviconID = \(TableFavicons).id AND \(TableBookmarks).url IS ?"
let args: Args = [url]
return db.runQuery(sql, args: args, factory: SQLiteHistory.iconColumnFactory)
}
public func clearAllFavicons() -> Success {
var err: NSError? = nil
db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in
err = conn.executeChange("DELETE FROM \(TableFaviconSites)", withArgs: nil)
if err == nil {
err = conn.executeChange("DELETE FROM \(TableFavicons)", withArgs: nil)
}
return 1
}
return failOrSucceed(err, op: "Clear favicons")
}
public func addFavicon(icon: Favicon) -> Deferred<Maybe<Int>> {
var err: NSError?
let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in
// Blind! We don't see failure here.
let id = self.favicons.insertOrUpdate(conn, obj: icon)
return id ?? 0
}
if err == nil {
return deferMaybe(res)
}
return deferMaybe(DatabaseError(err: err))
}
/**
* This method assumes that the site has already been recorded
* in the history table.
*/
public func addFavicon(icon: Favicon, forSite site: Site) -> Deferred<Maybe<Int>> {
if Logger.logPII {
log.verbose("Adding favicon \(icon.url) for site \(site.url).")
}
func doChange(query: String, args: Args?) -> Deferred<Maybe<Int>> {
var err: NSError?
let res = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in
// Blind! We don't see failure here.
let id = self.favicons.insertOrUpdate(conn, obj: icon)
// Now set up the mapping.
err = conn.executeChange(query, withArgs: args)
if let err = err {
log.error("Got error adding icon: \(err).")
return 0
}
// Try to update the favicon ID column in the bookmarks table as well for this favicon
// if this site has been bookmarked
if let id = id {
conn.executeChange("UPDATE \(TableBookmarks) SET faviconID = ? WHERE url = ?", withArgs: [id, site.url])
}
return id ?? 0
}
if res == 0 {
return deferMaybe(DatabaseError(err: err))
}
return deferMaybe(icon.id!)
}
let siteSubselect = "(SELECT id FROM \(TableHistory) WHERE url = ?)"
let iconSubselect = "(SELECT id FROM \(TableFavicons) WHERE url = ?)"
let insertOrIgnore = "INSERT OR IGNORE INTO \(TableFaviconSites)(siteID, faviconID) VALUES "
if let iconID = icon.id {
// Easy!
if let siteID = site.id {
// So easy!
let args: Args? = [siteID, iconID]
return doChange("\(insertOrIgnore) (?, ?)", args: args)
}
// Nearly easy.
let args: Args? = [site.url, iconID]
return doChange("\(insertOrIgnore) (\(siteSubselect), ?)", args: args)
}
// Sigh.
if let siteID = site.id {
let args: Args? = [siteID, icon.url]
return doChange("\(insertOrIgnore) (?, \(iconSubselect))", args: args)
}
// The worst.
let args: Args? = [site.url, icon.url]
return doChange("\(insertOrIgnore) (\(siteSubselect), \(iconSubselect))", args: args)
}
}
extension SQLiteHistory: SyncableHistory {
/**
* TODO:
* When we replace an existing row, we want to create a deleted row with the old
* GUID and switch the new one in -- if the old record has escaped to a Sync server,
* we want to delete it so that we don't have two records with the same URL on the server.
* We will know if it's been uploaded because it'll have a server_modified time.
*/
public func ensurePlaceWithURL(url: String, hasGUID guid: GUID) -> Success {
let args: Args = [guid, url, guid]
// The additional IS NOT is to ensure that we don't do a write for no reason.
return db.run("UPDATE \(TableHistory) SET guid = ? WHERE url = ? AND guid IS NOT ?", withArgs: args)
}
public func deleteByGUID(guid: GUID, deletedAt: Timestamp) -> Success {
let args: Args = [guid]
// This relies on ON DELETE CASCADE to remove visits.
return db.run("DELETE FROM \(TableHistory) WHERE guid = ?", withArgs: args)
}
// Fails on non-existence.
private func getSiteIDForGUID(guid: GUID) -> Deferred<Maybe<Int>> {
let args: Args = [guid]
let query = "SELECT id FROM history WHERE guid = ?"
let factory: SDRow -> Int = { return $0["id"] as! Int }
return db.runQuery(query, args: args, factory: factory)
>>== { cursor in
if cursor.count == 0 {
return deferMaybe(NoSuchRecordError(guid: guid))
}
return deferMaybe(cursor[0]!)
}
}
public func storeRemoteVisits(visits: [Visit], forGUID guid: GUID) -> Success {
return self.getSiteIDForGUID(guid)
>>== { (siteID: Int) -> Success in
let visitArgs = visits.map { (visit: Visit) -> Args in
let realDate = NSNumber(unsignedLongLong: visit.date)
let isLocal = 0
let args: Args = [siteID, realDate, visit.type.rawValue, isLocal]
return args
}
// Magic happens here. The INSERT OR IGNORE relies on the multi-column uniqueness
// constraint on `visits`: we allow only one row for (siteID, date, type), so if a
// local visit already exists, this silently keeps it. End result? Any new remote
// visits are added with only one query, keeping any existing rows.
return self.db.bulkInsert(TableVisits, op: .InsertOrIgnore, columns: ["siteID", "date", "type", "is_local"], values: visitArgs)
}
}
private struct HistoryMetadata {
let id: Int
let serverModified: Timestamp?
let localModified: Timestamp?
let isDeleted: Bool
let shouldUpload: Bool
let title: String
}
private func metadataForGUID(guid: GUID) -> Deferred<Maybe<HistoryMetadata?>> {
let select = "SELECT id, server_modified, local_modified, is_deleted, should_upload, title FROM \(TableHistory) WHERE guid = ?"
let args: Args = [guid]
let factory = { (row: SDRow) -> HistoryMetadata in
return HistoryMetadata(
id: row["id"] as! Int,
serverModified: row.getTimestamp("server_modified"),
localModified: row.getTimestamp("local_modified"),
isDeleted: row.getBoolean("is_deleted"),
shouldUpload: row.getBoolean("should_upload"),
title: row["title"] as! String
)
}
return db.runQuery(select, args: args, factory: factory) >>== { cursor in
return deferMaybe(cursor[0])
}
}
public func insertOrUpdatePlace(place: Place, modified: Timestamp) -> Deferred<Maybe<GUID>> {
// One of these things will be true here.
// 0. The item is new.
// (a) We have a local place with the same URL but a different GUID.
// (b) We have never visited this place locally.
// In either case, reconcile and proceed.
// 1. The remote place is not modified when compared to our mirror of it. This
// can occur when we redownload after a partial failure.
// (a) And it's not modified locally, either. Nothing to do. Ideally we
// will short-circuit so we don't need to update visits. (TODO)
// (b) It's modified locally. Don't overwrite anything; let the upload happen.
// 2. The remote place is modified (either title or visits).
// (a) And it's not locally modified. Update the local entry.
// (b) And it's locally modified. Preserve the title of whichever was modified last.
// N.B., this is the only instance where we compare two timestamps to see
// which one wins.
// We use this throughout.
let serverModified = NSNumber(unsignedLongLong: modified)
// Check to see if our modified time is unchanged, if the record exists locally, etc.
let insertWithMetadata = { (metadata: HistoryMetadata?) -> Deferred<Maybe<GUID>> in
if let metadata = metadata {
// The item exists locally (perhaps originally with a different GUID).
if metadata.serverModified == modified {
log.verbose("History item \(place.guid) is unchanged; skipping insert-or-update.")
return deferMaybe(place.guid)
}
// Otherwise, the server record must have changed since we last saw it.
if metadata.shouldUpload {
// Uh oh, it changed locally.
// This might well just be a visit change, but we can't tell. Usually this conflict is harmless.
log.debug("Warning: history item \(place.guid) changed both locally and remotely. Comparing timestamps from different clocks!")
if metadata.localModified > modified {
log.debug("Local changes overriding remote.")
// Update server modified time only. (Though it'll be overwritten again after a successful upload.)
let update = "UPDATE \(TableHistory) SET server_modified = ? WHERE id = ?"
let args: Args = [serverModified, metadata.id]
return self.db.run(update, withArgs: args) >>> always(place.guid)
}
log.verbose("Remote changes overriding local.")
// Fall through.
}
// The record didn't change locally. Update it.
log.verbose("Updating local history item for guid \(place.guid).")
let update = "UPDATE \(TableHistory) SET title = ?, server_modified = ?, is_deleted = 0 WHERE id = ?"
let args: Args = [place.title, serverModified, metadata.id]
return self.db.run(update, withArgs: args) >>> always(place.guid)
}
// The record doesn't exist locally. Insert it.
log.verbose("Inserting remote history item for guid \(place.guid).")
if let host = place.url.asURL?.normalizedHost() {
if Logger.logPII {
log.debug("Inserting: \(place.url).")
}
let insertDomain = "INSERT OR IGNORE INTO \(TableDomains) (domain) VALUES (?)"
let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " +
"SELECT ?, ?, ?, ?, 0, 0, id FROM \(TableDomains) where domain = ?"
return self.db.run([
(insertDomain, [host]),
(insertHistory, [place.guid, place.url, place.title, serverModified, host])
]) >>> always(place.guid)
} else {
// This is a URL with no domain. Insert it directly.
if Logger.logPII {
log.debug("Inserting: \(place.url) with no domain.")
}
let insertHistory = "INSERT INTO \(TableHistory) (guid, url, title, server_modified, is_deleted, should_upload, domain_id) " +
"VALUES (?, ?, ?, ?, 0, 0, NULL)"
return self.db.run([
(insertHistory, [place.guid, place.url, place.title, serverModified])
]) >>> always(place.guid)
}
}
// Make sure that we only need to compare GUIDs by pre-merging on URL.
return self.ensurePlaceWithURL(place.url, hasGUID: place.guid)
>>> { self.metadataForGUID(place.guid) >>== insertWithMetadata }
}
public func getDeletedHistoryToUpload() -> Deferred<Maybe<[GUID]>> {
// Use the partial index on should_upload to make this nice and quick.
let sql = "SELECT guid FROM \(TableHistory) WHERE \(TableHistory).should_upload = 1 AND \(TableHistory).is_deleted = 1"
let f: SDRow -> String = { $0["guid"] as! String }
return self.db.runQuery(sql, args: nil, factory: f) >>== { deferMaybe($0.asArray()) }
}
public func getModifiedHistoryToUpload() -> Deferred<Maybe<[(Place, [Visit])]>> {
// What we want to do: find all items flagged for update, selecting some number of their
// visits alongside.
//
// A difficulty here: we don't want to fetch *all* visits, only some number of the most recent.
// (It's not enough to only get new ones, because the server record should contain more.)
//
// That's the greatest-N-per-group problem in SQL. Please read and understand the solution
// to this (particularly how the LEFT OUTER JOIN/HAVING clause works) before changing this query!
//
// We can do this in a single query, rather than the N+1 that desktop takes.
// We then need to flatten the cursor. We do that by collecting
// places as a side-effect of the factory, producing visits as a result, and merging in memory.
let args: Args = [
20, // Maximum number of visits to retrieve.
]
// Exclude 'unknown' visits, because they're not syncable.
let filter = "history.should_upload = 1 AND v1.type IS NOT 0"
let sql =
"SELECT " +
"history.id AS siteID, history.guid AS guid, history.url AS url, history.title AS title, " +
"v1.siteID AS siteID, v1.date AS visitDate, v1.type AS visitType " +
"FROM " +
"visits AS v1 " +
"JOIN history ON history.id = v1.siteID AND \(filter) " +
"LEFT OUTER JOIN " +
"visits AS v2 " +
"ON v1.siteID = v2.siteID AND v1.date < v2.date " +
"GROUP BY v1.date " +
"HAVING COUNT(*) < ? " +
"ORDER BY v1.siteID, v1.date DESC"
var places = [Int: Place]()
var visits = [Int: [Visit]]()
// Add a place to the accumulator, prepare to accumulate visits, return the ID.
let ensurePlace: SDRow -> Int = { row in
let id = row["siteID"] as! Int
if places[id] == nil {
let guid = row["guid"] as! String
let url = row["url"] as! String
let title = row["title"] as! String
places[id] = Place(guid: guid, url: url, title: title)
visits[id] = Array()
}
return id
}
// Store the place and the visit.
let factory: SDRow -> Int = { row in
let date = row.getTimestamp("visitDate")!
let type = VisitType(rawValue: row["visitType"] as! Int)!
let visit = Visit(date: date, type: type)
let id = ensurePlace(row)
visits[id]?.append(visit)
return id
}
return db.runQuery(sql, args: args, factory: factory)
>>== { c in
// Consume every row, with the side effect of populating the places
// and visit accumulators.
var ids = Set<Int>()
for row in c {
// Collect every ID first, so that we're guaranteed to have
// fully populated the visit lists, and we don't have to
// worry about only collecting each place once.
ids.insert(row!)
}
// Now we're done with the cursor. Close it.
c.close()
// Now collect the return value.
return deferMaybe(ids.map { return (places[$0]!, visits[$0]!) } )
}
}
public func markAsDeleted(guids: [GUID]) -> Success {
// TODO: support longer GUID lists.
assert(guids.count < BrowserDB.MaxVariableNumber)
if guids.isEmpty {
return succeed()
}
log.debug("Wiping \(guids.count) deleted GUIDs.")
// We deliberately don't limit this to records marked as should_upload, just
// in case a coding error leaves records with is_deleted=1 but not flagged for
// upload -- this will catch those and throw them away.
let inClause = BrowserDB.varlist(guids.count)
let sql =
"DELETE FROM \(TableHistory) WHERE " +
"is_deleted = 1 AND guid IN \(inClause)"
let args: Args = guids.map { $0 as AnyObject }
return self.db.run(sql, withArgs: args)
}
public func markAsSynchronized(guids: [GUID], modified: Timestamp) -> Deferred<Maybe<Timestamp>> {
// TODO: support longer GUID lists.
assert(guids.count < 99)
if guids.isEmpty {
return deferMaybe(modified)
}
log.debug("Marking \(guids.count) GUIDs as synchronized. Returning timestamp \(modified).")
let inClause = BrowserDB.varlist(guids.count)
let sql =
"UPDATE \(TableHistory) SET " +
"should_upload = 0, server_modified = \(modified) " +
"WHERE guid IN \(inClause)"
let args: Args = guids.map { $0 as AnyObject }
return self.db.run(sql, withArgs: args) >>> always(modified)
}
public func doneApplyingRecordsAfterDownload() -> Success {
self.db.checkpoint()
return succeed()
}
public func doneUpdatingMetadataAfterUpload() -> Success {
self.db.checkpoint()
return succeed()
}
}
extension SQLiteHistory: ResettableSyncStorage {
// We don't drop deletions when we reset -- we might need to upload a deleted item
// that never made it to the server.
public func resetClient() -> Success {
let flag = "UPDATE \(TableHistory) SET should_upload = 1, server_modified = NULL"
return self.db.run(flag)
}
}
extension SQLiteHistory: AccountRemovalDelegate {
public func onRemovedAccount() -> Success {
log.info("Clearing history metadata and deleted items after account removal.")
let discard = "DELETE FROM \(TableHistory) WHERE is_deleted = 1"
return self.db.run(discard) >>> self.resetClient
}
}
| da181f490b3eaff417df6871a775982e | 42.89666 | 304 | 0.586807 | false | false | false | false |
material-components/material-components-ios-codelabs | refs/heads/master | MDC-104/Swift/Starter/Shrine/Shrine/BackdropViewController.swift | apache-2.0 | 1 | /*
Copyright 2018-present the Material Components for iOS authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MaterialComponents
class BackdropViewController: UIViewController {
var appBar = MDCAppBar()
var containerView: UIView = {
//TODO: Change the following line from UIView to ShapedShadowedView and apply the shape.
let view = UIView(frame: .zero)
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = ApplicationScheme.shared.colorScheme.surfaceColor
return view
}()
let featuredButton: MDCButton = {
let button = MDCButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("FEATURED", for: .normal)
button.addTarget(self, action: #selector(didTapCategory(sender:)), for: .touchUpInside)
MDCTextButtonThemer.applyScheme(ApplicationScheme.shared.buttonScheme, to: button)
return button
}()
let clothingButton: MDCButton = {
let button = MDCButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("CLOTHING", for: .normal)
button.addTarget(self, action: #selector(didTapCategory(sender:)), for: .touchUpInside)
MDCTextButtonThemer.applyScheme(ApplicationScheme.shared.buttonScheme, to: button)
return button
}()
let homeButton: MDCButton = {
let button = MDCButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("HOME", for: .normal)
button.addTarget(self, action: #selector(didTapCategory(sender:)), for: .touchUpInside)
MDCTextButtonThemer.applyScheme(ApplicationScheme.shared.buttonScheme, to: button)
return button
}()
let accessoriesButton: MDCButton = {
let button = MDCButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("ACCESSORIES", for: .normal)
button.addTarget(self, action: #selector(didTapCategory(sender:)), for: .touchUpInside)
MDCTextButtonThemer.applyScheme(ApplicationScheme.shared.buttonScheme, to: button)
return button
}()
let accountButton: MDCButton = {
let button = MDCButton()
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle("ACCOUNT", for: .normal)
button.addTarget(self, action: #selector(menuItemTapped(sender:)), for: .touchUpInside)
MDCTextButtonThemer.applyScheme(ApplicationScheme.shared.buttonScheme, to: button)
return button
}()
var embeddedView: UIView?
var embeddedViewController: UIViewController?
var isFocusedEmbeddedController: Bool = false {
didSet {
UIView.animate(withDuration: 0.2) {
self.containerView.frame = self.frameForEmbeddedController()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = ApplicationScheme.shared.colorScheme.surfaceColor
self.title = "Shrine"
// Setup Navigation Items
let menuItemImage = UIImage(named: "MenuItem")
let templatedMenuItemImage = menuItemImage?.withRenderingMode(.alwaysTemplate)
let menuItem = UIBarButtonItem(image: templatedMenuItemImage,
style: .plain,
target: self,
action: #selector(menuItemTapped(sender:)))
self.navigationItem.leftBarButtonItem = menuItem
let searchItemImage = UIImage(named: "SearchItem")
let templatedSearchItemImage = searchItemImage?.withRenderingMode(.alwaysTemplate)
let searchItem = UIBarButtonItem(image: templatedSearchItemImage,
style: .plain,
target: self,
action: #selector(filterItemTapped(sender:)))
let tuneItemImage = UIImage(named: "TuneItem")
let templatedTuneItemImage = tuneItemImage?.withRenderingMode(.alwaysTemplate)
let tuneItem = UIBarButtonItem(image: templatedTuneItemImage,
style: .plain,
target: self,
action: #selector(filterItemTapped(sender:)))
self.navigationItem.rightBarButtonItems = [ tuneItem, searchItem ]
// AppBar Init
self.addChildViewController(appBar.headerViewController)
appBar.addSubviewsToParent()
MDCAppBarColorThemer.applySemanticColorScheme(ApplicationScheme.shared.colorScheme, to: appBar)
self.appBar.navigationBar.translatesAutoresizingMaskIntoConstraints = false
// Buttons
self.view.addSubview(featuredButton)
self.view.addSubview(clothingButton)
self.view.addSubview(homeButton)
self.view.addSubview(accessoriesButton)
self.view.addSubview(accountButton)
var constraints = [NSLayoutConstraint]()
constraints.append(NSLayoutConstraint(item: self.featuredButton,
attribute: .centerX,
relatedBy: .equal,
toItem: self.view,
attribute: .centerX,
multiplier: 1.0,
constant: 0.0))
let nameView = [
"navigationbar" : self.appBar.navigationBar,
"featured" : self.featuredButton,
"clothing" : self.clothingButton,
"home" : self.homeButton,
"accessories" : self.accessoriesButton,
"account" : self.accountButton
]
constraints.append(contentsOf:
NSLayoutConstraint.constraints(withVisualFormat: "V:|[navigationbar]-[featured]-[clothing]-[home]-[accessories]-[account]", options: .alignAllCenterX, metrics: nil, views: nameView))
NSLayoutConstraint.activate(constraints)
let recognizer = UITapGestureRecognizer(target: self, action: #selector(filterItemTapped(sender:)))
self.view.addGestureRecognizer(recognizer)
self.view.addSubview(self.containerView)
//TODO: Insert the HomeViewController into our BackdropViewController
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
let embeddedFrame = self.frameForEmbeddedController()
self.containerView.frame = embeddedFrame
self.embeddedView?.frame = self.containerView.bounds
}
func frameForEmbeddedController() -> CGRect {
var embeddedFrame = self.view.bounds
var insetHeader = UIEdgeInsets()
insetHeader.top = self.appBar.headerViewController.view.frame.maxY
embeddedFrame = UIEdgeInsetsInsetRect(embeddedFrame, insetHeader)
if !isFocusedEmbeddedController {
embeddedFrame.origin.y = self.view.bounds.size.height - self.appBar.navigationBar.frame.height
}
if (embeddedView == nil) {
embeddedFrame.origin.y = self.view.bounds.maxY
}
return embeddedFrame
}
//MARK - Actions
@objc func menuItemTapped(sender: Any) {
let loginViewController = LoginViewController(nibName: nil, bundle: nil)
self.present(loginViewController, animated: true, completion: nil)
}
@objc func filterItemTapped(sender: Any) {
isFocusedEmbeddedController = !isFocusedEmbeddedController
}
@objc func didTapCategory(sender: Any) {
let filter: String
let view = sender as! UIView
if (view == self.featuredButton) {
filter = "Featured"
} else if (view == self.homeButton) {
filter = "Home"
} else if (view == self.accessoriesButton) {
filter = "Accessories"
} else if (view == self.clothingButton) {
filter = "Clothing"
} else {
filter = ""
}
//TODO: Set the catalog filter based on the button pressed
isFocusedEmbeddedController = !isFocusedEmbeddedController
}
}
//MARK: - View Controller Containment
// The following methods implement View Controller Containment
extension BackdropViewController {
func insert(_ controller: UIViewController) {
if let controller = self.embeddedViewController,
let view = self.embeddedView {
controller.willMove(toParentViewController: nil)
controller.removeFromParentViewController()
self.embeddedViewController = nil
view.removeFromSuperview()
self.embeddedView = nil
isFocusedEmbeddedController = false
}
controller.willMove(toParentViewController: self)
self.addChildViewController(controller)
self.embeddedViewController = controller
self.containerView.addSubview(controller.view)
self.embeddedView = controller.view
self.embeddedView?.backgroundColor = .clear
isFocusedEmbeddedController = true
}
func removeController() {
if let controller = self.embeddedViewController,
let view = self.embeddedView {
controller.willMove(toParentViewController: nil)
controller.removeFromParentViewController()
self.embeddedViewController = nil
view.removeFromSuperview()
self.embeddedView = nil
isFocusedEmbeddedController = false
}
}
}
| f301e82c09618513eb9ff6d6ca5d89e1 | 35.180769 | 190 | 0.696609 | false | false | false | false |
guoc/excerptor | refs/heads/master | Excerptor/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// excerptor
//
// Created by Chen Guo on 17/05/2015.
// Copyright (c) 2015 guoc. All rights reserved.
//
import Cocoa
import PreferencePanes
class AppDelegate: NSObject, NSApplicationDelegate {
lazy var preferencesWindowController: PreferencesWindowController = PreferencesWindowController(windowNibName: NSNib.Name(rawValue: "PreferencesWindow"))
func applicationWillFinishLaunching(_ notification: Notification) {
preferencesWindowController.showPreferencesOnlyOnceIfNecessaryAfterDelay(0.3)
let servicesProvider = ServicesProvider()
NSApplication.shared.servicesProvider = servicesProvider
let appleEventManager: NSAppleEventManager = NSAppleEventManager.shared()
appleEventManager.setEventHandler(self, andSelector: #selector(handleGetURLEvent(_:withReplyEvent:)), forEventClass: AEEventClass(kInternetEventClass), andEventID: AEEventID(kAEGetURL))
}
func applicationDidBecomeActive(_ notification: Notification) {
preferencesWindowController.showPreferencesOnlyOnceIfNecessaryAfterDelay(0.3)
}
@objc func handleGetURLEvent(_ event: NSAppleEventDescriptor, withReplyEvent: NSAppleEventDescriptor) {
PreferencesWindowController.needShowPreferences = false
if let theURLString = event.forKeyword(AEKeyword(keyDirectObject))?.stringValue {
if let link = AnnotationLink(linkString: theURLString) ?? SelectionLink(linkString: theURLString) {
PasteboardHelper.writeExcerptorPasteboardWithLocation(link.location)
let applicationName: String
switch Preferences.sharedPreferences.appForOpenPDF {
case .preview:
applicationName = "Preview.app"
case .skim:
applicationName = "Skim.app"
}
NSWorkspace().openFile(link.getFilePath(), withApplication: applicationName, andDeactivate: true)
}
}
}
}
| 9752a6dee3772b831b7717d36abe2aea | 41.574468 | 193 | 0.715642 | false | false | false | false |
ben-ng/swift | refs/heads/master | stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift | apache-2.0 | 1 | //===--- Subprocess.swift -------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftPrivate
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
import Darwin
#elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android)
import Glibc
#endif
#if !os(Windows) || CYGWIN
// posix_spawn is not available on Android or Windows.
#if !os(Android)
// swift_posix_spawn isn't available in the public watchOS SDK, we sneak by the
// unavailable attribute declaration here of the APIs that we need.
// FIXME: Come up with a better way to deal with APIs that are pointers on some
// platforms but not others.
#if os(Linux)
typealias swift_posix_spawn_file_actions_t = posix_spawn_file_actions_t
#else
typealias swift_posix_spawn_file_actions_t = posix_spawn_file_actions_t?
#endif
@_silgen_name("swift_posix_spawn_file_actions_init")
func swift_posix_spawn_file_actions_init(
_ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t>
) -> CInt
@_silgen_name("swift_posix_spawn_file_actions_destroy")
func swift_posix_spawn_file_actions_destroy(
_ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t>
) -> CInt
@_silgen_name("swift_posix_spawn_file_actions_addclose")
func swift_posix_spawn_file_actions_addclose(
_ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t>,
_ filedes: CInt) -> CInt
@_silgen_name("swift_posix_spawn_file_actions_adddup2")
func swift_posix_spawn_file_actions_adddup2(
_ file_actions: UnsafeMutablePointer<swift_posix_spawn_file_actions_t>,
_ filedes: CInt,
_ newfiledes: CInt) -> CInt
@_silgen_name("swift_posix_spawn")
func swift_posix_spawn(
_ pid: UnsafeMutablePointer<pid_t>?,
_ file: UnsafePointer<Int8>,
_ file_actions: UnsafePointer<swift_posix_spawn_file_actions_t>?,
_ attrp: UnsafePointer<posix_spawnattr_t>?,
_ argv: UnsafePointer<UnsafeMutablePointer<Int8>?>,
_ envp: UnsafePointer<UnsafeMutablePointer<Int8>?>?) -> CInt
#endif
/// Calls POSIX `pipe()`.
func posixPipe() -> (readFD: CInt, writeFD: CInt) {
var fds: [CInt] = [ -1, -1 ]
if pipe(&fds) != 0 {
preconditionFailure("pipe() failed")
}
return (fds[0], fds[1])
}
/// Start the same executable as a child process, redirecting its stdout and
/// stderr.
public func spawnChild(_ args: [String])
-> (pid: pid_t, stdinFD: CInt, stdoutFD: CInt, stderrFD: CInt) {
// The stdout, stdin, and stderr from the child process will be redirected
// to these pipes.
let childStdout = posixPipe()
let childStdin = posixPipe()
let childStderr = posixPipe()
#if os(Android)
// posix_spawn isn't available on Android. Instead, we fork and exec.
// To correctly communicate the exit status of the child process to this
// (parent) process, we'll use this pipe.
let childToParentPipe = posixPipe()
let pid = fork()
precondition(pid >= 0, "fork() failed")
if pid == 0 {
// pid of 0 means we are now in the child process.
// Capture the output before executing the program.
dup2(childStdout.writeFD, STDOUT_FILENO)
dup2(childStdin.readFD, STDIN_FILENO)
dup2(childStderr.writeFD, STDERR_FILENO)
// Set the "close on exec" flag on the parent write pipe. This will
// close the pipe if the execve() below successfully executes a child
// process.
let closeResult = fcntl(childToParentPipe.writeFD, F_SETFD, FD_CLOEXEC)
let closeErrno = errno
precondition(
closeResult == 0,
"Could not set the close behavior of the child-to-parent pipe; " +
"errno: \(closeErrno)")
// Start the executable. If execve() does not encounter an error, the
// code after this block will never be executed, and the parent write pipe
// will be closed.
withArrayOfCStrings([CommandLine.arguments[0]] + args) {
execve(CommandLine.arguments[0], $0, _getEnviron())
}
// If execve() encountered an error, we write the errno encountered to the
// parent write pipe.
let errnoSize = MemoryLayout.size(ofValue: errno)
var execveErrno = errno
let writtenBytes = withUnsafePointer(to: &execveErrno) {
write(childToParentPipe.writeFD, UnsafePointer($0), errnoSize)
}
let writeErrno = errno
if writtenBytes > 0 && writtenBytes < errnoSize {
// We were able to write some of our error, but not all of it.
// FIXME: Retry in this case.
preconditionFailure("Unable to write entire error to child-to-parent " +
"pipe.")
} else if writtenBytes == 0 {
preconditionFailure("Unable to write error to child-to-parent pipe.")
} else if writtenBytes < 0 {
preconditionFailure("An error occurred when writing error to " +
"child-to-parent pipe; errno: \(writeErrno)")
}
// Close the pipe when we're done writing the error.
close(childToParentPipe.writeFD)
}
#else
var fileActions = _make_posix_spawn_file_actions_t()
if swift_posix_spawn_file_actions_init(&fileActions) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_init() failed")
}
// Close the write end of the pipe on the child side.
if swift_posix_spawn_file_actions_addclose(
&fileActions, childStdin.writeFD) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stdin.
if swift_posix_spawn_file_actions_adddup2(
&fileActions, childStdin.readFD, STDIN_FILENO) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_adddup2() failed")
}
// Close the read end of the pipe on the child side.
if swift_posix_spawn_file_actions_addclose(
&fileActions, childStdout.readFD) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stdout.
if swift_posix_spawn_file_actions_adddup2(
&fileActions, childStdout.writeFD, STDOUT_FILENO) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_adddup2() failed")
}
// Close the read end of the pipe on the child side.
if swift_posix_spawn_file_actions_addclose(
&fileActions, childStderr.readFD) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stderr.
if swift_posix_spawn_file_actions_adddup2(
&fileActions, childStderr.writeFD, STDERR_FILENO) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_adddup2() failed")
}
var pid: pid_t = -1
var childArgs = args
childArgs.insert(CommandLine.arguments[0], at: 0)
let interpreter = getenv("SWIFT_INTERPRETER")
if interpreter != nil {
if let invocation = String(validatingUTF8: interpreter!) {
childArgs.insert(invocation, at: 0)
}
}
let spawnResult = withArrayOfCStrings(childArgs) {
swift_posix_spawn(
&pid, childArgs[0], &fileActions, nil, $0, _getEnviron())
}
if spawnResult != 0 {
print(String(cString: strerror(spawnResult)))
preconditionFailure("swift_posix_spawn() failed")
}
if swift_posix_spawn_file_actions_destroy(&fileActions) != 0 {
preconditionFailure("swift_posix_spawn_file_actions_destroy() failed")
}
#endif
// Close the read end of the pipe on the parent side.
if close(childStdin.readFD) != 0 {
preconditionFailure("close() failed")
}
// Close the write end of the pipe on the parent side.
if close(childStdout.writeFD) != 0 {
preconditionFailure("close() failed")
}
// Close the write end of the pipe on the parent side.
if close(childStderr.writeFD) != 0 {
preconditionFailure("close() failed")
}
return (pid, childStdin.writeFD, childStdout.readFD, childStderr.readFD)
}
#if !os(Android)
#if os(Linux)
internal func _make_posix_spawn_file_actions_t()
-> swift_posix_spawn_file_actions_t {
return posix_spawn_file_actions_t()
}
#else
internal func _make_posix_spawn_file_actions_t()
-> swift_posix_spawn_file_actions_t {
return nil
}
#endif
#endif
internal func _signalToString(_ signal: Int) -> String {
switch CInt(signal) {
case SIGILL: return "SIGILL"
case SIGTRAP: return "SIGTRAP"
case SIGABRT: return "SIGABRT"
case SIGFPE: return "SIGFPE"
case SIGBUS: return "SIGBUS"
case SIGSEGV: return "SIGSEGV"
case SIGSYS: return "SIGSYS"
default: return "SIG???? (\(signal))"
}
}
public enum ProcessTerminationStatus : CustomStringConvertible {
case exit(Int)
case signal(Int)
public var description: String {
switch self {
case .exit(let status):
return "Exit(\(status))"
case .signal(let signal):
return "Signal(\(_signalToString(signal)))"
}
}
}
public func posixWaitpid(_ pid: pid_t) -> ProcessTerminationStatus {
var status: CInt = 0
if waitpid(pid, &status, 0) < 0 {
preconditionFailure("waitpid() failed")
}
if (WIFEXITED(status)) {
return .exit(Int(WEXITSTATUS(status)))
}
if (WIFSIGNALED(status)) {
return .signal(Int(WTERMSIG(status)))
}
preconditionFailure("did not understand what happened to child process")
}
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
@_silgen_name("swift_SwiftPrivateLibcExtras_NSGetEnviron")
func _NSGetEnviron() -> UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>>
#endif
internal func _getEnviron() -> UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> {
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS)
return _NSGetEnviron().pointee
#elseif os(FreeBSD)
return environ
#elseif os(PS4)
return environ
#elseif os(Android)
return environ
#else
return __environ
#endif
}
#endif
| 8d0d93606c64adcbc566502c4e380752 | 32.187919 | 96 | 0.686855 | false | false | false | false |
loudnate/Loop | refs/heads/master | LoopCore/LoopCompletionFreshness.swift | apache-2.0 | 1 | //
// LoopCompletionFreshness.swift
// Loop
//
// Created by Pete Schwamb on 1/17/20.
// Copyright © 2020 LoopKit Authors. All rights reserved.
//
import Foundation
public enum LoopCompletionFreshness {
case fresh
case aging
case stale
case unknown
public var maxAge: TimeInterval? {
switch self {
case .fresh:
return TimeInterval(minutes: 6)
case .aging:
return TimeInterval(minutes: 16)
case .stale:
return TimeInterval(hours: 12)
case .unknown:
return nil
}
}
public init(age: TimeInterval?) {
guard let age = age else {
self = .unknown
return
}
switch age {
case let t where t <= LoopCompletionFreshness.fresh.maxAge!:
self = .fresh
case let t where t <= LoopCompletionFreshness.aging.maxAge!:
self = .aging
case let t where t <= LoopCompletionFreshness.stale.maxAge!:
self = .stale
default:
self = .unknown
}
}
public init(lastCompletion: Date?, at date: Date = Date()) {
guard let lastCompletion = lastCompletion else {
self = .unknown
return
}
self = LoopCompletionFreshness(age: date.timeIntervalSince(lastCompletion))
}
}
| d42d790ae01132fca1571fc955d88090 | 23.403509 | 83 | 0.556434 | false | false | false | false |
LeoFangQ/CMSwiftUIKit | refs/heads/master | CMSwiftUIKit/Pods/EZSwiftExtensions/Sources/BlockButton.swift | mit | 7 | //
// BlockButton.swift
//
//
// Created by Cem Olcay on 12/08/15.
//
//
import UIKit
public typealias BlockButtonAction = (_ sender: BlockButton) -> Void
///Make sure you use "[weak self] (sender) in" if you are using the keyword self inside the closure or there might be a memory leak
open class BlockButton: UIButton {
// MARK: Propeties
open var highlightLayer: CALayer?
open var action: BlockButtonAction?
// MARK: Init
public init() {
super.init(frame: CGRect(x: 0, y: 0, width: 0, height: 0))
defaultInit()
}
public init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) {
super.init(frame: CGRect(x: x, y: y, width: w, height: h))
defaultInit()
}
public init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat, action: BlockButtonAction?) {
super.init (frame: CGRect(x: x, y: y, width: w, height: h))
self.action = action
defaultInit()
}
public init(action: @escaping BlockButtonAction) {
super.init(frame: CGRect.zero)
self.action = action
defaultInit()
}
public override init(frame: CGRect) {
super.init(frame: frame)
defaultInit()
}
public init(frame: CGRect, action: @escaping BlockButtonAction) {
super.init(frame: frame)
self.action = action
defaultInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
defaultInit()
}
private func defaultInit() {
addTarget(self, action: #selector(BlockButton.didPressed(_:)), for: UIControlEvents.touchUpInside)
addTarget(self, action: #selector(BlockButton.highlight), for: [UIControlEvents.touchDown, UIControlEvents.touchDragEnter])
addTarget(self, action: #selector(BlockButton.unhighlight), for: [
UIControlEvents.touchUpInside,
UIControlEvents.touchUpOutside,
UIControlEvents.touchCancel,
UIControlEvents.touchDragExit
])
setTitleColor(UIColor.black, for: UIControlState.normal)
setTitleColor(UIColor.blue, for: UIControlState.selected)
}
open func addAction(_ action: @escaping BlockButtonAction) {
self.action = action
}
// MARK: Action
open func didPressed(_ sender: BlockButton) {
action?(sender)
}
// MARK: Highlight
open func highlight() {
if action == nil {
return
}
let highlightLayer = CALayer()
highlightLayer.frame = layer.bounds
highlightLayer.backgroundColor = UIColor.black.cgColor
highlightLayer.opacity = 0.5
var maskImage: UIImage? = nil
UIGraphicsBeginImageContextWithOptions(layer.bounds.size, false, 0)
if let context = UIGraphicsGetCurrentContext() {
layer.render(in: context)
maskImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
let maskLayer = CALayer()
maskLayer.contents = maskImage?.cgImage
maskLayer.frame = highlightLayer.frame
highlightLayer.mask = maskLayer
layer.addSublayer(highlightLayer)
self.highlightLayer = highlightLayer
}
open func unhighlight() {
if action == nil {
return
}
highlightLayer?.removeFromSuperlayer()
highlightLayer = nil
}
}
| 9d85c8b36b91c5f017f0d49b3fedab42 | 28.807018 | 132 | 0.629782 | false | false | false | false |
PiXeL16/PasswordTextField | refs/heads/master | PasswordTextFieldTests/PasswordTextFieldSpecs.swift | mit | 1 | //
// PasswordTextFieldSpecs.swift
// PasswordTextField
//
// Created by Chris Jimenez on 2/11/16.
// Copyright © 2016 Chris Jimenez. All rights reserved.
//
import Foundation
import Nimble
import Quick
import PasswordTextField
//Specs for the delayer class
class PasswordTextFieldSpecs: QuickSpec {
override func spec() {
let passwordTextField = PasswordTextField()
it("initial values are correct"){
let passwordString = "1234Abcd8988!"
passwordTextField.text = passwordString
passwordTextField.imageTintColor = UIColor.red
passwordTextField.setSecureMode(false)
expect(passwordTextField.isValid()).to(beTrue())
expect(passwordTextField.errorMessage()).toNot(beNil())
expect(passwordTextField.showButtonWhile).to(equal(PasswordTextField.ShowButtonWhile.Editing))
expect(passwordTextField.imageTintColor).to(equal(UIColor.red))
expect(passwordTextField.secureTextButton.tintColor).to(equal(UIColor.red))
expect(passwordTextField.isSecureTextEntry).to(beFalse())
}
it("values are correct after button pressed"){
let passwordString = "love"
passwordTextField.text = passwordString
passwordTextField.secureTextButton.buttonTouch()
expect(passwordTextField.isValid()).to(beFalse())
expect(passwordTextField.errorMessage()).toNot(beNil())
expect(passwordTextField.secureTextButton.isSecure).to(beFalse())
expect(passwordTextField.isSecureTextEntry).to(beFalse())
}
it("validates with custom validator"){
let passwordString = "LOVE"
passwordTextField.text = passwordString
let validationRule = RegexRule(regex:"^[A-Z ]+$", errorMessage: "test")
passwordTextField.validationRule = validationRule
expect(passwordTextField.isValid()).to(beTrue())
expect(passwordTextField.errorMessage()).to(equal("test"))
}
}
}
| f07268ec86315f00a4f626908f6a39d0 | 29.571429 | 106 | 0.584962 | false | false | false | false |
BrandonMA/SwifterUI | refs/heads/master | SwifterUI/SwifterUI/UILibrary/Assets/SFColors.swift | mit | 1 | //
// SFAssets.swift
// SwifterUI
//
// Created by Brandon Maldonado on 25/12/17.
// Copyright © 2017 . All rights reserved.
//
import UIKit
/**
Main colors hand picked to work well on iOS
*/
public struct SFColors {
// MARK: - Static Properties
/**
HexCode: FFFFFF
*/
static public let white: UIColor = UIColor(hex: "FFFFFF")
/**
HexCode: 000000
*/
static public let black: UIColor = UIColor(hex: "000000")
/**
HexCode: E2E2E4
*/
static public let separatorWhite: UIColor = UIColor(hex: "E2E2E4")
/**
HexCode: 2B2B2D
*/
static public let separatorBlack: UIColor = UIColor(hex: "2B2B2D")
/**
HexCode: F7F7F7
*/
static public let alternativeWhite: UIColor = UIColor(hex: "F7F7F7")
/**
HexCode: 1A1A1A
*/
static public let alternativeBlack: UIColor = UIColor(hex: "0D0D0D")
/**
HexCode: E8E8E8
*/
static public let contrastWhite: UIColor = UIColor(hex: "E8E8E8")
/**
HexCode: 0F0F0F
*/
static public let contrastBlack: UIColor = UIColor(hex: "171717")
/**
HexCode: F0F0F0
*/
static public let gray: UIColor = UIColor(hex: "F0F0F0")
/**
HexCode: "CCCCCC"
*/
static public let lightGray: UIColor = UIColor(hex: "808080")
/**
HexCode: 999999
*/
static public let darkGray: UIColor = UIColor(hex: "B3B3B3")
/**
HexCode: FF941A
*/
static public let orange: UIColor = UIColor(hex: "FF941A")
/**
HexCode: 0088FF
*/
static public let blue: UIColor = UIColor(hex: "0088FF")
}
| e7c13ee3fe9ce3c5039aafc7bcd111e4 | 19.313253 | 72 | 0.569988 | false | false | false | false |
balazs630/Bob-Cat-Runner | refs/heads/develop | BobRunner/Model and state/Stage.swift | apache-2.0 | 1 | //
// Stage.swift
// BobRunner
//
// Created by Horváth Balázs on 2017. 10. 06..
// Copyright © 2017. Horváth Balázs. All rights reserved.
//
import SpriteKit
struct Stage {
static var maxCount: Int {
var stageNumber = 0
while SKScene(fileNamed: "Stage\(stageNumber + 1)") != nil {
stageNumber += 1
}
return stageNumber
}
static var current: Int {
get {
return UserDefaults.standard.integer(forKey: UserDefaults.Key.actualStage)
}
set(newStage) {
UserDefaults.standard.set(newStage, forKey: UserDefaults.Key.actualStage)
UserDefaults.standard.synchronize()
}
}
static var name: String {
return "Stage\(current)"
}
static var clouds: [String] {
var currentClouds = [String]()
(1...Constant.clouds[current]!).forEach { index in
currentClouds.append("cloud\(index)")
}
return currentClouds
}
static var rainIntensity: Double {
return Constant.rainIntensity[current]!
}
static func isAllCompleted() -> Bool {
return Stage.current == Stage.maxCount
}
}
| 09b963b1b333d81388e963652134f088 | 22.76 | 86 | 0.590909 | false | false | false | false |
ThePacielloGroup/CCA-OSX | refs/heads/master | Colour Contrast Analyser/CCAColourBrightnessDifferenceController.swift | gpl-3.0 | 1 | //
// ResultsController.swift
// Colour Contrast Analyser
//
// Created by Cédric Trévisan on 27/01/2015.
// Copyright (c) 2015 Cédric Trévisan. All rights reserved.
//
import Cocoa
class CCAColourBrightnessDifferenceController: NSViewController {
@IBOutlet weak var colourDifferenceText: NSTextField!
@IBOutlet weak var brightnessDifferenceText: NSTextField!
@IBOutlet weak var colourBrightnessSample: CCAColourBrightnessDifferenceField!
@IBOutlet weak var menuShowRGBSliders: NSMenuItem!
var fColor: NSColor = NSColor(red: 0, green: 0, blue: 0, alpha: 1.0)
var bColor: NSColor = NSColor(red: 1, green: 1, blue: 1, alpha: 1.0)
var colourDifferenceValue:Int?
var brightnessDifferenceValue:Int?
override func viewDidLoad() {
super.viewDidLoad()
// Do view setup here.
self.updateResults()
NotificationCenter.default.addObserver(self, selector: #selector(CCAColourBrightnessDifferenceController.updateForeground(_:)), name: NSNotification.Name(rawValue: "ForegroundColorChangedNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(CCAColourBrightnessDifferenceController.updateBackground(_:)), name: NSNotification.Name(rawValue: "BackgroundColorChangedNotification"), object: nil)
}
func updateResults() {
brightnessDifferenceValue = ColourBrightnessDifference.getBrightnessDifference(self.fColor, bc:self.bColor)
colourDifferenceValue = ColourBrightnessDifference.getColourDifference(self.fColor, bc:self.bColor)
colourDifferenceText.stringValue = String(format: NSLocalizedString("colour_diff", comment:"Colour difference: %d (minimum 500)"), colourDifferenceValue!)
brightnessDifferenceText.stringValue = String(format: NSLocalizedString("brightness_diff", comment:"Brightness difference: %d (minimum 125)"), brightnessDifferenceValue!)
colourBrightnessSample.validateColourBrightnessDifference(brightnessDifferenceValue!, colour: colourDifferenceValue!)
}
@objc func updateForeground(_ notification: Notification) {
self.fColor = notification.userInfo!["colorWithOpacity"] as! NSColor
self.updateResults()
var color:NSColor = self.fColor
// Fix for #3 : use almost black color
if (color.isBlack()) {
color = NSColor(red: 0.000001, green: 0, blue: 0, alpha: 1.0)
}
colourBrightnessSample.textColor = color
}
@objc func updateBackground(_ notification: Notification) {
self.bColor = notification.userInfo!["color"] as! NSColor
self.updateResults()
colourBrightnessSample.backgroundColor = self.bColor
}
}
| 17663438301bbd0b705e51a7e9755437 | 49.314815 | 223 | 0.729481 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.