repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
google/iosched-ios | Source/IOsched/Screens/Home/NoAnnoucementsBackgroundView.swift | 1 | 4014 | //
// Copyright (c) 2019 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import MaterialComponents
class NoAnnouncementsBackgroundView: UIView {
let label: UILabel = {
let label = UILabel()
label.font = ProductSans.regular.style(.body)
label.text = NSLocalizedString("There's no announcements to show right now.",
comment: "Hint for empty announcements screen")
label.numberOfLines = 2
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor(r: 32, g: 33, b: 36)
label.textAlignment = .center
return label
}()
public override init(frame: CGRect) {
super.init(frame: frame)
addSubview(label)
setupConstraints()
}
private func setupConstraints() {
let constraints: [NSLayoutConstraint] = [
NSLayoutConstraint(item: label,
attribute: .centerY,
relatedBy: .equal,
toItem: self,
attribute: .centerY,
multiplier: 1,
constant: 0),
NSLayoutConstraint(item: label,
attribute: .leading,
relatedBy: .equal,
toItem: self,
attribute: .leading,
multiplier: 1,
constant: 32),
NSLayoutConstraint(item: label,
attribute: .trailing,
relatedBy: .equal,
toItem: self,
attribute: .trailing,
multiplier: 1,
constant: -32)
]
addConstraints(constraints)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class NoAnnouncementsCollectionViewCell: UICollectionViewCell {
static var height: CGFloat {
return 140
}
private lazy var noAnnouncementsView = NoAnnouncementsBackgroundView(frame: contentView.frame)
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(noAnnouncementsView)
noAnnouncementsView.translatesAutoresizingMaskIntoConstraints = false
setupConstraints()
}
private func setupConstraints() {
let constraints = [
NSLayoutConstraint(item: noAnnouncementsView, attribute: .top,
relatedBy: .equal,
toItem: contentView, attribute: .top,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: noAnnouncementsView, attribute: .bottom,
relatedBy: .equal,
toItem: contentView, attribute: .bottom,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: noAnnouncementsView, attribute: .left,
relatedBy: .equal,
toItem: contentView, attribute: .left,
multiplier: 1, constant: 0),
NSLayoutConstraint(item: noAnnouncementsView, attribute: .right,
relatedBy: .equal,
toItem: contentView, attribute: .right,
multiplier: 1, constant: 0)
]
contentView.addConstraints(constraints)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| apache-2.0 | 3fb534727a4a3864b96357358273e867 | 33.016949 | 96 | 0.5857 | 5.281579 | false | false | false | false |
coderZsq/coderZsq.target.swift | StudyNotes/Swift Note/ObjC.io/Swift4/Functional/ParserCombinator.swift | 1 | 8973 | //
// ParserCombinator.swift
// Functional
//
// Created by 朱双泉 on 2018/5/22.
// Copyright © 2018 Castie!. All rights reserved.
//
import Foundation
#if false
typealias Parser<Result> = (String) -> (Result, String)?
#endif
#if false
typealias Stream = String.CharacterView
typealias Parser<Result> = (Stream) -> (Result, Stream)?
#endif
struct Parser<Result> {
typealias Stream = String.CharacterView
let parse: (Stream) -> (Result, Stream)?
}
func character(matching condition: @escaping (Character) -> Bool) -> Parser<Character> {
return Parser(parse: { input in
guard let char = input.first, condition(char) else { return nil }
return (char, input.dropFirst())
})
}
class ParserCombinator {
static func run() {
let one = character { $0 == "1" }
print(one.parse("123".characters))
}
}
extension Parser {
func run(_ string: String) -> (Result, String)? {
guard let (result, reminder) = parse(string.characters) else { return nil }
return (result, String(reminder))
}
}
extension ParserCombinator {
static func run2() {
let one = character { $0 == "1" }
print(one.run("123"))
}
}
extension CharacterSet {
func contains(_ c: Character) -> Bool {
let scalars = String(c).unicodeScalars
guard scalars.count == 1 else { return false }
return contains(scalars.first!)
}
}
extension ParserCombinator {
static func run3() {
let digit = character { CharacterSet.decimalDigits.contains($0) }
print(digit.run("456"))
}
}
extension Parser {
var many: Parser<[Result]> {
return Parser<[Result]> { input in
var result: [Result] = []
var remainder = input
while let (element, newRemainder) = self.parse(remainder) {
result.append(element)
remainder = newRemainder
}
return (result, remainder)
}
}
}
extension ParserCombinator {
static func run4() {
let digit = character { CharacterSet.decimalDigits.contains($0) }
print(digit.many.run("123"))
}
}
extension Parser {
func map<T>(_ transform: @escaping (Result) -> T) -> Parser<T> {
return Parser<T> { input in
guard let (result, remainder) = self.parse(input) else { return nil }
return (transform(result), remainder)
}
}
}
extension ParserCombinator {
static func run5() {
let digit = character { CharacterSet.decimalDigits.contains($0) }
let integer = digit.many.map { Int(String($0))! }
print(integer.run("123"))
print(integer.run("123abc"))
}
}
extension Parser {
func followed<A>(by other: Parser<A>) -> Parser<(Result, A)> {
return Parser<(Result, A)> { input in
guard let (result1, remainder1) = self.parse(input) else { return nil }
guard let (result2, remainder2) = other.parse(remainder1) else { return nil }
return ((result1, result2), remainder2)
}
}
}
extension ParserCombinator {
static func run6() {
let digit = character { CharacterSet.decimalDigits.contains($0) }
let integer = digit.many.map { Int(String($0))! }
let multiplication = integer
.followed(by: character { $0 == "*" })
.followed(by: integer)
print(multiplication.run("2*3"))
let multiplication2 = multiplication.map { $0.0 * $1 }
print(multiplication2.run("2*3"))
}
}
#if false
func multiply(lhs: (Int, Character), rhs: Int) -> Int {
return lhs.0 * rhs
}
#endif
func multiply(_ x: Int, _ op: Character, _ y: Int) -> Int {
return x * y
}
func curriedMultiply(_ x: Int) -> (Character) -> (Int) -> Int {
return { op in
return { y in
return x * y
}
}
}
extension ParserCombinator {
static func run7() {
print(curriedMultiply(2)("*")(3))
}
}
func curry<A, B, C>(_ f: @escaping (A, B) -> C) -> (A) -> (B) -> C {
return { a in { b in f(a, b) } }
}
extension ParserCombinator {
static func run8() {
let digit = character { CharacterSet.decimalDigits.contains($0) }
let integer = digit.many.map { Int(String($0))! }
let p1 = integer.map(curriedMultiply)
let p2 = p1.followed(by: character { $0 == "*" })
let p3 = p2.map { f, op in f(op) }
let p4 = p3.followed(by: integer)
let p5 = p4.map { f, y in f(y) }
print(p5.run("2*3"))
let multiplication3 = integer.map(curriedMultiply)
.followed(by: character { $0 == "*" }).map { f, op in f(op) }
.followed(by: integer).map { f, y in f(y) }
print(multiplication3.run("4*5"))
}
}
infix operator <*>: SequencePrecedence
precedencegroup SequencePrecedence {
associativity: left
higherThan: AdditionPrecedence
}
//func <*>(lhs: Parser<...>, rhs: Parser<...>) -> Parser<...> {
// return lhs.followed(by: rhs).map { f, x in f(x) }
//}
func <*><A, B>(lhs: Parser<(A) -> B>, rhs: Parser<A>) -> Parser<B> {
return lhs.followed(by: rhs).map { f, x in f(x) }
}
extension ParserCombinator {
static func run9() {
let digit = character { CharacterSet.decimalDigits.contains($0) }
let integer = digit.many.map { Int(String($0))! }
let multiplication4 = integer.map(curriedMultiply)<*>character { $0 == "*" }<*>integer
print(multiplication4.run("3*7"))
}
}
infix operator <^>: SequencePrecedence
func <^><A, B>(lhs: @escaping (A) -> B, rhs: Parser<A>) -> Parser<B> {
return rhs.map(lhs)
}
extension ParserCombinator {
static func run10() {
let digit = character { CharacterSet.decimalDigits.contains($0) }
let integer = digit.many.map { Int(String($0))! }
let multiplication5 = curriedMultiply<^>integer<*>character { $0 == "*" }<*>integer
print(multiplication5.run("5*7"))
// print(multiply(integer, character { $0 == "*" }, integer)
}
}
infix operator *>: SequencePrecedence
func *><A, B>(lhs: Parser<A>, rhs: Parser<B>) -> Parser<B> {
return curry({ _, y in y })<^>lhs<*>rhs
}
infix operator <*: SequencePrecedence
func <*<A, B>(lhs: Parser<A>, rhs: Parser<B>) -> Parser<A> {
return curry({x, _ in x})<^>lhs<*>rhs
}
extension Parser {
func or(_ other: Parser<Result>) -> Parser<Result> {
return Parser<Result> { input in
return self.parse(input) ?? other.parse(input)
}
}
}
extension ParserCombinator {
static func run11() {
let star = character { $0 == "*" }
let plus = character { $0 == "+" }
let starOrPlus = star.or(plus)
print(starOrPlus.run("+"))
}
}
infix operator <|>
func <|><A>(lhs: Parser<A>, rhs: Parser<A>) -> Parser<A> {
return lhs.or(rhs)
}
extension ParserCombinator {
static func run12() {
let star = character { $0 == "*" }
let plus = character { $0 == "+" }
print((star<|>plus).run("+"))
}
}
extension Parser {
#if false
var many1: Parser<[Result]> {
return { x in { manyX in [x] + manyX } }<^>self<*>self.many
}
#endif
var many1: Parser<[Result]> {
return curry({ [$0] + $1 })<^>self<*>self.many
}
}
extension Parser {
var optional: Parser<Result?> {
return Parser<Result?> { input in
guard let (result, remainder) = self.parse(input) else { return (nil, input) }
return (result, remainder)
}
}
}
extension ParserCombinator {
static func run13() {
let digit = character { CharacterSet.decimalDigits.contains($0) }
let integer = digit.many.map { Int(String($0))! }
let multiplication = curry({ $0 * ($1 ?? 1) })<^>integer<*>(character { $0 == "*" } *> integer).optional
let division = curry({ $0 / ($1 ?? 1) })<^>multiplication<*>(character { $0 == "/" } *> multiplication).optional
let addition = curry({$0 + ($1 ?? 0) })<^>division<*>(character { $0 == "+" } *> division).optional
let minus = curry({ $0 - ($1 ?? 0) })<^>addition<*>(character { $0 == "-" } *> addition).optional
let expression = minus
print(expression.run("2*3+4*6/2-10"))
}
}
struct Parser2<Result> {
typealias Stream = String.CharacterView
let parse: (inout Stream) -> Result?
}
extension Parser2 {
var many: Parser2<[Result]> {
return Parser2<[Result]> { input in
var result: [Result] = []
while let element = self.parse(&input) {
result.append(element)
}
return result
}
}
}
extension Parser2 {
func or(_ other: Parser2<Result>) -> Parser2<Result> {
return Parser2<Result> { input in
let original = input
if let result = self.parse(&input) { return result }
input = original
return other.parse(&input)
}
}
}
| mit | 6bae62197acb840647d7e30068cb31f6 | 27.463492 | 120 | 0.568927 | 3.638799 | false | false | false | false |
KrishMunot/swift | test/Serialization/transparent.swift | 1 | 3740 | // RUN: rm -rf %t
// RUN: mkdir %t
// RUN: %target-swift-frontend -emit-module -sil-serialize-all -o %t %S/Inputs/def_transparent.swift
// RUN: llvm-bcanalyzer %t/def_transparent.swiftmodule | FileCheck %s
// RUN: %target-swift-frontend -emit-silgen -sil-link-all -I %t %s | FileCheck %s -check-prefix=SIL
// CHECK-NOT: UnknownCode
import def_transparent
// SIL-LABEL: sil @main : $@convention(c) (Int32, UnsafeMutablePointer<UnsafeMutablePointer<Int8>>) -> Int32 {
// SIL: [[RAW:%.+]] = global_addr @_Tv11transparent3rawSb : $*Bool
// SIL: [[FUNC:%.+]] = function_ref @_TF15def_transparent15testTransparentFT1xSb_Sb : $@convention(thin) (Bool) -> Bool
// SIL: [[RESULT:%.+]] = apply [[FUNC]]({{%.+}}) : $@convention(thin) (Bool) -> Bool
// SIL: store [[RESULT]] to [[RAW]] : $*Bool
var raw = testTransparent(x: false)
// SIL: [[TMP:%.+]] = global_addr @_Tv11transparent3tmpVs5Int32 : $*Int32
// SIL: [[FUNC2:%.+]] = function_ref @_TF15def_transparent11testBuiltinFT_Vs5Int32 : $@convention(thin) () -> Int32
// SIL: [[RESULT2:%.+]] = apply [[FUNC2]]() : $@convention(thin) () -> Int32
// SIL: store [[RESULT2]] to [[TMP]] : $*Int32
var tmp = testBuiltin()
// SIL-LABEL: sil public_external [transparent] [fragile] @_TF15def_transparent15testTransparentFT1xSb_Sb : $@convention(thin) (Bool) -> Bool {
// SIL: bb0(%0 : $Bool):
// SIL: return %0 : $Bool
// SIL-LABEL: sil public_external [transparent] [fragile] @_TF15def_transparent11testBuiltinFT_Vs5Int32 : $@convention(thin) () -> Int32 {
// SIL: bb0:
// SIL: integer_literal $Builtin.Int32, 300
// SIL: string_literal utf8 "foo"
// SIL: return %{{.*}} : $Int32
// SIL-LABEL: sil public_external [transparent] [fragile] @_TF15def_transparent7test_brFT_T_ : $@convention(thin) () -> () {
// SIL: bb{{.*}}:
// SIL: cond_br %{{.*}}, bb{{.*}}, bb{{.*}}
// SIL: bb{{.*}}:
// SIL: br bb{{.*}}
func wrap_br() {
test_br()
}
// SIL-LABEL: sil public_external [fragile] @_TF15def_transparent9do_switchFT1uOS_9MaybePair_T_ : $@convention(thin) (@owned MaybePair) -> () {
// SIL: bb0(%0 : $MaybePair):
// SIL: retain_value %0 : $MaybePair
// SIL: switch_enum %0 : $MaybePair, case #MaybePair.Neither!enumelt: bb[[CASE1:[0-9]+]], case #MaybePair.Left!enumelt.1: bb[[CASE2:[0-9]+]], case #MaybePair.Right!enumelt.1: bb[[CASE3:[0-9]+]], case #MaybePair.Both!enumelt.1: bb[[CASE4:[0-9]+]]
// SIL: bb[[CASE1]]:
// SIL: bb[[CASE2]](%{{.*}} : $Int32):
// SIL: bb[[CASE3]](%{{.*}} : $String):
// SIL: bb[[CASE4]](%{{.*}} : $(Int32, String)):
func test_switch(u: MaybePair) {
do_switch(u: u)
}
// SIL-LABEL: sil public_external [transparent] [fragile] @_TFV15def_transparent7WrapperCfT3ValVs5Int32_S0_ : $@convention(method) (Int32, @thin Wrapper.Type) -> Wrapper {
// SIL-LABEL: sil public_external [transparent] [fragile] @_TFV15def_transparent7Wrapper8getValue{{.*}} : $@convention(method) (Wrapper) -> Int32 {
// SIL-LABEL: sil public_external [transparent] [fragile] @_TFV15def_transparent7Wrapperg10valueAgainVs5Int32 : $@convention(method) (Wrapper) -> Int32 {
// SIL-LABEL: sil public_external [transparent] [fragile] @_TFV15def_transparent7Wrapper13getValueAgain{{.*}} : $@convention(method) (Wrapper) -> Int32 {
func test_wrapper() {
var w = Wrapper(Val: 42)
print(w.value, terminator: "")
print(w.getValue(), terminator: "")
print(w.valueAgain, terminator: "")
print(w.getValueAgain(), terminator: "")
}
// SIL-LABEL: sil public_external [transparent] [fragile] @_TF15def_transparent17open_existentialsFT1pPS_1P_2cpPS_2CP__T_
func test_open_existentials(p: P, cp: CP) {
// SIL: open_existential_addr [[EXIST:%[0-9]+]] : $*P to $*@opened([[N:".*"]]) P
// SIL: open_existential_ref [[EXIST:%[0-9]+]] : $CP to $@opened([[M:".*"]]) CP
open_existentials(p: p, cp: cp)
}
| apache-2.0 | f2f7e56473cbde58a93399d90620c950 | 50.232877 | 245 | 0.649198 | 3.101161 | false | true | false | false |
AshuMishra/BMSLocationFinder | BMSLocationFinder/BMSLocationFinder/View Classes/ListCell.swift | 1 | 2298 | //
// ListCell.swift
// BMSLocationFinder
//
// Created by Ashutosh on 03/04/2015.
// Copyright (c) 2015 Ashutosh. All rights reserved.
//
import Foundation
import UIKit
import CoreLocation
class ListCell: UITableViewCell {
@IBOutlet weak var distanceLabel: UILabel!
@IBOutlet weak var placeImageView: UIImageView!
@IBOutlet weak var placeName: UILabel!
@IBOutlet weak var favoritePlaceImageView: UIImageView!
var place:Place!
func configure(#placeObject:Place) {
//Configure cell in ListView Controller
self.place = placeObject
placeName.text = placeObject.placeName
distanceLabel.text = NSString(format: "%.2lf Km.", placeObject.distance/1000)
//To check Whether this place is favorite is not using it's loaction and apply image according to that.
var favoritePlace: NSManagedObject? = DataModel.sharedModel.fetchFavoritePlacesForId(place!.placeId)
var imageName = (favoritePlace != nil) ? "favorite_selected.png" : "favorite_unselected.png"
self.favoritePlaceImageView.image = UIImage(named: imageName)
//Load image asynchronously.
self.loadAsynchronousImage()
}
func loadAsynchronousImage() {
// If the image does not exist, we need to download it
var imgURL: NSURL = NSURL(string: place.iconUrl)!
// Download an NSData representation of the image at the URL
let request: NSURLRequest = NSURLRequest(URL: imgURL)
var checkInternetConnection:Bool = IJReachability.isConnectedToNetwork()
if checkInternetConnection {
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue(), completionHandler: {(response: NSURLResponse!,data: NSData!,error: NSError!) -> Void in
if error == nil {
// Store the image in to our cache
dispatch_async(dispatch_get_main_queue(), {
self.placeImageView.image = UIImage(data: data)
})
}
else {
UIAlertView(title: "Error", message: error.localizedDescription, delegate: nil, cancelButtonTitle: "OK").show()
}
})
}
}
}
| mit | 428219d2d3d6988e8fc24f6a554b5ec4 | 36.672131 | 185 | 0.638381 | 4.941935 | false | false | false | false |
adrfer/swift | test/1_stdlib/Reflection_objc.swift | 11 | 8532 | // RUN: rm -rf %t && mkdir %t
//
// RUN: %target-clang %S/Inputs/Mirror/Mirror.mm -c -o %t/Mirror.mm.o -g
// RUN: %target-build-swift -parse-stdlib %s -module-name Reflection -I %S/Inputs/Mirror/ -Xlinker %t/Mirror.mm.o -o %t/a.out
// RUN: %S/timeout.sh 360 %target-run %t/a.out %S/Inputs/shuffle.jpg | FileCheck %s
// REQUIRES: executable_test
// FIXME: timeout wrapper is necessary because the ASan test runs for hours
//
// DO NOT add more tests to this file. Add them to test/1_stdlib/Runtime.swift.
//
// XFAIL: linux
import Swift
import Foundation
#if os(OSX)
import AppKit
typealias OSImage = NSImage
typealias OSColor = NSColor
typealias OSBezierPath = NSBezierPath
#endif
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
typealias OSImage = UIImage
typealias OSColor = UIColor
typealias OSBezierPath = UIBezierPath
#endif
// Check ObjC mirror implementation.
// CHECK-LABEL: ObjC:
print("ObjC:")
// CHECK-NEXT: <NSObject: {{0x[0-9a-f]+}}>
dump(NSObject())
// CHECK-LABEL: ObjC subclass:
print("ObjC subclass:")
// CHECK-NEXT: woozle wuzzle
dump("woozle wuzzle" as NSString)
// Test a mixed Swift-ObjC hierarchy.
class NSGood : NSObject {
let x: Int = 22
}
class NSBetter : NSGood {
let y: String = "333"
}
// CHECK-LABEL: Swift ObjC subclass:
// CHECK-NEXT: Reflection.NSBetter #0
// CHECK-NEXT: super: Reflection.NSGood
// CHECK-NEXT: super: <Reflection.NSBetter: {{0x[0-9a-f]+}}>
print("Swift ObjC subclass:")
dump(NSBetter())
// CHECK-LABEL: ObjC quick look objects:
print("ObjC quick look objects:")
// CHECK-LABEL: ObjC enums:
print("ObjC enums:")
// CHECK-NEXT: We cannot reflect NSComparisonResult yet
print("We cannot reflect \(NSComparisonResult.OrderedAscending) yet")
// Don't crash when introspecting framework types such as NSURL.
// <rdar://problem/16592777>
// CHECK-LABEL: NSURL:
// CHECK-NEXT: file:///Volumes/
print("NSURL:")
dump(NSURL(fileURLWithPath: "/Volumes", isDirectory: true))
// -- Check that quick look Cocoa objects get binned correctly to their
// associated enum tag.
// CHECK-NEXT: got the expected quick look text
switch _reflect("woozle wuzzle" as NSString).quickLookObject {
case .Some(.Text("woozle wuzzle")):
print("got the expected quick look text")
case _:
print("got something else")
}
// CHECK-NEXT: foobar
let somesubclassofnsstring = ("foo" + "bar") as NSString
switch _reflect(somesubclassofnsstring).quickLookObject {
case .Some(.Text(let text)): print(text)
default: print("not the expected quicklook")
}
// CHECK-NEXT: got the expected quick look attributed string
let astr = NSAttributedString(string: "yizzle pizzle")
switch _reflect(astr as NSAttributedString).quickLookObject {
case .Some(.AttributedString(let astr2 as NSAttributedString))
where astr === astr2:
print("got the expected quick look attributed string")
case _:
print("got something else")
}
// CHECK-NEXT: got the expected quick look int
switch _reflect(Int.max as NSNumber).quickLookObject {
case .Some(.Int(+Int64(Int.max))):
print("got the expected quick look int")
case _:
print("got something else")
}
// CHECK-NEXT: got the expected quick look uint
switch _reflect(NSNumber(unsignedLongLong: UInt64.max)).quickLookObject {
case .Some(.UInt(UInt64.max)):
print("got the expected quick look uint")
case _:
print("got something else")
}
// CHECK-NEXT: got the expected quick look double
switch _reflect(22.5 as NSNumber).quickLookObject {
case .Some(.Double(22.5)):
print("got the expected quick look double")
case _:
print("got something else")
}
// CHECK-NEXT: got the expected quick look float
switch _reflect(Float32(1.25)).quickLookObject {
case .Some(.Float(1.25)):
print("got the expected quick look float")
case _:
print("got something else")
}
// CHECK-NEXT: got the expected quick look image
// CHECK-NEXT: got the expected quick look color
// CHECK-NEXT: got the expected quick look bezier path
let image = OSImage(contentsOfFile:Process.arguments[1])!
switch _reflect(image).quickLookObject {
case .Some(.Image(let image2 as OSImage)) where image === image2:
print("got the expected quick look image")
case _:
print("got something else")
}
let color = OSColor.blackColor()
switch _reflect(color).quickLookObject {
case .Some(.Color(let color2 as OSColor)) where color === color2:
print("got the expected quick look color")
case _:
print("got something else")
}
let path = OSBezierPath()
switch _reflect(path).quickLookObject {
case .Some(.BezierPath(let path2 as OSBezierPath)) where path === path2:
print("got the expected quick look bezier path")
case _:
print("got something else")
}
let intNSArray : NSArray = [1 as NSNumber,2 as NSNumber,3 as NSNumber,4 as NSNumber,5 as NSNumber]
let intNSArrayMirror = _reflect(intNSArray)
// CHECK-NEXT: 5 elements
print(intNSArrayMirror.summary)
// CHECK-NEXT: [0]: 1
print("\(intNSArrayMirror[0].0): \(intNSArrayMirror[0].1.summary)")
// CHECK-NEXT: [4]: 5
print("\(intNSArrayMirror[4].0): \(intNSArrayMirror[4].1.summary)")
let numset = NSSet(objects: 1,2,3,4)
let numsetMirror = _reflect(numset)
// CHECK-NEXT: 4 elements
print(numsetMirror.summary)
// CHECK-NEXT: I see all four elements
let num0 = (numsetMirror[0].1.summary)
let num1 = (numsetMirror[1].1.summary)
let num2 = (numsetMirror[2].1.summary)
let num3 = (numsetMirror[3].1.summary)
let have1 = (num0 == "1" || num1 == "1" || num2 == "1" || num3 == "1")
let have2 = (num0 == "2" || num1 == "2" || num2 == "2" || num3 == "2")
let have3 = (num0 == "3" || num1 == "3" || num2 == "3" || num3 == "3")
let have4 = (num0 == "4" || num1 == "4" || num2 == "4" || num3 == "4")
if have1 && have2 && have3 && have4 {
print("I see all four elements")
} else {
print("I see \(num0), \(num1), \(num2), \(num3)")
}
// CHECK-NEXT: 42
class MyQLTestClass {
@objc func debugQuickLookObject() -> AnyObject {
return (42 as NSNumber)
}
}
switch _reflect(MyQLTestClass()).quickLookObject {
case .Some(.Int(let value)): print(value)
case .Some(_): print("non-Int object")
default: print("None")
}
// CHECK-NEXT: nil is good here
class MyNonQLTestClass {
func debugQuickLookObject() -> AnyObject {
return (42 as NSNumber)
}
}
switch _reflect(MyNonQLTestClass()).quickLookObject {
case .Some(.Int(let value)): print(value)
case .Some(_): print("non-Int object")
default: print("nil is good here")
}
// CHECK-NEXT: (3.0, 6.0)
print(_reflect(CGPoint(x: 3,y: 6)).summary)
// CHECK-NEXT: (30.0, 60.0)
print(_reflect(CGSize(width: 30, height: 60)).summary)
// CHECK-NEXT: (50.0, 60.0, 100.0, 150.0)
print(_reflect(CGRect(x: 50, y: 60, width: 100, height: 150)).summary)
// rdar://problem/18513769 -- Make sure that QuickLookObject lookup correctly
// manages memory.
@objc class CanaryBase {
deinit {
print("\(self.dynamicType) overboard")
}
required init() { }
}
var CanaryHandle = false
class IsDebugQLO : CanaryBase, CustomStringConvertible {
@objc var description: String {
return "I'm a QLO"
}
}
class HasDebugQLO : CanaryBase {
@objc var debugQuickLookObject: AnyObject {
return IsDebugQLO()
}
}
class HasNumberQLO : CanaryBase {
@objc var debugQuickLookObject: AnyObject {
let number = NSNumber(integer: 97210)
return number
}
}
class HasAttributedQLO : CanaryBase {
@objc var debugQuickLookObject: AnyObject {
let str = NSAttributedString(string: "attributed string")
objc_setAssociatedObject(str, &CanaryHandle, CanaryBase(),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return str
}
}
class HasStringQLO : CanaryBase {
@objc var debugQuickLookObject: AnyObject {
let str = NSString(string: "plain string")
objc_setAssociatedObject(str, &CanaryHandle, CanaryBase(),
.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return str
}
}
func testQLO<T : CanaryBase>(type: T.Type) {
autoreleasepool {
_ = _reflect(type.init()).quickLookObject
}
}
testQLO(IsDebugQLO.self)
// CHECK-NEXT: IsDebugQLO overboard
testQLO(HasDebugQLO.self)
// CHECK-NEXT: HasDebugQLO overboard
// CHECK-NEXT: IsDebugQLO overboard
testQLO(HasNumberQLO.self)
// CHECK-NEXT: HasNumberQLO overboard
// TODO: tagged numbers are immortal, so we can't reliably check for
// cleanup here
testQLO(HasAttributedQLO.self)
// CHECK-NEXT: HasAttributedQLO overboard
// CHECK-NEXT: CanaryBase overboard
testQLO(HasStringQLO.self)
// CHECK-NEXT: HasStringQLO overboard
// CHECK-NEXT: CanaryBase overboard
// CHECK-LABEL: and now our song is done
print("and now our song is done")
| apache-2.0 | 958edbae1763eb6a25ae45ca6a737df1 | 27.065789 | 125 | 0.697961 | 3.44171 | false | false | false | false |
josherick/DailySpend | DailySpend/CalendarPeriodPickerTableViewCell.swift | 1 | 1236 | //
// DatePickerTableViewCell.swift
// DailySpend
//
// Created by Josh Sherick on 9/9/17.
// Copyright © 2017 Josh Sherick. All rights reserved.
//
import UIKit
class CalendarPeriodPickerTableViewCell: UITableViewCell, CalendarPeriodPickerViewDelegate {
var periodPicker: CalendarPeriodPickerView!
private var changedCallback: ((CalendarDateProvider, PeriodScope) -> ())?
override func layoutSubviews() {
super.layoutSubviews()
if periodPicker != nil {
periodPicker.frame = bounds
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
periodPicker = CalendarPeriodPickerView()
self.addSubview(periodPicker)
periodPicker.calendarPickerDelegate = self
self.clipsToBounds = true
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func changedToDate(date: CalendarDateProvider, scope: PeriodScope) {
changedCallback?(date, scope)
}
func setCallback(_ cb: @escaping ((CalendarDateProvider, PeriodScope) -> ())) {
changedCallback = cb
}
}
| mit | f0b194bc1001cae29f818b25f0d3a589 | 27.068182 | 92 | 0.661538 | 4.979839 | false | false | false | false |
wj2061/WJBarCodeScanner | BarcodeScanDemo/WJBarCodeScaner/WJScanView.swift | 1 | 4738 | //
// WJScanView.swift
// BarcodeScanDemo
//
// Created by WJ on 15/12/4.
// Copyright © 2015年 wj. All rights reserved.
//
import UIKit
let kScanLineAnimateDuration:TimeInterval = 0.02
let kCornerStrokelength:CGFloat = 15
class WJScanView: UIView {
public var transparentArea = CGRect(){//area to be scanned
didSet{
setNeedsDisplay()
setNeedsLayout()
}
}
public var isShowScanLine = true
public var scanColor = UIColor.green{//scanLine's color
didSet{
setNeedsDisplay()
setNeedsLayout()
}
}
fileprivate var timer : Timer?
fileprivate var scanLine = UIImageView()
override init(frame: CGRect) {
super.init(frame: frame)
backgroundColor = UIColor.clear
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
backgroundColor = UIColor.clear
}
deinit{
timer?.invalidate()
timer = nil
}
override func layoutSubviews() {
super.layoutSubviews()
if isShowScanLine{
initScanLine()
weak var weakSelf = self
timer = Timer.scheduledTimer(timeInterval: kScanLineAnimateDuration,
target: weakSelf!,
selector: #selector(WJScanView.scan),
userInfo: nil,
repeats: true)
}
}
fileprivate func initScanLine(){
scanLine.frame = CGRect(x: transparentArea.origin.x,
y: transparentArea.origin.y,
width: transparentArea.width,
height: 2)
scanLine.contentMode = .scaleAspectFill
let scanImage = UIImage(named: "WJScanLine")!
scanLine.image = scanImage.withRenderingMode(.alwaysTemplate)
scanLine.tintColor = scanColor
self.addSubview(scanLine)
}
func scan(){
UIView.animate(withDuration: kScanLineAnimateDuration, animations: { () -> Void in
var point = self.scanLine.center
if self.transparentArea.contains(self.scanLine.frame){
point.y += 1
}else {
point.y = self.transparentArea.minY + 1
}
self.scanLine.center = point
})
}
override func draw(_ rect: CGRect) {
let ctx = UIGraphicsGetCurrentContext()
ctx?.setFillColor(red: 40/255.0, green: 40/255.0, blue: 40/255.0, alpha: 0.5)
ctx?.fill(bounds) //dim background
ctx?.clear(transparentArea) // clear transparentArea
let path = UIBezierPath(rect: transparentArea)
path.lineWidth = 1
UIColor.white.setStroke()
path.stroke()
addCornerLineWithContext(ctx!, rect: transparentArea)
}
fileprivate func addCornerLineWithContext(_ ctx:CGContext,rect:CGRect){
ctx.setLineWidth(2)
let components = scanColor.cgColor.components
ctx.setStrokeColor(red: (components?[0])!, green: (components?[1])!, blue: (components?[2])!, alpha: (components?[3])!)
let upLreftPoints = [CGPoint(x: rect.origin.x, y: rect.origin.y+kCornerStrokelength),
rect.origin,
CGPoint(x: rect.origin.x+kCornerStrokelength, y: rect.origin.y)]
ctx.addLines(between:upLreftPoints)
let upRightPoint = CGPoint(x: rect.maxX, y: rect.origin.y)
let upRightPoints = [CGPoint(x: upRightPoint.x-kCornerStrokelength, y: upRightPoint.y),
upRightPoint,
CGPoint(x: upRightPoint.x, y: upRightPoint.y+kCornerStrokelength)]
ctx.addLines(between:upRightPoints);
let downLeftPoint = CGPoint(x: rect.origin.x, y: rect.maxY)
let downLeftPoints = [CGPoint(x: downLeftPoint.x, y: downLeftPoint.y-kCornerStrokelength),
downLeftPoint,
CGPoint(x: downLeftPoint.x+kCornerStrokelength, y: downLeftPoint.y)]
ctx.addLines(between:downLeftPoints);
let downRightPoint = CGPoint(x: rect.maxX, y: rect.maxY)
let downRightPoints = [CGPoint(x: downRightPoint.x-kCornerStrokelength, y: downRightPoint.y),
downRightPoint,
CGPoint(x: downRightPoint.x, y: downRightPoint.y-kCornerStrokelength)]
ctx.addLines(between:downRightPoints);
ctx.strokePath()
}
}
| mit | 782c8665ab47445bea409978c35771d8 | 34.601504 | 127 | 0.560084 | 4.651277 | false | false | false | false |
slightair/SwiftUtilities | SwiftUtilities/Data/BitRange.swift | 2 | 7227 | //
// BitRange.swift
// BinaryTest
//
// Created by Jonathan Wight on 6/24/15.
//
// Copyright (c) 2014, Jonathan Wight
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
import Foundation
public func bitRange <T: UnsignedIntegerType> (value: T, start: Int, length: Int, flipped: Bool = false) -> T {
assert(sizeof(T) <= sizeof(UIntMax))
let bitSize = UIntMax(sizeof(T) * 8)
assert(start + length <= Int(bitSize))
if flipped {
let shift = bitSize - UIntMax(start) - UIntMax(length)
let mask = (1 << UIntMax(length)) - 1
let intermediate = value.toUIntMax() >> shift & mask
let result = intermediate
return T.init(result)
}
else {
let shift = UIntMax(start)
let mask = (1 << UIntMax(length)) - 1
let result = value.toUIntMax() >> shift & mask
return T.init(result)
}
}
public func bitRange <T: UnsignedIntegerType> (value: T, range: Range <Int>, flipped: Bool = false) -> T {
return bitRange(value, start: range.startIndex, length: range.endIndex - range.startIndex, flipped: flipped)
}
// MARK: -
public func bitRange <Element>(buffer: UnsafeBufferPointer <Element>, start: Int, length: Int) -> UIntMax {
let pointer = UnsafePointer <Void> (buffer.baseAddress)
// Fast path; we want whole integers and the range is aligned to integer size.
if length == 64 && start % 64 == 0 {
return UnsafePointer <UInt64> (pointer)[start / 64]
}
else if length == 32 && start % 32 == 0 {
return UIntMax(UnsafePointer <UInt32> (pointer)[start / 32])
}
else if length == 16 && start % 16 == 0 {
return UIntMax(UnsafePointer <UInt16> (pointer)[start / 16])
}
else if length == 8 && start % 8 == 0 {
return UIntMax(UnsafePointer <UInt8> (pointer)[start / 8])
}
else {
// Slow(er) path. Range is not aligned.
let pointer = UnsafePointer <UIntMax> (pointer)
let wordSize = sizeof(UIntMax) * 8
let end = start + length
if start / wordSize == (end - 1) / wordSize {
// Bit range does not cross two words
let offset = start / wordSize
let result = bitRange(pointer[offset].bigEndian, start: start % wordSize, length: length, flipped: true)
return result
}
else {
// Bit range spans two words, get bit ranges for both words and then combine them.
let offset = start / wordSize
let offsettedStart = start % wordSize
let msw = bitRange(pointer[offset].bigEndian, range: offsettedStart ..< wordSize, flipped: true)
let bits = (end - offset * wordSize) % wordSize
let lsw = bitRange(pointer[offset + 1].bigEndian, range: 0 ..< bits, flipped: true)
return msw << UIntMax(bits) | lsw
}
}
}
public func bitRange <Element>(buffer: UnsafeBufferPointer <Element>, range: Range <Int>) -> UIntMax {
return bitRange(buffer, start: range.startIndex, length: range.endIndex - range.startIndex)
}
// MARK: -
public func bitSet <T: UnsignedIntegerType> (value: T, start: Int, length: Int, flipped: Bool = false, newValue: T) -> T {
assert(start + length <= sizeof(T) * 8)
let mask: T = onesMask(start: start, length: length, flipped: flipped)
let shift = UIntMax(flipped == false ? start: (sizeof(T) * 8 - start - length))
let shiftedNewValue = newValue.toUIntMax() << UIntMax(shift)
let result = (value.toUIntMax() & ~mask.toUIntMax()) | (shiftedNewValue & mask.toUIntMax())
return T(result)
}
public func bitSet <T: UnsignedIntegerType> (value: T, range: Range <Int>, flipped: Bool = false, newValue: T) -> T {
return bitSet(value, start: range.startIndex, length: range.endIndex - range.startIndex, flipped: flipped, newValue: newValue)
}
// MARK: -
public func bitSet <Element>(buffer: UnsafeMutableBufferPointer <Element>, start: Int, length: Int, newValue: UIntMax) {
let pointer = UnsafeMutablePointer <Void> (buffer.baseAddress)
// Fast path; we want whole integers and the range is aligned to integer size.
if length == 64 && start % 64 == 0 {
UnsafeMutablePointer <UInt64> (pointer)[start / 64] = newValue
}
else if length == 32 && start % 32 == 0 {
UnsafeMutablePointer <UInt32> (pointer)[start / 32] = UInt32(newValue)
}
else if length == 16 && start % 16 == 0 {
UnsafeMutablePointer <UInt16> (pointer)[start / 16] = UInt16(newValue)
}
else if length == 8 && start % 8 == 0 {
UnsafeMutablePointer <UInt8> (pointer)[start / 8] = UInt8(newValue)
}
else {
// Slow(er) path. Range is not aligned.
let pointer = UnsafeMutablePointer <UIntMax> (pointer)
let wordSize = sizeof(UIntMax) * 8
let end = start + length
if start / wordSize == (end - 1) / wordSize {
// Bit range does not cross two words
let offset = start / wordSize
let value = pointer[offset].bigEndian
let result = UIntMax(bigEndian: bitSet(value, start: start % wordSize, length: length, flipped: true, newValue: newValue))
pointer[offset] = result
}
else {
// Bit range spans two words, get bit ranges for both words and then combine them.
unimplementedFailure()
}
}
}
public func bitSet <Element>(buffer: UnsafeMutableBufferPointer <Element>, range: Range <Int>, newValue: UIntMax) {
bitSet(buffer, start: range.startIndex, length: range.endIndex - range.startIndex, newValue: newValue)
}
// MARK: -
func onesMask <T: UnsignedIntegerType> (start start: Int, length: Int, flipped: Bool = false) -> T {
let size = UIntMax(sizeof(T) * 8)
let start = UIntMax(start)
let length = UIntMax(length)
let shift = flipped == false ? start: (size - start - length)
let mask = ((1 << length) - 1) << shift
return T(mask)
}
| bsd-2-clause | 50cb92a91debab134b2857ab371a0f11 | 40.774566 | 134 | 0.648817 | 4.062395 | false | false | false | false |
ruter/Strap-in-Swift | SocialMedia/SocialMedia/AppDelegate.swift | 1 | 3225 | //
// AppDelegate.swift
// SocialMedia
//
// Created by Ruter on 16/4/14.
// Copyright © 2016年 Ruter. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UISplitViewControllerDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let splitViewController = self.window!.rootViewController as! UISplitViewController
let navigationController = splitViewController.viewControllers[splitViewController.viewControllers.count-1] as! UINavigationController
navigationController.topViewController!.navigationItem.leftBarButtonItem = splitViewController.displayModeButtonItem()
splitViewController.delegate = self
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: - Split view
func splitViewController(splitViewController: UISplitViewController, collapseSecondaryViewController secondaryViewController:UIViewController, ontoPrimaryViewController primaryViewController:UIViewController) -> Bool {
guard let secondaryAsNavController = secondaryViewController as? UINavigationController else { return false }
guard let topAsDetailController = secondaryAsNavController.topViewController as? DetailViewController else { return false }
if topAsDetailController.detailItem == nil {
// Return true to indicate that we have handled the collapse by doing nothing; the secondary controller will be discarded.
return true
}
return false
}
}
| apache-2.0 | e659175d73682fd8ab32a79cefa83c91 | 51.819672 | 281 | 0.78802 | 5.977737 | false | false | false | false |
cuzv/EasySwift | Sources/BoundsExpandable.swift | 1 | 2005 | //
// BoundsExpandable.swift
// EasySwift
//
// Created by Shaw on 7/20/18.
// Copyright © 2018 Shaw. All rights reserved.
//
import UIKit
public protocol BoundsExpandable {
var boundsInset: UIEdgeInsets { get }
}
public extension BoundsExpandable where Self: UIView {
public var intrinsicContentSizeOverride: CGSize {
let size = sizeThatFits(CGSize(width: bounds.size.width, height: bounds.size.height))
let width = size.width - boundsInset.left - boundsInset.right
let height = size.height - boundsInset.top - boundsInset.bottom
return CGSize(width: width, height: height)
}
public func drawRectOverride(_ rect: CGRect) -> CGRect {
let inset = boundsInset
let newInset = UIEdgeInsets(top: -inset.top, left: -inset.left, bottom: -inset.bottom, right: -inset.right)
return rect.inset(by: newInset)
}
}
/// The following lines show you how you use this protocol in you own project.
/**
final class CustomButton: UIButton, BoundsExpandable {
@IBInspectable var horizontalInset: CGPoint = .zero
@IBInspectable var verticalInset: CGPoint = .zero
open var boundsInset: UIEdgeInsets {
return UIEdgeInsetsMake(verticalInset.x, horizontalInset.x, verticalInset.y, horizontalInset.y)
}
override var intrinsicContentSize: CGSize {
return intrinsicContentSizeOverride
}
override func draw(_ rect: CGRect) {
super.draw(drawRectOverride(rect))
}
}
final class CustomLabel: UILabel, BoundsExpandable {
@IBInspectable var horizontalInset: CGPoint = .zero
@IBInspectable var verticalInset: CGPoint = .zero
open var boundsInset: UIEdgeInsets {
return UIEdgeInsetsMake(verticalInset.x, horizontalInset.x, verticalInset.y, horizontalInset.y)
}
override var intrinsicContentSize: CGSize {
return intrinsicContentSizeOverride
}
override func drawText(in rect: CGRect) {
super.drawText(in: drawRectOverride(rect))
}
}
*/
| mit | 835b122a9e760a22c7976b689d8782db | 29.363636 | 115 | 0.703094 | 4.503371 | false | false | false | false |
Minecodecraft/EstateBand | EstateBand/UserHealthViewController.swift | 1 | 1581 | //
// UserHealthViewController.swift
// EstateBand
//
// Created by Minecode on 2017/6/12.
// Copyright © 2017年 org.minecode. All rights reserved.
//
import UIKit
import UserNotifications
class UserHealthViewController: UITableViewController {
// Widget Data
@IBOutlet weak var logoutButton: UIButton!
@IBOutlet weak var warningButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// 设置导航数据
self.navigationItem.title = "Health Managment"
// 设置底栏数据
// self.tabBarItem.title = "Warning management"
// self.tabBarItem.image = UIImage(named: "userHealth")
}
@IBAction func warnAction(_ sender: UIButton) {
let content = UNMutableNotificationContent()
content.sound = UNNotificationSound.default();
content.title = "Alert"
content.subtitle = "Dangrous area"
content.body = "One worker in dangerous area!"
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let request = UNNotificationRequest(identifier: "identifer", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request, withCompletionHandler: nil)
}
@IBAction func logoutActiuon(_ sender: UIButton) {
// let loginViewController = self.storyboard?.instantiateViewController(withIdentifier: "loginView")
// present(loginViewController!, animated: true, completion: nil)
self.dismiss(animated: true, completion: nil)
}
}
| mit | 155b642bcce394d2ff849100e6e31760 | 31.375 | 107 | 0.675676 | 4.826087 | false | false | false | false |
jensmeder/DarkLightning | Sources/Daemon/Sources/Messages/ReceivingDataReaction.swift | 1 | 2310 | /**
*
* DarkLightning
*
*
*
* The MIT License (MIT)
*
* Copyright (c) 2017 Jens Meder
*
* 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
internal final class ReceivingDataReaction: DataDecoding {
private let mapping: ([String: Any]) -> (USBMuxMessage)
private let dataMapping: (Data) -> (OODataArray)
private let tcpMode: Memory<Bool>
// MARK: Init
internal convenience init(mapping: @escaping ([String: Any]) -> (USBMuxMessage), dataMapping: @escaping (Data) -> (OODataArray)) {
self.init(
tcpMode: Memory<Bool>(initialValue: false),
mapping: mapping,
dataMapping: dataMapping)
}
internal required init(tcpMode: Memory<Bool>, mapping: @escaping ([String: Any]) -> (USBMuxMessage), dataMapping: @escaping (Data) -> (OODataArray)) {
self.mapping = mapping
self.dataMapping = dataMapping
self.tcpMode = tcpMode
}
// MARK: DataDecoding
public func decode(data: OOData) {
if !tcpMode.rawValue {
let messages = dataMapping(data.dataValue)
for i in 0..<messages.count {
let plist: [String: Any] = try! PropertyListSerialization.propertyList(from: messages[i].dataValue, options: [], format: nil) as! [String : Any]
let message = mapping(plist)
message.decode()
}
}
}
}
| mit | 81c3be1c71950bad8dde4bccf0690891 | 35.666667 | 154 | 0.715152 | 3.830846 | false | false | false | false |
zfj4/Epi-Info-iOS | EpiInfo/CaseControlSimulationView.swift | 3 | 13896 | //
// CaseControlSimulationView.swift
// EpiInfo
//
// Created by John Copeland on 3/27/15.
// Copyright (c) 2015 John Copeland. All rights reserved.
//
import UIKit
class CaseControlSimulationsView: UIView, UITextFieldDelegate {
var fadingColorView = UIImageView()
var resignAllButton = UIButton()
var header = UILabel()
var inputBackground = UIButton()
var resultsLabel = EpiInfoMultiLineIndentedUILabel()
var casesLabel = UIButton()
var cases = NumberField()
var controlsLabel = UIButton()
var controls = NumberField()
var percentCasesExposedLabel = UIButton()
var percentCasesExposed = NumberField()
var percentControlsExposedLabel = UIButton()
var percentControlsExposed = NumberField()
var maxWidth = CGFloat()
var maxHeight = CGFloat()
var killThread = false
override init(frame: CGRect) {
super.init(frame: frame)
if frame.height == 0.0 {
return
}
self.clipsToBounds = true
maxHeight = frame.height
maxWidth = frame.width
if UIDevice.currentDevice().userInterfaceIdiom == .Pad {
} else {
// Add background image
fadingColorView = UIImageView(frame: frame)
let frameHeight: Float = Float(frame.size.height)
if frameHeight > 500 {
fadingColorView.image = UIImage(named: "iPhone5Background.png")
} else {
fadingColorView.image = UIImage(named: "iPhone4Background.png")
}
self.addSubview(fadingColorView)
self.sendSubviewToBack(fadingColorView)
//Add the screen-sized clear button to dismiss all keyboards
resignAllButton = UIButton(frame: frame)
resignAllButton.backgroundColor = .clearColor()
resignAllButton.addTarget(self, action: "resignAll", forControlEvents: .TouchUpInside)
self.addSubview(resignAllButton)
//Screen header
header = UILabel(frame: CGRectMake(0, 4 * (frame.height / maxHeight), frame.width * (frame.width / maxWidth), 26 * (frame.height / maxHeight)))
header.backgroundColor = .clearColor()
header.textColor = .whiteColor()
header.textAlignment = .Center
header.font = UIFont(name: "HelveticaNeue-Bold", size: 20.0)
header.text = "Simulate Case Control Study"
self.addSubview(header)
//Add navy background for input fields
inputBackground = UIButton(frame: CGRectMake(4 * (frame.width / maxWidth), 40 * (frame.height / maxHeight), 312 * (frame.width / maxWidth), 170 * (frame.height / maxHeight)))
inputBackground.backgroundColor = UIColor(red: 3/255.0, green: 36/255.0, blue: 77/255.0, alpha: 1.0)
inputBackground.layer.masksToBounds = true
inputBackground.layer.cornerRadius = 8.0
inputBackground.addTarget(self, action: "resignAll", forControlEvents: .TouchUpInside)
self.addSubview(inputBackground)
//Add the NumberField for number of cases
casesLabel = UIButton(frame: CGRectMake(4 * (frame.width / maxWidth), 2 * (frame.height / maxHeight), 148 * (frame.width / maxWidth), 40 * (frame.height / maxHeight)))
casesLabel.backgroundColor = .clearColor()
casesLabel.clipsToBounds = true
casesLabel.setTitle("Number of Cases", forState: .Normal)
casesLabel.contentHorizontalAlignment = .Left
casesLabel.titleLabel!.textAlignment = .Left
casesLabel.titleLabel!.textColor = .whiteColor()
casesLabel.titleLabel!.font = UIFont(name: "HelveticaNeue-Bold", size: 14.0)
casesLabel.addTarget(self, action: "resignAll", forControlEvents: .TouchUpInside)
inputBackground.addSubview(casesLabel)
cases = NumberField(frame: CGRectMake(230 * (frame.width / maxWidth), 2 * (frame.height / maxHeight), 80 * (frame.width / maxWidth), 40 * (frame.height / maxHeight)))
cases.borderStyle = .RoundedRect
cases.keyboardType = .NumberPad
cases.delegate = self
cases.returnKeyType = .Done
inputBackground.addSubview(cases)
//Add the NumberField for number of controls
controlsLabel = UIButton(frame: CGRectMake(4 * (frame.width / maxWidth), 44 * (frame.height / maxHeight), 148 * (frame.width / maxWidth), 40 * (frame.height / maxHeight)))
controlsLabel.backgroundColor = .clearColor()
controlsLabel.clipsToBounds = true
controlsLabel.setTitle("Number of Controls", forState: .Normal)
controlsLabel.contentHorizontalAlignment = .Left
controlsLabel.titleLabel!.textAlignment = .Left
controlsLabel.titleLabel!.textColor = .whiteColor()
controlsLabel.titleLabel!.font = UIFont(name: "HelveticaNeue-Bold", size: 14.0)
controlsLabel.addTarget(self, action: "resignAll", forControlEvents: .TouchUpInside)
inputBackground.addSubview(controlsLabel)
controls = NumberField(frame: CGRectMake(230 * (frame.width / maxWidth), 44 * (frame.height / maxHeight), 80 * (frame.width / maxWidth), 40 * (frame.height / maxHeight)))
controls.borderStyle = .RoundedRect
controls.keyboardType = .NumberPad
controls.delegate = self
controls.returnKeyType = .Done
inputBackground.addSubview(controls)
//Add the NumberField for percent in cases
percentCasesExposedLabel = UIButton(frame: CGRectMake(4 * (frame.width / maxWidth), 86 * (frame.height / maxHeight), 224 * (frame.width / maxWidth), 40 * (frame.height / maxHeight)))
percentCasesExposedLabel.backgroundColor = .clearColor()
percentCasesExposedLabel.clipsToBounds = true
percentCasesExposedLabel.setTitle("Expected % Exposed in Cases", forState: .Normal)
percentCasesExposedLabel.contentHorizontalAlignment = .Left
percentCasesExposedLabel.titleLabel!.textAlignment = .Left
percentCasesExposedLabel.titleLabel!.textColor = .whiteColor()
percentCasesExposedLabel.titleLabel!.font = UIFont(name: "HelveticaNeue-Bold", size: 14.0)
percentCasesExposedLabel.titleLabel?.adjustsFontSizeToFitWidth = true
percentCasesExposedLabel.addTarget(self, action: "resignAll", forControlEvents: .TouchUpInside)
inputBackground.addSubview(percentCasesExposedLabel)
percentCasesExposed = NumberField(frame: CGRectMake(230 * (frame.width / maxWidth), 86 * (frame.height / maxHeight), 80 * (frame.width / maxWidth), 40 * (frame.height / maxHeight)))
percentCasesExposed.borderStyle = .RoundedRect
percentCasesExposed.keyboardType = .DecimalPad
percentCasesExposed.delegate = self
percentCasesExposed.returnKeyType = .Done
inputBackground.addSubview(percentCasesExposed)
//Add the NumberField for percent in controls
percentControlsExposedLabel = UIButton(frame: CGRectMake(4 * (frame.width / maxWidth), 128 * (frame.height / maxHeight), 224 * (frame.width / maxWidth), 40 * (frame.height / maxHeight)))
percentControlsExposedLabel.backgroundColor = .clearColor()
percentControlsExposedLabel.clipsToBounds = true
percentControlsExposedLabel.setTitle("Expected % Exposed in Controls", forState: .Normal)
percentControlsExposedLabel.contentHorizontalAlignment = .Left
percentControlsExposedLabel.titleLabel!.textAlignment = .Left
percentControlsExposedLabel.titleLabel!.textColor = .whiteColor()
percentControlsExposedLabel.titleLabel!.font = UIFont(name: "HelveticaNeue-Bold", size: 14.0)
percentControlsExposedLabel.titleLabel?.adjustsFontSizeToFitWidth = true
percentControlsExposedLabel.addTarget(self, action: "resignAll", forControlEvents: .TouchUpInside)
inputBackground.addSubview(percentControlsExposedLabel)
percentControlsExposed = NumberField(frame: CGRectMake(230 * (frame.width / maxWidth), 128 * (frame.height / maxHeight), 80 * (frame.width / maxWidth), 40 * (frame.height / maxHeight)))
percentControlsExposed.borderStyle = .RoundedRect
percentControlsExposed.keyboardType = .DecimalPad
percentControlsExposed.delegate = self
percentControlsExposed.returnKeyType = .Done
inputBackground.addSubview(percentControlsExposed)
//Add the results label
resultsLabel = EpiInfoMultiLineIndentedUILabel(frame: CGRectMake(4, frame.height - 60, 312, 60))
resultsLabel.backgroundColor = UIColor(red: 3/255.0, green: 36/255.0, blue: 77/255.0, alpha: 1.0)
resultsLabel.layer.masksToBounds = true
resultsLabel.layer.cornerRadius = 8.0
resultsLabel.textColor = .whiteColor()
resultsLabel.textAlignment = .Left
resultsLabel.font = UIFont(name: "HelveticaNeue-Bold", size: 18.0)
resultsLabel.numberOfLines = 0
resultsLabel.numLines = 2
resultsLabel.lineBreakMode = .ByWordWrapping
self.addSubview(resultsLabel)
resultsLabel.hidden = true
}
}
func changeFrame(frame: CGRect) {
self.frame = frame
fadingColorView.frame = CGRectMake(0, 0, frame.width, frame.height)
resignAllButton.frame = fadingColorView.frame
if frame.width < maxWidth {
header.transform = CGAffineTransformScale(header.transform , 10 / maxWidth, 10 / maxHeight)
} else {
header.transform = CGAffineTransformScale(header.transform , maxWidth / 10, maxHeight / 10)
}
header.frame = CGRectMake(0, 4 * (frame.height / maxHeight), frame.width * (frame.width / maxWidth), 26 * (frame.height / maxHeight))
inputBackground.frame = CGRectMake(4 * (frame.width / maxWidth), 40 * (frame.height / maxHeight), 312 * (frame.width / maxWidth), 170 * (frame.height / maxHeight))
casesLabel.frame = CGRectMake(4 * (frame.width / maxWidth), 2 * (frame.height / maxHeight), 148 * (frame.width / maxWidth), 40 * (frame.height / maxHeight))
cases.frame = CGRectMake(230 * (frame.width / maxWidth), 2 * (frame.height / maxHeight), 80 * (frame.width / maxWidth), 40 * (frame.height / maxHeight))
controlsLabel.frame = CGRectMake(4 * (frame.width / maxWidth), 44 * (frame.height / maxHeight), 148 * (frame.width / maxWidth), 40 * (frame.height / maxHeight))
controls.frame = CGRectMake(230 * (frame.width / maxWidth), 44 * (frame.height / maxHeight), 80 * (frame.width / maxWidth), 40 * (frame.height / maxHeight))
percentCasesExposedLabel.frame = CGRectMake(4 * (frame.width / maxWidth), 86 * (frame.height / maxHeight), 224 * (frame.width / maxWidth), 40 * (frame.height / maxHeight))
percentCasesExposed.frame = CGRectMake(230 * (frame.width / maxWidth), 86 * (frame.height / maxHeight), 80 * (frame.width / maxWidth), 40 * (frame.height / maxHeight))
percentControlsExposedLabel.frame = CGRectMake(4 * (frame.width / maxWidth), 128 * (frame.height / maxHeight), 224 * (frame.width / maxWidth), 40 * (frame.height / maxHeight))
percentControlsExposed.frame = CGRectMake(230 * (frame.width / maxWidth), 128 * (frame.height / maxHeight), 80 * (frame.width / maxWidth), 40 * (frame.height / maxHeight))
if !resultsLabel.hidden {
resultsLabel.frame = CGRectMake(resultsLabel.frame.origin.x * (frame.width / maxWidth), resultsLabel.frame.origin.y * (frame.height / maxHeight), resultsLabel.frame.width * (frame.width / maxWidth), resultsLabel.frame.height * (frame.height / maxHeight))
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
return textField.resignFirstResponder()
}
func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
killThread = true
UIView.animateWithDuration(0.2, delay: 0.0, options: UIViewAnimationOptions.CurveLinear, animations: {
self.resultsLabel.frame = CGRectMake(4, self.frame.height - 60, 312, 60)
}, completion: {
(value: Bool) in
self.resultsLabel.hidden = true
self.resultsLabel.text = ""
})
return true
}
func resignAll() {
var noFirstResponder = true
for v in inputBackground.subviews as! [UIView] {
if let tf = v as? UITextField {
if tf.isFirstResponder() {
tf.resignFirstResponder()
noFirstResponder = false
}
}
}
if (noFirstResponder) {
return
}
if cases.text?.characters.count > 0 && controls.text?.characters.count > 0 && percentCasesExposed.text?.characters.count > 0 && percentControlsExposed.text?.characters.count > 0 {
let numCases = (cases.text! as NSString).floatValue
let numControls = (controls.text! as NSString).floatValue
let pctCasesExposed = (percentCasesExposed.text! as NSString).floatValue
let pctControlsExposed = (percentControlsExposed.text! as NSString).floatValue
if pctCasesExposed > 100 {
percentCasesExposed.text = ""
percentCasesExposed.placeholder = "<=100"
return
} else if pctControlsExposed > 100 {
percentControlsExposed.text = ""
percentControlsExposed.placeholder = "<=100"
return
}
killThread = false
let queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
dispatch_async(queue) {
self.runComputer((numCases, numControls, pctCasesExposed, pctControlsExposed))
}
resultsLabel.hidden = false
UIView.animateWithDuration(0.3, delay: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: {
self.resultsLabel.frame = CGRectMake(self.resultsLabel.frame.origin.x, self.inputBackground.frame.origin.y + self.inputBackground.frame.height + 8, self.resultsLabel.frame.width, self.resultsLabel.frame.height)
}, completion: {
(value: Bool) in
})
}
}
func runComputer(inputs : (Float, Float, Float, Float)) {
while !killThread {
let rr = CaseControlSimulationModel.compute(inputs.0, b: inputs.1, c: inputs.2, d: inputs.3)
dispatch_async(dispatch_get_main_queue()) {
self.resultsLabel.text = "\(rr.0)% of simulations found a significant relative risk."
}
sleep(2)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
} | apache-2.0 | 227a50fc1e5045956c4cb5792dd88df1 | 51.048689 | 260 | 0.699698 | 4.386364 | false | false | false | false |
breadwallet/breadwallet-ios | breadwallet/src/Platform/BRReplicatedKVStore.swift | 1 | 37431 | //
// BRReplicatedKVStore.swift
// BreadWallet
//
// Created by Samuel Sutch on 8/10/16.
// Copyright © 2016-2019 Breadwinner AG. All rights reserved.
//
import Foundation
import SQLite3
import WalletKit
public enum BRReplicatedKVStoreError: Error {
case sqLiteError
case replicationError
case alreadyReplicating
case conflict
case notFound
case invalidKey
case unknown
case malformedData
}
public enum BRRemoteKVStoreError: Error {
case notFound
case conflict
case tombstone
case unknown
}
/// An interface to a remote key value store which utilizes optimistic-locking for concurrency control
public protocol BRRemoteKVStoreAdaptor {
/// Fetch the version of the key from the remote store
/// returns a tuple of (remoteVersion, remoteDate, remoteErr?)
func ver(key: String, completionFunc: @escaping (UInt64, Date, BRRemoteKVStoreError?) -> Void)
/// Save a new version of the key to the remote server
/// takes the value and current remote version (zero if creating)
/// returns a tuple of (remoteVersion, remoteDate, remoteErr?)
func put(_ key: String,
value: [UInt8],
version: UInt64,
completionFunc: @escaping (UInt64, Date, BRRemoteKVStoreError?) -> Void)
/// Marks a key as deleted on the remote server
/// takes the current remote version (which same as put() must match the current servers time)
/// returns a tuple of (remoteVersion, remoteDate, remoteErr?)
func del(_ key: String, version: UInt64, completionFunc: @escaping (UInt64, Date, BRRemoteKVStoreError?) -> Void)
/// Get a key from the server
/// takes the current remote version (which may optionally be zero to fetch the newest version)
/// returns a tuple of (remoteVersion, remoteDate, remoteBytes, remoteErr?)
func get(_ key: String,
version: UInt64,
completionFunc: @escaping (UInt64, Date, [UInt8], BRRemoteKVStoreError?) -> Void)
/// Get a list of all keys on the remote server
/// returns a list of tuples of (remoteKey, remoteVersion, remoteDate, remoteErr?)
func keys(_ completionFunc: @escaping ([(String, UInt64, Date, BRRemoteKVStoreError?)], BRRemoteKVStoreError?) -> Void)
}
private func dispatch_sync_throws(_ queue: DispatchQueue, f: () throws -> Void) throws {
var e: Error?
queue.sync {
do {
try f()
} catch let caught {
e = caught
}
}
if let e = e {
throw e
}
}
// swiftlint:disable type_body_length
/// A key value store which can replicate its data to remote servers that utilizes optimistic locking for local
/// concurrency control
open class BRReplicatedKVStore: NSObject {
fileprivate var db: OpaquePointer? // sqlite3*
fileprivate(set) var key: Key
fileprivate(set) var remote: BRRemoteKVStoreAdaptor
fileprivate(set) var syncRunning = false
fileprivate var dbQueue: DispatchQueue
fileprivate let keyRegex: NSRegularExpression = (try? NSRegularExpression(pattern: "^[^_][\\w-]{1,255}$", options: [])) ?? NSRegularExpression()
/// Whether or not we immediately sync a key when set() or del() is called
/// by default it is off because only one sync can run at a time, and if you set or del a lot of keys
/// most operations will err out
open var syncImmediately = false
/// Whether or not the data replicated to the serve is encrypted. Default value should always be yes,
/// this property should only be used for testing with non-sensitive data
open var encryptedReplication = true
/// Whether the data is encrypted at rest on disk
open var encrypted = true
static var dbPath: URL {
let fm = FileManager.default
let docsUrl = fm.urls(for: .documentDirectory, in: .userDomainMask).first!
let filename = E.isRunningTests ? "kvstore_test.sqlite3" : "kvstore.sqlite3"
let path = docsUrl.appendingPathComponent(filename)
return path
}
init(encryptionKey: Key, remoteAdaptor: BRRemoteKVStoreAdaptor) throws {
key = encryptionKey
remote = remoteAdaptor
dbQueue = DispatchQueue(label: "com.voisine.breadwallet.kvDBQueue", attributes: [])
super.init()
try self.openDatabase()
try self.migrateDatabase()
}
static func rmdb() throws {
guard (Backend.kvStore != nil) || E.isRunningTests else {
if FileManager.default.fileExists(atPath: BRReplicatedKVStore.dbPath.path) {
try FileManager.default.removeItem(at: BRReplicatedKVStore.dbPath)
}
return
}
try Backend.kvStore?.rmdb()
}
/// Removes the entire database all at once. One must call openDatabase() and migrateDatabase()
/// if one wishes to use this instance again after calling this
private func rmdb() throws {
try dispatch_sync_throws(dbQueue) {
try self.checkErr(sqlite3_close(self.db), s: "rmdb - close")
if FileManager.default.fileExists(atPath: BRReplicatedKVStore.dbPath.path) {
try FileManager.default.removeItem(at: BRReplicatedKVStore.dbPath)
}
self.db = nil
}
}
/// Creates the internal database connection. Called automatically in init()
func openDatabase() throws {
try dispatch_sync_throws(dbQueue) {
if self.db != nil {
print("Database already open")
throw BRReplicatedKVStoreError.sqLiteError
}
try self.checkErr(sqlite3_open_v2(
BRReplicatedKVStore.dbPath.absoluteString, &self.db,
SQLITE_OPEN_FULLMUTEX | SQLITE_OPEN_CREATE | SQLITE_OPEN_READWRITE, nil
), s: "opening db")
self.log("opened DB at \(BRReplicatedKVStore.dbPath.absoluteString)")
}
}
deinit {
sqlite3_close(db)
}
/// Creates the local database structure. Called automatically in init()
func migrateDatabase() throws {
try dispatch_sync_throws(dbQueue) {
let commands = [
"CREATE TABLE IF NOT EXISTS dbversion (ver INT NOT NULL PRIMARY KEY ON CONFLICT REPLACE);",
"INSERT INTO dbversion (ver) VALUES (1);",
"CREATE TABLE IF NOT EXISTS kvstore (" +
" version BIGINT NOT NULL, " +
" remote_version BIGINT NOT NULL DEFAULT 0, " +
" key TEXT NOT NULL, " +
" value BLOB NOT NULL, " +
" thetime BIGINT NOT NULL, " + // server unix timestamp in MS
" deleted BOOL NOT NULL, " +
" PRIMARY KEY (key, version) " +
");"
]
for cmd in commands {
var stmt: OpaquePointer?
defer {
sqlite3_finalize(stmt)
}
try self.checkErr(sqlite3_prepare_v2(self.db, cmd, -1, &stmt, nil), s: "migrate prepare")
try self.checkErr(sqlite3_step(stmt), s: "migrate stmt exec")
}
}
}
// get a key from the local database, optionally specifying a version
func get(_ key: String, version: UInt64 = 0) throws -> (UInt64, Date, Bool, [UInt8]) {
try checkKey(key)
var ret = [UInt8]()
var curVer: UInt64 = 0
var deleted = false
var time = Date(timeIntervalSince1970: Double())
try txn {
if version == 0 {
(curVer, _) = try self._localVersion(key)
} else {
// check for the existence of such a version
var vStmt: OpaquePointer?
defer {
sqlite3_finalize(vStmt)
}
try self.checkErr(sqlite3_prepare_v2(
self.db, "SELECT version FROM kvstore WHERE key = ? AND version = ? ORDER BY version DESC LIMIT 1",
-1, &vStmt, nil
), s: "get - get version - prepare")
sqlite3_bind_text(vStmt, 1, NSString(string: key).utf8String, -1, nil)
sqlite3_bind_int64(vStmt, 2, Int64(version))
try self.checkErr(sqlite3_step(vStmt), s: "get - get version - exec", r: SQLITE_ROW)
curVer = UInt64(sqlite3_column_int64(vStmt, 0))
}
if curVer == 0 {
throw BRReplicatedKVStoreError.notFound
}
self.log("GET key: \(key) ver: \(curVer)")
var stmt: OpaquePointer?
defer {
sqlite3_finalize(stmt)
}
try self.checkErr(sqlite3_prepare_v2(
self.db, "SELECT value, length(value), thetime, deleted FROM kvstore WHERE key=? AND version=? LIMIT 1",
-1, &stmt, nil
), s: "get - prepare stmt")
sqlite3_bind_text(stmt, 1, NSString(string: key).utf8String, -1, nil)
sqlite3_bind_int64(stmt, 2, Int64(curVer))
try self.checkErr(sqlite3_step(stmt), s: "get - step stmt", r: SQLITE_ROW)
let blob = sqlite3_column_blob(stmt, 0)
let blobLength = sqlite3_column_int(stmt, 1)
time = Date.withMsTimestamp(UInt64(sqlite3_column_int64(stmt, 2)))
deleted = sqlite3_column_int(stmt, 3) > 0
ret = Array(UnsafeBufferPointer<UInt8>(start: blob?.assumingMemoryBound(to: UInt8.self), count: Int(blobLength)))
}
return (curVer, time, deleted, (encrypted ? try decrypt(ret) : ret))
}
/// Set the value of a key locally in the database. If syncImmediately is true (the default) then immediately
/// after successfully saving locally, replicate to server. The `localVer` key must be the same as is currently
/// stored in the database. To create a new key, pass `0` as `localVer`
func set(_ key: String, value: [UInt8], localVer: UInt64) throws -> (UInt64, Date) {
try checkKey(key)
let (newVer, time) = try _set(key, value: value, localVer: localVer)
if syncImmediately {
try syncKey(key) { _ in
self.log("[KV] SET key synced: \(key)")
}
}
return (newVer, time)
}
fileprivate func _set(_ key: String, value: [UInt8], localVer: UInt64) throws -> (UInt64, Date) {
var newVer: UInt64 = 0
let time = Date()
try txn {
let (curVer, _) = try self._localVersion(key)
if curVer != localVer {
self.log("set key \(key) conflict: version \(localVer) != current version \(curVer)")
throw BRReplicatedKVStoreError.conflict
}
self.log("SET key: \(key) ver: \(curVer)")
newVer = curVer + 1
let encryptedData = self.encrypted ? try self.encrypt(value) : value
var stmt: OpaquePointer?
defer {
sqlite3_finalize(stmt)
}
try self.checkErr(sqlite3_prepare_v2(self.db,
"INSERT INTO kvstore (version, key, value, thetime, deleted) " +
"VALUES (?, ?, ?, ?, ?)", -1, &stmt, nil
), s: "set - prepare stmt")
sqlite3_bind_int64(stmt, 1, Int64(newVer))
sqlite3_bind_text(stmt, 2, NSString(string: key).utf8String, -1, nil)
sqlite3_bind_blob(stmt, 3, encryptedData, Int32(encryptedData.count), nil)
sqlite3_bind_int64(stmt, 4, Int64(time.msTimestamp()))
sqlite3_bind_int(stmt, 5, 0)
try self.checkErr(sqlite3_step(stmt), s: "set - step stmt")
}
return (newVer, time)
}
/// Mark a key as removed locally. If syncImmediately is true (the defualt) then immediately mark the key
/// as removed on the server as well. `localVer` must match the most recent version in the local database.
func del(_ key: String, localVer: UInt64) throws -> (UInt64, Date) {
try checkKey(key)
let (newVer, time) = try _del(key, localVer: localVer)
if syncImmediately {
try syncKey(key) { _ in
self.log("DEL key synced: \(key)")
}
}
return (newVer, time)
}
func _del(_ key: String, localVer: UInt64) throws -> (UInt64, Date) {
if localVer == 0 {
throw BRReplicatedKVStoreError.notFound
}
var newVer: UInt64 = 0
let time = Date()
try txn {
let (curVer, _) = try self._localVersion(key)
if curVer != localVer {
self.log("del key \(key) conflict: version \(localVer) != current version \(curVer)")
throw BRReplicatedKVStoreError.conflict
}
self.log("DEL key: \(key) ver: \(curVer)")
newVer = curVer + 1
var stmt: OpaquePointer?
defer {
sqlite3_finalize(stmt)
}
try self.checkErr(sqlite3_prepare_v2(
self.db, "INSERT INTO kvstore (version, key, value, thetime, deleted) " +
"SELECT ?, key, value, ?, ? " +
"FROM kvstore WHERE key=? AND version=?",
-1, &stmt, nil
), s: "del - prepare stmt")
sqlite3_bind_int64(stmt, 1, Int64(newVer))
sqlite3_bind_int64(stmt, 2, Int64(time.msTimestamp()))
sqlite3_bind_int(stmt, 3, 1)
sqlite3_bind_text(stmt, 4, NSString(string: key).utf8String, -1, nil)
sqlite3_bind_int64(stmt, 5, Int64(curVer))
try self.checkErr(sqlite3_step(stmt), s: "del - exec stmt")
}
return (newVer, time)
}
/// Gets the local version of the provided key, or 0 if it doesn't exist
func localVersion(_ key: String) throws -> (UInt64, Date) {
try checkKey(key)
var retVer: UInt64 = 0
var retTime = Date(timeIntervalSince1970: Double())
try txn {
(retVer, retTime) = try self._localVersion(key)
}
return (retVer, retTime)
}
func _localVersion(_ key: String) throws -> (UInt64, Date) {
var stmt: OpaquePointer?
defer {
sqlite3_finalize(stmt)
}
try self.checkErr(sqlite3_prepare_v2(
self.db, "SELECT version, thetime FROM kvstore WHERE key = ? ORDER BY version DESC LIMIT 1", -1,
&stmt, nil
), s: "get version - prepare")
sqlite3_bind_text(stmt, 1, NSString(string: key).utf8String, -1, nil)
try self.checkErr(sqlite3_step(stmt), s: "get version - exec", r: SQLITE_ROW)
return (
UInt64(sqlite3_column_int64(stmt, 0)),
Date.withMsTimestamp(UInt64(sqlite3_column_int64(stmt, 1)))
)
}
/// Get the remote version for the key for the most recent local version of the key, if stored.
// If local key doesn't exist, return 0
// func remoteVersion(key: String) throws -> UInt64 {
//// return 0
// }
func remoteVersion(_ key: String) throws -> Int { // this would be UInt64.. but it makes the compiler crash
try checkKey(key)
var ret: UInt64 = 0
try txn {
var stmt: OpaquePointer?
defer {
sqlite3_finalize(stmt)
}
try self.checkErr(sqlite3_prepare_v2(
self.db, "SELECT remote_version FROM kvstore WHERE key = ? ORDER BY version DESC LIMIT 1", -1, &stmt, nil
), s: "get remote version - prepare")
sqlite3_bind_text(stmt, 1, NSString(string: key).utf8String, -1, nil)
try self.checkErr(sqlite3_step(stmt), s: "get remote version - exec", r: SQLITE_ROW)
ret = UInt64(sqlite3_column_int64(stmt, 0))
}
return Int(ret)
}
/// Record the remote version for the object in a new version of the local key
func setRemoteVersion(key: String, localVer: UInt64, remoteVer: UInt64) throws -> (UInt64, Date) {
try checkKey(key)
if localVer < 1 {
throw BRReplicatedKVStoreError.conflict // setRemoteVersion can't be used for creates
}
var newVer: UInt64 = 0
let time = Date()
try txn {
let (curVer, _) = try self._localVersion(key)
if curVer != localVer {
self.log("set remote version key \(key) conflict: version \(localVer) != current version \(curVer)")
throw BRReplicatedKVStoreError.conflict
}
self.log("SET REMOTE VERSION: \(key) ver: \(localVer) remoteVer=\(remoteVer)")
newVer = curVer + 1
var stmt: OpaquePointer?
defer {
sqlite3_finalize(stmt)
}
try self.checkErr(sqlite3_prepare_v2(
self.db, "INSERT INTO kvstore (version, key, value, thetime, deleted, remote_version) " +
"SELECT ?, key, value, ?, deleted, ? " +
"FROM kvstore WHERE key=? AND version=?",
-1, &stmt, nil
), s: "update remote version - prepare stmt")
sqlite3_bind_int64(stmt, 1, Int64(newVer))
sqlite3_bind_int64(stmt, 2, Int64(time.msTimestamp()))
sqlite3_bind_int64(stmt, 3, Int64(remoteVer))
sqlite3_bind_text(stmt, 4, NSString(string: key).utf8String, -1, nil)
sqlite3_bind_int64(stmt, 5, Int64(curVer))
try self.checkErr(sqlite3_step(stmt), s: "update remote - exec stmt")
}
return (newVer, time)
}
/// Get a list of (key, localVer, localTime, remoteVer, deleted)
func localKeys() throws -> [(String, UInt64, Date, UInt64, Bool)] {
var ret = [(String, UInt64, Date, UInt64, Bool)]()
try txn {
var stmt: OpaquePointer?
defer {
sqlite3_finalize(stmt)
}
try self.checkErr(sqlite3_prepare_v2(self.db,
"SELECT kvs.key, kvs.version, kvs.thetime, kvs.remote_version, kvs.deleted " +
"FROM kvstore kvs " +
"INNER JOIN ( " +
" SELECT MAX(version) AS latest_version, key " +
" FROM kvstore " +
" GROUP BY key " +
") vermax " +
"ON kvs.version = vermax.latest_version " +
"AND kvs.key = vermax.key", -1, &stmt, nil),
s: "local keys - prepare stmt")
while sqlite3_step(stmt) == SQLITE_ROW {
let key = sqlite3_column_text(stmt, 0)
let ver = sqlite3_column_int64(stmt, 1)
let date = sqlite3_column_int64(stmt, 2)
let rver = sqlite3_column_int64(stmt, 3)
let del = sqlite3_column_int(stmt, 4)
if let key = key {
ret.append((
String(cString: key),
UInt64(ver),
Date.withMsTimestamp(UInt64(date)),
UInt64(rver),
del > 0
))
}
}
}
return ret
}
/// Sync all keys to and from the remote kv store adaptor
func syncAllKeys(_ completionHandler: @escaping (BRReplicatedKVStoreError?) -> Void) {
// update all keys locally and on the remote server, replacing missing keys
//
// 1. get a list of all keys from the server
// 2. for keys that we don't have, add em
// 3. for keys that we do have, sync em
// 4. for keys that they don't have that we do, upload em
if syncRunning {
DispatchQueue.main.async(execute: {
completionHandler(.alreadyReplicating)
})
return
}
syncRunning = true
let startTime = Date()
remote.keys { (keyData, err) in
if let err = err {
self.log("Error fetching remote key data: \(err)")
self.syncRunning = false
return completionHandler(.replicationError)
}
var localKeyData: [(String, UInt64, Date, UInt64, Bool)]
do {
localKeyData = try self.localKeys()
} catch let e {
self.syncRunning = false
self.log("Error getting local key data: \(e)")
return completionHandler(.replicationError)
}
let allRemoteKeys = Set(keyData.map { e in return e.0 })
var allKeyData = keyData
for k in localKeyData {
if !allRemoteKeys.contains(k.0) {
// server is missing a key that we have
allKeyData.append((k.0, 0, Date(timeIntervalSince1970: Double()), nil))
}
}
self.log("Syncing \(allKeyData.count) keys")
var failures = 0
let q = DispatchQueue(label: "com.voisine.breadwallet.kvSyncQueue", attributes: DispatchQueue.Attributes.concurrent)
let grp = DispatchGroup()
let seph = DispatchSemaphore(value: 10)
grp.enter()
q.async {
q.async {
for k in allKeyData {
grp.enter()
_ = seph.wait(timeout: DispatchTime.distantFuture)
q.async(group: grp) {
do {
try self._syncKey(k.0, remoteVer: k.1, remoteTime: k.2, remoteErr: k.3,
completionHandler: { (err) in
if err != nil {
failures += 1
}
seph.signal()
grp.leave()
})
} catch {
failures += 1
seph.signal()
grp.leave()
}
}
}
grp.leave()
}
_ = grp.wait(timeout: DispatchTime.distantFuture)
DispatchQueue.main.async {
self.syncRunning = false
self.log("Finished syncing in \(Date().timeIntervalSince(startTime))")
completionHandler(failures > 0 ? .replicationError : nil)
}
}
}
}
/// Sync an individual key. Normally this is only called internally and you should call syncAllKeys
func syncKey(_ key: String,
remoteVersion: UInt64? = nil,
remoteTime: Date? = nil,
remoteErr: BRRemoteKVStoreError? = nil,
completionHandler: @escaping (BRReplicatedKVStoreError?) -> Void) throws {
try checkKey(key)
if syncRunning {
throw BRReplicatedKVStoreError.alreadyReplicating
}
syncRunning = true
let myCompletionHandler: (_ e: BRReplicatedKVStoreError?) -> Void = { e in
self.syncRunning = false
completionHandler(e)
}
if let remoteVersion = remoteVersion, let remoteTime = remoteTime {
try _syncKey(key, remoteVer: remoteVersion, remoteTime: remoteTime,
remoteErr: remoteErr, completionHandler: myCompletionHandler)
} else {
remote.ver(key: key) { (remoteVer, remoteTime, err) in
_ = try? self._syncKey(key, remoteVer: remoteVer, remoteTime: remoteTime,
remoteErr: err, completionHandler: myCompletionHandler)
}
}
}
// the syncKey kernel - this is provided so syncAllKeys can provide get a bunch of key versions at once
// and fan out the _syncKey operations
fileprivate func _syncKey(_ key: String,
remoteVer: UInt64,
remoteTime: Date,
remoteErr: BRRemoteKVStoreError?,
completionHandler: @escaping (BRReplicatedKVStoreError?) -> Void) throws {
// this is a basic last-write-wins strategy. data loss is possible but in general
// we will attempt to sync before making any local modifications to the data
// and concurrency will be so low that we don't really need a fancier solution than this.
// the strategy is:
//
// 1. get the remote version. this is our "lock"
// 2. along with the remote version will come the last-modified date of the remote object
// 3. if their last-modified date is newer than ours, overwrite ours
// 4. if their last-modified date is older than ours, overwrite theirs
if !syncRunning {
throw BRReplicatedKVStoreError.unknown // how did we get here
}
// one optimization is we keep the remote version on the most recent local version, if they match,
// there is nothing to do
let recordedRemoteVersion = try UInt64(remoteVersion(key))
if remoteErr != .some(.notFound) && remoteVer > 0 && recordedRemoteVersion == remoteVer {
log("Remote version of key \(key) is the same as the one we have")
return completionHandler(nil) // this key is already up to date
}
var localVer: UInt64
var localTime: Date
var localDeleted: Bool
var localValue: [UInt8]
do {
(localVer, localTime, localDeleted, localValue) = try get(key)
localValue = self.encryptedReplication ? try encrypt(localValue) : localValue
} catch BRReplicatedKVStoreError.notFound {
// missing key locally
(localVer, localTime, localDeleted, localValue) = (0, Date(timeIntervalSince1970: Double()), false, [])
}
let (lt, rt) = (localTime.msTimestamp(), remoteTime.msTimestamp())
switch remoteErr {
case nil, .some(.tombstone), .some(.notFound):
if localDeleted && remoteErr == .some(.tombstone) { // was removed on both server and locally
log("Local key \(key) was deleted, and so was the remote key")
do {
_ = try self.setRemoteVersion(key: key, localVer: localVer, remoteVer: remoteVer)
} catch let e as BRReplicatedKVStoreError {
return completionHandler(e)
} catch {
return completionHandler(.replicationError)
}
return completionHandler(nil)
}
if lt > rt || lt == rt { // local is newer (or a tiebreaker)
if localDeleted {
log("Local key \(key) was deleted, removing remotely...")
self.remote.del(key, version: remoteVer, completionFunc: { (newRemoteVer, _, delErr) in
if delErr == .some(.notFound) {
self.log("Local key \(key) was already missing on the server. Ignoring")
return completionHandler(nil)
}
if let delErr = delErr {
self.log("Error deleting remote version for key \(key), error: \(delErr)")
return completionHandler(.replicationError)
}
do {
_ = try self.setRemoteVersion(key: key, localVer: localVer, remoteVer: newRemoteVer)
} catch let e as BRReplicatedKVStoreError {
return completionHandler(e)
} catch {
return completionHandler(.replicationError)
}
self.log("Local key \(key) removed on server")
completionHandler(nil)
})
} else {
log("Local key \(key) is newer remoteVer=\(remoteVer), updating remotely...")
// if the remote version is zero it means it doesnt yet exist on the server. set the remote version
// to "1" to create the key on the server
let useRemoteVer = remoteVer == 0 || remoteVer < recordedRemoteVersion ? 1 : remoteVer
self.remote.put(key, value: localValue, version: useRemoteVer,
completionFunc: { (newRemoteVer, _, putErr) in
if let putErr = putErr {
self.log("Error updating remote version for key \(key), newRemoteVer=\(newRemoteVer) error: \(putErr)")
return completionHandler(.replicationError)
}
do {
_ = try self.setRemoteVersion(key: key, localVer: localVer, remoteVer: newRemoteVer)
} catch let e as BRReplicatedKVStoreError {
return completionHandler(e)
} catch {
return completionHandler(.replicationError)
}
self.log("Local key \(key) updated on server")
completionHandler(nil)
})
}
} else {
// local is out-of-date
if remoteErr == .some(.tombstone) {
// remote is deleted
log("Remote key \(key) deleted, removing locally")
do {
let (newLocalVer, _) = try self._del(key, localVer: localVer)
_ = try self.setRemoteVersion(key: key, localVer: newLocalVer, remoteVer: remoteVer)
} catch BRReplicatedKVStoreError.notFound {
// well a deleted key isn't found, so why do we care
} catch let e as BRReplicatedKVStoreError {
return completionHandler(e)
} catch {
return completionHandler(.replicationError)
}
log("Remote key \(key) was removed locally")
completionHandler(nil)
} else {
log("Remote key \(key) is newer, fetching...")
// get the remote version
self.remote.get(key, version: remoteVer, completionFunc: { (newRemoteVer, _, remoteData, getErr) in
if let getErr = getErr {
self.log("Error fetching the remote value for key \(getErr), error: \(getErr)")
return completionHandler(.replicationError)
}
do {
let decryptedValue = self.encryptedReplication ? try self.decrypt(remoteData) : remoteData
let (newLocalVer, _) = try self._set(key, value: decryptedValue, localVer: localVer)
_ = try self.setRemoteVersion(key: key, localVer: newLocalVer, remoteVer: newRemoteVer)
} catch BRReplicatedKVStoreError.malformedData {
_ = try? self.del(key, localVer: localVer)
return completionHandler(BRReplicatedKVStoreError.malformedData)
} catch let e as BRReplicatedKVStoreError {
return completionHandler(e)
} catch {
return completionHandler(.replicationError)
}
self.log("Updated local key \(key)")
completionHandler(nil)
})
}
}
default:
log("Error fetching remote version for key \(key), error: \(String(describing: remoteErr))")
completionHandler(.replicationError)
}
}
// execute a function inside a transaction, if that function throws then rollback, otherwise commit
// calling txn() from within a txn function will deadlock
fileprivate func txn(_ fn: () throws -> Void) throws {
try dispatch_sync_throws(dbQueue) {
var beginStmt: OpaquePointer?
var finishStmt: OpaquePointer?
defer {
sqlite3_finalize(beginStmt)
sqlite3_finalize(finishStmt)
}
try self.checkErr(sqlite3_prepare_v2(self.db, "BEGIN", -1, &beginStmt, nil), s: "txn - prepare begin")
try self.checkErr(sqlite3_step(beginStmt), s: "txn - exec begin begin")
do {
try fn()
} catch let e {
try self.checkErr(sqlite3_prepare_v2(
self.db, "ROLLBACK", -1, &finishStmt, nil), s: "txn - prepare rollback")
try self.checkErr(sqlite3_step(finishStmt), s: "txn - execute rollback")
throw e
}
try self.checkErr(sqlite3_prepare_v2(self.db, "COMMIT", -1, &finishStmt, nil), s: "txn - prepare commit")
try self.checkErr(sqlite3_step(finishStmt), s: "txn - execute commit")
}
}
// ensure the sqlite3 error code is an acceptable one (or that its the one you provide as `r`
// this MUST be called from within the dbQueue
fileprivate func checkErr(_ e: Int32, s: String, r: Int32 = SQLITE_NULL) throws {
if (r == SQLITE_NULL && (e != SQLITE_OK && e != SQLITE_DONE && e != SQLITE_ROW))
&& (e != SQLITE_NULL && e != r) {
let es = NSString(cString: sqlite3_errstr(e), encoding: String.Encoding.utf8.rawValue)
let em = NSString(cString: sqlite3_errmsg(db), encoding: String.Encoding.utf8.rawValue)
log("\(s): errcode=\(e) errstr=\(String(describing: es)) errmsg=\(String(describing: em))")
throw BRReplicatedKVStoreError.sqLiteError
}
}
// validates the key. keys can not start with a _
fileprivate func checkKey(_ key: String) throws {
let m = keyRegex.matches(in: key, options: [], range: NSRange(location: 0, length: key.count))
if m.count != 1 {
throw BRReplicatedKVStoreError.invalidKey
}
}
// encrypt some data using self.key
fileprivate func encrypt(_ data: [UInt8]) throws -> [UInt8] {
return [UInt8](Data(data).chacha20Poly1305AEADEncrypt(key: key))
}
// decrypt some data using self.key
fileprivate func decrypt(_ data: [UInt8]) throws -> [UInt8] {
return try [UInt8](Data(data).chacha20Poly1305AEADDecrypt(key: key))
}
// generate a nonce using microseconds-since-epoch
fileprivate func genNonce() -> [UInt8] {
var tv = timeval()
gettimeofday(&tv, nil)
var t = UInt64(tv.tv_usec) * 1_000_000 + UInt64(tv.tv_usec)
let p = [UInt8](repeating: 0, count: 4)
return Data(bytes: &t, count: MemoryLayout<UInt64>.size).withUnsafeBytes { (buf: UnsafeRawBufferPointer) -> [UInt8] in
return p + Array(buf)
}
}
fileprivate func log(_ s: String) {
print("[KVStore] \(s)")
}
}
// MARK: - Objective-C compatability layer
@objc open class BRKVStoreObject: NSObject {
open var version: UInt64
open var lastModified: Date
open var deleted: Bool
open var key: String
fileprivate var _data: Data?
var data: Data {
get {
return getData() ?? _data ?? Data() // allow subclasses to override the data that is retrieved
}
set(v) {
_data = v
dataWasSet(v)
}
}
init(key: String, version: UInt64, lastModified: Date, deleted: Bool, data: Data) {
self.version = version
self.key = key
self.lastModified = lastModified
self.deleted = deleted
super.init()
if !data.isEmpty {
self.data = data
}
}
func getData() -> Data? { return nil }
func dataWasSet(_ value: Data) { }
}
extension BRReplicatedKVStore {
public func get(_ key: String) throws -> BRKVStoreObject {
let (v, d, r, b) = try get(key)
return BRKVStoreObject(key: key, version: v, lastModified: d, deleted: r,
data: Data(bytes: UnsafePointer<UInt8>(b), count: b.count))
}
public func set(_ object: BRKVStoreObject) throws -> BRKVStoreObject {
let dat = object.data
var bytes = [UInt8](repeating: 0, count: dat.count)
(dat as NSData).getBytes(&bytes, length: dat.count)
(object.version, object.lastModified) = try set(object.key, value: bytes, localVer: object.version)
return object
}
public func del(_ object: BRKVStoreObject) throws -> BRKVStoreObject {
(object.version, object.lastModified) = try del(object.key, localVer: object.version)
object.deleted = true
return object
}
}
| mit | 7b3f5e7bf07f77fb4c0bfe257f2473b7 | 43.933974 | 148 | 0.545204 | 4.441149 | false | false | false | false |
mshhmzh/firefox-ios | Client/Frontend/Home/BookmarksPanel.swift | 2 | 21360 | /* 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
import Storage
import Shared
import XCGLogger
private let log = Logger.browserLogger
let BookmarkStatusChangedNotification = "BookmarkStatusChangedNotification"
// MARK: - Placeholder strings for Bug 1232810.
let deleteWarningTitle = NSLocalizedString("This folder isn't empty.", tableName: "BookmarkPanelDeleteConfirm", comment: "Title of the confirmation alert when the user tries to delete a folder that still contains bookmarks and/or folders.")
let deleteWarningDescription = NSLocalizedString("Are you sure you want to delete it and its contents?", tableName: "BookmarkPanelDeleteConfirm", comment: "Main body of the confirmation alert when the user tries to delete a folder that still contains bookmarks and/or folders.")
let deleteCancelButtonLabel = NSLocalizedString("Cancel", tableName: "BookmarkPanelDeleteConfirm", comment: "Button label to cancel deletion when the user tried to delete a non-empty folder.")
let deleteDeleteButtonLabel = NSLocalizedString("Delete", tableName: "BookmarkPanelDeleteConfirm", comment: "Button label for the button that deletes a folder and all of its children.")
// Placeholder strings for Bug 1248034
let emptyBookmarksText = NSLocalizedString("Bookmarks you save will show up here.", comment: "Status label for the empty Bookmarks state.")
// MARK: - UX constants.
struct BookmarksPanelUX {
private static let BookmarkFolderHeaderViewChevronInset: CGFloat = 10
private static let BookmarkFolderChevronSize: CGFloat = 20
private static let BookmarkFolderChevronLineWidth: CGFloat = 4.0
private static let BookmarkFolderTextColor = UIColor(red: 92/255, green: 92/255, blue: 92/255, alpha: 1.0)
private static let WelcomeScreenPadding: CGFloat = 15
private static let WelcomeScreenItemTextColor = UIColor.grayColor()
private static let WelcomeScreenItemWidth = 170
private static let SeparatorRowHeight: CGFloat = 0.5
}
class BookmarksPanel: SiteTableViewController, HomePanel {
weak var homePanelDelegate: HomePanelDelegate? = nil
var source: BookmarksModel?
var parentFolders = [BookmarkFolder]()
var bookmarkFolder: BookmarkFolder?
private lazy var emptyStateOverlayView: UIView = self.createEmptyStateOverlayView()
private let BookmarkFolderCellIdentifier = "BookmarkFolderIdentifier"
private let BookmarkSeparatorCellIdentifier = "BookmarkSeparatorIdentifier"
private let BookmarkFolderHeaderViewIdentifier = "BookmarkFolderHeaderIdentifier"
init() {
super.init(nibName: nil, bundle: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(BookmarksPanel.notificationReceived(_:)), name: NotificationFirefoxAccountChanged, object: nil)
self.tableView.registerClass(SeparatorTableCell.self, forCellReuseIdentifier: BookmarkSeparatorCellIdentifier)
self.tableView.registerClass(BookmarkFolderTableViewCell.self, forCellReuseIdentifier: BookmarkFolderCellIdentifier)
self.tableView.registerClass(BookmarkFolderTableViewHeader.self, forHeaderFooterViewReuseIdentifier: BookmarkFolderHeaderViewIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self, name: NotificationFirefoxAccountChanged, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
// If we've not already set a source for this panel, fetch a new model from
// the root; otherwise, just use the existing source to select a folder.
guard let source = self.source else {
// Get all the bookmarks split by folders
if let bookmarkFolder = bookmarkFolder {
profile.bookmarks.modelFactory >>== { $0.modelForFolder(bookmarkFolder).upon(self.onModelFetched) }
} else {
profile.bookmarks.modelFactory >>== { $0.modelForRoot().upon(self.onModelFetched) }
}
return
}
if let bookmarkFolder = bookmarkFolder {
source.selectFolder(bookmarkFolder).upon(onModelFetched)
} else {
source.selectFolder(BookmarkRoots.MobileFolderGUID).upon(onModelFetched)
}
self.tableView.accessibilityIdentifier = "Bookmarks List"
}
func notificationReceived(notification: NSNotification) {
switch notification.name {
case NotificationFirefoxAccountChanged:
self.reloadData()
break
default:
// no need to do anything at all
log.warning("Received unexpected notification \(notification.name)")
break
}
}
private func createEmptyStateOverlayView() -> UIView {
let overlayView = UIView()
overlayView.backgroundColor = UIColor.whiteColor()
let logoImageView = UIImageView(image: UIImage(named: "emptyBookmarks"))
overlayView.addSubview(logoImageView)
logoImageView.snp_makeConstraints { make in
make.centerX.equalTo(overlayView)
// Sets proper top constraint for iPhone 6 in portait and for iPad.
make.centerY.equalTo(overlayView).offset(HomePanelUX.EmptyTabContentOffset).priorityMedium()
// Sets proper top constraint for iPhone 4, 5 in portrait.
make.top.greaterThanOrEqualTo(overlayView).offset(50)
}
let welcomeLabel = UILabel()
overlayView.addSubview(welcomeLabel)
welcomeLabel.text = emptyBookmarksText
welcomeLabel.textAlignment = NSTextAlignment.Center
welcomeLabel.font = DynamicFontHelper.defaultHelper.DeviceFontLight
welcomeLabel.textColor = BookmarksPanelUX.WelcomeScreenItemTextColor
welcomeLabel.numberOfLines = 0
welcomeLabel.adjustsFontSizeToFitWidth = true
welcomeLabel.snp_makeConstraints { make in
make.centerX.equalTo(overlayView)
make.top.equalTo(logoImageView.snp_bottom).offset(BookmarksPanelUX.WelcomeScreenPadding)
make.width.equalTo(BookmarksPanelUX.WelcomeScreenItemWidth)
}
return overlayView
}
private func updateEmptyPanelState() {
if source?.current.count == 0 && source?.current.guid == BookmarkRoots.MobileFolderGUID {
if self.emptyStateOverlayView.superview == nil {
self.view.addSubview(self.emptyStateOverlayView)
self.view.bringSubviewToFront(self.emptyStateOverlayView)
self.emptyStateOverlayView.snp_makeConstraints { make -> Void in
make.edges.equalTo(self.tableView)
}
}
} else {
self.emptyStateOverlayView.removeFromSuperview()
}
}
private func onModelFetched(result: Maybe<BookmarksModel>) {
guard let model = result.successValue else {
self.onModelFailure(result.failureValue)
return
}
self.onNewModel(model)
}
private func onNewModel(model: BookmarksModel) {
if NSThread.currentThread().isMainThread {
self.source = model
self.tableView.reloadData()
return
}
dispatch_async(dispatch_get_main_queue()) {
self.source = model
self.tableView.reloadData()
self.updateEmptyPanelState()
}
}
private func onModelFailure(e: Any) {
log.error("Error: failed to get data: \(e)")
}
override func reloadData() {
self.source?.reloadData().upon(onModelFetched)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return source?.current.count ?? 0
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
guard let source = source, bookmark = source.current[indexPath.row] else { return super.tableView(tableView, cellForRowAtIndexPath: indexPath) }
switch (bookmark) {
case let item as BookmarkItem:
let cell = super.tableView(tableView, cellForRowAtIndexPath: indexPath)
if item.title.isEmpty {
cell.textLabel?.text = item.url
} else {
cell.textLabel?.text = item.title
}
if let url = bookmark.favicon?.url.asURL where url.scheme == "asset" {
cell.imageView?.image = UIImage(named: url.host!)
} else if let bookmarkURL = NSURL(string: item.url) {
cell.imageView?.setIcon(bookmark.favicon, withPlaceholder: FaviconFetcher.getDefaultFavicon(bookmarkURL))
} else {
cell.imageView?.setIcon(bookmark.favicon, withPlaceholder: FaviconFetcher.defaultFavicon)
}
return cell
case is BookmarkSeparator:
return tableView.dequeueReusableCellWithIdentifier(BookmarkSeparatorCellIdentifier, forIndexPath: indexPath)
case let bookmark as BookmarkFolder:
let cell = tableView.dequeueReusableCellWithIdentifier(BookmarkFolderCellIdentifier, forIndexPath: indexPath)
cell.textLabel?.text = bookmark.title
return cell
default:
// This should never happen.
return super.tableView(tableView, cellForRowAtIndexPath: indexPath)
}
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if let cell = cell as? BookmarkFolderTableViewCell {
cell.textLabel?.font = DynamicFontHelper.defaultHelper.DeviceFontHistoryPanel
}
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
// Don't show a header for the root
if source == nil || parentFolders.isEmpty {
return nil
}
guard let header = tableView.dequeueReusableHeaderFooterViewWithIdentifier(BookmarkFolderHeaderViewIdentifier) as? BookmarkFolderTableViewHeader else { return nil }
// register as delegate to ensure we get notified when the user interacts with this header
if header.delegate == nil {
header.delegate = self
}
if parentFolders.count == 1 {
header.textLabel?.text = NSLocalizedString("Bookmarks", comment: "Panel accessibility label")
} else if let parentFolder = parentFolders.last {
header.textLabel?.text = parentFolder.title
}
return header
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if let it = self.source?.current[indexPath.row] where it is BookmarkSeparator {
return BookmarksPanelUX.SeparatorRowHeight
}
return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
// Don't show a header for the root. If there's no root (i.e. source == nil), we'll also show no header.
if source == nil || parentFolders.isEmpty {
return 0
}
return SiteTableViewControllerUX.RowHeight
}
func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
if let header = view as? BookmarkFolderTableViewHeader {
// for some reason specifying the font in header view init is being ignored, so setting it here
header.textLabel?.font = DynamicFontHelper.defaultHelper.DeviceFontHistoryPanel
}
}
override func tableView(tableView: UITableView, hasFullWidthSeparatorForRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Show a full-width border for cells above separators, so they don't have a weird step.
// Separators themselves already have a full-width border, but let's force the issue
// just in case.
let this = self.source?.current[indexPath.row]
if (indexPath.row + 1) < self.source?.current.count {
let below = self.source?.current[indexPath.row + 1]
if this is BookmarkSeparator || below is BookmarkSeparator {
return true
}
}
return super.tableView(tableView, hasFullWidthSeparatorForRowAtIndexPath: indexPath)
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: false)
guard let source = source else {
return
}
let bookmark = source.current[indexPath.row]
switch (bookmark) {
case let item as BookmarkItem:
homePanelDelegate?.homePanel(self, didSelectURLString: item.url, visitType: VisitType.Bookmark)
break
case let folder as BookmarkFolder:
log.debug("Selected \(folder.guid)")
let nextController = BookmarksPanel()
nextController.parentFolders = parentFolders + [source.current]
nextController.bookmarkFolder = folder
nextController.homePanelDelegate = self.homePanelDelegate
nextController.profile = self.profile
source.modelFactory.uponQueue(dispatch_get_main_queue()) { maybe in
guard let factory = maybe.successValue else {
// Nothing we can do.
return
}
nextController.source = BookmarksModel(modelFactory: factory, root: folder)
self.navigationController?.pushViewController(nextController, animated: true)
}
break
default:
// You can't do anything with separators.
break
}
}
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
// Intentionally blank. Required to use UITableViewRowActions
}
func tableView(tableView: UITableView, editingStyleForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCellEditingStyle {
guard let source = source else {
return .None
}
if source.current[indexPath.row] is BookmarkSeparator {
// Because the deletion block is too big.
return .None
}
if source.current.itemIsEditableAtIndex(indexPath.row) ?? false {
return .Delete
}
return .None
}
func tableView(tableView: UITableView, editActionsForRowAtIndexPath indexPath: NSIndexPath) -> [AnyObject]? {
guard let source = self.source else {
return [AnyObject]()
}
let title = NSLocalizedString("Delete", tableName: "BookmarkPanel", comment: "Action button for deleting bookmarks in the bookmarks panel.")
let delete = UITableViewRowAction(style: UITableViewRowActionStyle.Default, title: title, handler: { (action, indexPath) in
guard let bookmark = source.current[indexPath.row] else {
return
}
assert(!(bookmark is BookmarkFolder))
if bookmark is BookmarkFolder {
// TODO: check whether the folder is empty (excluding separators). If it isn't
// then we must ask the user to confirm. Bug 1232810.
log.debug("Not deleting folder.")
return
}
log.debug("Removing rows \(indexPath).")
// Block to do this -- this is UI code.
guard let factory = source.modelFactory.value.successValue else {
log.error("Couldn't get model factory. This is unexpected.")
self.onModelFailure(DatabaseError(description: "Unable to get factory."))
return
}
if let err = factory.removeByGUID(bookmark.guid).value.failureValue {
log.debug("Failed to remove \(bookmark.guid).")
self.onModelFailure(err)
return
}
guard let reloaded = source.reloadData().value.successValue else {
log.debug("Failed to reload model.")
return
}
self.tableView.beginUpdates()
self.source = reloaded
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: UITableViewRowAnimation.Left)
self.tableView.endUpdates()
self.updateEmptyPanelState()
NSNotificationCenter.defaultCenter().postNotificationName(BookmarkStatusChangedNotification, object: bookmark, userInfo:["added": false])
})
return [delete]
}
}
private protocol BookmarkFolderTableViewHeaderDelegate {
func didSelectHeader()
}
extension BookmarksPanel: BookmarkFolderTableViewHeaderDelegate {
private func didSelectHeader() {
self.navigationController?.popViewControllerAnimated(true)
}
}
class BookmarkFolderTableViewCell: TwoLineTableViewCell {
private let ImageMargin: CGFloat = 12
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = SiteTableViewControllerUX.HeaderBackgroundColor
textLabel?.backgroundColor = UIColor.clearColor()
textLabel?.tintColor = BookmarksPanelUX.BookmarkFolderTextColor
imageView?.image = UIImage(named: "bookmarkFolder")
let chevron = ChevronView(direction: .Right)
chevron.tintColor = BookmarksPanelUX.BookmarkFolderTextColor
chevron.frame = CGRectMake(0, 0, BookmarksPanelUX.BookmarkFolderChevronSize, BookmarksPanelUX.BookmarkFolderChevronSize)
chevron.lineWidth = BookmarksPanelUX.BookmarkFolderChevronLineWidth
accessoryView = chevron
separatorInset = UIEdgeInsetsZero
}
override func layoutSubviews() {
super.layoutSubviews()
// Do this here as TwoLineTableViewCell changes the imageView frame
// in its own layoutSubviews, and we have to make sure it is right.
if let imageSize = imageView?.image?.size {
imageView?.frame = CGRectMake(ImageMargin, (frame.height - imageSize.width) / 2, imageSize.width, imageSize.height)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private class BookmarkFolderTableViewHeader : UITableViewHeaderFooterView {
var delegate: BookmarkFolderTableViewHeaderDelegate?
lazy var titleLabel: UILabel = {
let label = UILabel()
label.textColor = UIConstants.HighlightBlue
return label
}()
lazy var chevron: ChevronView = {
let chevron = ChevronView(direction: .Left)
chevron.tintColor = UIConstants.HighlightBlue
chevron.lineWidth = BookmarksPanelUX.BookmarkFolderChevronLineWidth
return chevron
}()
lazy var topBorder: UIView = {
let view = UIView()
view.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
return view
}()
lazy var bottomBorder: UIView = {
let view = UIView()
view.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
return view
}()
override var textLabel: UILabel? {
return titleLabel
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
userInteractionEnabled = true
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(BookmarkFolderTableViewHeader.viewWasTapped(_:)))
tapGestureRecognizer.numberOfTapsRequired = 1
addGestureRecognizer(tapGestureRecognizer)
addSubview(topBorder)
addSubview(bottomBorder)
contentView.addSubview(chevron)
contentView.addSubview(titleLabel)
chevron.snp_makeConstraints { make in
make.left.equalTo(contentView).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.centerY.equalTo(contentView)
make.size.equalTo(BookmarksPanelUX.BookmarkFolderChevronSize)
}
titleLabel.snp_makeConstraints { make in
make.left.equalTo(chevron.snp_right).offset(BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.right.greaterThanOrEqualTo(contentView).offset(-BookmarksPanelUX.BookmarkFolderHeaderViewChevronInset)
make.centerY.equalTo(contentView)
}
topBorder.snp_makeConstraints { make in
make.left.right.equalTo(self)
make.top.equalTo(self).offset(-0.5)
make.height.equalTo(0.5)
}
bottomBorder.snp_makeConstraints { make in
make.left.right.bottom.equalTo(self)
make.height.equalTo(0.5)
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func viewWasTapped(gestureRecognizer: UITapGestureRecognizer) {
delegate?.didSelectHeader()
}
}
| mpl-2.0 | b84b6d6a06bfb82a9208ec77a909cbe1 | 40.964637 | 278 | 0.677013 | 5.735768 | false | false | false | false |
Sidetalker/TapMonkeys | TapMonkeys/TapMonkeys/UpgradesViewController.swift | 1 | 3191 | //
// UpgradesViewController.swift
// TapMonkeys
//
// Created by Kevin Sullivan on 5/18/15.
// Copyright (c) 2015 Kevin Sullivan. All rights reserved.
//
import UIKit
class UpgradesViewController: UIViewController {
@IBOutlet weak var dataHeader: DataHeader!
var upgradesTable: UpgradesTableViewController?
override func viewDidLoad() {
super.viewDidLoad()
}
override func prefersStatusBarHidden() -> Bool {
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "segueUpgradesTable" {
upgradesTable = segue.destinationViewController as? UpgradesTableViewController
}
}
}
class UpgradesTableViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate {
var collapseFlags = [true, true, true]
var upgrades = [
[ "Tap A",
"Mega Tap"
],
[ "Noice",
"Blaster",
"Fang",
"Killer",
"Pikaschie"
],
[ "Tibbyt",
"Frag",
"Libel"
]]
override func viewDidLoad() {
super.viewDidLoad()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return count(getRowTypes())
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 80
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if isSectionRow(indexPath.row) {
if let
cell = tableView.dequeueReusableCellWithIdentifier("cellSection") as? UITableViewCell,
img = cell.viewWithTag(1) as? UIImageView,
title = cell.viewWithTag(2) as? UILabel,
lock = cell.viewWithTag(3) as? UIImageView
{
lock.alpha = 0.0
return cell
}
}
else {
if let
cell = tableView.dequeueReusableCellWithIdentifier("cellUpgrade") as? UITableViewCell,
title = cell.viewWithTag(1) as? UILabel
{
}
}
return UITableViewCell()
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
return
}
func isSectionRow(row: Int) -> Bool {
return getRowTypes()[row]
}
// Return an array of booleans - true are "section" cells
func getRowTypes() -> [Bool] {
var rowCount = [Bool]()
for i in 0...count(upgrades) - 1 {
rowCount.append(true)
if !collapseFlags[i] {
for upgrade in 0...count(upgrades[i]) - 1 {
rowCount.append(false)
}
}
}
return rowCount
}
} | mit | dc123ef3f408107ce488a8194bc1958c | 26.517241 | 118 | 0.555625 | 5.327212 | false | false | false | false |
TCA-Team/iOS | TUM Campus App/DepartureView.swift | 1 | 2250 | //
// DepartureView.swift
// Campus
//
// Created by Florian Fittschen on 16.10.18.
// Copyright © 2018 LS1 TUM. All rights reserved.
//
import UIKit
class DepartureView: UIView {
@IBOutlet private var contentView: UIView!
@IBOutlet private weak var lineLabel: UILabel!
@IBOutlet private weak var destinationLabel: UILabel!
@IBOutlet private weak var departureLabel: UILabel! {
didSet {
// Use monospaced font to avoid a jumping destinationLabel on every tick of the countdown
departureLabel.font = UIFont.monospacedDigitSystemFont(ofSize: departureLabel!.font!.pointSize,
weight: UIFont.Weight.regular)
}
}
private var departure: Departure?
private var timer: Timer?
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
deinit {
timer?.invalidate()
}
func configure(with departure: Departure) {
self.departure = departure
destinationLabel.text = departure.destination
lineLabel.backgroundColor = UIColor(hexString: departure.lineBackgroundColor)
if ["u", "s"].contains(departure.product) {
lineLabel.text = "\(departure.product.uppercased())\(departure.label)"
} else {
lineLabel.text = departure.label
}
timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
self?.updateTimeRemaining()
}
updateTimeRemaining()
}
private func commonInit() {
Bundle.main.loadNibNamed(String(describing: DepartureView.self), owner: self, options: nil)
addSubview(contentView)
contentView.frame = self.bounds
contentView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
}
private func updateTimeRemaining() {
guard let departure = departure else { return }
let secondsLeft = departure.departureTime.timeIntervalSinceNow
departureLabel.text = DateComponentsFormatter.shortTimeFormatter.string(from: secondsLeft) ?? ""
}
}
| gpl-3.0 | 983e4fab08a615579d5c232f3d8f89b7 | 29.808219 | 107 | 0.63984 | 4.88913 | false | false | false | false |
eBardX/XestiMonitors | Tests/Mock/MockNotificationCenter.swift | 1 | 2329 | //
// MockNotificationCenter.swift
// XestiMonitorsTests
//
// Created by J. G. Pusey on 2017-12-27.
//
// © 2017 J. G. Pusey (see LICENSE.md)
//
import Foundation
@testable import XestiMonitors
internal class MockNotificationCenter: NotificationCenterProtocol {
class MockObserver {
let block: (Notification) -> Void
let object: Any?
let queue: OperationQueue?
init(object: Any?,
queue: OperationQueue?,
block: @escaping (Notification) -> Void) {
self.block = block
self.object = object
self.queue = queue
}
}
var observers: [String: MockObserver] = [:]
func addObserver(forName name: NSNotification.Name?,
object: Any?,
queue: OperationQueue?,
using block: @escaping (Notification) -> Void) -> NSObjectProtocol {
guard
let name = name
else { fatalError("Name must be specified for testing") }
guard
observers[name.rawValue] == nil
else { fatalError("Cannot have multiple observers for same name") }
observers[name.rawValue] = MockObserver(object: object,
queue: queue,
block: block)
return name.rawValue as NSString
}
func post(name: NSNotification.Name,
object: Any?,
userInfo: [AnyHashable: Any]? = nil) {
guard
let observer = observers[name.rawValue]
else { return }
if let filter = observer.object as AnyObject? {
guard
let object = object as AnyObject?,
filter === object
else { return }
}
let notification = Notification(name: name,
object: object,
userInfo: userInfo)
if let queue = observer.queue {
queue.addOperation { observer.block(notification) }
} else {
observer.block(notification)
}
}
func removeObserver(_ observer: Any) {
guard
let name = observer as? String
else { return }
observers[name] = nil
}
}
| mit | 262971b84a4535027c2c523fc05b7733 | 27.740741 | 89 | 0.516753 | 5.290909 | false | false | false | false |
gowansg/firefox-ios | ClientTests/MockProfile.swift | 1 | 2237 | /* 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 Account
import ReadingList
import Shared
import Storage
import Sync
import XCTest
public class MockProfile: Profile {
private let name: String = "mockaccount"
func localName() -> String {
return name
}
lazy var db: BrowserDB = {
return BrowserDB(files: self.files)
} ()
lazy var bookmarks: protocol<BookmarksModelFactory, ShareToDestination> = {
// Eventually this will be a SyncingBookmarksModel or an OfflineBookmarksModel, perhaps.
return BookmarksSqliteFactory(db: self.db)
} ()
lazy var searchEngines: SearchEngines = {
return SearchEngines(prefs: self.prefs)
} ()
lazy var prefs: Prefs = {
return MockProfilePrefs()
} ()
lazy var files: FileAccessor = {
return ProfileFileAccessor(profile: self)
} ()
lazy var favicons: Favicons = {
return SQLiteFavicons(db: self.db)
}()
lazy var history: BrowserHistory = {
return SQLiteHistory(db: self.db)
}()
lazy var readingList: ReadingListService? = {
return ReadingListService(profileStoragePath: self.files.rootPath)
}()
private lazy var remoteClientsAndTabs: RemoteClientsAndTabs = {
return SQLiteRemoteClientsAndTabs(db: self.db)
}()
lazy var passwords: Passwords = {
return MockPasswords(files: self.files)
}()
lazy var thumbnails: Thumbnails = {
return SDWebThumbnails(files: self.files)
}()
let accountConfiguration: FirefoxAccountConfiguration = ProductionFirefoxAccountConfiguration()
var account: FirefoxAccount? = nil
func getAccount() -> FirefoxAccount? {
return account
}
func setAccount(account: FirefoxAccount?) {
self.account = account
}
func getClients() -> Deferred<Result<[RemoteClient]>> {
return deferResult([])
}
func getClientsAndTabs() -> Deferred<Result<[ClientAndTabs]>> {
return deferResult([])
}
} | mpl-2.0 | 7b31a5b84e76504029d55af238c6f3a7 | 25.963855 | 99 | 0.651319 | 4.982183 | false | false | false | false |
digitrick/LocalizedStringSwift | LocalizedStringSwiftDemo/LocalizedStringSwiftDemo/ViewController.swift | 1 | 1659 | //
// ViewController.swift
// LocalizedStringSwiftDemo
//
// Created by Kenta Nakae on 11/29/16.
// Copyright © 2016 digitrick. All rights reserved.
//
import UIKit
import LocalizedStringSwift
class ViewController: UIViewController {
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBOutlet weak var label: UILabel!
let localizedLanguage = LocalizedString.language
override func viewDidLoad() {
super.viewDidLoad()
// localizedLanguage.resetLanguage()
if localizedLanguage.currentIdentifier == "ja" {
segmentedControl.selectedSegmentIndex = 1
} else {
segmentedControl.selectedSegmentIndex = 0
}
selectLanguage(segmentedControl)
NotificationCenter.default.addObserver(self, selector: #selector(changedLanguage), name: NSNotification.Name(.localizedLanguageChanged), object: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func changedLanguage() {
print("Changed to \(localizedLanguage.currentDisplayName) ")
}
@IBAction func selectLanguage(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
label.text = label.text?.localized(key: "title", language: "en")
localizedLanguage.currentIdentifier = "en"
case 1:
label.text = label.text?.localized(key: "title", language: "ja")
localizedLanguage.currentIdentifier = "ja"
default:
return
}
}
}
| mit | 26babf8b1013282a2632f6da52e6df93 | 28.607143 | 157 | 0.650181 | 5.133127 | false | false | false | false |
Antondomashnev/FBSnapshotsViewer | FBSnapshotsViewer/Managers/SnapshotTestResultAcceptor.swift | 1 | 4195 | //
// SnapshotTestResultAcceptor.swift
// FBSnapshotsViewer
//
// Created by Anton Domashnev on 27.06.17.
// Copyright © 2017 Anton Domashnev. All rights reserved.
//
import Foundation
import Nuke
enum SnapshotTestResultAcceptorError: Error {
case canNotBeAccepted(testResult: SnapshotTestResult)
case nonRetinaImages(testResult: SnapshotTestResult)
case notExistedRecordedImage(testResult: SnapshotTestResult)
case canNotPerformFileManagerOperation(testResult: SnapshotTestResult, underlyingError: Error)
}
class SnapshotTestResultAcceptor {
private let fileManager: FileManager
private let imageCache: ImageCache
init(fileManager: FileManager = FileManager.default, imageCache: ImageCache = Nuke.Cache.shared) {
self.imageCache = imageCache
self.fileManager = fileManager
}
// MARK: - Helpers
private func buildRecordedImageURL(from imagePath: String, of testResult: SnapshotTestResult) throws -> URL {
guard let failedImageSizeSuffixRange = imagePath.range(of: "@\\d{1}x", options: .regularExpression) else {
throw SnapshotTestResultAcceptorError.nonRetinaImages(testResult: testResult)
}
let failedImageSizeSuffix = imagePath.substring(with: failedImageSizeSuffixRange)
let recordedImageURLs = testResult.build.fbReferenceImageDirectoryURLs.flatMap { fbReferenceImageDirectoryURL -> URL? in
let url = fbReferenceImageDirectoryURL.appendingPathComponent(testResult.testClassName).appendingPathComponent("\(testResult.testName)\(failedImageSizeSuffix)").appendingPathExtension("png")
return fileManager.fileExists(atPath: url.path) ? url : nil
}
guard let url = recordedImageURLs.first else {
throw SnapshotTestResultAcceptorError.notExistedRecordedImage(testResult: testResult)
}
return url
}
// MARK: - Interface
func canAccept(_ testResult: SnapshotTestResult) -> Bool {
if case SnapshotTestResult.failed(_, _, _, _, _) = testResult {
return true
}
return false
}
func accept(_ testResult: SnapshotTestResult) throws -> SnapshotTestResult {
let removeAcceptedImages = true
guard case let SnapshotTestResult.failed(testInformation, _, _, failedImagePath, build) = testResult, canAccept(testResult) else {
throw SnapshotTestResultAcceptorError.canNotBeAccepted(testResult: testResult)
}
let failedImageURL = URL(fileURLWithPath: failedImagePath, isDirectory: false)
do {
let recordedImageURL = try buildRecordedImageURL(from: failedImagePath, of: testResult)
try fileManager.moveItem(at: failedImageURL, to: recordedImageURL)
if removeAcceptedImages {
try removeTestImages(testResult)
}
imageCache.invalidate()
return SnapshotTestResult.recorded(testInformation: testInformation, referenceImagePath: recordedImageURL.path, build: build)
}
catch let error {
throw SnapshotTestResultAcceptorError.canNotPerformFileManagerOperation(testResult: testResult, underlyingError: error)
}
}
func removeTestImages(_ testResult: SnapshotTestResult) throws {
guard case let SnapshotTestResult.failed(_, referenceImagePath, diffImagePath, failedImagePath, _) = testResult else {
throw SnapshotTestResultAcceptorError.canNotBeAccepted(testResult: testResult)
}
let referenceImageURL = URL(fileURLWithPath: referenceImagePath, isDirectory: false)
let diffImageURL = URL(fileURLWithPath: diffImagePath, isDirectory: false)
let failedImageURL = URL(fileURLWithPath: failedImagePath, isDirectory: false)
do {
try fileManager.deleteIfExists(at: referenceImageURL)
try fileManager.deleteIfExists(at: diffImageURL)
try fileManager.deleteIfExists(at: failedImageURL)
}
catch let error {
throw SnapshotTestResultAcceptorError.canNotPerformFileManagerOperation(testResult: testResult, underlyingError: error)
}
}
}
| mit | 9326476545738cbf9f213f8b5f4ac21d | 44.096774 | 202 | 0.709347 | 5.209938 | false | true | false | false |
pauljohanneskraft/Math | CoreMath/Classes/Linear Algebra/TransposedDenseMatrix.swift | 1 | 2520 | //
// TransposedDenseMatrix.swift
// Math
//
// Created by Paul Kraft on 13.12.17.
// Copyright © 2017 pauljohanneskraft. All rights reserved.
//
import Foundation
public struct TransposedDenseMatrix<Number: BasicArithmetic>: LinearAlgebraicArithmetic {
public typealias MultiplicationResult = DenseMatrix<Number>
public typealias Transposed = DenseMatrix<Number>
public typealias Row = [Number]
public typealias TwoDimensionalArray = [[Number]]
public typealias Size = (rows: Int, columns: Int)
public var transposed: DenseMatrix<Number>
public var denseMatrix: DenseMatrix<Number> {
return DenseMatrix(matrix)
}
public init(_ original: DenseMatrix<Number>) {
transposed = original
}
public var matrix: [[Number]] {
let (rows, columns) = self.size
let matrix = (0..<columns).map { column in
(0..<rows).map { row in transposed[row, column] }
}
return matrix
}
public var size: LinearAlgebraic.Size {
let orig = transposed.size
return (orig.columns, orig.rows)
}
public subscript(row: Int) -> Row {
get {
return transposed.elements.map { $0[row] }
}
set {
for index in newValue.indices {
transposed[index, row] = newValue[index]
}
}
}
public subscript(row: Int, column: Int) -> Number {
get {
return transposed[column, row]
}
set {
transposed[column, row] = newValue
}
}
public static func * <L: LinearAlgebraic>(lhs: TransposedDenseMatrix<Number>, rhs: L)
-> DenseMatrix<Number> where Number == L.Number {
assert(lhs.size.columns == rhs.size.rows)
let ls = lhs.size, lrows = 0..<ls.rows, lcols = 0..<ls.columns
let rcols = 0..<rhs.size.columns
let elements = lrows.map { i -> Row in
rcols.map { j -> Number in
lcols.reduce(into: 0) { value, k in value += lhs[i, k] * rhs[k, j] }
}
}
return DenseMatrix(elements)
}
public static func *= (lhs: inout TransposedDenseMatrix, rhs: Number) {
lhs.transposed *= rhs
}
}
extension TransposedDenseMatrix: All {}
extension TransposedDenseMatrix: CustomStringConvertible {
public var description: String {
return transposed.description + "^T"
}
}
| mit | e6abe20356c7d97820b83a5f74f525a7 | 28.290698 | 89 | 0.57761 | 4.27674 | false | false | false | false |
zmeyc/GRDB.swift | GRDB/QueryInterface/SQLExpression.swift | 1 | 4783 | // MARK: - SQLExpression
/// This protocol is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// # Low Level Query Interface
///
/// SQLExpression is the protocol for types that represent an SQL expression, as
/// described at https://www.sqlite.org/lang_expr.html
///
/// GRDB ships with a variety of types that already adopt this protocol, and
/// allow to represent many SQLite expressions:
///
/// - Column
/// - DatabaseValue
/// - SQLExpressionLiteral
/// - SQLExpressionUnary
/// - SQLExpressionBinary
/// - SQLExpressionExists
/// - SQLExpressionFunction
/// - SQLExpressionCollate
public protocol SQLExpression : SQLSpecificExpressible, SQLSelectable, SQLOrderingTerm {
/// This function is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// # Low Level Query Interface
///
/// Returns an SQL string that represents the expression.
///
/// When the arguments parameter is nil, any value must be written down as
/// a literal in the returned SQL:
///
/// var arguments: StatementArguments? = nil
/// let expression = "foo'bar".databaseValue
/// expression.expressionSQL(&arguments) // "'foo''bar'"
///
/// When the arguments parameter is not nil, then values may be replaced by
/// `?` or colon-prefixed tokens, and fed into arguments.
///
/// var arguments = StatementArguments()
/// let expression = "foo'bar".databaseValue
/// expression.expressionSQL(&arguments) // "?"
/// arguments // ["foo'bar"]
func expressionSQL(_ arguments: inout StatementArguments?) -> String
/// This property is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// # Low Level Query Interface
///
/// Returns the expression, negated. This property fuels the `!` operator.
///
/// The default implementation returns the expression prefixed by `NOT`.
///
/// let column = Column("favorite")
/// column.negated // NOT favorite
///
/// Some expressions may provide a custom implementation that returns a
/// more natural SQL expression.
///
/// let expression = [1,2,3].contains(Column("id")) // id IN (1,2,3)
/// expression.negated // id NOT IN (1,2,3)
var negated: SQLExpression { get }
}
extension SQLExpression {
/// This property is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// # Low Level Query Interface
///
/// The default implementation returns the expression prefixed by `NOT`.
///
/// let column = Column("favorite")
/// column.negated // NOT favorite
///
public var negated: SQLExpression {
return SQLExpressionNot(self)
}
}
// SQLExpression: SQLExpressible
extension SQLExpression {
/// This property is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// # Low Level Query Interface
///
/// See SQLExpressible.sqlExpression
public var sqlExpression: SQLExpression {
return self
}
}
// SQLExpression: SQLSelectable
extension SQLExpression {
/// This function is an implementation detail of the query interface.
/// Do not use it directly.
///
/// See https://github.com/groue/GRDB.swift/#the-query-interface
///
/// # Low Level Query Interface
///
/// See SQLSelectable.count(distinct:from:aliased:)
public func count(distinct: Bool) -> SQLCount? {
if distinct {
// SELECT DISTINCT expr FROM tableName ...
// ->
// SELECT COUNT(DISTINCT expr) FROM tableName ...
return .distinct(self)
} else {
// SELECT expr FROM tableName ...
// ->
// SELECT COUNT(*) FROM tableName ...
return .star
}
}
}
// MARK: - SQLExpressionNot
struct SQLExpressionNot : SQLExpression {
let expression: SQLExpression
init(_ expression: SQLExpression) {
self.expression = expression
}
func expressionSQL(_ arguments: inout StatementArguments?) -> String {
return "NOT \(expression.expressionSQL(&arguments))"
}
var negated: SQLExpression {
return expression
}
}
| mit | be59c9806aa99885d67a4700e6949798 | 30.467105 | 88 | 0.619486 | 4.698428 | false | false | false | false |
AceWangLei/BYWeiBo | BYWeiBo/BYRetweetStatusView.swift | 1 | 2625 | //
// BYRetweetStatusView.swift
// BYWeiBo
//
// Created by qingyun on 16/1/28.
// Copyright © 2016年 lit. All rights reserved.
//
import UIKit
import SnapKit
class BYRetweetStatusView: UIView {
/** Constraint 当前View的底部约束 */
var bottonCons: Constraint?
var statusViewModel: BYStatusViewModel? {
didSet {
contentLabel.text = statusViewModel?.retweetText
bottonCons?.uninstall()
if let pic_urls = statusViewModel?.status?.retweeted_status?.pic_urls where pic_urls.count > 0 {
// 显示view
pictureView.hidden = false
pictureView.pic_urls = pic_urls
self.snp_makeConstraints(closure: { (make) -> Void in
bottonCons = make.bottom.equalTo(pictureView).offset(BYStatusCellMargin).constraint
})
}
else
{
pictureView.hidden = true
self.snp_makeConstraints(closure: { (make) -> Void in
bottonCons = make.bottom.equalTo(contentLabel).offset(BYStatusCellMargin).constraint
})
}
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
backgroundColor = UIColor(white: 242/255, alpha: 1)
addSubview(contentLabel)
addSubview(pictureView)
contentLabel.snp_makeConstraints { make in
make.leading.equalTo(self).offset(BYStatusCellMargin)
make.top.equalTo(self).offset(BYStatusCellMargin)
make.trailing.equalTo(self).offset(-BYStatusCellMargin)
}
pictureView.snp_makeConstraints { make in
make.leading.equalTo(contentLabel)
make.top.equalTo(contentLabel.snp_bottom).offset(BYStatusCellMargin)
}
snp_makeConstraints{ (make) -> Void in
bottonCons = make.bottom.equalTo(pictureView).offset(BYStatusCellMargin)
.constraint
}
}
// MARK: - 懒加载
private lazy var contentLabel: UILabel = {
let label = UILabel(textColor: UIColor.darkGrayColor(), fontSize: 15)
label.numberOfLines = 0
return label
}()
private lazy var pictureView: BYStatusPictureView = {
let view = BYStatusPictureView()
view.backgroundColor = self.backgroundColor
return view
}()
}
| apache-2.0 | 5d75c53709a4bcc15c972febb7e5094d | 28.862069 | 108 | 0.585065 | 4.828996 | false | false | false | false |
Pluto-Y/SwiftyEcharts | SwiftyEchartsTest_iOS/SplitAreaSpec.swift | 1 | 1641 | //
// SplitAreaSpec.swift
// SwiftyEcharts
//
// Created by Pluto Y on 28/06/2017.
// Copyright © 2017 com.pluto-y. All rights reserved.
//
import Quick
import Nimble
@testable import SwiftyEcharts
class SplitAreaSpec: QuickSpec {
override func spec() {
describe("For SplitArea") {
let showValue = true
let intervalValue: UInt = 12
let areaStyleValue = AreaStyle(
.color(.array([.rgba(114, 172, 209, 0.2), .rgba(114, 172, 209, 0.4), .rgba(114, 172, 209, 0.6), .rgba(114, 172, 209, 0.8), .rgba(114, 172, 209, 1)])),
.shadowColor(.rgba(0, 0, 0, 0.3)),
.shadowBlur(10)
)
let splitArea = SplitArea()
splitArea.show = showValue
splitArea.interval = intervalValue
splitArea.areaStyle = areaStyleValue
it("needs to check the jsonString") {
let resultDic: [String: Jsonable] = [
"show": showValue,
"interval": intervalValue,
"areaStyle": areaStyleValue
]
expect(splitArea.jsonString).to(equal(resultDic.jsonString))
}
it("needs to check the Enumable") {
let splitAreaByEnums = SplitArea(
.show(showValue),
.interval(intervalValue),
.areaStyle(areaStyleValue)
)
expect(splitAreaByEnums.jsonString).to(equal(splitArea.jsonString))
}
}
}
}
| mit | e07d29fd935310bf89c35fb14261c85c | 31.8 | 166 | 0.50122 | 4.568245 | false | false | false | false |
jairoeli/Habit | Zero/Sources/Reactors/HabitListViewReactor.swift | 1 | 6831 | //
// HabitListViewReactor.swift
// Zero
//
// Created by Jairo Eli de Leon on 5/9/17.
// Copyright © 2017 Jairo Eli de León. All rights reserved.
//
import ReactorKit
import RxCocoa
import RxDataSources
import RxSwift
typealias HabitListSection = SectionModel<Void, HabitCellReactor>
final class HabitListViewReactor: BaseReactor {
enum Action {
case updateHabitTitle(String)
case submit
case refresh
case moveHabit(IndexPath, IndexPath)
case deleteHabit(IndexPath)
case habitIncreaseValue(IndexPath)
case habitDecreaseValue(IndexPath)
}
enum Mutation {
case updateHabitTitle(String)
case setSections([HabitListSection])
case insertSectionItem(IndexPath, HabitListSection.Item)
case updateSectionItem(IndexPath, HabitListSection.Item)
case deleteSectionItem(IndexPath)
case moveSectionItem(IndexPath, IndexPath)
}
struct State {
var sections: [HabitListSection]
var habitTitle: String
var canSubmit: Bool
init(sections: [HabitListSection], habitTitle: String, canSubmit: Bool) {
self.sections = sections
self.habitTitle = habitTitle
self.canSubmit = canSubmit
}
}
let provider: ServiceProviderType
let initialState: State
init(provider: ServiceProviderType) {
self.provider = provider
self.initialState = State(sections: [HabitListSection(model: Void(), items: [])], habitTitle: "", canSubmit: false)
}
// MARK: - Mutate
func mutate(action: Action) -> Observable<Mutation> {
switch action {
case let .updateHabitTitle(habitTitle): return .just(.updateHabitTitle(habitTitle))
case .submit:
guard self.currentState.canSubmit else { return .empty() }
return self.provider.habitService.create(title: self.currentState.habitTitle, memo: nil).flatMap { _ in Observable.empty() }
case .refresh:
return self.provider.habitService.fetchHabit()
.map { habits in
let sectionItems = habits.map(HabitCellReactor.init)
let section = HabitListSection(model: Void(), items: sectionItems)
return .setSections([section])
}
case let .moveHabit(sourceIndexPath, destinationIndexPath):
let habit = self.currentState.sections[sourceIndexPath].currentState
return self.provider.habitService.move(habitID: habit.id, to: destinationIndexPath.item)
.flatMap { _ in Observable.empty() }
case let .deleteHabit(indexPath):
let habit = self.currentState.sections[indexPath].currentState
return self.provider.habitService.delete(habitID: habit.id).flatMap { _ in Observable.empty() }
case let .habitIncreaseValue(indexPath):
let habit = self.currentState.sections[indexPath].currentState
return self.provider.habitService.increaseValue(habitID: habit.id).flatMap { _ in Observable.empty() }
case let .habitDecreaseValue(indexPath):
let habit = self.currentState.sections[indexPath].currentState
return self.provider.habitService.decreaseValue(habitID: habit.id).flatMap { _ in Observable.empty() }
}
}
func transform(mutation: Observable<Mutation>) -> Observable<Mutation> {
let habitEventMutation = self.provider.habitService.event
.flatMap { [weak self] habitEvent -> Observable<Mutation> in
self?.mutate(habitEvent: habitEvent) ?? .empty()
}
return Observable.of(mutation, habitEventMutation).merge()
}
// swiftlint:disable cyclomatic_complexity
private func mutate(habitEvent: HabitEvent) -> Observable<Mutation> {
let state = self.currentState
switch habitEvent {
case let .create(habit):
let indexPath = IndexPath(item: 0, section: 0)
let reactor = HabitCellReactor(habit: habit)
return .just(.insertSectionItem(indexPath, reactor))
case let .update(habit):
guard let indexPath = self.indexPath(forHabitID: habit.id, from: state) else { return .empty() }
let reactor = HabitCellReactor(habit: habit)
return .just(.updateSectionItem(indexPath, reactor))
case let .delete(id):
guard let indexPath = self.indexPath(forHabitID: id, from: state) else { return .empty() }
return .just(.deleteSectionItem(indexPath))
case let .move(id, index):
guard let sourceIndexPath = self.indexPath(forHabitID: id, from: state) else { return .empty() }
let destinationIndexPath = IndexPath(item: index, section: 0)
return .just(.moveSectionItem(sourceIndexPath, destinationIndexPath))
case let .increaseValue(id):
guard let indexPath = self.indexPath(forHabitID: id, from: state) else { return .empty() }
var habit = state.sections[indexPath].currentState
habit.value += 1
let reactor = HabitCellReactor(habit: habit)
return .just(.updateSectionItem(indexPath, reactor))
case let .decreaseValue(id):
guard let indexPath = self.indexPath(forHabitID: id, from: state) else { return .empty() }
var habit = state.sections[indexPath].currentState
habit.value -= 1
let reactor = HabitCellReactor(habit: habit)
return .just(.updateSectionItem(indexPath, reactor))
}
}
// MARK: - Reduce
func reduce(state: State, mutation: Mutation) -> State {
var state = state
switch mutation {
case let .updateHabitTitle(habitTitle):
state.habitTitle = habitTitle
state.canSubmit = !habitTitle.isEmpty
return state
case let .setSections(sections):
state.sections = sections
return state
case let .insertSectionItem(indexPath, sectionItem):
state.sections.insert(sectionItem, at: indexPath)
return state
case let .updateSectionItem(indexPath, sectionItem):
state.sections[indexPath] = sectionItem
return state
case let .deleteSectionItem(indexPath):
state.sections.remove(at: indexPath)
return state
case let .moveSectionItem(sourceIndexPath, destinationIndexPath):
let sectionItem = state.sections.remove(at: sourceIndexPath)
state.sections.insert(sectionItem, at: destinationIndexPath)
return state
}
}
// MARK: - IndexPath
private func indexPath(forHabitID habitID: String, from state: State) -> IndexPath? {
let section = 0
let item = state.sections[section].items.index { reactor in reactor.currentState.id == habitID }
if let item = item {
return IndexPath(item: item, section: section)
} else {
return nil
}
}
// MARK: - Editing Habit
func reactorForEditingHabit(_ habitCellReactor: HabitCellReactor) -> HabitEditViewReactor {
let habit = habitCellReactor.currentState
return HabitEditViewReactor(provider: self.provider, mode: .edit(habit))
}
// MARK: - Present Settings
func settingsViewReactor() -> SettingsViewReactor {
return SettingsViewReactor(provider: provider)
}
}
| mit | 6dcb3be2331e6138fa33593dbccaf75b | 32.150485 | 130 | 0.705667 | 4.344148 | false | false | false | false |
lorentey/swift | stdlib/public/Windows/WinSDK.swift | 6 | 5032 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import WinSDK // Clang module
// WinBase.h
public let HANDLE_FLAG_INHERIT: DWORD = 0x00000001
// WinBase.h
public let STARTF_USESTDHANDLES: DWORD = 0x00000100
// WinBase.h
public let INFINITE: DWORD = DWORD(bitPattern: -1)
// WinBase.h
public let WAIT_OBJECT_0: DWORD = 0
// WinBase.h
public let STD_INPUT_HANDLE: DWORD = DWORD(bitPattern: -10)
public let STD_OUTPUT_HANDLE: DWORD = DWORD(bitPattern: -11)
public let STD_ERROR_HANDLE: DWORD = DWORD(bitPattern: -12)
// handleapi.h
public let INVALID_HANDLE_VALUE: HANDLE = HANDLE(bitPattern: -1)!
// shellapi.h
public let FOF_NO_UI: FILEOP_FLAGS =
FILEOP_FLAGS(FOF_SILENT | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_NOCONFIRMMKDIR)
// winioctl.h
public let FSCTL_SET_REPARSE_POINT: DWORD = 0x900a4
public let FSCTL_GET_REPARSE_POINT: DWORD = 0x900a8
public let FSCTL_DELETE_REPARSE_POINT: DWORD = 0x900ac
// WinSock2.h
public let INVALID_SOCKET: SOCKET = SOCKET(bitPattern: -1)
public let FIONBIO: Int32 = Int32(bitPattern: 0x8004667e)
// WinUser.h
public let CW_USEDEFAULT: Int32 = Int32(truncatingIfNeeded: 2147483648)
public let WS_OVERLAPPEDWINDOW: UINT =
UINT(WS_OVERLAPPED | WS_CAPTION | WS_SYSMENU | WS_THICKFRAME | WS_MINIMIZEBOX | WS_MAXIMIZEBOX)
public let WS_POPUPWINDOW: UINT =
UINT(Int32(WS_POPUP) | WS_BORDER | WS_SYSMENU)
// fileapi.h
public let INVALID_FILE_ATTRIBUTES: DWORD = DWORD(bitPattern: -1)
// CommCtrl.h
public let WC_BUTTONW: [WCHAR] = Array<WCHAR>("Button".utf16)
public let WC_COMBOBOXW: [WCHAR] = Array<WCHAR>("ComboBox".utf16)
public let WC_EDITW: [WCHAR] = Array<WCHAR>("Edit".utf16)
public let WC_HEADERW: [WCHAR] = Array<WCHAR>("SysHeader32".utf16)
public let WC_LISTBOXW: [WCHAR] = Array<WCHAR>("ListBox".utf16)
public let WC_LISTVIEWW: [WCHAR] = Array<WCHAR>("SysListView32".utf16)
public let WC_SCROLLBARW: [WCHAR] = Array<WCHAR>("ScrollBar".utf16)
public let WC_STATICW: [WCHAR] = Array<WCHAR>("Static".utf16)
public let WC_TABCONTROLW: [WCHAR] = Array<WCHAR>("SysTabControl32".utf16)
public let WC_TREEVIEWW: [WCHAR] = Array<WCHAR>("SysTreeView32".utf16)
public let ANIMATE_CLASSW: [WCHAR] = Array<WCHAR>("SysAnimate32".utf16)
public let HOTKEY_CLASSW: [WCHAR] = Array<WCHAR>("msctls_hotkey32".utf16)
public let PROGRESS_CLASSW: [WCHAR] = Array<WCHAR>("msctls_progress32".utf16)
public let STATUSCLASSNAMEW: [WCHAR] = Array<WCHAR>("msctls_statusbar32".utf16)
public let TOOLBARW_CLASSW: [WCHAR] = Array<WCHAR>("ToolbarWindow32".utf16)
public let TRACKBAR_CLASSW: [WCHAR] = Array<WCHAR>("msctls_trackbar32".utf16)
public let UPDOWN_CLASSW: [WCHAR] = Array<WCHAR>("msctls_updown32".utf16)
// consoleapi.h
public let PROC_THREAD_ATTRIBUTE_PSEUDOCONSOLE: DWORD_PTR = 0x00020016
// Swift Convenience
public extension FILETIME {
var time_t: time_t {
let NTTime: Int64 = Int64(self.dwLowDateTime) | (Int64(self.dwHighDateTime) << 32)
return (NTTime - 116444736000000000) / 10000000
}
init(from time: time_t) {
let UNIXTime: Int64 = ((time * 10000000) + 116444736000000000)
self = FILETIME(dwLowDateTime: DWORD(UNIXTime & 0xffffffff),
dwHighDateTime: DWORD((UNIXTime >> 32) & 0xffffffff))
}
}
// WindowsBool
/// The `BOOL` type declared in WinDefs.h and used throughout WinSDK
///
/// The C type is a typedef for `int`.
@frozen
public struct WindowsBool : ExpressibleByBooleanLiteral {
@usableFromInline
var _value: Int32
/// The value of `self`, expressed as a `Bool`.
@_transparent
public var boolValue: Bool {
return !(_value == 0)
}
@_transparent
public init(booleanLiteral value: Bool) {
self.init(value)
}
/// Create an instance initialized to `value`.
@_transparent
public init(_ value: Bool) {
self._value = value ? 1 : 0
}
}
extension WindowsBool : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(reflecting: boolValue)
}
}
extension WindowsBool : CustomStringConvertible {
/// A textual representation of `self`.
public var description: String {
return self.boolValue.description
}
}
extension WindowsBool : Equatable {
@_transparent
public static func ==(lhs: WindowsBool, rhs: WindowsBool) -> Bool {
return lhs.boolValue == rhs.boolValue
}
}
@_transparent
public // COMPILER_INTRINSIC
func _convertBoolToWindowsBool(_ b: Bool) -> WindowsBool {
return WindowsBool(b)
}
@_transparent
public // COMPILER_INTRINSIC
func _convertWindowsBoolToBool(_ b: WindowsBool) -> Bool {
return b.boolValue
}
| apache-2.0 | 44b2f409160fb93ca16faf86cb2e9a63 | 31.464516 | 99 | 0.698728 | 3.354667 | false | false | false | false |
Morgan-Kennedy/MJKLayout | MJKLayout.swift | 1 | 16670 | //
// MJKLayout.swift
// Fankins
//
// Created by Morgan Kennedy on 10/12/2014.
// Copyright (c) 2014 FankinsApp. All rights reserved.
//
import Foundation
import CoreGraphics
enum MJKHAlign: Int
{
// X Coordinate Alignments
case HCenter = 1,
Left,
Right,
ExactHCenter,
ExactLeft, // Aligns the view to the extreme left of the parent view (ie: x = 0)
ExactRight, // Aligns the view to the extreme right of the parent view
None
}
enum MJKVAlign: Int
{
// Y Coordinate Alignments
case VCenter = 1,
Top,
Bottom,
ExactVCenter,
ExactTop,
ExactBottom,
None
}
enum MJKPlace: Int
{
case OnLeft = 1,
OnRight,
Above,
Below,
Within
}
enum MJKSize: Int
{
case UseAllWidth = 1,
UseAllHeight,
UseAvailableWidth,
UseAvailableHeight
}
class MJKPadding
{
var top: CGFloat
var bottom: CGFloat
var left: CGFloat
var right: CGFloat
init()
{
self.top = 0
self.bottom = 0
self.left = 0
self.right = 0
}
init(top: CGFloat, bottom: CGFloat, left: CGFloat, right: CGFloat)
{
self.top = top
self.bottom = bottom
self.left = left
self.right = right
}
init(allSidesEqual side: CGFloat) // Generally make it zero (but standard initi does that)
{
self.top = side
self.bottom = side
self.left = side
self.right = side
}
}
class MJKLayout
{
// MARK: Size Determinant Helper Methods
class func sizeForLabel(#label: UILabel, maxSize: CGSize) -> CGSize
{
var labelSize = label.sizeThatFits(maxSize)
return labelSize
}
class func sizeForLabel(#label: UILabel, maxWidth: CGFloat, maxHeight: CGFloat) -> CGSize
{
return self.sizeForLabel(label: label, maxSize: CGSize(width: maxWidth, height: maxHeight))
}
class func sizeForTextView(#textView: UITextView, maxSize: CGSize) -> CGSize
{
var textViewSize = textView.sizeThatFits(maxSize)
return textViewSize
}
class func sizeForTextView(#textView: UITextView, maxWidth: CGFloat, maxHeight: CGFloat) -> CGSize
{
return self.sizeForTextView(textView: textView, maxSize: CGSize(width: maxWidth, height: maxHeight))
}
// MARK: Layout Methods
// View to View
class func layoutView(#view: UIView, relativeToView relativeView: UIView, placement: MJKPlace, horizontalAlignment: MJKHAlign, verticalAlignment: MJKVAlign, withSize size: CGSize, withPadding padding: MJKPadding) -> UIView
{
return self.layoutView(view: view, relativeToView: relativeView, placement: placement, horizontalAlignment: horizontalAlignment, verticalAlignment: verticalAlignment, withWidth: size.width, withHeight: size.height, withPadding: padding)
}
class func layoutView(#view: UIView, relativeToView relativeView: UIView, placement: MJKPlace, horizontalAlignment: MJKHAlign, verticalAlignment: MJKVAlign, withWidth width: CGFloat, withHeight height: CGFloat, withPadding padding: MJKPadding) -> UIView
{
if let nonNilViewSuperview = view.superview
{
if (placement == MJKPlace.Within)
{
relativeView.addSubview(view)
}
else if let nonNilRelativeViewSuperview = relativeView.superview
{
nonNilRelativeViewSuperview.addSubview(view)
}
}
var viewFrame = view.frame
viewFrame.size.width = width
viewFrame.size.height = height
// Update the view with the correct size
view.frame = viewFrame
// Is the view a child of the relative View
if (view.superview === relativeView)
{
view.frame = self.calculateLayoutFrame(frame: view.frame, withinParentBounds: relativeView.bounds, horizontalAlignment: horizontalAlignment, verticalAlignment: verticalAlignment, withWidth: width, withHeight: height, padding: padding)
}
else // Assume the view is a peer of the relative view
{
view.frame = self.calculateLayoutFrame(frame: view.frame, relativeToPeerFrame: relativeView.frame, horizontalAlignment: horizontalAlignment, verticalAlignment: verticalAlignment, placement: placement, withWidth: width, withHeight: height, padding: padding)
}
view.frame = self.roundFrame(frame: view.frame)
return view
}
// View to Node
class func layoutView(#view: UIView, relativeToNode relativeNode: ASDisplayNode, placement: MJKPlace, horizontalAlignment: MJKHAlign, verticalAlignment: MJKVAlign, withSize size: CGSize, withPadding padding: MJKPadding) -> UIView
{
return self.layoutView(view: view, relativeToNode: relativeNode, placement: placement, horizontalAlignment: horizontalAlignment, verticalAlignment: verticalAlignment, withWidth: size.width, withHeight: size.height, withPadding: padding)
}
class func layoutView(#view: UIView, relativeToNode relativeNode: ASDisplayNode, placement: MJKPlace, horizontalAlignment: MJKHAlign, verticalAlignment: MJKVAlign, withWidth width: CGFloat, withHeight height: CGFloat, withPadding padding: MJKPadding) -> UIView
{
if let nonNilViewSuperview = view.superview
{
if (placement == MJKPlace.Within)
{
relativeNode.view.addSubview(view)
}
else if let nonNilRelativeViewSuperview = relativeNode.view.superview
{
nonNilRelativeViewSuperview.addSubview(view)
}
}
var viewFrame = view.frame
viewFrame.size.width = width
viewFrame.size.height = height
// Update the view with the correct size
view.frame = viewFrame
// Is the view a child of the relative View
if (view.superview === relativeNode.view)
{
view.frame = self.calculateLayoutFrame(frame: view.frame, withinParentBounds: relativeNode.bounds, horizontalAlignment: horizontalAlignment, verticalAlignment: verticalAlignment, withWidth: width, withHeight: height, padding: padding)
}
else // Assume the view is a peer of the relative view
{
view.frame = self.calculateLayoutFrame(frame: view.frame, relativeToPeerFrame: relativeNode.frame, horizontalAlignment: horizontalAlignment, verticalAlignment: verticalAlignment, placement: placement, withWidth: width, withHeight: height, padding: padding)
}
view.frame = self.roundFrame(frame: view.frame)
return view
}
// Node to Node
class func layoutNode(#node: ASDisplayNode, relativeToNode relativeNode: ASDisplayNode, placement: MJKPlace, horizontalAlignment: MJKHAlign, verticalAlignment: MJKVAlign, withSize size: CGSize, withPadding padding: MJKPadding) -> ASDisplayNode
{
return self.layoutNode(node: node, relativeToNode: relativeNode, placement: placement, horizontalAlignment: horizontalAlignment, verticalAlignment: verticalAlignment, withWidth: size.width, withHeight: size.height, withPadding: padding)
}
class func layoutNode(#node: ASDisplayNode, relativeToNode relativeNode: ASDisplayNode, placement: MJKPlace, horizontalAlignment: MJKHAlign, verticalAlignment: MJKVAlign, withWidth width: CGFloat, withHeight height: CGFloat, withPadding padding: MJKPadding) -> ASDisplayNode
{
if let nonNilNodeSupernode = node.subnodes
{
if (placement == MJKPlace.Within)
{
relativeNode.addSubnode(node)
}
else if let nonNilRelativeNodeSupernode = relativeNode.supernode
{
nonNilRelativeNodeSupernode.addSubnode(node)
}
}
var nodeFrame = node.frame
nodeFrame.size.width = width
nodeFrame.size.height = height
// Update the view with the correct size
node.frame = nodeFrame
// Is the view a child of the relative View
if (node.supernode === relativeNode)
{
node.frame = self.calculateLayoutFrame(frame: node.frame, withinParentBounds: relativeNode.bounds, horizontalAlignment: horizontalAlignment, verticalAlignment: verticalAlignment, withWidth: width, withHeight: height, padding: padding)
}
else // Assume the view is a peer of the relative view
{
node.frame = self.calculateLayoutFrame(frame: node.frame, relativeToPeerFrame: relativeNode.frame, horizontalAlignment: horizontalAlignment, verticalAlignment: verticalAlignment, placement: placement, withWidth: width, withHeight: height, padding: padding)
}
node.frame = self.roundFrame(frame: node.frame)
return node
}
// Node to View
class func layoutNode(#node: ASDisplayNode, relativeToView relativeView: UIView, placement: MJKPlace, horizontalAlignment: MJKHAlign, verticalAlignment: MJKVAlign, withSize size: CGSize, withPadding padding: MJKPadding) -> ASDisplayNode
{
return self.layoutNode(node: node, relativeToView: relativeView, placement: placement, horizontalAlignment: horizontalAlignment, verticalAlignment: verticalAlignment, withWidth: size.width, withHeight: size.height, withPadding: padding)
}
class func layoutNode(#node: ASDisplayNode, relativeToView relativeView: UIView, placement: MJKPlace, horizontalAlignment: MJKHAlign, verticalAlignment: MJKVAlign, withWidth width: CGFloat, withHeight height: CGFloat, withPadding padding: MJKPadding) -> ASDisplayNode
{
if let nonNilNodeSuperview = node.view.superview
{
if (placement == MJKPlace.Within)
{
relativeView.addSubview(node.view)
}
else if let nonNilRelativeViewSuperview = relativeView.superview
{
nonNilRelativeViewSuperview.addSubview(node.view)
}
}
var nodeFrame = node.frame
nodeFrame.size.width = width
nodeFrame.size.height = height
// Update the view with the correct size
node.frame = nodeFrame
// Is the view a child of the relative View
if (node.view.superview === relativeView)
{
node.frame = self.calculateLayoutFrame(frame: node.frame, withinParentBounds: relativeView.bounds, horizontalAlignment: horizontalAlignment, verticalAlignment: verticalAlignment, withWidth: width, withHeight: height, padding: padding)
}
else // Assume the view is a peer of the relative view
{
node.frame = self.calculateLayoutFrame(frame: node.frame, relativeToPeerFrame: relativeView.frame, horizontalAlignment: horizontalAlignment, verticalAlignment: verticalAlignment, placement: placement, withWidth: width, withHeight: height, padding: padding)
}
node.frame = self.roundFrame(frame: node.frame)
return node
}
// MARK: Private Methods
private class func calculateLayoutFrame(#frame: CGRect, withinParentBounds parentBounds: CGRect, horizontalAlignment: MJKHAlign, verticalAlignment: MJKVAlign, withWidth width: CGFloat, withHeight height: CGFloat, padding: MJKPadding) -> CGRect
{
var layoutFrame = frame
// Horizontal Alignment
switch (horizontalAlignment)
{
case .Left:
layoutFrame.origin.x = padding.left
case .Right:
layoutFrame.origin.x = parentBounds.size.width - width - padding.right
case .ExactLeft:
layoutFrame.origin.x = 0
case .ExactRight:
layoutFrame.origin.x = parentBounds.size.width - width
case .HCenter:
layoutFrame.origin.x = (parentBounds.size.width / 2.0 - width / 2.0) + padding.left - padding.right
case .ExactHCenter:
layoutFrame.origin.x = (parentBounds.size.width / 2.0 - width / 2.0)
default:
layoutFrame.origin.x = layoutFrame.origin.x
}
// Vertical Alignment
switch (verticalAlignment)
{
case .VCenter:
layoutFrame.origin.y = (parentBounds.size.height / 2.0 - height / 2.0) + padding.top - padding.bottom
case .ExactVCenter:
layoutFrame.origin.y = (parentBounds.size.height / 2.0 - height / 2.0)
case .Top:
layoutFrame.origin.y = padding.top
case .Bottom:
layoutFrame.origin.y = parentBounds.size.height - height - padding.bottom
case .ExactTop:
layoutFrame.origin.y = 0
case .ExactBottom:
layoutFrame.origin.y = parentBounds.size.height - height
default:
layoutFrame.origin.y = layoutFrame.origin.y
}
return layoutFrame
}
private class func calculateLayoutFrame(#frame: CGRect, relativeToPeerFrame relativeFrame: CGRect, horizontalAlignment: MJKHAlign, verticalAlignment: MJKVAlign, placement: MJKPlace, withWidth width: CGFloat, withHeight height: CGFloat, padding: MJKPadding) -> CGRect
{
var layoutFrame = frame
// Placement
switch (placement)
{
case .OnLeft:
layoutFrame.origin.x = relativeFrame.origin.x - width - padding.right
case .OnRight:
layoutFrame.origin.x = relativeFrame.origin.x + relativeFrame.size.width + padding.left
case .Above:
layoutFrame.origin.y = relativeFrame.origin.y - height - padding.bottom
case .Below:
layoutFrame.origin.y = relativeFrame.origin.y + relativeFrame.size.height + padding.top
default:
layoutFrame.origin.x = relativeFrame.origin.x
}
// Horizontal Alignment
switch (horizontalAlignment)
{
case .Left:
layoutFrame.origin.x = relativeFrame.origin.x + padding.left
case .Right:
layoutFrame.origin.x = relativeFrame.origin.x + relativeFrame.size.width - width - padding.right
case .ExactLeft:
layoutFrame.origin.x = relativeFrame.origin.x
case .ExactRight:
layoutFrame.origin.x = relativeFrame.origin.x + relativeFrame.size.width - width
case .HCenter:
layoutFrame.origin.x = (relativeFrame.origin.x + relativeFrame.size.width / 2.0 - width / 2.0) + padding.left - padding.right
case .ExactHCenter:
layoutFrame.origin.x = (relativeFrame.origin.x + relativeFrame.size.width / 2.0 - width / 2.0)
default:
layoutFrame.origin.x = layoutFrame.origin.x
}
// Vertical Alignment
switch (verticalAlignment)
{
case .VCenter:
layoutFrame.origin.y = (relativeFrame.origin.y + relativeFrame.size.height / 2.0 - height / 2.0) + padding.left - padding.bottom
case .ExactVCenter:
layoutFrame.origin.y = (relativeFrame.origin.y + relativeFrame.size.height / 2.0 - height / 2.0)
case .Top:
layoutFrame.origin.y = relativeFrame.origin.y + padding.top
case .Bottom:
layoutFrame.origin.y = relativeFrame.origin.y + relativeFrame.size.height - height - padding.bottom
case .ExactTop:
layoutFrame.origin.y = relativeFrame.origin.y
case .ExactBottom:
layoutFrame.origin.y = relativeFrame.origin.y + relativeFrame.size.height - height
default:
layoutFrame.origin.y = layoutFrame.origin.y
}
return layoutFrame;
}
// Round off the coordinate and size to ensure picel perfect rendering
class private func roundFrame(#frame: CGRect) -> CGRect
{
var layoutFrame = frame
layoutFrame.origin.x = CGFloat(roundf(Float(frame.origin.x)))
layoutFrame.origin.y = CGFloat(roundf(Float(frame.origin.y)))
layoutFrame.size.width = CGFloat(roundf(Float(frame.size.width)))
layoutFrame.size.height = CGFloat(roundf(Float(frame.size.height)))
return layoutFrame
}
} | mit | f2cbfafb8f03f305bd3ec34a371dc62c | 37.679814 | 278 | 0.637612 | 4.762857 | false | false | false | false |
LawrenceHan/iOS-project-playground | SpeakLine/SpeakLine/MainWindowController.swift | 1 | 4955 | //
// MainWindowController.swift
// SpeakLine
//
// Created by Hanguang on 9/24/15.
// Copyright © 2015 Hanguang. All rights reserved.
//
import Cocoa
class MainWindowController: NSWindowController, NSSpeechSynthesizerDelegate, NSWindowDelegate,
NSTableViewDataSource, NSTableViewDelegate, NSTextFieldDelegate {
@IBOutlet weak var textField: NSTextField!
@IBOutlet weak var speakButton: NSButton!
@IBOutlet weak var stopButton: NSButton!
@IBOutlet weak var tableView: NSTableView!
let preferenceManager = PreferenceManager()
let speechSynth = NSSpeechSynthesizer()
let voices = NSSpeechSynthesizer.availableVoices()
var isStarted: Bool = false {
didSet {
updateButtons()
}
}
override var windowNibName: String {
return "MainWindowController"
}
override func windowDidLoad() {
super.windowDidLoad()
updateButtons()
speechSynth.delegate = self
for voice in voices {
print(voiceNameForIdentifier(voice)!)
}
let defaultVoice = preferenceManager.activeVoice!
if let defaultRow = voices.indexOf(defaultVoice) {
let indices = NSIndexSet(index: defaultRow)
tableView.selectRowIndexes(indices, byExtendingSelection: false)
tableView.scrollRowToVisible(defaultRow)
}
textField.stringValue = preferenceManager.activeText!
}
// MARK: - Action methods
@IBAction func speakIt(sender: NSButton) {
// Get typed-in text as a string
let string = textField.stringValue
if string.isEmpty {
print("string from \(textField) is empty")
} else {
speechSynth.startSpeakingString(textField.stringValue)
isStarted = true
}
}
@IBAction func stopIt(sender: NSButton) {
speechSynth.stopSpeaking()
}
@IBAction func resetPreferences(sender: AnyObject) {
preferenceManager.resetPreference()
let activeVoice = preferenceManager.activeVoice!
let row = voices.indexOf(activeVoice)!
let indices = NSIndexSet(index: row)
tableView.selectRowIndexes(indices, byExtendingSelection: false)
textField.stringValue = preferenceManager.activeText!
}
func updateButtons() {
if isStarted {
speakButton.enabled = false
stopButton.enabled = true
} else {
speakButton.enabled = true
stopButton.enabled = false
}
}
func updateTextField() {
if speechSynth.speaking {
textField.enabled = false
} else {
textField.enabled = true
}
}
func speechSynthesizer(sender: NSSpeechSynthesizer, didFinishSpeaking finishedSpeaking: Bool) {
isStarted = false
updateTextField()
print("finishedSpeaking=\(finishedSpeaking)")
}
func speechSynthesizer(sender: NSSpeechSynthesizer,
willSpeakWord characterRange: NSRange,
ofString string: String) {
let range = characterRange
let attributedString = NSMutableAttributedString(string: string)
attributedString.addAttributes([NSForegroundColorAttributeName: NSColor.greenColor()], range: range)
textField.attributedStringValue = attributedString
updateTextField()
}
func voiceNameForIdentifier(identifier: String) -> String? {
let attributes = NSSpeechSynthesizer.attributesForVoice(identifier)
return attributes[NSVoiceName] as? String
}
// MARK: - NSWindowDelegate
func windowShouldClose(sender: AnyObject) -> Bool {
return !isStarted
}
// func windowWillResize(sender: NSWindow, toSize frameSize: NSSize) -> NSSize {
// return NSSizeFromCGSize(CGSizeMake(frameSize.height * 2, frameSize.height))
// }
// MARK: NSTableViewDataSource
func numberOfRowsInTableView(tableView: NSTableView) -> Int {
return voices.count
}
func tableView(tableView: NSTableView, objectValueForTableColumn tableColumn: NSTableColumn?, row: Int) -> AnyObject? {
let voice = voices[row]
let voiceName = voiceNameForIdentifier(voice)
return voiceName
}
// MARK: NSTableViewDelegate
func tableViewSelectionDidChange(notification: NSNotification) {
let row = tableView.selectedRow
// Set the voice back to the default if the user has deseleted all rows
if row == -1 {
speechSynth.setVoice(nil)
return
}
let voice = voices[row]
speechSynth.setVoice(voice)
preferenceManager.activeVoice = voice
}
// MARK: - NSTextFieldDelegate
override func controlTextDidChange(obj: NSNotification) {
preferenceManager.activeText = textField.stringValue
}
}
| mit | f1f780b7fd98b38db42de8fbe13126a8 | 31.168831 | 123 | 0.646346 | 5.461963 | false | false | false | false |
ACENative/ACEViewSwift | ACEViewSwift/ACEBridge.swift | 1 | 13977 | //
// ACEBridge.swift
// ACEViewSwift
//
// Created by Vasilis Akoinoglou on 20/11/15.
// Copyright © 2015 Vasilis Akoinoglou. All rights reserved.
//
import Foundation
import WebKit
class ACEBridgedObject {
/// The underlying JSValue of the object
var jsValue: JSValue
/// The designated initializer for all ACEBridgedObjects
init(jsValue: JSValue) {
self.jsValue = jsValue
}
/**
This function translates a native call to the respective JS one.
_Note:_ By default it directly translates a call based on the caller signature
*/
@discardableResult func jsCall(_ functionName: String = #function, arguments: [AnyObject]! = nil) -> JSValue {
guard let selector = functionName.split(separator: "(").first else {
return JSValue(nullIn: JSContext())
}
return jsValue.invokeMethod(String(selector), withArguments: arguments)
}
}
/*--------------------------------------------------------------------------------*/
class ACESession: ACEBridgedObject {
func getOption(_ option: String) -> JSValue {
return jsCall(arguments: [option as AnyObject])
}
func setOptions(_ options: [String:AnyObject]) {
jsCall(arguments: [options as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getMode() -> ACEMode {
var modeName = getOption("mode").toString().components(separatedBy: "/").last!
modeName = modeName.replacingOccurrences(of: "-inline$", with: "", options: .regularExpression)
return ACEMode(name: modeName)
}
func setMode(_ mode: ACEMode, inline: Bool = false) {
let modeName = mode.name
let args = [
"path": "ace/mode/\(modeName)",
"inline": inline
] as [String : Any]
jsCall("setMode", arguments: [args as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getUseWrapMode() -> Bool {
return jsCall().toBool()
}
func setUseWrapMode(_ flag: Bool) {
jsCall(arguments: [flag as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getWrapLimitRange() -> NSRange {
let range = jsCall().toDictionary()
let min = (range?["min"] as? Int) ?? 0
let max = (range?["max"] as? Int) ?? 0
return NSRange(location: min, length: max)
}
func setWrapLimitRange(_ range: NSRange) {
setUseWrapMode(true)
jsCall(arguments: [range.location as AnyObject, range.length as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getLength() -> Int {
return Int(jsCall().toInt32())
}
/*--------------------------------------------------------------------------------*/
func getLine(_ line: Int) -> String {
return jsCall(arguments: [line as AnyObject]).toString()
}
/*--------------------------------------------------------------------------------*/
func getNewLineMode() -> String {
return jsCall().toString()
}
func setNewLineMode(_ mode: String) {
jsCall(arguments: [mode as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getUseSoftTabs() -> Bool {
return jsCall().toBool()
}
func setUseSoftTabs(_ flag: Bool) {
jsCall(arguments: [flag as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getTabSize() -> Int {
return Int(jsCall().toInt32())
}
func setTabSize(_ size: Int) {
jsCall(arguments: [size as AnyObject])
}
}
/*--------------------------------------------------------------------------------*/
class ACEEditor: ACEBridgedObject {
var string: String {
get {
return getValue()
}
set {
jsValue.context.evaluateScript("reportChanges = false;")
setValue(newValue)
jsCall("clearSelection")
jsCall("moveCursorTo", arguments: [0 as AnyObject,0 as AnyObject])
jsValue.context.evaluateScript("reportChanges = true;")
jsValue.context.evaluateScript("editor.getSession().setUndoManager(new ace.UndoManager());")
jsValue.context.evaluateScript("ACEView.aceTextDidChange();")
}
}
/*--------------------------------------------------------------------------------*/
func getValue() -> String {
return jsCall().toString()
}
func setValue(_ value: String) {
jsCall(arguments:[value as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getSession() -> ACESession {
return ACESession(jsValue: jsCall())
}
/*--------------------------------------------------------------------------------*/
func getTheme() -> ACETheme {
let themeName = getOption("theme").toString().components(separatedBy: "/")
return ACETheme(name: themeName.last!)
}
func setTheme(_ theme: ACETheme) {
jsCall(arguments: ["ace/theme/\(theme.name)" as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getWrapBehavioursEnabled() -> Bool {
return jsCall().toBool()
}
func setWrapBehavioursEnabled(_ flag: Bool) {
jsCall(arguments: [flag as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getShowInvisibles() -> Bool {
return jsCall().toBool()
}
func setShowInvisibles(_ flag: Bool) {
jsCall(arguments: [flag as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getReadOnly() -> Bool {
return jsCall().toBool()
}
func setReadOnly(_ flag: Bool) {
jsCall(arguments: [flag as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getShowFoldWidgets() -> Bool {
return jsCall().toBool()
}
func setShowFoldWidgets(_ flag: Bool) {
jsCall(arguments: [flag as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getFadeFoldWidgets() -> Bool {
return jsCall().toBool()
}
func setFadeFoldWidgets(_ flag: Bool) {
jsCall(arguments: [flag as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getHighlightActiveLine() -> Bool {
return jsCall().toBool()
}
func setHighlightActiveLine(_ flag: Bool) {
jsCall(arguments: [flag as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getHighlightGutterLine() -> Bool {
return jsCall().toBool()
}
func setHighlightGutterLine(_ flag: Bool) {
jsCall(arguments: [flag as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getHighlightSelectedWord() -> Bool {
return jsCall().toBool()
}
func setHighlightSelectedWord(_ flag: Bool) {
jsCall(arguments: [flag as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getDisplayIndentGuides() -> Bool {
return jsCall().toBool()
}
func setDisplayIndentGuides(_ flag: Bool) {
jsCall(arguments: [flag as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getAnimatedScroll() -> Bool {
return jsCall().toBool()
}
func setAnimatedScroll(_ flag: Bool) {
jsCall(arguments: [flag as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getScrollSpeed() -> Int {
return Int(jsCall().toInt32())
}
func setScrollSpeed(_ speed: Int) {
jsCall(arguments: [speed as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getKeyboardHandler() -> ACEKeyboardHandler {
let handler = jsCall().toDictionary()
if let id = handler?["$id"] as? String {
switch id {
case "ace/keyboard/vim": return .vim
case "ace/keyboard/emacs": return .emacs
default: break
}
}
return .ace
}
func setKeyboardHandler(_ handler: ACEKeyboardHandler) {
jsValue.context.evaluateScript("editor.setKeyboardHandler(\(handler.command))")
}
/*--------------------------------------------------------------------------------*/
func getOption(_ option: String) -> JSValue {
return jsCall(arguments: [option as AnyObject])
}
func setOptions(_ options: [String:AnyObject]) {
jsCall(arguments: [options as AnyObject])
}
/*--------------------------------------------------------------------------------*/
var basicAutocomplete: Bool {
get {
return getOption("enableBasicAutocompletion").toBool()
}
set {
let options = ["enableBasicAutocompletion":newValue]
setOptions(options as [String : AnyObject])
}
}
/*--------------------------------------------------------------------------------*/
var enableLiveAutocompletion: Bool {
get {
return getOption("enableLiveAutocompletion").toBool()
}
set {
let options = ["enableLiveAutocompletion":newValue]
setOptions(options as [String : AnyObject])
}
}
/*--------------------------------------------------------------------------------*/
var enableSnippets: Bool {
get {
return getOption("enableSnippets").toBool()
}
set {
let options = ["enableSnippets":newValue]
setOptions(options as [String : AnyObject])
}
}
/*--------------------------------------------------------------------------------*/
var emmet: Bool {
get {
return getOption("emmet").toBool()
}
set {
let options = ["emmet":newValue]
setOptions(options as [String : AnyObject])
}
}
/*--------------------------------------------------------------------------------*/
func getPrintMarginColumn() -> Int {
return Int(jsCall().toInt32())
}
func setPrintMarginColumn(_ margin: Int) {
jsCall(arguments: [margin as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getShowPrintMargin() -> Bool {
return jsCall().toBool()
}
func setShowPrintMargin(_ flag: Bool) {
jsCall(arguments: [flag as AnyObject])
}
/*--------------------------------------------------------------------------------*/
func getFontSize() -> Int {
return Int(jsCall().toInt32())
}
func setFontSize(_ size: Int) {
jsCall(arguments: [size as AnyObject])
}
/*--------------------------------------------------------------------------------*/
var fontFamily: String {
get {
let family = getOption("fontFamily").toString()
return family! == "undefined" ? "None" : family!
}
set {
let options = ["fontFamily":newValue]
setOptions(options as [String : AnyObject])
}
}
/*--------------------------------------------------------------------------------*/
func goToLine(_ line: Int, column:Int, animated: Bool) {
jsCall(arguments: [line as AnyObject, column as AnyObject, animated as AnyObject])
}
/*--------------------------------------------------------------------------------*/
var showLineNumbers: Bool {
get {
return getOption("showLineNumbers").toBool()
}
set {
let options = ["showLineNumbers":newValue]
setOptions(options as [String : AnyObject])
}
}
/*--------------------------------------------------------------------------------*/
var showGutter: Bool {
get {
return getOption("showGutter").toBool()
}
set {
let options = ["showGutter":newValue]
setOptions(options as [String : AnyObject])
}
}
}
class ACEContext {
fileprivate var jsContext: JSContext
weak var aceView: ACEView? {
didSet {
jsContext.setObject(aceView, forKeyedSubscript: "ACEView" as (NSCopying & NSObjectProtocol))
}
}
var editor: ACEEditor
var exceptionHandler: ((JSContext?, JSValue?) -> Void)! {
didSet {
jsContext.exceptionHandler = exceptionHandler
}
}
init(context: JSContext) {
self.jsContext = context
self.editor = ACEEditor(jsValue: context.objectForKeyedSubscript("editor"))
}
@discardableResult
func evaluateScript(_ script: String) -> JSValue! {
return jsContext.evaluateScript(script)
}
func focusEditor() {
jsContext.evaluateScript("focusEditor();")
}
}
| bsd-3-clause | ed3f17e9f244f3d2f3eacdc3d036a847 | 28.673036 | 114 | 0.427662 | 5.539437 | false | false | false | false |
MiMo42/XLForm | Examples/Swift/SwiftExample/Dates/DateAndTimeValueTrasformer.swift | 4 | 2382 | //
// DateAndTimeValueTransformer.swift
// XLForm ( https://github.com/xmartlabs/XLForm )
//
// Copyright (c) 2014-2015 Xmartlabs ( http://xmartlabs.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.
class DateValueTrasformer : ValueTransformer {
override class func transformedValueClass() -> AnyClass {
return NSString.self
}
override class func allowsReverseTransformation() -> Bool {
return false
}
override func transformedValue(_ value: Any?) -> Any? {
if let date = value as? Date {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .full
dateFormatter.timeStyle = .none
return dateFormatter.string(from: date)
}
return nil
}
}
class DateTimeValueTrasformer: ValueTransformer {
override class func transformedValueClass() -> AnyClass {
return NSString.self
}
override class func allowsReverseTransformation() -> Bool {
return false
}
override func transformedValue(_ value: Any?) -> Any? {
if let date = value as? Date {
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .short
return dateFormatter.string(from: date)
}
return nil
}
}
| mit | 5132bf88720d3a888623cffaa85334a8 | 34.029412 | 80 | 0.685558 | 5.004202 | false | false | false | false |
TeachersPayTeachers/PerspectivePhotoBrowser | Pod/Classes/Extensions/UIScrollView.swift | 1 | 1175 |
extension UIScrollView {
func zoom(to point: CGPoint, withScale scale: CGFloat, animated: Bool) {
var x, y, width, height: CGFloat
//Normalize current content size back to content scale of 1.0f
width = (self.contentSize.width / self.zoomScale)
height = (self.contentSize.height / self.zoomScale)
let contentSize = CGSize(width: width, height: height)
//translate the zoom point to relative to the content rect
x = (point.x / self.bounds.size.width) * contentSize.width
y = (point.y / self.bounds.size.height) * contentSize.height
let zoomPoint = CGPoint(x: x, y: y)
//derive the size of the region to zoom to
width = self.bounds.size.width / scale
height = self.bounds.size.height / scale
let zoomSize = CGSize(width: width, height: height)
//offset the zoom rect so the actual zoom point is in the middle of the rectangle
x = zoomPoint.x - zoomSize.width / 2.0
y = zoomPoint.y - zoomSize.height / 2.0
width = zoomSize.width
height = zoomSize.height
let zoomRect = CGRect(x: x, y: y, width: width, height: height)
//apply the resize
self.zoom(to: zoomRect, animated: animated)
}
}
| mit | 5820acef858f5550331891a6d47e043b | 36.903226 | 85 | 0.682553 | 3.790323 | false | false | false | false |
thompsonate/Shifty | Shifty/RuleManager.swift | 1 | 11539 | //
// RuleManager.swift
//
//
// Created by Saagar Jha on 1/14/18.
//
import Cocoa
import SwiftLog
import ScriptingBridge
class RuleManager {
static var shared = RuleManager()
init() {
if let appData = UserDefaults.standard.value(forKey: Keys.currentAppDisableRules) as? Data {
do {
currentAppDisableRules = try PropertyListDecoder().decode(Set<AppRule>.self, from: appData)
} catch {
logw("Error: \(error.localizedDescription)")
}
}
if let appData = UserDefaults.standard.value(forKey: Keys.runningAppDisableRules) as? Data {
do {
runningAppDisableRules = try PropertyListDecoder().decode(Set<AppRule>.self, from: appData)
} catch let error {
logw("Error: \(error.localizedDescription)")
}
}
if let browserData = UserDefaults.standard.value(forKey: Keys.browserRules) as? Data {
do {
browserRules = try PropertyListDecoder().decode(Set<BrowserRule>.self, from: browserData)
} catch let error {
logw("Error: \(error.localizedDescription)")
}
}
NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.didActivateApplicationNotification,
object: nil,
queue: nil)
{ notification in
self.appSwitched(notification: notification)
}
NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.didLaunchApplicationNotification,
object: nil,
queue: nil)
{ notification in
self.appSwitched(notification: notification)
}
NSWorkspace.shared.notificationCenter.addObserver(
forName: NSWorkspace.didTerminateApplicationNotification,
object: nil,
queue: nil)
{ notification in
self.appSwitched(notification: notification)
}
}
private var currentAppDisableRules = Set<AppRule>() {
didSet {
UserDefaults.standard.set(try? PropertyListEncoder().encode(currentAppDisableRules), forKey: Keys.currentAppDisableRules)
}
}
private var runningAppDisableRules = Set<AppRule>() {
didSet {
UserDefaults.standard.set(try? PropertyListEncoder().encode(runningAppDisableRules), forKey: Keys.runningAppDisableRules)
}
}
var browserRules = Set<BrowserRule>() {
didSet(newValue) {
UserDefaults.standard.set(try? PropertyListEncoder().encode(browserRules), forKey: Keys.browserRules)
}
}
var currentApp: NSRunningApplication? {
NSWorkspace.shared.menuBarOwningApplication
}
var runningApps: [NSRunningApplication] {
NSWorkspace.shared.runningApplications
}
var isDisabledForCurrentApp: Bool {
guard let bundleIdentifier = currentApp?.bundleIdentifier else {
logw("Could not obtain bundle identifier of current application")
return false
}
return currentAppDisableRules.filter {
$0.bundleIdentifier == bundleIdentifier }.count > 0
}
func addCurrentAppDisableRule(forApp app: NSRunningApplication) {
guard let bundleID = app.bundleIdentifier else { return }
let rule = AppRule(bundleIdentifier: bundleID, fullScreenOnly: false)
currentAppDisableRules.insert(rule)
NightShiftManager.shared.respond(to: .nightShiftDisableRuleActivated)
}
func removeCurrentAppDisableRule(forApp app: NSRunningApplication) {
guard let bundleID = app.bundleIdentifier,
let index = currentAppDisableRules.firstIndex(where: {
$0.bundleIdentifier == bundleID
}) else { return }
currentAppDisableRules.remove(at: index)
NightShiftManager.shared.respond(to: .nightShiftDisableRuleDeactivated)
}
var isDisabledForRunningApp: Bool {
disabledCurrentlyRunningApps.count > 0
}
/// The currently running apps that Night Shift is disabled for
var disabledCurrentlyRunningApps: [NSRunningApplication] {
let disabledBundleIDs = Set(runningAppDisableRules.map { $0.bundleIdentifier })
return runningApps.filter {
guard let bundleID = $0.bundleIdentifier else { return false }
return disabledBundleIDs.contains(bundleID)
}
}
func isDisabledWhenRunningApp(_ app: NSRunningApplication) -> Bool {
guard let bundleID = app.bundleIdentifier else { return false }
return runningAppDisableRules.contains(where: { $0.bundleIdentifier == bundleID })
}
func addRunningAppDisableRule(forApp app: NSRunningApplication) {
guard let bundleID = app.bundleIdentifier else { return }
let rule = AppRule(bundleIdentifier: bundleID, fullScreenOnly: false)
runningAppDisableRules.insert(rule)
NightShiftManager.shared.respond(to: .nightShiftDisableRuleActivated)
}
func removeRunningAppDisableRule(forApp app: NSRunningApplication) {
guard let bundleID = app.bundleIdentifier,
let index = runningAppDisableRules.firstIndex(where: {
$0.bundleIdentifier == bundleID
}) else { return }
runningAppDisableRules.remove(at: index)
NightShiftManager.shared.respond(to: .nightShiftDisableRuleDeactivated)
}
var isDisabledForDomain: Bool {
guard let currentDomain = BrowserManager.shared.currentDomain else { return false }
let disabledDomain = browserRules.filter {
$0.type == .domain && $0.host == currentDomain }.count > 0
return disabledDomain
}
func addDomainDisableRule(forDomain domain: String) {
let rule = BrowserRule(type: .domain, host: domain)
browserRules.insert(rule)
NightShiftManager.shared.respond(to: .nightShiftDisableRuleActivated)
}
func removeDomainDisableRule(forDomain domain: String) {
let rule = BrowserRule(type: .domain, host: domain)
guard let index = browserRules.firstIndex(of: rule) else { return }
browserRules.remove(at: index)
if let currentSubdomain = BrowserManager.shared.currentSubdomain,
getSubdomainRule(forSubdomain: currentSubdomain) == .enabled
{
setSubdomainRule(.none, forSubdomain: currentSubdomain)
}
NightShiftManager.shared.respond(to: .nightShiftDisableRuleDeactivated)
}
func getSubdomainRule(forSubdomain subdomain: String) -> SubdomainRuleType {
if isDisabledForDomain {
let isEnabled = (browserRules.filter {
$0.type == .subdomainEnabled
&& $0.host == subdomain
}.count > 0)
if isEnabled {
return .enabled
}
} else {
let isDisabled = (browserRules.filter {
$0.type == .subdomainDisabled
&& $0.host == subdomain
}.count > 0)
if isDisabled {
return .disabled
}
}
return .none
}
var ruleForCurrentSubdomain: SubdomainRuleType {
guard let currentSubdomain = BrowserManager.shared.currentSubdomain else { return .none }
return getSubdomainRule(forSubdomain: currentSubdomain)
}
func setSubdomainRule(_ ruleType: SubdomainRuleType, forSubdomain subdomain: String) {
switch ruleType {
case .disabled:
let rule = BrowserRule(type: .subdomainDisabled, host: subdomain)
browserRules.insert(rule)
NightShiftManager.shared.respond(to: .nightShiftDisableRuleActivated)
case .enabled:
let rule = BrowserRule(type: .subdomainEnabled, host: subdomain)
browserRules.insert(rule)
NightShiftManager.shared.respond(to: .nightShiftEnableRuleActivated)
case .none:
var rule: BrowserRule
let prevValue = getSubdomainRule(forSubdomain: subdomain)
//Remove rule from set before triggering NightShiftEvent
switch prevValue {
case .disabled:
rule = BrowserRule(type: .subdomainDisabled, host: subdomain)
case .enabled:
rule = BrowserRule(type: .subdomainEnabled, host: subdomain)
case .none:
return
}
guard let index = browserRules.firstIndex(of: rule) else { return }
browserRules.remove(at: index)
switch prevValue {
case .disabled:
NightShiftManager.shared.respond(to: .nightShiftDisableRuleDeactivated)
case .enabled:
NightShiftManager.shared.respond(to: .nightShiftEnableRuleDeactivated)
case .none:
break
}
}
}
var disableRuleIsActive: Bool {
return isDisabledForCurrentApp || isDisabledForRunningApp ||
(isDisabledForDomain && ruleForCurrentSubdomain != .enabled) ||
ruleForCurrentSubdomain == .disabled
}
func removeRulesForCurrentState() {
if let currentApp = currentApp {
removeCurrentAppDisableRule(forApp: currentApp)
for app in disabledCurrentlyRunningApps {
removeRunningAppDisableRule(forApp: app)
}
}
if let currentDomain = BrowserManager.shared.currentDomain {
removeDomainDisableRule(forDomain: currentDomain)
}
if let currentSubdomain = BrowserManager.shared.currentSubdomain {
setSubdomainRule(.none, forSubdomain: currentSubdomain)
}
}
private func appSwitched(notification: Notification) {
BrowserManager.shared.stopBrowserWatcher()
if isDisabledForCurrentApp || isDisabledForRunningApp {
NightShiftManager.shared.respond(to: .nightShiftDisableRuleActivated)
} else if BrowserManager.shared.currentAppIsSupportedBrowser {
BrowserManager.shared.updateForSupportedBrowser()
} else {
NightShiftManager.shared.respond(to: .nightShiftDisableRuleDeactivated)
}
}
}
enum RuleType: String, Codable {
case domain
case subdomainDisabled
case subdomainEnabled
}
enum SubdomainRuleType: String, Codable {
case none
case disabled
case enabled
}
struct AppRule: CustomStringConvertible, Hashable, Codable {
var bundleIdentifier: BundleIdentifier
// Currently unused
var fullScreenOnly: Bool
var description: String {
return "Rule for \(bundleIdentifier); full screen only: \(fullScreenOnly)"
}
static func == (lhs: AppRule, rhs: AppRule) -> Bool {
return lhs.bundleIdentifier == rhs.bundleIdentifier
&& lhs.fullScreenOnly == rhs.fullScreenOnly
}
}
struct BrowserRule: CustomStringConvertible, Hashable, Codable {
var type: RuleType
var host: String
var description: String {
return "Rule type: \(type) for host: \(host)"
}
static func == (lhs: BrowserRule, rhs: BrowserRule) -> Bool {
return lhs.type == rhs.type
&& lhs.host == rhs.host
}
}
| gpl-3.0 | 0fb820e20701fcc0614e51df688398ab | 33.547904 | 133 | 0.626657 | 5.036665 | false | false | false | false |
tqtifnypmb/SwiftyImage | Framenderer/Sources/Stream/FrameWriter.swift | 2 | 7132 | //
// FrameWriter.swift
// Framenderer
//
// Created by tqtifnypmb on 23/02/2017.
// Copyright © 2017 tqtifnypmb. All rights reserved.
//
import Foundation
import CoreMedia
import AVFoundation
class FrameWriter: BaseFilter {
private let _writer: AVAssetWriterInputPixelBufferAdaptor
private let _outputWidth: GLsizei
private let _outputHeight: GLsizei
private let _outputWriter: AVAssetWriter
private var _audioInput: AVAssetWriterInput!
private var _videoInput: AVAssetWriterInput!
private let _fileType: String
private var _audioSampleBufferQueue: [CMSampleBuffer] = []
private var _writeStarted = false
init(destURL: URL, width: GLsizei, height: GLsizei, type: String, outputSettings settings: [String: Any]?) throws {
_outputWriter = try AVAssetWriter(url: destURL, fileType: type)
_fileType = type
let input = AVAssetWriterInput(mediaType: AVMediaTypeVideo, outputSettings: settings)
input.expectsMediaDataInRealTime = true
_outputWriter.add(input)
let sourceAttrs: [String: Any] = [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA,
kCVPixelBufferWidthKey as String: width,
kCVPixelBufferHeightKey as String: height,
kCVPixelBufferIOSurfacePropertiesKey as String: [:]]
let adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: input, sourcePixelBufferAttributes: sourceAttrs)
_writer = adaptor
_outputWidth = width
_outputHeight = height
}
convenience init(destURL: URL, type: String, width: GLsizei, height: GLsizei) throws {
let settings: [String: Any] = [AVVideoCodecKey: AVVideoCodecH264,
AVVideoWidthKey: width,
AVVideoHeightKey: height]
try self.init(destURL: destURL, width: width, height: height, type: type, outputSettings: settings)
}
func startWriting() {
_writeStarted = true
}
func finishWriting(completionHandler handler: (() -> Void)?) {
_writeStarted = false
if !_audioSampleBufferQueue.isEmpty {
_audioInput.requestMediaDataWhenReady(on: DispatchQueue.global(qos: .background), using: { [weak self] in
guard let strong_self = self else { return }
if strong_self._audioSampleBufferQueue.isEmpty {
strong_self._audioInput.markAsFinished()
strong_self.doFinishWriting(completionHandler: handler)
} else {
let toAppend = strong_self._audioSampleBufferQueue.removeFirst()
strong_self._audioInput.append(toAppend)
}
})
} else {
doFinishWriting(completionHandler: handler)
}
}
private func doFinishWriting(completionHandler handler: (() -> Void)?) {
_outputWriter.finishWriting {
handler?()
}
}
func prepareAudioInput(sampleBuffer sm: CMSampleBuffer) throws {
guard _audioInput == nil else { return }
let desc = CMSampleBufferGetFormatDescription(sm)
_audioInput = AVAssetWriterInput(mediaType: AVMediaTypeAudio, outputSettings: nil, sourceFormatHint: desc)
if !_outputWriter.canAdd(_audioInput) {
throw AVAssetError.assetWriter(errorDessc: "Can't audio input")
}
_outputWriter.add(_audioInput)
}
override func buildProgram() throws {
_program = try Program.create(fragmentSourcePath: "PassthroughFragmentShader")
}
override public var name: String {
return "FrameWriter"
}
override func apply(context: Context) throws {
fatalError("FrameKeeper is not allowed to apply manually")
}
override func applyToFrame(context ctx: Context, inputFrameBuffer: InputFrameBuffer, presentationTimeStamp time: CMTime, next: @escaping (Context, InputFrameBuffer) throws -> Void) throws {
if !_writeStarted {
try next(ctx, inputFrameBuffer)
return
}
if _outputWriter.status == .unknown {
_outputWriter.startWriting()
_outputWriter.startSession(atSourceTime: time)
}
ctx.setAsCurrent()
if _program == nil {
try buildProgram()
bindAttributes(context: ctx)
try _program.link()
ctx.setCurrent(program: _program)
setUniformAttributs(context: ctx)
} else {
ctx.setCurrent(program: _program)
}
ctx.setInput(input: inputFrameBuffer)
var pixelBuffer: CVPixelBuffer?
if kCVReturnSuccess != CVPixelBufferPoolCreatePixelBuffer(nil, _writer.pixelBufferPool!, &pixelBuffer) {
throw DataError.pixelBuffer(errorDesc: "Can't create CVPixelBuffer from shared CVPixelBufferPool")
}
let outputFrameBuffer = try TextureOutputFrameBuffer(width: _outputWidth, height: _outputHeight, format: inputFrameBuffer.format, pixelBuffer: pixelBuffer)
ctx.setOutput(output: outputFrameBuffer)
try super.feedDataAndDraw(context: ctx, program: _program)
if !_writer.append(outputFrameBuffer._renderTarget, withPresentationTime: time) {
throw AVAssetError.assetWriter(errorDessc: "Can't append frame at time: \(time) to output")
}
try next(ctx, inputFrameBuffer)
}
override func applyToAudio(context ctx: Context, sampleBuffer: CMSampleBuffer, next: @escaping (Context, CMSampleBuffer) throws -> Void) throws {
// Assumption: At least on buffer arrive before write start.
if _audioInput == nil {
let captureDataOutput = ctx.audioCaptureOutput as? AVCaptureAudioDataOutput
let settings = captureDataOutput?.recommendedAudioSettingsForAssetWriter(withOutputFileType: _fileType) as? [String : Any]
_audioInput = AVAssetWriterInput(mediaType: AVMediaTypeAudio, outputSettings: settings)
_audioInput.expectsMediaDataInRealTime = true
if !_outputWriter.canAdd(_audioInput) {
throw AVAssetError.assetWriter(errorDessc: "Can't audio input")
}
_outputWriter.add(_audioInput)
}
if !_writeStarted || _outputWriter.status == .unknown {
try next(ctx, sampleBuffer)
return
}
_audioSampleBufferQueue.append(sampleBuffer)
if _audioInput.isReadyForMoreMediaData {
let toAppend = _audioSampleBufferQueue.removeFirst()
if !_audioInput.append(toAppend) {
throw AVAssetError.assetWriter(errorDessc: "Can't append audio data")
}
}
try next(ctx, sampleBuffer)
}
}
| mit | f33be2751a14266aaf1b8f364a6edba2 | 38.39779 | 193 | 0.619268 | 5.27051 | false | false | false | false |
dclelland/AudioKit | AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Three-Pole Low Pass Filter.xcplaygroundpage/Contents.swift | 2 | 2187 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## Three-Pole Low Pass Filter
//: ##
import XCPlayground
import AudioKit
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("mixloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
var filter = AKThreePoleLowpassFilter(player)
//: Set the parameters of the Moog Ladder Filter here.
filter.cutoffFrequency = 300 // Hz
filter.resonance = 0.6
filter.rampTime = 0.1
AudioKit.output = filter
AudioKit.start()
player.play()
//: User Interface Set up
class PlaygroundView: AKPlaygroundView {
var cutoffFrequencyLabel: Label?
var resonanceLabel: Label?
override func setup() {
addTitle("Three Pole Low Pass Filter")
addLabel("Audio Playback")
addButton("Start", action: #selector(start))
addButton("Stop", action: #selector(stop))
cutoffFrequencyLabel = addLabel("Cutoff Frequency: \(filter.cutoffFrequency)")
addSlider(#selector(setCutoffFrequency),
value: filter.cutoffFrequency,
minimum: 0,
maximum: 5000)
resonanceLabel = addLabel("Resonance: \(filter.resonance)")
addSlider(#selector(setResonance),
value: filter.resonance,
minimum: 0,
maximum: 0.99)
}
func start() {
player.play()
}
func stop() {
player.stop()
}
func setCutoffFrequency(slider: Slider) {
filter.cutoffFrequency = Double(slider.value)
cutoffFrequencyLabel!.text = "Cutoff Frequency: \(String(format: "%0.0f", filter.cutoffFrequency))"
}
func setResonance(slider: Slider) {
filter.resonance = Double(slider.value)
resonanceLabel!.text = "Resonance: \(String(format: "%0.3f", filter.resonance))"
}
}
let view = PlaygroundView(frame: CGRect(x: 0, y: 0, width: 500, height: 300))
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
XCPlaygroundPage.currentPage.liveView = view
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit | 979180f1b4b8aec1b6f8056d31d6c719 | 28.16 | 107 | 0.631916 | 4.356574 | false | false | false | false |
brentsimmons/Evergreen | iOS/MasterFeed/Cell/MasterFeedTableViewIdentifier.swift | 1 | 2143 | //
// MasterFeedTableViewIdentifier.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 6/3/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import Foundation
import Account
import RSTree
final class MasterFeedTableViewIdentifier: NSObject, NSCopying {
let feedID: FeedIdentifier?
let containerID: ContainerIdentifier?
let parentContainerID: ContainerIdentifier?
let isEditable: Bool
let isPsuedoFeed: Bool
let isFolder: Bool
let isWebFeed: Bool
let nameForDisplay: String
let url: String?
let unreadCount: Int
let childCount: Int
var account: Account? {
if isFolder, let parentContainerID = parentContainerID {
return AccountManager.shared.existingContainer(with: parentContainerID) as? Account
}
if isWebFeed, let feedID = feedID {
return (AccountManager.shared.existingFeed(with: feedID) as? WebFeed)?.account
}
return nil
}
init(node: Node, unreadCount: Int) {
let feed = node.representedObject as! Feed
self.feedID = feed.feedID
self.containerID = (node.representedObject as? Container)?.containerID
self.parentContainerID = (node.parent?.representedObject as? Container)?.containerID
self.isEditable = !(node.representedObject is PseudoFeed)
self.isPsuedoFeed = node.representedObject is PseudoFeed
self.isFolder = node.representedObject is Folder
self.isWebFeed = node.representedObject is WebFeed
self.nameForDisplay = feed.nameForDisplay
if let webFeed = node.representedObject as? WebFeed {
self.url = webFeed.url
} else {
self.url = nil
}
self.unreadCount = unreadCount
self.childCount = node.numberOfChildNodes
}
override func isEqual(_ object: Any?) -> Bool {
guard let otherIdentifier = object as? MasterFeedTableViewIdentifier else { return false }
if self === otherIdentifier { return true }
return feedID == otherIdentifier.feedID && parentContainerID == otherIdentifier.parentContainerID
}
override var hash: Int {
var hasher = Hasher()
hasher.combine(feedID)
hasher.combine(parentContainerID)
return hasher.finalize()
}
func copy(with zone: NSZone? = nil) -> Any {
return self
}
}
| mit | 864ca78a8dc0975923f00fb9a7944813 | 26.461538 | 99 | 0.748833 | 3.79115 | false | false | false | false |
vmanot/swift-package-manager | Sources/PackageDescription4/PackageRequirement.swift | 1 | 3190 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
extension Package.Dependency.Requirement: Equatable {
/// The requirement is specified by an exact version.
public static func exact(_ version: Version) -> Package.Dependency.Requirement {
return .exactItem(version)
}
/// The requirement is specified by a source control revision.
public static func revision(_ ref: String) -> Package.Dependency.Requirement {
return .revisionItem(ref)
}
/// The requirement is specified by a source control branch.
public static func branch(_ name: String) -> Package.Dependency.Requirement {
return .branchItem(name)
}
/// Creates a specified for a range starting at the given lower bound
/// and going upto next major version.
public static func upToNextMajor(from version: Version) -> Package.Dependency.Requirement {
return .rangeItem(version..<Version(version.major + 1, 0, 0))
}
/// Creates a specified for a range starting at the given lower bound
/// and going upto next minor version.
public static func upToNextMinor(from version: Version) -> Package.Dependency.Requirement {
return .rangeItem(version..<Version(version.major, version.minor + 1, 0))
}
public static func == (
lhs: Package.Dependency.Requirement,
rhs: Package.Dependency.Requirement
) -> Bool {
switch (lhs, rhs) {
case (.rangeItem(let lhs), .rangeItem(let rhs)):
return lhs == rhs
case (.rangeItem, _):
return false
case (.revisionItem(let lhs), .revisionItem(let rhs)):
return lhs == rhs
case (.revisionItem, _):
return false
case (.branchItem(let lhs), .branchItem(let rhs)):
return lhs == rhs
case (.branchItem, _):
return false
case (.exactItem(let lhs), .exactItem(let rhs)):
return lhs == rhs
case (.exactItem, _):
return false
}
}
func toJSON() -> JSON {
switch self {
case .rangeItem(let range):
return .dictionary([
"type": .string("range"),
"lowerBound": .string(range.lowerBound.description),
"upperBound": .string(range.upperBound.description),
])
case .exactItem(let version):
return .dictionary([
"type": .string("exact"),
"identifier": .string(version.description),
])
case .branchItem(let identifier):
return .dictionary([
"type": .string("branch"),
"identifier": .string(identifier),
])
case .revisionItem(let identifier):
return .dictionary([
"type": .string("revision"),
"identifier": .string(identifier),
])
}
}
}
| apache-2.0 | be7dddbefc6b6e2641f8ce5d9b39ffdf | 34.842697 | 95 | 0.597492 | 4.754098 | false | false | false | false |
BirdBrainTechnologies/Hummingbird-iOS-Support | BirdBlox/BirdBlox/AudioManager.swift | 1 | 8034 | //
// AudioManager.swift
// BirdBlox
//
// Created by birdbrain on 1/18/17.
// Copyright © 2017 Birdbrain Technologies LLC. All rights reserved.
//
import Foundation
import AudioToolbox
import AVFoundation
class AudioManager: NSObject, AVAudioRecorderDelegate {
var audioEngine:AVAudioEngine
var sampler:AVAudioUnitSampler
var mixer:AVAudioMixerNode
var players:[AVAudioPlayer]
let sharedAudioSession: AVAudioSession = AVAudioSession.sharedInstance()
var recorder: AVAudioRecorder?
override init() {
//super.init()
// Instatiate audio engine
self.audioEngine = AVAudioEngine()
do {
//try sharedAudioSession.setCategory(convertFromAVAudioSessionCategory(AVAudioSession.Category.playAndRecord))
if #available(iOS 11.0, *) {
//try sharedAudioSession.setCategory(.playAndRecord, mode: .default)
try sharedAudioSession.setCategory(.playback, mode: .default)
} else {
try AVAudioSessionPatch.setAudioSession()
}
do {
try sharedAudioSession.setActive(true)
}
catch {
NSLog("Failed to set audio session as active")
}
}
catch {
NSLog("Failed to set audio session category")
}
// get the reference to the mixer to
// connect the output of the AVAudio
mixer = audioEngine.mainMixerNode
// instantiate sampler. Initialization arguments
// are currently unneccesary
sampler = AVAudioUnitSampler()
// add sampler to audio engine graph
// and connect it to the mixer node
audioEngine.attach(sampler)
audioEngine.connect(sampler, to: mixer, format: nil)
players = [AVAudioPlayer]()
do {
try audioEngine.start()
} catch {
NSLog("Failed to start audio player")
}
}
//MARK: Recording Audio
public func startRecording(saveName: String) -> Bool {
if #available(iOS 11.0, *) {
do {
try sharedAudioSession.setCategory(.record, mode: .default)
} catch {
NSLog("Failed to set record mode in startRecording.")
}
}
//TODO: Use the data model
let location = DataModel.shared.recordingsLoc.appendingPathComponent(saveName + ".m4a")
let settings = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 12000,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.medium.rawValue
]
//Try to get permission if we don't have it
guard sharedAudioSession.recordPermission == .granted else {
sharedAudioSession.requestRecordPermission { permissionGranted in
if permissionGranted {
// BBXCallbackManager.current.addAvailableSensor(.Microphone)
} else {
// BBXCallbackManager.current.removeAvailableSensor(.Microphone)
}
return
}
//The frontend can put up a dialog to tell the user how to give us permission
return false
}
do {
self.recorder = try AVAudioRecorder(url: location, settings: settings)
self.recorder?.delegate = self
self.recorder?.record()
} catch {
self.finishRecording()
return false
}
return true
}
public func pauseRecording() -> Bool {
guard let recorder = self.recorder else {
return false
}
recorder.pause()
if #available(iOS 11.0, *) {
do {
try sharedAudioSession.setCategory(.playback, mode: .default)
} catch {
NSLog("Failed to set playback mode in pauseRecording.")
}
}
return true
}
public func unpauseRecording() -> Bool {
guard let recorder = self.recorder else {
return false
}
if #available(iOS 11.0, *) {
do {
try sharedAudioSession.setCategory(.record, mode: .default)
} catch {
NSLog("Failed to set record mode in unpauseRecording.")
}
}
return recorder.record()
}
@objc
public func finishRecording(deleteRecording: Bool = false) {
guard let recorder = self.recorder,
recorder.currentTime != 0 else {
return
}
recorder.stop()
if deleteRecording {
recorder.deleteRecording()
try? FileManager.default.removeItem(at: recorder.url)
}
self.recorder = nil
if #available(iOS 11.0, *) {
do {
try sharedAudioSession.setCategory(.playback, mode: .default)
} catch {
NSLog("Failed to set playback mode in finishRecording.")
}
}
let _ = FrontendCallbackCenter.shared.recordingEnded()
}
func audioRecorderDidFinishRecording(_ recorder: AVAudioRecorder, successfully flag: Bool) {
self.finishRecording(deleteRecording: !flag)
}
var permissionsState: AVAudioSession.RecordPermission {
return sharedAudioSession.recordPermission
}
//MARK: Playing sounds
public func getSoundNames(type: DataModel.BBXFileType) -> [String]{
do {
let paths = try FileManager.default.contentsOfDirectory(atPath:
DataModel.shared.folder(of: type).path)
// let files = paths.filter {
// (DataModel.shared.soundsLoc.appendingPathComponent($0)).pathExtension == "wav"
// }
print(type)
print(paths)
let files = paths
return files
} catch {
NSLog("Listing sounds failed.")
return []
}
}
func getSoundDuration(filename: String, type: DataModel.BBXFileType) -> Int {
do {
let player = try AVAudioPlayer(contentsOf:
DataModel.shared.fileLocation(forName: filename, type: type))
//convert to milliseconds
print("\(player.duration) secs")
let audioDuration: Float64 = player.duration * 1000
return Int(audioDuration)
} catch {
NSLog("Failed to get duration")
return 0
}
}
func playSound(filename: String, type: DataModel.BBXFileType) -> Bool {
print("play sound")
do {
let loc = DataModel.shared.fileLocation(forName: filename, type: type)
print("\(FileManager.default.fileExists(atPath: loc.path))")
let player = try AVAudioPlayer(contentsOf: loc)
player.prepareToPlay()
player.play()
players.append(player)
} catch {
NSLog("failed to play: " + filename)
return false
}
return true
}
func stopSounds() {
for player in players {
player.stop()
}
players.removeAll()
}
//MARK: Playing Tones/Notes
func playNote(noteIndex: UInt, duration: Int) {
var cappedNote = noteIndex
if(cappedNote >= UInt(UInt8.max)) {
cappedNote = 255
}
let noteEightBit = UInt8(cappedNote)
if !audioEngine.isRunning {
NSLog("Restarting audio engine...")
do {
try audioEngine.start()
} catch {
NSLog("Failed to start engine")
return
}
}
print("Playing note \(noteEightBit)")
sampler.startNote(noteEightBit, withVelocity: 127, onChannel: 1)
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(duration)) {
self.sampler.stopNote(noteEightBit, onChannel: 1)
}
}
/*
* Stop any notes that are playing. 120 is the midi controller value for stop all
* see https://www.midi.org/specifications-old/item/table-1-summary-of-midi-message
*/
func stopTones() {
sampler.sendController(120, withValue: 0, onChannel: 1)
/*
audioEngine.stop()
do {
try audioEngine.start()
} catch {
NSLog("Failed to start audio player")
}*/
}
}
// Helper function inserted by Swift 4.2 migrator.
fileprivate func convertFromAVAudioSessionCategory(_ input: AVAudioSession.Category) -> String {
return input.rawValue
}
| mit | 50bff46a9d63dc1f0858aa207f1a60bb | 26.510274 | 122 | 0.614465 | 4.433223 | false | false | false | false |
tappollo/OSCKit | Source/Session.swift | 1 | 2304 | //
// Session.swift
// ThreeSixtyCamera
//
// Created by Zhigang Fang on 4/18/17.
// Copyright © 2017 Tappollo Inc. All rights reserved.
//
import Foundation
import SwiftyyJSON
import PromiseKit
import AwaitKit
public struct Session {
let id: String
let expires: Date
let issued: Date
init (json: JSON) throws {
self.id = try json["results"]["sessionId"].string !! OSCKit.SDKError.unableToParse(json)
let expire = try json["results"]["timeout"].int !! OSCKit.SDKError.unableToParse(json)
self.expires = Date().addingTimeInterval(TimeInterval(expire))
self.issued = Date()
}
var isExpired: Bool {
return self.expires < Date()
}
var wasJustedIssued: Bool {
return self.issued.addingTimeInterval(10) > Date()
}
}
extension OSCKit {
func updateIfNeeded(session: Session) -> Promise<Session> {
let result: Promise<Session>
if session.wasJustedIssued {
result = Promise.value(session)
} else if session.isExpired {
result = startSession
} else {
result = update(session: session)
}
return result.map({ session -> Session in
self.currentApiVersion = .version2(session)
return session
})
}
var startSession: Promise<Session> {
return async {
let response = try await(self.execute(command: CommandV1.startSession))
let session = try Session(json: response)
return session
}
}
private func update(session: Session) -> Promise<Session> {
return async {
do {
let response = try await(self.execute(command: CommandV1.updateSession(sessionId: session.id)))
return try Session(json: response)
} catch {
return try await(self.startSession)
}
}
}
public func end() -> Promise<Void> {
return async {
switch try await(self.apiVersion) {
case .version2(let session):
try await(self.execute(command: CommandV1._finishWlan(sessionId: session.id)))
case .version2_1:
try await(self.execute(command: CommandV2._finishWlan))
}
}
}
}
| mit | 83b13f1f89401e1252cecb0920c45869 | 27.085366 | 111 | 0.589666 | 4.3371 | false | false | false | false |
CoderST/DYZB | DYZB/DYZB/Class/Home/View/SearchCell.swift | 1 | 2602 | //
// SearchCell.swift
// DYZB
//
// Created by xiudou on 2017/6/23.
// Copyright © 2017年 xiudo. All rights reserved.
//
import UIKit
fileprivate let rankWH : CGFloat = 15
class SearchCell: UICollectionViewCell {
fileprivate let rankLabel : UILabel = {
let rankLabel = UILabel()
rankLabel.font = UIFont.systemFont(ofSize: 12)
rankLabel.textAlignment = .center
return rankLabel
}()
fileprivate let titleLabel : UILabel = {
let titleLabel = UILabel()
titleLabel.font = UIFont.systemFont(ofSize: 12)
return titleLabel
}()
fileprivate let lineView : UIView = {
let lineView = UIView()
lineView.backgroundColor = UIColor(r: 239, g: 239, b: 239)
return lineView
}()
var searchModel : SearchModel?{
didSet{
guard let searchModel = searchModel else { return }
let rank = searchModel.rank
switch rank {
case 1:
rankLabel.backgroundColor = UIColor.red
case 2:
rankLabel.backgroundColor = UIColor.purple
case 3:
rankLabel.backgroundColor = UIColor.orange
default:
rankLabel.backgroundColor = UIColor.gray
}
rankLabel.text = "\(searchModel.rank)"
titleLabel.text = searchModel.title
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(rankLabel)
// rankLabel.isHidden = true
contentView.addSubview(titleLabel)
contentView.addSubview(lineView)
}
override func layoutSubviews() {
super.layoutSubviews()
// if searchModel?.rank == 0 {
// rankLabel.isHidden = true
// rankLabel.frame = CGRect(x: 10, y: (frame.height - rankWH) * 0.5, width: 0, height: rankWH)
// }else{
// rankLabel.isHidden = false
rankLabel.frame = CGRect(x: 10, y: (frame.height - rankWH) * 0.5, width: rankWH, height: rankWH)
// }
titleLabel.frame = CGRect(x: rankLabel.frame.maxX + 10, y: 0, width: sScreenW, height: frame.height)
lineView.frame = CGRect(x: 0, y: frame.height - 1, width: sScreenW, height: 1)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | bf8c4036665ab051b9486da948784005 | 26.946237 | 108 | 0.540593 | 4.812963 | false | false | false | false |
EstebanVallejo/sdk-ios | MercadoPagoSDK/MercadoPagoSDK/CurrenciesUtil.swift | 2 | 1983 | //
// CurrenciesUtil.swift
// MercadoPagoSDK
//
// Created by Matias Gualino on 3/3/15.
// Copyright (c) 2015 com.mercadopago. All rights reserved.
//
import Foundation
public class CurrenciesUtil {
public class var currenciesList : [String: Currency] { return [
"ARS" : Currency(_id: "ARS", description: "Peso argentino", symbol: "$", decimalPlaces: 2, decimalSeparator: ",", thousandSeparator: "."),
"BRL" : Currency(_id: "BRL", description: "Real", symbol: "R$", decimalPlaces: 2, decimalSeparator: ",", thousandSeparator: "."),
"CLP" : Currency(_id: "CLP", description: "Peso chileno", symbol: "$", decimalPlaces: 2, decimalSeparator: ",", thousandSeparator: "."),
"COP" : Currency(_id: "COP", description: "Peso colombiano", symbol: "$", decimalPlaces: 2, decimalSeparator: ",", thousandSeparator: "."),
"MXN" : Currency(_id: "MXN", description: "Peso mexicano", symbol: "$", decimalPlaces: 2, decimalSeparator: ".", thousandSeparator: ","),
"VEF" : Currency(_id: "VEF", description: "Bolipublic var fuerte", symbol: "BsF", decimalPlaces: 2, decimalSeparator: ",", thousandSeparator: ".")
]}
public class func formatNumber(amount: Double, currencyId: String) -> String? {
// Get currency configuration
let currency : Currency? = currenciesList[currencyId]
if currency != nil {
// Set formatters
var formatter : NSNumberFormatter = NSNumberFormatter()
formatter.decimalSeparator = String(currency!.decimalSeparator)
formatter.groupingSeparator = String(currency!.thousandsSeparator)
formatter.numberStyle = .NoStyle
formatter.maximumFractionDigits = currency!.decimalPlaces
// return formatted string
let number = amount as NSNumber
return currency!.symbol + " " + formatter.stringFromNumber(number)!
} else {
return nil
}
}
} | mit | e7681cb57a0420278627000fd816013b | 46.238095 | 154 | 0.631871 | 4.466216 | false | false | false | false |
chenkanck/iOSNoteBook | iOSNoteBook/iOSNoteBook/XibTest2ViewController.swift | 1 | 1267 | import UIKit
class XibTest2ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
loadXib()
}
private func loadXib(){
let appviewHeight: CGFloat = 100
let appviewWidth:CGFloat = 60
let x:CGFloat = 20
let y:CGFloat = 30
let count = 9
for i in 0..<9 {
let col = CGFloat(i%3)
let row = CGFloat(i/3)
let xPoint = x + appviewWidth * col
let yPoint = y + appviewHeight * row
//Core part: Load nib
let xibs = NSBundle.mainBundle().loadNibNamed("XibTest2", owner: nil, options: nil)
// let appview: UIView = xibs.first as! UIView
let appview: XibTest2 = xibs.first as! XibTest2
appview.frame = CGRectMake(xPoint, yPoint, appviewWidth, appviewHeight)
//Use Tag of UIView to manage UI
appview.label.text = "Xib\(i+1)"
if i%2 == 0 {
appview.imageView.backgroundColor = UIColor.greenColor()
}else{
appview.imageView.backgroundColor = UIColor.yellowColor()
}
self.view.addSubview(appview)
}
}
}
| mit | ee809fd5b7a6d1a51d3d4cd949ed3700 | 29.902439 | 95 | 0.532755 | 4.461268 | false | true | false | false |
Eitot/vienna-rss | Vienna/Sources/Shared/WebKitContextMenuCustomizer.swift | 1 | 3011 | //
// WebKitContextMenuCustomizer.swift
// Vienna
//
// Copyright 2021 Tassilo Karge
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
class WebKitContextMenuCustomizer {
static func contextMenuItemsFor(purpose: WKWebViewContextMenuContext, existingMenuItems: [NSMenuItem]) -> [NSMenuItem] {
var menuItems = existingMenuItems
switch purpose {
case .page(url: _):
break
case .link(let url):
addLinkMenuCustomizations(&menuItems, url)
case .picture:
break
case .pictureLink(image: _, link: let link):
addLinkMenuCustomizations(&menuItems, link)
case .text:
break
}
return menuItems
}
private static func addLinkMenuCustomizations(_ menuItems: inout [NSMenuItem], _ url: (URL)) {
guard var index = menuItems.firstIndex(where: { $0.identifier == .WKMenuItemOpenLinkInNewWindow }) else {
return
}
if let openInBackgroundIndex = menuItems.firstIndex(where: { $0.identifier == NSUserInterfaceItemIdentifier.WKMenuItemOpenLinkInBackground }) {
// Swap open link in new tab and open link in background items if
// necessary/
let openInBackground = Preferences.standard.openLinksInBackground
if openInBackground && index < openInBackgroundIndex
|| !openInBackground && openInBackgroundIndex < index {
menuItems.swapAt(index, openInBackgroundIndex)
}
index = max(index, openInBackgroundIndex)
}
let defaultBrowser = getDefaultBrowser() ?? NSLocalizedString("External Browser", comment: "")
let openInExternalBrowserTitle = NSLocalizedString("Open Link in %@", comment: "")
.replacingOccurrences(of: "%@", with: defaultBrowser)
let openInDefaultBrowserItem = NSMenuItem(
title: openInExternalBrowserTitle,
action: #selector(openLinkInDefaultBrowser(menuItem:)), keyEquivalent: "")
openInDefaultBrowserItem.identifier = .WKMenuItemOpenLinkInSystemBrowser
openInDefaultBrowserItem.representedObject = url
menuItems.insert(openInDefaultBrowserItem, at: menuItems.index(after: index))
}
@objc
static func openLinkInDefaultBrowser(menuItem: NSMenuItem) {
if let url = menuItem.representedObject as? URL {
NSApp.appController.openURL(inDefaultBrowser: url)
}
}
}
| apache-2.0 | fe521f0d0db5b7960a2dea2e21796b5a | 39.146667 | 151 | 0.672534 | 4.903909 | false | false | false | false |
scottkawai/sendgrid-swift | Sources/SendGrid/Protocols/EmailHeaderRepresentable.swift | 1 | 1919 | import Foundation
/// The `EmailHeaderRepresentable` protocol provides a method for ensuring
/// custom headers are valid.
public protocol EmailHeaderRepresentable {
/// A dictionary representing the headers that should be added to the email.
var headers: [String: String]? { get set }
/// Validates the `headers` property to ensure they are not using any
/// reserved headers. If there is a problem, an error is thrown. If
/// everything is fine, then this method returns nothing.
///
/// - Throws: If there is an invalid header, an error will be
/// thrown.
func validateHeaders() throws
}
public extension EmailHeaderRepresentable {
/// The default implementation validates against the following headers:
///
/// - X-SG-ID
/// - X-SG-EID
/// - Received
/// - DKIM-Signature
/// - Content-Type
/// - Content-Transfer-Encoding
/// - To
/// - From
/// - Subject
/// - Reply-To
/// - CC
/// - BCC
func validateHeaders() throws {
guard let head = self.headers else { return }
let reserved: [String] = [
"x-sg-id",
"x-sg-eid",
"received",
"dkim-signature",
"content-type",
"content-transfer-encoding",
"to",
"from",
"subject",
"reply-to",
"cc",
"bcc"
]
for (key, _) in head {
guard reserved.firstIndex(of: key.lowercased()) == nil else { throw Exception.Mail.headerNotAllowed(key) }
let regex = try NSRegularExpression(pattern: #"(\s)"#, options: [.caseInsensitive, .anchorsMatchLines])
guard regex.numberOfMatches(in: key, options: [], range: NSMakeRange(0, key.count)) == 0 else {
throw Exception.Mail.malformedHeader(key)
}
}
}
}
| mit | 78e8ea9071402c54c24f42868bf60386 | 32.666667 | 118 | 0.559145 | 4.483645 | false | false | false | false |
i-schuetz/SwiftCharts | SwiftCharts/AxisValues/ChartAxisValueFloat.swift | 1 | 1205 | //
// ChartAxisValueFloat.swift
// swift_charts
//
// Created by ischuetz on 15/03/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
@available(*, deprecated, message: "use ChartAxisValueDouble instead")
open class ChartAxisValueFloat: ChartAxisValue {
public let formatter: NumberFormatter
open var float: CGFloat {
return CGFloat(scalar)
}
public init(_ float: CGFloat, formatter: NumberFormatter = ChartAxisValueFloat.defaultFormatter, labelSettings: ChartLabelSettings = ChartLabelSettings()) {
self.formatter = formatter
super.init(scalar: Double(float), labelSettings: labelSettings)
}
override open func copy(_ scalar: Double) -> ChartAxisValueFloat {
return ChartAxisValueFloat(CGFloat(scalar), formatter: formatter, labelSettings: labelSettings)
}
public static var defaultFormatter: NumberFormatter = {
let formatter = NumberFormatter()
formatter.maximumFractionDigits = 2
return formatter
}()
// MARK: CustomStringConvertible
override open var description: String {
return formatter.string(from: NSNumber(value: Float(float)))!
}
}
| apache-2.0 | 983f8debac87d9f3056d3bd5e35fe67f | 29.125 | 160 | 0.701245 | 5.285088 | false | false | false | false |
seem-sky/SwiftColorArt | SwiftColorArt/MasterViewController.swift | 3 | 2772 | //
// MasterViewController.swift
// SwiftColorArt
//
// Created by Jan Gregor Triebel on 06.01.15.
// Copyright (c) 2015 Jan Gregor Triebel. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
var examples:[ExampleData] = []
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
let example1 = ExampleData(title: "Ponte Sisto", imageName: "pontesisto.jpg", url: "http://commons.wikimedia.org/wiki/File:Rome_(IT),_Ponte_Sisto_--_2013_--_4094.jpg")
let example2 = ExampleData(title: "Reykjavik", imageName: "reykjavik.jpg", url: "http://commons.wikimedia.org/wiki/File:Vista_de_Reikiavik_desde_Perlan,_Distrito_de_la_Capital,_Islandia,_2014-08-13,_DD_137-139_HDR.JPG")
let example3 = ExampleData(title: "Carousel", imageName: "carousel.jpg", url: "http://commons.wikimedia.org/wiki/File:Dülmen,_Viktorkirmes_auf_dem_Marktplatz_--_2014_--_3712.jpg")
let example4 = ExampleData(title: "Centaurea", imageName: "centaurea.jpg", url: "http://commons.wikimedia.org/wiki/File:Centaurea_jacea_01.JPG")
let example5 = ExampleData(title: "Mount Hood", imageName: "mounthood.jpg", url: "http://commons.wikimedia.org/wiki/File:Mount_Hood_reflected_in_Mirror_Lake,_Oregon.jpg")
let example6 = ExampleData(title: "Green Peas", imageName: "greenpeas.jpg", url: "http://commons.wikimedia.org/wiki/File:India_-_Varanasi_green_peas_-_2714.jpg")
self.examples.append(example1)
self.examples.append(example2)
self.examples.append(example3)
self.examples.append(example4)
self.examples.append(example5)
self.examples.append(example6)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
if let indexPath = self.tableView.indexPathForSelectedRow() {
let example = examples[indexPath.row]
(segue.destinationViewController as DetailViewController).detailItem = example
}
}
}
// MARK: - Table View
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return examples.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let example = examples[indexPath.row]
cell.textLabel!.text = example.title
return cell
}
}
| mit | 8beed456813b28baff6e20bbcec6cea6 | 37.486111 | 223 | 0.7214 | 3.689747 | false | false | false | false |
CallMeDaKing/DouYuAPP | DouYuProject/DouYuProject/Classes/Home/Controller/HomeViewController.swift | 1 | 7088 | //
// HomeViewController.swift
// DouYuProject
//
// Created by li king on 2017/10/26.
// Copyright © 2017年 li king. All rights reserved.
//
import UIKit
private let kTitleViewH : CGFloat = 40
class HomeViewController: UIViewController {
//MARK -- 懒加载我们的自定义 view 可以使用闭包的形式实现懒加载
private lazy var pageTitleView : PageTitleView = {[weak self] in
let titleFrame = CGRect(x: 0, y: kStateBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH)
let titles = ["推荐","游戏","娱乐","趣玩"]
let titleView = PageTitleView(frame: titleFrame, titles: titles)
titleView.delegate = self
return titleView
}()
// MARK -- 懒加载pageContentView
private lazy var pageContentView : PageContentView = { [weak self] in
//确定内容的frame
let contentH = kScreenH - kStateBarH - kNavigationBarH - kTitleViewH - kTabBarH
let contentFrame = CGRect(x: 0, y: kStateBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH)
//确定所有的自控器
var childVcs = [UIViewController]()
childVcs.append(RecommendViewController())
childVcs.append(GameViewController())
childVcs.append(AmouseViewController())
for _ in 0..<1 {
let vc = UIViewController()
//给 UIColor 扩展 acr4Random 随机生成的是整数,需要在此转为 cgfloat 类型
vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255)))
childVcs.append(vc)
}
let contentView = PageContentView(frame: contentFrame, chikdVcs: childVcs, parentViewController: self)
contentView.delegate = self
return contentView
}()
//Mark --系统回调函数
override func viewDidLoad() {
super.viewDidLoad()
//设置UI界面
setUpUI()
// swiftTest()
}
}
extension HomeViewController{
private func swiftTest(){
//1 swift 测试
print("----------------------这是一个swift 的测试")
let galaxy = "King li "
print(galaxy.count) //8
print(galaxy.isEmpty)// false 通过isempty 检测确定值是否为空
print(galaxy.dropFirst())// "ing li " 删除第一个元素
print(String(galaxy.reversed()))// " il gnik" 字符串头末倒置 ,返回String类型
print(galaxy.dropLast()) // king li 删除最后一个元素
var variableString = "Horse"
variableString += " and carriage" //使用+号 直接进行字符串的相加
//print(variableString.characters.count) // Swift3.0写法
print(variableString.count) // Swift4.0写法
// variableString is now "Horse and carriage"
//2 你也可以通过for in 循环访问字符串的单个的Character值
for character in "Dog!🐶" {
print(character)
}
// D
// o
// g
// !
// 🐶
let catCharacters: [Character] = ["C", "a", "t", "!", "🐱"]
let catString = String(catCharacters)
print(catString)
// Prints "Cat!🐱"
let linsWithIndentation = """
this is lne \n\
thsi is twoline \n\
this is threeline
"""
print(linsWithIndentation)
print("----------------------这是一个swift 的测试")
}
private func setUpUI(){
//不需要系统调整UIScrolView 的内边距
automaticallyAdjustsScrollViewInsets = false
//设置导航栏
setUpNavigationBar()
//添加titleView
view.addSubview(pageTitleView)
//添加内容VIEW
view.addSubview(pageContentView)
pageContentView.backgroundColor = UIColor.cyan
}
private func setUpNavigationBar(){
//设置左侧的item
/* let btn = UIButton()
btn.setImage(UIImage(named:"logo"), for: .normal)
btn.sizeToFit()
navigationItem.leftBarButtonItem = UIBarButtonItem(customView: btn)
*/
let size = CGSize(width: 40, height: 40)
//设置右侧的item
/* let historyBtn = UIButton()
historyBtn.setImage(UIImage(named:"image_my_history"), for: .normal)
historyBtn.setImage(UIImage(named:"Image_my_history_click"), for: .highlighted)
historyBtn.frame = CGRect(origin: CGPoint.zero, size: size)
let historyItem = UIBarButtonItem(customView: historyBtn)
let serchBtn = UIButton()
serchBtn.setImage(UIImage(named:"btn_search"), for: .normal)
serchBtn.setImage(UIImage(named:"btn_search_clicked"), for: .highlighted)
serchBtn.frame = CGRect(origin: CGPoint.zero, size: size)
let searchitem = UIBarButtonItem(customView: serchBtn)
let qrcodeBtn = UIButton()
qrcodeBtn.setImage(UIImage(named:"Image_scan"), for: .normal)
qrcodeBtn.setImage(UIImage(named:"Image_scan_click"), for: .highlighted)
qrcodeBtn.frame = CGRect(origin: CGPoint.zero, size: size)
let qrcodeItem = UIBarButtonItem(customView: qrcodeBtn)
*/
//方法二 优化方法一 ,使用类扩展的方式 直接创建 四个 但是swift 中用更多的是构造函数
/*let historyItem = UIBarButtonItem.creatItem(imageName: "image_my_history", highLightImageLName: "Image_my_history_click", size: size)
let searchItem = UIBarButtonItem.creatItem(imageName: "btn_search", highLightImageLName: "btn_search_clicked", size: size)
let qrcodeItem = UIBarButtonItem.creatItem(imageName: "Image_scan", highLightImageLName: "Image_scan_click", size: size)
*/
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
let historyItem = UIBarButtonItem(imageName: "image_my_history", highLightImageLName: "Image_my_history_click", size: size)
let searchItem = UIBarButtonItem(imageName: "btn_search", highLightImageLName: "btn_search_clicked", size: size)
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highLightImageLName: "Image_scan_click", size: size)
navigationItem.rightBarButtonItems = [historyItem,searchItem,qrcodeItem]
}
}
//mark -- 遵守PageTitleViewDelegate
extension HomeViewController :PageTitleViewDelegate{
func pageTitleView(titleView: PageTitleView, selectedIndex Index: Int) {
pageContentView.setCurrentIndex(currentIndex: Index)
}
}
//MARK --遵守PageContentViewDelegate的代理方法
extension HomeViewController:PageContentViewDelegate{
func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
pageTitleView.setTitleWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
| mit | ee46fc5f898d2dde10310b021d128ed4 | 36.225989 | 156 | 0.629989 | 4.500683 | false | false | false | false |
Monnoroch/Cuckoo | Generator/Dependencies/SourceKitten/Carthage/Checkouts/Commandant/Carthage/Checkouts/Quick/Externals/Nimble/Sources/Nimble/DSL.swift | 12 | 2457 | import Foundation
/// Make an expectation on a given actual value. The value given is lazily evaluated.
public func expect<T>(_ expression: @autoclosure @escaping () throws -> T?, file: FileString = #file, line: UInt = #line) -> Expectation<T> {
return Expectation(
expression: Expression(
expression: expression,
location: SourceLocation(file: file, line: line),
isClosure: true))
}
/// Make an expectation on a given actual value. The closure is lazily invoked.
public func expect<T>(_ file: FileString = #file, line: UInt = #line, expression: @escaping () throws -> T?) -> Expectation<T> {
return Expectation(
expression: Expression(
expression: expression,
location: SourceLocation(file: file, line: line),
isClosure: true))
}
/// Always fails the test with a message and a specified location.
public func fail(_ message: String, location: SourceLocation) {
let handler = NimbleEnvironment.activeInstance.assertionHandler
handler.assert(false, message: FailureMessage(stringValue: message), location: location)
}
/// Always fails the test with a message.
public func fail(_ message: String, file: FileString = #file, line: UInt = #line) {
fail(message, location: SourceLocation(file: file, line: line))
}
/// Always fails the test.
public func fail(_ file: FileString = #file, line: UInt = #line) {
fail("fail() always fails", file: file, line: line)
}
/// Like Swift's precondition(), but raises NSExceptions instead of sigaborts
internal func nimblePrecondition(
_ expr: @autoclosure() -> Bool,
_ name: @autoclosure() -> String,
_ message: @autoclosure() -> String,
file: StaticString = #file,
line: UInt = #line) -> Bool {
let result = expr()
if !result {
#if _runtime(_ObjC)
let e = NSException(
name: NSExceptionName(name()),
reason: message(),
userInfo: nil)
e.raise()
#else
preconditionFailure("\(name()) - \(message())", file: file, line: line)
#endif
}
return result
}
internal func internalError(_ msg: String, file: FileString = #file, line: UInt = #line) -> Never {
fatalError(
"Nimble Bug Found: \(msg) at \(file):\(line).\n" +
"Please file a bug to Nimble: https://github.com/Quick/Nimble/issues with the " +
"code snippet that caused this error."
)
}
| mit | e6cdc628e731d8a48c6deb7786f88fac | 36.8 | 141 | 0.634107 | 4.250865 | false | false | false | false |
OscarSwanros/swift | test/SILGen/generic_witness.swift | 2 | 2481 | // RUN: %target-swift-frontend -emit-silgen -enable-sil-ownership %s | %FileCheck %s
// RUN: %target-swift-frontend -emit-ir -enable-sil-ownership %s
protocol Runcible {
func runce<A>(_ x: A)
}
// CHECK-LABEL: sil hidden @_T015generic_witness3foo{{[_0-9a-zA-Z]*}}F : $@convention(thin) <B where B : Runcible> (@in B) -> () {
func foo<B : Runcible>(_ x: B) {
// CHECK: [[METHOD:%.*]] = witness_method $B, #Runcible.runce!1 : {{.*}} : $@convention(witness_method) <τ_0_0 where τ_0_0 : Runcible><τ_1_0> (@in τ_1_0, @in_guaranteed τ_0_0) -> ()
// CHECK: apply [[METHOD]]<B, Int>
x.runce(5)
}
// CHECK-LABEL: sil hidden @_T015generic_witness3bar{{[_0-9a-zA-Z]*}}F : $@convention(thin) (@in Runcible) -> ()
func bar(_ x: Runcible) {
var x = x
// CHECK: [[BOX:%.*]] = alloc_box ${ var Runcible }
// CHECK: [[TEMP:%.*]] = alloc_stack $Runcible
// CHECK: [[EXIST:%.*]] = open_existential_addr immutable_access [[TEMP]] : $*Runcible to $*[[OPENED:@opened(.*) Runcible]]
// CHECK: [[METHOD:%.*]] = witness_method $[[OPENED]], #Runcible.runce!1
// CHECK: apply [[METHOD]]<[[OPENED]], Int>
x.runce(5)
}
protocol Color {}
protocol Ink {
associatedtype Paint
}
protocol Pen {}
protocol Pencil : Pen {
associatedtype Stroke : Pen
}
protocol Medium {
associatedtype Texture : Ink
func draw<P : Pencil>(paint: Texture.Paint, pencil: P) where P.Stroke == Texture.Paint
}
struct Canvas<I : Ink> where I.Paint : Pen {
typealias Texture = I
func draw<P : Pencil>(paint: I.Paint, pencil: P) where P.Stroke == Texture.Paint { }
}
extension Canvas : Medium {}
// CHECK-LABEL: sil private [transparent] [thunk] @_T015generic_witness6CanvasVyxGAA6MediumA2aEP4drawy6StrokeQyd__5paint_qd__6penciltAA6PencilRd__7Texture_5PaintQZAIRSlFTW : $@convention(witness_method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, @in_guaranteed Canvas<τ_0_0>) -> () {
// CHECK: [[FN:%.*]] = function_ref @_T015generic_witness6CanvasV4drawy5PaintQz5paint_qd__6penciltAA6PencilRd__6StrokeQyd__AFRSlF : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: apply [[FN]]<τ_0_0, τ_1_0>({{.*}}) : $@convention(method) <τ_0_0 where τ_0_0 : Ink><τ_1_0 where τ_1_0 : Pencil, τ_0_0.Paint == τ_1_0.Stroke> (@in τ_0_0.Paint, @in τ_1_0, Canvas<τ_0_0>) -> ()
// CHECK: }
| apache-2.0 | fd35f12d1f768e2a19a422ee0b46b74e | 42.696429 | 352 | 0.628933 | 2.787016 | false | false | false | false |
ashfurrow/pragma-2015-rx-workshop | Session 3/Entities Demo/Entities Demo/MasterViewController.swift | 1 | 2334 | //
// MasterViewController.swift
// Entities Demo
//
// Created by Ash Furrow on 2015-10-08.
// Copyright © 2015 Artsy. All rights reserved.
//
import UIKit
import RxCocoa
import RxSwift
class MasterViewController: UITableViewController {
lazy var viewModel = MasterViewModel()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = self.editButtonItem()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "addObject:")
self.navigationItem.rightBarButtonItem = addButton
}
func addObject(sender: AnyObject!) {
let newIndexPath = viewModel.addObject()
tableView.insertRowsAtIndexPaths([newIndexPath], withRowAnimation: .Automatic)
}
// MARK: - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail",
let indexPath = self.tableView.indexPathForSelectedRow {
let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController
viewModel.configureDetailItem(controller, forIndexPath: indexPath)
controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem()
controller.navigationItem.leftItemsSupplementBackButton = true
}
}
// MARK: - Table View
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = viewModel.titleForIndexPath(indexPath)
return cell
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
viewModel.deleteObjectAtIndexPath(indexPath)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
}
}
}
| mit | e46b28dac60f7ce415b9e13887644c27 | 30.958904 | 155 | 0.756965 | 5.635266 | false | false | false | false |
LoopKit/LoopKit | LoopKitTests/BasalRateScheduleTests.swift | 1 | 5726 | //
// BasalRateScheduleTests.swift
// Naterade
//
// Created by Nathan Racklyeft on 2/5/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import XCTest
@testable import LoopKit
func ==<T: Equatable>(lhs: RepeatingScheduleValue<T>, rhs: RepeatingScheduleValue<T>) -> Bool {
return lhs.startTime == rhs.startTime && lhs.value == rhs.value
}
func ==<T: Equatable>(lhs: AbsoluteScheduleValue<T>, rhs: AbsoluteScheduleValue<T>) -> Bool {
return lhs.startDate == rhs.startDate && lhs.endDate == rhs.endDate && lhs.value == rhs.value
}
func ==<T: Equatable>(lhs: ArraySlice<AbsoluteScheduleValue<T>>, rhs: ArraySlice<AbsoluteScheduleValue<T>>) -> Bool {
guard lhs.count == rhs.count else {
return false
}
for (l, r) in zip(lhs, rhs) {
if !(l == r) {
return false
}
}
return true
}
class BasalRateScheduleTests: XCTestCase {
var items: [RepeatingScheduleValue<Double>]!
override func setUp() {
super.setUp()
let path = Bundle(for: type(of: self)).path(forResource: "basal", ofType: "json")!
let fixture = try! JSONSerialization.jsonObject(with: Data(contentsOf: URL(fileURLWithPath: path)), options: []) as! [JSONDictionary]
items = fixture.map {
return RepeatingScheduleValue(startTime: TimeInterval(minutes: $0["minutes"] as! Double), value: $0["rate"] as! Double)
}
}
func testBasalScheduleRanges() {
let therapyTimeZone = TimeZone(secondsFromGMT: -6*60*60)!
let schedule = BasalRateSchedule(dailyItems: items, timeZone: therapyTimeZone)!
var calendar = Calendar(identifier: .gregorian)
calendar.timeZone = therapyTimeZone
let midnight = calendar.startOfDay(for: Date())
var absoluteItems: [AbsoluteScheduleValue<Double>] = (0..<items.count).map {
let endTime = ($0 + 1) < items.count ? items[$0 + 1].startTime : .hours(24)
return AbsoluteScheduleValue(
startDate: midnight.addingTimeInterval(items[$0].startTime),
endDate: midnight.addingTimeInterval(endTime),
value: items[$0].value
)
}
absoluteItems += (0..<items.count).map {
let endTime = ($0 + 1) < items.count ? items[$0 + 1].startTime : .hours(24)
return AbsoluteScheduleValue(
startDate: midnight.addingTimeInterval(items[$0].startTime + .hours(24)),
endDate: midnight.addingTimeInterval(endTime + .hours(24)),
value: items[$0].value
)
}
XCTAssert(
absoluteItems[0..<items.count] ==
schedule.between(
start: midnight,
end: midnight.addingTimeInterval(TimeInterval(hours: 24))
)[0..<items.count]
)
let twentyThree30 = midnight.addingTimeInterval(TimeInterval(hours: 23)).addingTimeInterval(TimeInterval(minutes: 30))
XCTAssert(
absoluteItems[0..<items.count] ==
schedule.between(
start: midnight,
end: twentyThree30
)[0..<items.count]
)
XCTAssert(
absoluteItems[0..<items.count + 1] ==
schedule.between(
start: midnight,
end: midnight.addingTimeInterval(TimeInterval(hours: 24) + TimeInterval(1))
)[0..<items.count + 1]
)
XCTAssert(
absoluteItems[items.count - 1..<items.count * 2] ==
schedule.between(
start: twentyThree30,
end: twentyThree30.addingTimeInterval(TimeInterval(hours: 24))
)[0..<items.count + 1]
)
XCTAssert(
absoluteItems[0..<1] ==
schedule.between(
start: midnight,
end: midnight.addingTimeInterval(TimeInterval(hours: 1))
)[0..<1]
)
XCTAssert(
absoluteItems[1..<3] ==
schedule.between(
start: midnight.addingTimeInterval(TimeInterval(hours: 4)),
end: midnight.addingTimeInterval(TimeInterval(hours: 9))
)[0..<2]
)
XCTAssert(
absoluteItems[5..<6] ==
schedule.between(
start: midnight.addingTimeInterval(TimeInterval(hours: 16)),
end: midnight.addingTimeInterval(TimeInterval(hours: 20))
)[0..<1]
)
XCTAssert(
schedule.between(
start: midnight.addingTimeInterval(TimeInterval(hours: 4)),
end: midnight.addingTimeInterval(TimeInterval(hours: 3))
).isEmpty
)
}
func testTotalDelivery() {
let schedule = BasalRateSchedule(dailyItems: items, timeZone: nil)!
XCTAssertEqual(20.275, schedule.total(), accuracy: 1e-14)
}
func testRawValueSerialization() {
let schedule = BasalRateSchedule(dailyItems: items, timeZone: nil)!
let reSchedule = BasalRateSchedule(rawValue: schedule.rawValue)!
let calendar = Calendar.current
let midnight = calendar.startOfDay(for: Date())
XCTAssertEqual(reSchedule.timeZone.secondsFromGMT(), schedule.timeZone.secondsFromGMT())
XCTAssertEqual(reSchedule.value(at: midnight), schedule.value(at: midnight))
let threethirty = midnight.addingTimeInterval(TimeInterval(hours: 3.5))
XCTAssertEqual(reSchedule.value(at: threethirty), schedule.value(at: threethirty))
let fourthirty = midnight.addingTimeInterval(TimeInterval(hours: 4.5))
XCTAssertEqual(reSchedule.value(at: fourthirty), schedule.value(at: fourthirty))
}
}
| mit | 4afb101da176eae5edca76d566c9f3eb | 32.87574 | 141 | 0.596507 | 4.65069 | false | false | false | false |
ifels/swiftDemo | DragDropGridviewDemo/DragDropGridviewDemo/gridview/GridPosition.swift | 1 | 1246 | //
// GridPosition.swift
// mdx-audio
//
// Created by ifels on 2016/11/14.
// Copyright © 2016年 ifels. All rights reserved.
//
import Foundation
func == (lhs: GridPosition, rhs: GridPosition) -> Bool {
return (lhs.x == rhs.x && lhs.y == rhs.y)
}
struct GridPosition: Equatable {
var x: Int?
var y: Int?
func col () -> Int {
return x!
}
func row () -> Int {
return y!
}
func arrayIndex (_ colsInRow: Int) -> Int {
let index = row()*colsInRow + col()
return index
}
func up () -> GridPosition? {
if y! <= 0 {
return nil
} else {
return GridPosition(x: x!, y: y!-1)
}
}
func down () -> GridPosition {
return GridPosition(x: x!, y: y!+1)
}
func left () -> GridPosition? {
if x! <= 0 {
return nil
} else {
return GridPosition (x: x!-1, y: y!)
}
}
func right () -> GridPosition {
return GridPosition (x: x!+1, y: y!)
}
func string () -> String {
return "\(x!), \(y!)"
}
func detailedString () -> String {
return "x: \(x!), y: \(y!)"
}
}
| apache-2.0 | bb72cce3d955a4ee11c9f267700f0017 | 17.833333 | 56 | 0.452132 | 3.634503 | false | false | false | false |
BoxJeon/funjcam-ios | Domain/Usecase/Implementation/DaumSearchImageResult.swift | 1 | 1430 | import Foundation
import Entity
import Usecase
struct DaumSearchImageResult: Decodable {
let searchedImages: [SearchImage]
let next: Int?
private enum CodingKeys: String, CodingKey {
case documents
case meta
}
private struct Image: Decodable {
var image_url: String
var width: Int
var height: Int
var thumbnail_url: String
var collection: String
var display_sitename: String
var doc_url: String
var datetime: String
}
struct Metadata: Decodable {
var total_count: Int = 0
var pageable_count: Int = 0
var is_end: Bool = true
}
static let currentPage: CodingUserInfoKey = CodingUserInfoKey(rawValue: "currentPage")!
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.searchedImages = (try values.decodeIfPresent([Image].self, forKey: .documents) ?? []).map { image in
return SearchImage(
displayName: image.display_sitename,
urlString: image.image_url,
pixelWidth: image.width,
pixelHeight: image.height,
thumbnailURLString: image.thumbnail_url
)
}
let metadata = try values.decodeIfPresent(Metadata.self, forKey: .meta) ?? Metadata()
if let currentPage = decoder.userInfo[DaumSearchImageResult.currentPage] as? Int, !metadata.is_end {
self.next = currentPage + 1
} else {
self.next = nil
}
}
}
| mit | 72e50714209f1a60d5e395c4cb585452 | 26.5 | 109 | 0.674825 | 4.255952 | false | false | false | false |
fireflyexperience/BSImagePicker | Pod/Classes/View/AlbumCell.swift | 1 | 2178 | // The MIT License (MIT)
//
// Copyright (c) 2015 Joakim Gyllström
//
// 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
final class AlbumCell: UITableViewCell {
@IBOutlet weak var firstImageView: UIImageView!
@IBOutlet weak var secondImageView: UIImageView!
@IBOutlet weak var thirdImageView: UIImageView!
@IBOutlet weak var albumTitleLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
// Add a little shadow to images views
for imageView in [firstImageView, secondImageView, thirdImageView] {
imageView?.layer.shadowColor = UIColor.white.cgColor
imageView?.layer.shadowRadius = 1.0
imageView?.layer.shadowOffset = CGSize(width: 0.5, height: -0.5)
imageView?.layer.shadowOpacity = 1.0
}
}
override var isSelected: Bool {
didSet {
// Selection checkmark
if isSelected == true {
accessoryType = .checkmark
} else {
accessoryType = .none
}
}
}
}
| mit | debe6fe8db2720291c543a704c9dc966 | 39.075472 | 81 | 0.66927 | 4.774123 | false | false | false | false |
ddimitrov90/EverliveSDK | Tests/Pods/EverliveSDK/EverliveSDK/FilesHandler.swift | 2 | 1882 | //
// FilesHandler.swift
// EverliveSwift
//
// Created by Dimitar Dimitrov on 4/4/16.
// Copyright © 2016 ddimitrov. All rights reserved.
//
import Foundation
import EVReflection
public class FilesHandler {
var connection: EverliveConnection
var typeName: String!
init(connection: EverliveConnection){
self.connection = connection
self.typeName = "Files"
//TODO: discuss the time format
let formatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
formatter.timeZone = NSTimeZone(forSecondsFromGMT: 0)
formatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
EVReflection.setDateFormatter(formatter)
}
public func download(id:String)-> DownloadFileHandler {
return DownloadFileHandler(id: id, connection: self.connection, typeName: self.typeName)
}
public func upload(file: File) -> UploadFileHandler {
return UploadFileHandler(newFile: file, connection: self.connection, typeName: self.typeName)
}
public func getById(id:String)-> GetByIdHandler<File> {
return GetByIdHandler(id: id, connection: self.connection, typeName: self.typeName)
}
public func getAll() -> GetAllHandler<File> {
return GetAllHandler(connection: self.connection, typeName: self.typeName)
}
public func getByFilter(filter: EverliveQuery) -> GetByFilter<File>{
return GetByFilter(filter: filter, connection: self.connection, typeName: self.typeName)
}
public func deleteById(id:String) -> DeleteByIdHandler{
return DeleteByIdHandler(id: id, connection: self.connection, typeName: self.typeName)
}
public func deleteAll() -> DeleteAllHandler {
return DeleteAllHandler(connection: self.connection, typeName: self.typeName)
}
} | mit | b56783ded558d81ec8dc3912780e99b0 | 32.017544 | 101 | 0.683147 | 4.425882 | false | false | false | false |
algoliareadmebot/algoliasearch-client-swift | Source/Client.swift | 1 | 10662 | //
// Copyright (c) 2015 Algolia
// http://www.algolia.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 Foundation
/// Entry point into the Swift API.
///
@objc public class Client : AbstractClient {
// MARK: Properties
/// Algolia application ID.
@objc public var appID: String { return _appID! } // will never be nil in this class
/// Algolia API key.
@objc public var apiKey: String {
get { return _apiKey! }
set { _apiKey = newValue }
}
/// Cache of already created indices.
///
/// This dictionary is used to avoid creating two instances to represent the same index, as it is (1) inefficient
/// and (2) potentially harmful since instances are stateful (that's especially true of mirrored/offline indices,
/// but also of online indices because of the search cache).
///
/// + Note: The values are zeroing weak references to avoid leaking memory when an index is no longer used.
///
var indices: NSMapTable<NSString, AnyObject> = NSMapTable(keyOptions: [.strongMemory], valueOptions: [.weakMemory])
/// Queue for purely in-memory operations (no I/Os).
/// Typically used for aggregate, concurrent operations.
///
internal var inMemoryQueue: OperationQueue = OperationQueue()
// MARK: Initialization
/// Create a new Algolia Search client.
///
/// - parameter appID: The application ID (available in your Algolia Dashboard).
/// - parameter apiKey: A valid API key for the service.
///
@objc public init(appID: String, apiKey: String) {
// Initialize hosts to their default values.
//
// NOTE: The host list comes in two parts:
//
// 1. The fault-tolerant, load-balanced DNS host.
// 2. The non-fault-tolerant hosts. Those hosts must be randomized to ensure proper load balancing in case
// of the first host's failure.
//
let fallbackHosts = [
"\(appID)-1.algolianet.com",
"\(appID)-2.algolianet.com",
"\(appID)-3.algolianet.com"
].shuffle()
let readHosts = [ "\(appID)-dsn.algolia.net" ] + fallbackHosts
let writeHosts = [ "\(appID).algolia.net" ] + fallbackHosts
super.init(appID: appID, apiKey: apiKey, readHosts: readHosts, writeHosts: writeHosts)
inMemoryQueue.maxConcurrentOperationCount = onlineRequestQueue.maxConcurrentOperationCount
}
/// Obtain a proxy to an Algolia index (no server call required by this method).
///
/// + Note: Only one instance can exist for a given index name. Subsequent calls to this method with the same
/// index name will return the same instance, unless it has already been released.
///
/// - parameter indexName: The name of the index.
/// - returns: A proxy to the specified index.
///
@objc(indexWithName:)
public func index(withName indexName: String) -> Index {
if let index = indices.object(forKey: indexName as NSString) {
assert(index is Index, "An index with the same name but a different type has already been created") // may happen in offline mode
return index as! Index
} else {
let index = Index(client: self, name: indexName)
indices.setObject(index, forKey: indexName as NSString)
return index
}
}
// MARK: - Operations
/// List existing indexes.
///
/// - parameter completionHandler: Completion handler to be notified of the request's outcome.
/// - returns: A cancellable operation.
///
@objc(listIndexes:)
@discardableResult public func listIndexes(completionHandler: @escaping CompletionHandler) -> Operation {
return performHTTPQuery(path: "1/indexes", method: .GET, body: nil, hostnames: readHosts, completionHandler: completionHandler)
}
/// Delete an index.
///
/// - parameter name: Name of the index to delete.
/// - parameter completionHandler: Completion handler to be notified of the request's outcome.
/// - returns: A cancellable operation.
///
@objc(deleteIndexWithName:completionHandler:)
@discardableResult public func deleteIndex(withName name: String, completionHandler: CompletionHandler? = nil) -> Operation {
let path = "1/indexes/\(name.urlEncodedPathComponent())"
return performHTTPQuery(path: path, method: .DELETE, body: nil, hostnames: writeHosts, completionHandler: completionHandler)
}
/// Move an existing index.
///
/// If the destination index already exists, its specific API keys will be preserved and the source index specific
/// API keys will be added.
///
/// - parameter srcIndexName: Name of index to move.
/// - parameter dstIndexName: The new index name.
/// - parameter completionHandler: Completion handler to be notified of the request's outcome.
/// - returns: A cancellable operation.
///
@objc(moveIndexFrom:to:completionHandler:)
@discardableResult public func moveIndex(from srcIndexName: String, to dstIndexName: String, completionHandler: CompletionHandler? = nil) -> Operation {
let path = "1/indexes/\(srcIndexName.urlEncodedPathComponent())/operation"
let request = [
"destination": dstIndexName,
"operation": "move"
]
return performHTTPQuery(path: path, method: .POST, body: request as [String : Any]?, hostnames: writeHosts, completionHandler: completionHandler)
}
/// Copy an existing index.
///
/// If the destination index already exists, its specific API keys will be preserved and the source index specific
/// API keys will be added.
///
/// - parameter srcIndexName: Name of the index to copy.
/// - parameter dstIndexName: The new index name.
/// - parameter completionHandler: Completion handler to be notified of the request's outcome.
/// - returns: A cancellable operation.
///
@objc(copyIndexFrom:to:completionHandler:)
@discardableResult public func copyIndex(from srcIndexName: String, to dstIndexName: String, completionHandler: CompletionHandler? = nil) -> Operation {
let path = "1/indexes/\(srcIndexName.urlEncodedPathComponent())/operation"
let request = [
"destination": dstIndexName,
"operation": "copy"
]
return performHTTPQuery(path: path, method: .POST, body: request as [String : Any]?, hostnames: writeHosts, completionHandler: completionHandler)
}
/// Strategy when running multiple queries. See `Client.multipleQueries(...)`.
///
public enum MultipleQueriesStrategy: String {
/// Execute the sequence of queries until the end.
///
/// + Warning: Beware of confusion with `Optional.none` when using type inference!
///
case none = "none"
/// Execute the sequence of queries until the number of hits is reached by the sum of hits.
case stopIfEnoughMatches = "stopIfEnoughMatches"
}
/// Query multiple indexes with one API call.
///
/// - parameter queries: List of queries.
/// - parameter strategy: The strategy to use.
/// - parameter completionHandler: Completion handler to be notified of the request's outcome.
/// - returns: A cancellable operation.
///
@objc(multipleQueries:strategy:completionHandler:)
@discardableResult public func multipleQueries(_ queries: [IndexQuery], strategy: String?, completionHandler: @escaping CompletionHandler) -> Operation {
// IMPLEMENTATION NOTE: Objective-C bridgeable alternative.
let path = "1/indexes/*/queries"
var requests = [JSONObject]()
requests.reserveCapacity(queries.count)
for query in queries {
requests.append([
"indexName": query.indexName as Any,
"params": query.query.build() as Any
])
}
var request = JSONObject()
request["requests"] = requests
if strategy != nil {
request["strategy"] = strategy
}
return performHTTPQuery(path: path, method: .POST, body: request, hostnames: readHosts, completionHandler: completionHandler)
}
/// Query multiple indexes with one API call.
///
/// - parameter queries: List of queries.
/// - parameter strategy: The strategy to use.
/// - parameter completionHandler: Completion handler to be notified of the request's outcome.
/// - returns: A cancellable operation.
///
@discardableResult public func multipleQueries(_ queries: [IndexQuery], strategy: MultipleQueriesStrategy? = nil, completionHandler: @escaping CompletionHandler) -> Operation {
// IMPLEMENTATION NOTE: Not Objective-C bridgeable because of enum.
return multipleQueries(queries, strategy: strategy?.rawValue, completionHandler: completionHandler)
}
/// Batch operations.
///
/// - parameter operations: List of operations.
/// - parameter completionHandler: Completion handler to be notified of the request's outcome.
/// - returns: A cancellable operation.
///
@objc(batchOperations:completionHandler:)
@discardableResult public func batch(operations: [Any], completionHandler: CompletionHandler? = nil) -> Operation {
let path = "1/indexes/*/batch"
let body = ["requests": operations]
return performHTTPQuery(path: path, method: .POST, body: body as [String : Any]?, hostnames: writeHosts, completionHandler: completionHandler)
}
}
| mit | 7f35a9900d1a937bfde009553c883007 | 44.956897 | 180 | 0.668261 | 4.813544 | false | false | false | false |
jkolb/ModestProposal | ModestProposal/HTTPRequestMethod.swift | 2 | 1406 | // Copyright (c) 2016 Justin Kolb - http://franticapparatus.net
//
// 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.
public enum HTTPRequestMethod : String {
case CONNECT = "CONNECT"
case DELETE = "DELETE"
case GET = "GET"
case HEAD = "HEAD"
case OPTIONS = "OPTIONS"
case PATCH = "PATCH"
case POST = "POST"
case PUT = "PUT"
case TRACE = "TRACE"
}
| mit | af3493f6b50eb70f400f12160999be7c | 44.354839 | 80 | 0.732575 | 4.421384 | false | false | false | false |
soulfly/guinea-pig-smart-bot | node_modules/quickblox/samples/cordova/video_chat/plugins/cordova-plugin-iosrtc/src/PluginMediaStreamRenderer.swift | 4 | 7466 | import Foundation
import AVFoundation
class PluginMediaStreamRenderer : NSObject, RTCEAGLVideoViewDelegate {
var webView: UIView
var eventListener: (data: NSDictionary) -> Void
var elementView: UIView
var videoView: RTCEAGLVideoView
var pluginMediaStream: PluginMediaStream?
var rtcAudioTrack: RTCAudioTrack?
var rtcVideoTrack: RTCVideoTrack?
init(
webView: UIView,
eventListener: (data: NSDictionary) -> Void
) {
NSLog("PluginMediaStreamRenderer#init()")
// The browser HTML view.
self.webView = webView
self.eventListener = eventListener
// The video element view.
self.elementView = UIView()
// The effective video view in which the the video stream is shown.
// It's placed over the elementView.
self.videoView = RTCEAGLVideoView()
self.elementView.userInteractionEnabled = false
self.elementView.hidden = true
self.elementView.backgroundColor = UIColor.blackColor()
self.elementView.addSubview(self.videoView)
self.elementView.layer.masksToBounds = true
self.videoView.userInteractionEnabled = false
// Place the video element view inside the WebView's superview
self.webView.superview?.addSubview(self.elementView)
}
deinit {
NSLog("PluginMediaStreamRenderer#deinit()")
}
func run() {
NSLog("PluginMediaStreamRenderer#run()")
self.videoView.delegate = self
}
func render(pluginMediaStream: PluginMediaStream) {
NSLog("PluginMediaStreamRenderer#render()")
if self.pluginMediaStream != nil {
self.reset()
}
self.pluginMediaStream = pluginMediaStream
// Take the first audio track.
for (_, track) in pluginMediaStream.audioTracks {
self.rtcAudioTrack = track.rtcMediaStreamTrack as? RTCAudioTrack
break
}
// Take the first video track.
for (_, track) in pluginMediaStream.videoTracks {
self.rtcVideoTrack = track.rtcMediaStreamTrack as? RTCVideoTrack
break
}
if self.rtcVideoTrack != nil {
self.rtcVideoTrack!.addRenderer(self.videoView)
}
}
func mediaStreamChanged() {
NSLog("PluginMediaStreamRenderer#mediaStreamChanged()")
if self.pluginMediaStream == nil {
return
}
let oldRtcVideoTrack: RTCVideoTrack? = self.rtcVideoTrack
self.rtcAudioTrack = nil
self.rtcVideoTrack = nil
// Take the first audio track.
for (_, track) in self.pluginMediaStream!.audioTracks {
self.rtcAudioTrack = track.rtcMediaStreamTrack as? RTCAudioTrack
break
}
// Take the first video track.
for (_, track) in pluginMediaStream!.videoTracks {
self.rtcVideoTrack = track.rtcMediaStreamTrack as? RTCVideoTrack
break
}
// If same video track as before do nothing.
if oldRtcVideoTrack != nil && self.rtcVideoTrack != nil &&
oldRtcVideoTrack!.label == self.rtcVideoTrack!.label {
NSLog("PluginMediaStreamRenderer#mediaStreamChanged() | same video track as before")
}
// Different video track.
else if oldRtcVideoTrack != nil && self.rtcVideoTrack != nil &&
oldRtcVideoTrack!.label != self.rtcVideoTrack!.label {
NSLog("PluginMediaStreamRenderer#mediaStreamChanged() | has a new video track")
oldRtcVideoTrack!.removeRenderer(self.videoView)
self.rtcVideoTrack!.addRenderer(self.videoView)
}
// Did not have video but now it has.
else if oldRtcVideoTrack == nil && self.rtcVideoTrack != nil {
NSLog("PluginMediaStreamRenderer#mediaStreamChanged() | video track added")
self.rtcVideoTrack!.addRenderer(self.videoView)
}
// Had video but now it has not.
else if oldRtcVideoTrack != nil && self.rtcVideoTrack == nil {
NSLog("PluginMediaStreamRenderer#mediaStreamChanged() | video track removed")
oldRtcVideoTrack!.removeRenderer(self.videoView)
}
}
func refresh(data: NSDictionary) {
let elementLeft = data.objectForKey("elementLeft") as? Float ?? 0
let elementTop = data.objectForKey("elementTop") as? Float ?? 0
let elementWidth = data.objectForKey("elementWidth") as? Float ?? 0
let elementHeight = data.objectForKey("elementHeight") as? Float ?? 0
var videoViewWidth = data.objectForKey("videoViewWidth") as? Float ?? 0
var videoViewHeight = data.objectForKey("videoViewHeight") as? Float ?? 0
let visible = data.objectForKey("visible") as? Bool ?? true
let opacity = data.objectForKey("opacity") as? Float ?? 1
let zIndex = data.objectForKey("zIndex") as? Float ?? 0
let mirrored = data.objectForKey("mirrored") as? Bool ?? false
let clip = data.objectForKey("clip") as? Bool ?? true
let borderRadius = data.objectForKey("borderRadius") as? Float ?? 0
NSLog("PluginMediaStreamRenderer#refresh() [elementLeft:%@, elementTop:%@, elementWidth:%@, elementHeight:%@, videoViewWidth:%@, videoViewHeight:%@, visible:%@, opacity:%@, zIndex:%@, mirrored:%@, clip:%@, borderRadius:%@]",
String(elementLeft), String(elementTop), String(elementWidth), String(elementHeight),
String(videoViewWidth), String(videoViewHeight), String(visible), String(opacity), String(zIndex),
String(mirrored), String(clip), String(borderRadius))
let videoViewLeft: Float = (elementWidth - videoViewWidth) / 2
let videoViewTop: Float = (elementHeight - videoViewHeight) / 2
self.elementView.frame = CGRectMake(
CGFloat(elementLeft),
CGFloat(elementTop),
CGFloat(elementWidth),
CGFloat(elementHeight)
)
// NOTE: Avoid a zero-size UIView for the video (the library complains).
if videoViewWidth == 0 || videoViewHeight == 0 {
videoViewWidth = 1
videoViewHeight = 1
self.videoView.hidden = true
} else {
self.videoView.hidden = false
}
self.videoView.frame = CGRectMake(
CGFloat(videoViewLeft),
CGFloat(videoViewTop),
CGFloat(videoViewWidth),
CGFloat(videoViewHeight)
)
if visible {
self.elementView.hidden = false
} else {
self.elementView.hidden = true
}
self.elementView.alpha = CGFloat(opacity)
self.elementView.layer.zPosition = CGFloat(zIndex)
// if the zIndex is 0 (the default) bring the view to the top, last one wins
if zIndex == 0 {
self.webView.superview?.bringSubviewToFront(self.elementView)
}
if !mirrored {
self.elementView.transform = CGAffineTransformIdentity
} else {
self.elementView.transform = CGAffineTransformMakeScale(-1.0, 1.0)
}
if clip {
self.elementView.clipsToBounds = true
} else {
self.elementView.clipsToBounds = false
}
self.elementView.layer.cornerRadius = CGFloat(borderRadius)
}
func close() {
NSLog("PluginMediaStreamRenderer#close()")
self.reset()
self.elementView.removeFromSuperview()
}
/**
* Private API.
*/
private func reset() {
NSLog("PluginMediaStreamRenderer#reset()")
if self.rtcVideoTrack != nil {
self.rtcVideoTrack!.removeRenderer(self.videoView)
}
self.pluginMediaStream = nil
self.rtcAudioTrack = nil
self.rtcVideoTrack = nil
}
/**
* Methods inherited from RTCEAGLVideoViewDelegate.
*/
func videoView(videoView: RTCEAGLVideoView!, didChangeVideoSize size: CGSize) {
NSLog("PluginMediaStreamRenderer | video size changed [width:%@, height:%@]",
String(size.width), String(size.height))
self.eventListener(data: [
"type": "videoresize",
"size": [
"width": Int(size.width),
"height": Int(size.height)
]
])
}
}
| apache-2.0 | 832a3cf94484ffcb8ba047737bfe5e18 | 27.164063 | 226 | 0.694348 | 3.969165 | false | false | false | false |
salemoh/GoldenQuraniOS | GoldenQuranSwift/GoldenQuranSwift/AKPickerView.swift | 1 | 21539 | //
// AKPickerView.swift
// AKPickerView
//
// Created by Akio Yasui on 1/29/15.
// Copyright (c) 2015 Akkyie Y. All rights reserved.
//
import UIKit
/**
Styles of AKPickerView.
- Wheel: Style with 3D appearance like UIPickerView.
- Flat: Flat style.
*/
public enum AKPickerViewStyle {
case wheel
case flat
}
// MARK: - Protocols
// MARK: AKPickerViewDataSource
/**
Protocols to specify the number and type of contents.
*/
@objc public protocol AKPickerViewDataSource {
func numberOfItemsInPickerView(_ pickerView: AKPickerView) -> Int
@objc optional func pickerView(_ pickerView: AKPickerView, titleForItem item: Int) -> String
@objc optional func pickerView(_ pickerView: AKPickerView, imageForItem item: Int) -> UIImage
}
// MARK: AKPickerViewDelegate
/**
Protocols to specify the attitude when user selected an item,
and customize the appearance of labels.
*/
@objc public protocol AKPickerViewDelegate: UIScrollViewDelegate {
@objc optional func pickerView(_ pickerView: AKPickerView, didSelectItem item: Int)
@objc optional func pickerView(_ pickerView: AKPickerView, marginForItem item: Int) -> CGSize
@objc optional func pickerView(_ pickerView: AKPickerView, configureLabel label: UILabel, forItem item: Int)
}
// MARK: - Private Classes and Protocols
// MARK: AKCollectionViewLayoutDelegate
/**
Private. Used to deliver the style of the picker.
*/
private protocol AKCollectionViewLayoutDelegate {
func pickerViewStyleForCollectionViewLayout(_ layout: AKCollectionViewLayout) -> AKPickerViewStyle
}
// MARK: AKCollectionViewCell
/**
Private. A subclass of UICollectionViewCell used in AKPickerView's collection view.
*/
private class AKCollectionViewCell: UICollectionViewCell {
var label: UILabel!
var imageView: UIImageView!
var font = UIFont.systemFont(ofSize: UIFont.systemFontSize)
var highlightedFont = UIFont.systemFont(ofSize: UIFont.systemFontSize)
var _selected: Bool = false {
didSet(selected) {
let animation = CATransition()
animation.type = kCATransitionFade
animation.duration = 0.15
self.label.layer.add(animation, forKey: "")
self.label.font = self.isSelected ? self.highlightedFont : self.font
}
}
func initialize() {
self.layer.isDoubleSided = false
self.layer.shouldRasterize = true
self.layer.rasterizationScale = UIScreen.main.scale
self.label = UILabel(frame: self.contentView.bounds)
self.label.backgroundColor = UIColor.clear
self.label.textAlignment = .center
self.label.textColor = UIColor.gray
self.label.numberOfLines = 1
self.label.lineBreakMode = .byTruncatingTail
self.label.highlightedTextColor = UIColor.black
self.label.font = self.font
self.label.autoresizingMask = [.flexibleTopMargin, .flexibleLeftMargin, .flexibleBottomMargin, .flexibleRightMargin]
self.contentView.addSubview(self.label)
self.imageView = UIImageView(frame: self.contentView.bounds)
self.imageView.backgroundColor = UIColor.clear
self.imageView.contentMode = .center
self.imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
self.contentView.addSubview(self.imageView)
}
init() {
super.init(frame: CGRect.zero)
self.initialize()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
required init!(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
}
// MARK: AKCollectionViewLayout
/**
Private. A subclass of UICollectionViewFlowLayout used in the collection view.
*/
private class AKCollectionViewLayout: UICollectionViewFlowLayout {
var delegate: AKCollectionViewLayoutDelegate!
var width: CGFloat!
var midX: CGFloat!
var maxAngle: CGFloat!
func initialize() {
self.sectionInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0)
self.scrollDirection = .horizontal
self.minimumLineSpacing = 0.0
}
override init() {
super.init()
self.initialize()
}
required init!(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
fileprivate override func prepare() {
let visibleRect = CGRect(origin: self.collectionView!.contentOffset, size: self.collectionView!.bounds.size)
self.midX = visibleRect.midX;
self.width = visibleRect.width / 2;
self.maxAngle = CGFloat(Double.pi/2.0);
}
fileprivate override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
fileprivate override func layoutAttributesForItem(at indexPath: IndexPath) -> UICollectionViewLayoutAttributes? {
if let attributes = super.layoutAttributesForItem(at: indexPath)?.copy() as? UICollectionViewLayoutAttributes {
switch self.delegate.pickerViewStyleForCollectionViewLayout(self) {
case .flat:
return attributes
case .wheel:
let distance = attributes.frame.midX - self.midX;
let currentAngle = self.maxAngle * distance / self.width / CGFloat(Double.pi/2.0);
var transform = CATransform3DIdentity;
transform = CATransform3DTranslate(transform, -distance, 0, -self.width);
transform = CATransform3DRotate(transform, currentAngle, 0, 1, 0);
transform = CATransform3DTranslate(transform, 0, 0, self.width);
attributes.transform3D = transform;
attributes.alpha = fabs(currentAngle) < self.maxAngle ? 1.0 : 0.0;
return attributes;
}
}
return nil
}
fileprivate func layoutAttributesForElementsInRect(_ rect: CGRect) -> [AnyObject]? {
switch self.delegate.pickerViewStyleForCollectionViewLayout(self) {
case .flat:
return super.layoutAttributesForElements(in: rect)
case .wheel:
var attributes = [AnyObject]()
if self.collectionView!.numberOfSections > 0 {
for i in 0 ..< self.collectionView!.numberOfItems(inSection: 0) {
let indexPath = IndexPath(item: i, section: 0)
attributes.append(self.layoutAttributesForItem(at: indexPath)!)
}
}
return attributes
}
}
}
// MARK: AKPickerViewDelegateIntercepter
/**
Private. Used to hook UICollectionViewDelegate and throw it AKPickerView,
and if it conforms to UIScrollViewDelegate, also throw it to AKPickerView's delegate.
*/
private class AKPickerViewDelegateIntercepter: NSObject, UICollectionViewDelegate {
weak var pickerView: AKPickerView?
weak var delegate: UIScrollViewDelegate?
init(pickerView: AKPickerView, delegate: UIScrollViewDelegate?) {
self.pickerView = pickerView
self.delegate = delegate
}
fileprivate override func forwardingTarget(for aSelector: Selector) -> Any? {
if self.pickerView!.responds(to: aSelector) {
return self.pickerView
} else if self.delegate != nil && self.delegate!.responds(to: aSelector) {
return self.delegate
} else {
return nil
}
}
fileprivate override func responds(to aSelector: Selector) -> Bool {
if self.pickerView!.responds(to: aSelector) {
return true
} else if self.delegate != nil && self.delegate!.responds(to: aSelector) {
return true
} else {
return super.responds(to: aSelector)
}
}
}
// MARK: - AKPickerView
// TODO: Make these delegate conformation private
/**
Horizontal picker view. This is just a subclass of UIView, contains a UICollectionView.
*/
open class AKPickerView: UIView, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, AKCollectionViewLayoutDelegate {
// MARK: - Properties
// MARK: Readwrite Properties
/// Readwrite. Data source of picker view.
open weak var dataSource: AKPickerViewDataSource? = nil
/// Readwrite. Delegate of picker view.
open weak var delegate: AKPickerViewDelegate? = nil {
didSet(delegate) {
self.intercepter.delegate = delegate
}
}
/// Readwrite. A font which used in NOT selected cells.
open lazy var font = UIFont.systemFont(ofSize: 20)
/// Readwrite. A font which used in selected cells.
open lazy var highlightedFont = UIFont.boldSystemFont(ofSize: 20)
/// Readwrite. A color of the text on NOT selected cells.
@IBInspectable open lazy var textColor: UIColor = UIColor.darkGray
/// Readwrite. A color of the text on selected cells.
@IBInspectable open lazy var highlightedTextColor: UIColor = UIColor.black
/// Readwrite. A float value which indicates the spacing between cells.
@IBInspectable open var interitemSpacing: CGFloat = 0.0
/// Readwrite. The style of the picker view. See AKPickerViewStyle.
open var pickerViewStyle = AKPickerViewStyle.wheel
/// Readwrite. A float value which determines the perspective representation which used when using AKPickerViewStyle.Wheel style.
@IBInspectable open var viewDepth: CGFloat = 1000.0 {
didSet {
self.collectionView.layer.sublayerTransform = self.viewDepth > 0.0 ? {
var transform = CATransform3DIdentity;
transform.m34 = -1.0 / self.viewDepth;
return transform;
}() : CATransform3DIdentity;
}
}
/// Readwrite. A boolean value indicates whether the mask is disabled.
@IBInspectable open var maskDisabled: Bool! = nil {
didSet {
self.collectionView.layer.mask = self.maskDisabled == true ? nil : {
let maskLayer = CAGradientLayer()
maskLayer.frame = self.collectionView.bounds
maskLayer.colors = [
UIColor.clear.cgColor,
UIColor.black.cgColor,
UIColor.black.cgColor,
UIColor.clear.cgColor]
maskLayer.locations = [0.0, 0.33, 0.66, 1.0]
maskLayer.startPoint = CGPoint(x: 0.0, y: 0.0)
maskLayer.endPoint = CGPoint(x: 1.0, y: 0.0)
return maskLayer
}()
}
}
// MARK: Readonly Properties
/// Readonly. Index of currently selected item.
open fileprivate(set) var selectedItem: Int = 0
/// Readonly. The point at which the origin of the content view is offset from the origin of the picker view.
open var contentOffset: CGPoint {
get {
return self.collectionView.contentOffset
}
}
// MARK: Private Properties
/// Private. A UICollectionView which shows contents on cells.
fileprivate var collectionView: UICollectionView!
/// Private. An intercepter to hook UICollectionViewDelegate then throw it picker view and its delegate
fileprivate var intercepter: AKPickerViewDelegateIntercepter!
/// Private. A UICollectionViewFlowLayout used in picker view's collection view.
fileprivate var collectionViewLayout: AKCollectionViewLayout {
let layout = AKCollectionViewLayout()
layout.delegate = self
return layout
}
// MARK: - Functions
// MARK: View Lifecycle
/**
Private. Initializes picker view's subviews and friends.
*/
fileprivate func initialize() {
self.collectionView?.removeFromSuperview()
self.collectionView = UICollectionView(frame: self.bounds, collectionViewLayout: self.collectionViewLayout)
self.collectionView.showsHorizontalScrollIndicator = false
self.collectionView.backgroundColor = UIColor.clear
self.collectionView.decelerationRate = UIScrollViewDecelerationRateFast
self.collectionView.autoresizingMask = [UIViewAutoresizing.flexibleWidth, UIViewAutoresizing.flexibleHeight]
self.collectionView.dataSource = self
self.collectionView.register(
AKCollectionViewCell.self,
forCellWithReuseIdentifier: NSStringFromClass(AKCollectionViewCell.self))
self.addSubview(self.collectionView)
self.intercepter = AKPickerViewDelegateIntercepter(pickerView: self, delegate: self.delegate)
self.collectionView.delegate = self.intercepter
self.maskDisabled = self.maskDisabled == nil ? false : self.maskDisabled
}
public init() {
super.init(frame: CGRect.zero)
self.initialize()
}
public override init(frame: CGRect) {
super.init(frame: frame)
self.initialize()
}
public required init!(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initialize()
}
deinit {
self.collectionView.delegate = nil
}
// MARK: Layout
open override func layoutSubviews() {
super.layoutSubviews()
if self.dataSource != nil && self.dataSource!.numberOfItemsInPickerView(self) > 0 {
self.collectionView.collectionViewLayout = self.collectionViewLayout
self.scrollToItem(self.selectedItem, animated: false)
}
self.collectionView.layer.mask?.frame = self.collectionView.bounds
}
open override var intrinsicContentSize : CGSize {
return CGSize(width: UIViewNoIntrinsicMetric, height: max(self.font.lineHeight, self.highlightedFont.lineHeight))
}
// MARK: Calculation Functions
/**
Private. Used to calculate bounding size of given string with picker view's font and highlightedFont
:param: string A NSString to calculate size
:returns: A CGSize which contains given string just.
*/
fileprivate func sizeForString(_ string: NSString) -> CGSize {
let size = string.size(attributes: [NSFontAttributeName: self.font])
let highlightedSize = string.size(attributes: [NSFontAttributeName: self.highlightedFont])
return CGSize(
width: ceil(max(size.width, highlightedSize.width)),
height: ceil(max(size.height, highlightedSize.height)))
}
/**
Private. Used to calculate the x-coordinate of the content offset of specified item.
:param: item An integer value which indicates the index of cell.
:returns: An x-coordinate of the cell whose index is given one.
*/
fileprivate func offsetForItem(_ item: Int) -> CGFloat {
var offset: CGFloat = 0
for i in 0 ..< item {
let indexPath = IndexPath(item: i, section: 0)
let cellSize = self.collectionView(
self.collectionView,
layout: self.collectionView.collectionViewLayout,
sizeForItemAt: indexPath)
offset += cellSize.width
}
let firstIndexPath = IndexPath(item: 0, section: 0)
let firstSize = self.collectionView(
self.collectionView,
layout: self.collectionView.collectionViewLayout,
sizeForItemAt: firstIndexPath)
let selectedIndexPath = IndexPath(item: item, section: 0)
let selectedSize = self.collectionView(
self.collectionView,
layout: self.collectionView.collectionViewLayout,
sizeForItemAt: selectedIndexPath)
offset -= (firstSize.width - selectedSize.width) / 2.0
return offset
}
// MARK: View Controls
/**
Reload the picker view's contents and styles. Call this method always after any property is changed.
*/
open func reloadData() {
self.invalidateIntrinsicContentSize()
self.collectionView.collectionViewLayout.invalidateLayout()
self.collectionView.reloadData()
if self.dataSource != nil && self.dataSource!.numberOfItemsInPickerView(self) > 0 {
self.selectItem(self.selectedItem, animated: false, notifySelection: false)
}
}
/**
Move to the cell whose index is given one without selection change.
:param: item An integer value which indicates the index of cell.
:param: animated True if the scrolling should be animated, false if it should be immediate.
*/
open func scrollToItem(_ item: Int, animated: Bool = false) {
switch self.pickerViewStyle {
case .flat:
self.collectionView.scrollToItem(
at: IndexPath(
item: item,
section: 0),
at: .centeredHorizontally,
animated: animated)
case .wheel:
self.collectionView.setContentOffset(
CGPoint(
x: self.offsetForItem(item),
y: self.collectionView.contentOffset.y),
animated: animated)
}
}
/**
Select a cell whose index is given one and move to it.
:param: item An integer value which indicates the index of cell.
:param: animated True if the scrolling should be animated, false if it should be immediate.
*/
open func selectItem(_ item: Int, animated: Bool = false) {
self.selectItem(item, animated: animated, notifySelection: true)
}
/**
Private. Select a cell whose index is given one and move to it, with specifying whether it calls delegate method.
:param: item An integer value which indicates the index of cell.
:param: animated True if the scrolling should be animated, false if it should be immediate.
:param: notifySelection True if the delegate method should be called, false if not.
*/
fileprivate func selectItem(_ item: Int, animated: Bool, notifySelection: Bool) {
self.collectionView.selectItem(
at: IndexPath(item: item, section: 0),
animated: animated,
scrollPosition: UICollectionViewScrollPosition())
self.scrollToItem(item, animated: animated)
self.selectedItem = item
if notifySelection {
self.delegate?.pickerView?(self, didSelectItem: item)
}
}
// MARK: Delegate Handling
/**
Private.
*/
fileprivate func didEndScrolling() {
switch self.pickerViewStyle {
case .flat:
let center = self.convert(self.collectionView.center, to: self.collectionView)
if let indexPath = self.collectionView.indexPathForItem(at: center) {
self.selectItem(indexPath.item, animated: true, notifySelection: true)
}
case .wheel:
if let numberOfItems = self.dataSource?.numberOfItemsInPickerView(self) {
for i in 0 ..< numberOfItems {
let indexPath = IndexPath(item: i, section: 0)
let cellSize = self.collectionView(
self.collectionView,
layout: self.collectionView.collectionViewLayout,
sizeForItemAt: indexPath)
if self.offsetForItem(i) + cellSize.width / 2 > self.collectionView.contentOffset.x {
self.selectItem(i, animated: true, notifySelection: true)
break
}
}
}
}
}
// MARK: UICollectionViewDataSource
open func numberOfSections(in collectionView: UICollectionView) -> Int {
return self.dataSource != nil && self.dataSource!.numberOfItemsInPickerView(self) > 0 ? 1 : 0
}
open func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.dataSource != nil ? self.dataSource!.numberOfItemsInPickerView(self) : 0
}
open func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NSStringFromClass(AKCollectionViewCell.self), for: indexPath) as! AKCollectionViewCell
if let title = self.dataSource?.pickerView?(self, titleForItem: indexPath.item) {
cell.label.text = title
cell.label.textColor = self.textColor
cell.label.highlightedTextColor = self.highlightedTextColor
cell.label.font = self.font
cell.font = self.font
cell.highlightedFont = self.highlightedFont
cell.label.bounds = CGRect(origin: CGPoint.zero, size: self.sizeForString(title as NSString))
if let delegate = self.delegate {
delegate.pickerView?(self, configureLabel: cell.label, forItem: indexPath.item)
if let margin = delegate.pickerView?(self, marginForItem: indexPath.item) {
cell.label.frame = cell.label.frame.insetBy(dx: -margin.width, dy: -margin.height)
}
}
} else if let image = self.dataSource?.pickerView?(self, imageForItem: indexPath.item) {
cell.imageView.image = image
}
cell._selected = (indexPath.item == self.selectedItem)
return cell
}
// MARK: UICollectionViewDelegateFlowLayout
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
var size = CGSize(width: self.interitemSpacing, height: collectionView.bounds.size.height)
if let title = self.dataSource?.pickerView?(self, titleForItem: indexPath.item) {
size.width += self.sizeForString(title as NSString).width
if let margin = self.delegate?.pickerView?(self, marginForItem: indexPath.item) {
size.width += margin.width * 2
}
} else if let image = self.dataSource?.pickerView?(self, imageForItem: indexPath.item) {
size.width += image.size.width
}
return size
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0.0
}
open func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
let number = self.collectionView(collectionView, numberOfItemsInSection: section)
let firstIndexPath = IndexPath(item: 0, section: section)
let firstSize = self.collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAt: firstIndexPath)
let lastIndexPath = IndexPath(item: number - 1, section: section)
let lastSize = self.collectionView(collectionView, layout: collectionView.collectionViewLayout, sizeForItemAt: lastIndexPath)
return UIEdgeInsetsMake(
0, (collectionView.bounds.size.width - firstSize.width) / 2,
0, (collectionView.bounds.size.width - lastSize.width) / 2
)
}
// MARK: UICollectionViewDelegate
open func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.selectItem(indexPath.item, animated: true)
}
// MARK: UIScrollViewDelegate
open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
self.delegate?.scrollViewDidEndDecelerating?(scrollView)
self.didEndScrolling()
}
open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
self.delegate?.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate)
if !decelerate {
self.didEndScrolling()
}
}
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.delegate?.scrollViewDidScroll?(scrollView)
CATransaction.begin()
CATransaction.setValue(kCFBooleanTrue, forKey: kCATransactionDisableActions)
self.collectionView.layer.mask?.frame = self.collectionView.bounds
CATransaction.commit()
}
// MARK: AKCollectionViewLayoutDelegate
fileprivate func pickerViewStyleForCollectionViewLayout(_ layout: AKCollectionViewLayout) -> AKPickerViewStyle {
return self.pickerViewStyle
}
}
| mit | 67cb2d3669d6891fa812f0d20cc6b955 | 34.484349 | 177 | 0.753703 | 4.130201 | false | false | false | false |
minubia/SwiftKeychain | Source/Certificate.swift | 1 | 3265 | // Certificate.swift
//
// Copyright (c) 2016 Minubia (http://minubia.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 Foundation
public class Certificate: Key {
var _subject: CFDataRef!
var _issuer: CFDataRef!
var _serialNumber: CFDataRef!
var _subjectKeyID: CFDataRef!
var _publicKeyHash: CFDataRef!
var _certificateType: CFNumberRef!
var _certificateEncoding: CFNumberRef!
var subject: CFDataRef {
get {
return _subject
}
}
var issuer: CFDataRef {
get {
return _issuer
}
}
var serialNumber: CFDataRef {
get {
return _serialNumber
}
}
var subjectKeyID: CFDataRef {
get {
return _subjectKeyID
}
}
var publicKeyHash: CFDataRef {
get {
return _publicKeyHash
}
}
var certificateType: CFNumberRef {
get {
return _certificateType
}
}
var certificateEncoding: CFNumberRef {
get {
return _certificateEncoding
}
}
public required override init(attributes: Dictionary<String, Any>) {
super.init(attributes: attributes)
if((attributes["subject"]) != nil){
_subject = attributes["subject"] as! NSData
}
if((attributes["issuer"]) != nil){
_issuer = attributes["issuer"] as! NSData
}
if((attributes["serialNumber"]) != nil){
_serialNumber = attributes["serialNumber"]as! NSData
}
if((attributes["subjectKeyID"]) != nil){
_subjectKeyID = attributes["subjectKeyID"] as! NSData
}
if((attributes["publicKeyHash"]) != nil){
_publicKeyHash = attributes["publicKeyHash"] as! NSData
}
if((attributes["certificateType"]) != nil){
_certificateType = attributes["certificateType"] as! CFNumberRef
}
if((attributes["certificateEncoding"]) != nil){
_certificateEncoding = attributes["certificateEncoding"] as! CFNumberRef
}
}
} | mit | dabf502684c97ffecabc19bfb514dad7 | 28.963303 | 84 | 0.60827 | 4.808542 | false | false | false | false |
dreamsxin/swift | test/Sema/unsupported_recursive_value_type.swift | 12 | 4280 | // RUN: %target-parse-verify-swift
struct SelfRecursiveStruct { // expected-error{{value type 'SelfRecursiveStruct' cannot have a stored property that references itself}}
let a: SelfRecursiveStruct
}
struct OptionallyRecursiveStruct { // expected-error{{value type 'OptionallyRecursiveStruct' cannot have a stored property that references itself}}
let a: OptionallyRecursiveStruct?
init() { a = OptionallyRecursiveStruct() }
}
struct IndirectlyRecursiveStruct1 { // expected-error{{value type 'IndirectlyRecursiveStruct1' cannot have a stored property that references itself}}
let a: IndirectlyRecursiveStruct2
}
struct IndirectlyRecursiveStruct2 { // expected-error{{value type 'IndirectlyRecursiveStruct2' cannot have a stored property that references itself}}
let a: IndirectlyRecursiveStruct1
}
enum NonterminatingSelfRecursiveEnum { // expected-error{{recursive enum 'NonterminatingSelfRecursiveEnum' is not marked 'indirect'}} {{1-1=indirect }}
case A(NonterminatingSelfRecursiveEnum)
}
enum TerminatingSelfRecursiveEnum { // expected-error{{recursive enum 'TerminatingSelfRecursiveEnum' is not marked 'indirect'}} {{1-1=indirect }}
case A(TerminatingSelfRecursiveEnum)
case B
}
enum IndirectlyRecursiveEnum1 { // expected-error{{recursive enum 'IndirectlyRecursiveEnum1' is not marked 'indirect'}} {{1-1=indirect }}
case A(IndirectlyRecursiveEnum2)
}
enum IndirectlyRecursiveEnum2 { // expected-error{{recursive enum 'IndirectlyRecursiveEnum2' is not marked 'indirect'}}
case A(IndirectlyRecursiveEnum1)
}
enum RecursiveByGenericSubstitutionEnum<T> {
case A(T)
}
struct RecursiveByBeingInTupleStruct { // expected-error{{value type 'RecursiveByBeingInTupleStruct' cannot have a stored property that references itself}}
let a: (Int, RecursiveByBeingInTupleStruct)
}
struct OptionallySelfRecursiveStruct { // expected-error{{value type 'OptionallySelfRecursiveStruct' cannot have a stored property that references itself}}
let a: Optional<OptionallyRecursiveStruct>
}
enum OptionallySelfRecursiveEnum { // expected-error{{recursive enum 'OptionallySelfRecursiveEnum' is not marked 'indirect'}}
case A(Optional<OptionallySelfRecursiveEnum>)
}
// self-recursive struct with self as member's type argument, a proper name would
// be too long.
struct X<T> { // expected-error{{value type 'X<T>' cannot have a stored property that references itself}}
let s: X<X>
}
// self-recursive enum with self as generic argument associated type, a proper
// name would be too long
enum Y<T> { // expected-error{{recursive enum 'Y<T>' is not marked 'indirect'}}
case A(Int, Y<Y>)
}
// ultra super nest-acular type
struct Z<T, U> { // expected-error{{value type 'Z<T, U>' cannot have a stored property that references itself}}
let a: Z<Optional<Z<Z<Z, Z>, X<Z>>>, (Int, Z)>
}
struct RecursiveByGenericSubstitutionStruct { // expected-error{{value type 'RecursiveByGenericSubstitutionStruct' cannot have a stored property that references itself}}
let a: RecursiveByGenericSubstitutionEnum<RecursiveByGenericSubstitutionStruct>
}
struct RecursiveWithLocal { // expected-error{{value type 'RecursiveWithLocal' cannot have a stored property that references itself}}
init(t: Local) { self.t = t }
struct Local { // expected-error{{value type 'RecursiveWithLocal.Local'}}
init(s: RecursiveWithLocal) { self.s = s }
var s: RecursiveWithLocal
}
var t: Local
}
struct R<T> { let t: () -> T }
struct S { let r: R<S> } // S should be valid in this scenario
// It's valid for ParentStruct.B to contain ParentStruct.A
struct ParentStruct {
struct A {}
struct B {
let s: A
}
}
// another valid case
struct Outer {
struct Inner {
var o: Outer
}
}
// nested generic parameters are valid
struct NestedGenericParamStruct {
let n: [[Int]]
}
struct NestedGenericParamEnum {
let n: Int??
}
// Neither 'Bad' nor 'Holder' appear in generic parameter of 'Bad', but
// recursion happens anyways.
protocol Holdable {
associatedtype Holding
}
struct Holder<T : Holdable> {
let x: T.Holding
}
struct NoStorage : Holdable {
typealias Holding = Bad
}
struct Bad { // expected-error{{value type 'Bad' cannot have a stored property that references itself}}
var s: Holder<NoStorage>
}
| apache-2.0 | e53491a893aa5d733624c59a39678c55 | 33.24 | 169 | 0.748364 | 3.873303 | false | false | false | false |
marius-/GraphTheory | GraphTheory/Algorithms/Dijkstra.swift | 1 | 1584 | //
// Dijkstra.swift
// GraphTheory
//
// Created by Marius Kažemėkaitis on 2015-06-10.
// Copyright © 2015 TAPTAP mobile. All rights reserved.
//
import Foundation
class Dijkstra: ShortestPathBase {
override func go(from from : Vertex, to : Vertex, graphView : GraphView) {
for vertex : Vertex in self.vertices {
vertex.minDistance = Double.infinity
vertex.previous = nil
}
from.minDistance = 0.0
let queue : PriorityQueue<Double, Vertex> = PriorityQueue()
queue.push(0, item: from)
while(queue.count > 0) {
let current : Vertex = queue.next()!
guard current != to else { break }
for e : Edge in current.adjacencies {
let next : Vertex = e.target
dispatch_async(dispatch_get_main_queue()) {
graphView.addActivityLine(current, to: next)
}
if graphView.activityLines.count < self.totalEdges() {
NSThread.sleepForTimeInterval(0.01)
}
let weight : Double = e.weight
let distanceThroughU : Double = current.minDistance + weight
if (distanceThroughU < next.minDistance) {
next.minDistance = distanceThroughU
next.previous = current
queue.push(next.minDistance, item: next)
}
}
}
}
} | mit | f7ef990afc369cd6b5e369e162718930 | 30.64 | 78 | 0.507274 | 4.925234 | false | false | false | false |
creatubbles/ctb-api-swift | CreatubblesAPIClient/Sources/Requests/Challenges/ChallengesRequest.swift | 1 | 2539 | //
// ChallengesRequest.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 UIKit
public enum ChallengeGroup: String {
case home
case favorite
case popular
case challengeDetails = "challenge_details"
}
class ChallengesRequest: Request {
override var method: RequestMethod { return .get }
override var endpoint: String { return "challenges" }
override var parameters: Dictionary<String, AnyObject> { return prepareParams() }
fileprivate let group: ChallengeGroup?
fileprivate let state: ChallengeState?
fileprivate let page: Int?
fileprivate let perPage: Int?
init(group: ChallengeGroup? = nil, state: ChallengeState? = nil, page: Int? = nil, perPage: Int? = nil) {
self.group = group
self.page = page
self.perPage = perPage
self.state = state
}
func prepareParams() -> Dictionary<String, AnyObject> {
var params = Dictionary<String, AnyObject>()
if let group = group {
params["filter[group]"] = group.rawValue as AnyObject?
}
if let state = state {
params["filter[state]"] = state.rawValue as AnyObject?
}
if let page = page {
params["page"] = page as AnyObject?
}
if let perPage = perPage {
params["per_page"] = perPage as AnyObject?
}
return params
}
}
| mit | f95c620b8b56896119d93eac8ff83e60 | 35.271429 | 109 | 0.6731 | 4.525847 | false | false | false | false |
julienbodet/wikipedia-ios | Wikipedia/Code/WMFWelcomeAnimationView.swift | 1 | 2909 | import Foundation
open class WMFWelcomeAnimationView : UIView {
// Reminder - these transforms are on WMFWelcomeAnimationView
// so they can scale proportionally to the view size.
fileprivate var wmf_proportionalHorizontalOffset: CGFloat{
return CGFloat(0.35).wmf_denormalizeUsingReference(frame.width)
}
fileprivate var wmf_proportionalVerticalOffset: CGFloat{
return CGFloat(0.35).wmf_denormalizeUsingReference(frame.height)
}
var wmf_rightTransform: CATransform3D{
return CATransform3DMakeTranslation(wmf_proportionalHorizontalOffset, 0, 0)
}
var wmf_leftTransform: CATransform3D{
return CATransform3DMakeTranslation(-wmf_proportionalHorizontalOffset, 0, 0)
}
var wmf_lowerTransform: CATransform3D{
return CATransform3DMakeTranslation(0.0, wmf_proportionalVerticalOffset, 0)
}
let wmf_scaleZeroTransform = CATransform3DMakeScale(0, 0, 1)
var wmf_scaleZeroAndLeftTransform: CATransform3D{
return CATransform3DConcat(wmf_scaleZeroTransform, wmf_leftTransform)
}
var wmf_scaleZeroAndRightTransform: CATransform3D{
return CATransform3DConcat(wmf_scaleZeroTransform, wmf_rightTransform)
}
var wmf_scaleZeroAndLowerLeftTransform: CATransform3D{
return CATransform3DConcat(wmf_scaleZeroAndLeftTransform, wmf_lowerTransform)
}
var wmf_scaleZeroAndLowerRightTransform: CATransform3D {
return CATransform3DConcat(wmf_scaleZeroAndRightTransform, wmf_lowerTransform)
}
open func beginAnimations() {
}
open func addAnimationElementsScaledToCurrentFrameSize(){
}
public var hasCircleBackground: Bool = false {
didSet {
if hasCircleBackground {
backgroundColor = UIColor(0xdee6f6)
layer.masksToBounds = true
} else {
// backgroundColor = UIColor(0xdddddd)
backgroundColor = .clear
layer.masksToBounds = false
}
setNeedsLayout()
}
}
var sizeAtLastAnimationElementAddition = CGSize.zero
open override func layoutSubviews() {
super.layoutSubviews()
guard bounds.size != sizeAtLastAnimationElementAddition else {
return
}
sizeAtLastAnimationElementAddition = bounds.size
addAnimationElementsScaledToCurrentFrameSize()
if hasCircleBackground {
layer.cornerRadius = bounds.size.width / 2.0
} else {
layer.cornerRadius = 0
}
}
open func removeExistingSubviewsAndSublayers() {
for subview in subviews {
subview.removeFromSuperview()
}
if let sublayers = layer.sublayers {
for sublayer in sublayers {
sublayer.removeFromSuperlayer()
}
}
}
}
| mit | 6f9fc554552ec0bd23c8f836b12fc31e | 32.056818 | 88 | 0.662083 | 5.015517 | false | false | false | false |
adrfer/swift | test/Driver/unknown-inputs.swift | 20 | 2164 | // RUN: rm -rf %t && mkdir -p %t
// RUN: touch %t/empty
// RUN: touch %t/empty.swiftmodule
// RUN: touch %t/empty.o
// RUN: touch %t/empty.h
// RUN: touch %t/empty.swift
// ERROR: error: unexpected input file: {{.*}}empty
// COMPILE: 0: input
// COMPILE: 1: compile, {0}, object
// RUN: %swiftc_driver -driver-print-actions %t/empty 2>&1 | FileCheck -check-prefix=LINK-%target-object-format %s
// RUN: not %swiftc_driver -driver-print-actions %t/empty.swiftmodule 2>&1 | FileCheck -check-prefix=ERROR %s
// RUN: %swiftc_driver -driver-print-actions %t/empty.o 2>&1 | FileCheck -check-prefix=LINK-%target-object-format %s
// RUN: not %swiftc_driver -driver-print-actions %t/empty.h 2>&1 | FileCheck -check-prefix=ERROR %s
// RUN: %swiftc_driver -driver-print-actions %t/empty.swift 2>&1 | FileCheck -check-prefix=COMPILE %s
// LINK-macho: 0: input
// LINK-macho: 1: link, {0}, image
// LINK-elf: 0: input
// LINK-elf: 1: swift-autolink-extract, {0}, autolink
// LINK-elf: 2: link, {0, 1}, image
// RUN: not %swiftc_driver -driver-print-actions -emit-module %t/empty 2>&1 | FileCheck -check-prefix=ERROR %s
// RUN: %swiftc_driver -driver-print-actions -emit-module %t/empty.swiftmodule 2>&1 | FileCheck -check-prefix=MODULE %s
// RUN: not %swiftc_driver -driver-print-actions -emit-module %t/empty.o 2>&1 | FileCheck -check-prefix=ERROR %s
// RUN: not %swiftc_driver -driver-print-actions -emit-module %t/empty.h 2>&1 | FileCheck -check-prefix=ERROR %s
// RUN: %swiftc_driver -driver-print-actions %t/empty.swift 2>&1 | FileCheck -check-prefix=COMPILE %s
// MODULE: 0: input
// MODULE: 1: merge-module, {0}, swiftmodule
// RUN: not %swiftc_driver -driver-print-actions -parse %t/empty 2>&1 | FileCheck -check-prefix=ERROR %s
// RUN: not %swiftc_driver -driver-print-actions -parse %t/empty.swiftmodule 2>&1 | FileCheck -check-prefix=ERROR %s
// RUN: not %swiftc_driver -driver-print-actions -parse %t/empty.o 2>&1 | FileCheck -check-prefix=ERROR %s
// RUN: not %swiftc_driver -driver-print-actions -parse %t/empty.h 2>&1 | FileCheck -check-prefix=ERROR %s
// RUN: %swiftc_driver -driver-print-actions %t/empty.swift 2>&1 | FileCheck -check-prefix=COMPILE %s
| apache-2.0 | ed8fd1463d6575c556f1aad76418ea4b | 54.487179 | 119 | 0.695471 | 2.972527 | false | false | true | false |
stevehe-campray/BSBDJ | BSBDJ/BSBDJ/Essence(精华)/Views/BSBTopicVoiceView.swift | 1 | 1743 | //
// BSBTopicVoiceView.swift
// BSBDJ
//
// Created by hejingjin on 16/6/21.
// Copyright © 2016年 baisibudejie. All rights reserved.
//
import UIKit
class BSBTopicVoiceView: UIView {
@IBOutlet weak var playtimelabel: UILabel!
@IBOutlet weak var playbutton: UIButton!
@IBOutlet weak var playtimesLabel: UILabel!
@IBOutlet weak var contentimageview: UIImageView!
@IBOutlet weak var indecaterimageview: UIImageView!
class func topicVoiceView() -> BSBTopicVoiceView{
return (NSBundle.mainBundle().loadNibNamed("BSBTopicVoiceView", owner: nil, options: nil).last)as! BSBTopicVoiceView
}
override func awakeFromNib() {
super.awakeFromNib()
self.autoresizingMask = UIViewAutoresizing.None //这个view不被上一个view的改变而伸缩
//
self.insertSubview(contentimageview, atIndex: 1)
}
var topic: BSBTopic?{
didSet{
contentimageview.sd_setImageWithURL((NSURL(string:(topic?.image0)! as String)), placeholderImage: nil, options: SDWebImageOptions.LowPriority, progress: { (min, max) in
}) { (image, error, cashtype, url) in
self.indecaterimageview.hidden = true;
}
let minute = topic!.voicetime / 60
let second = (topic?.voicetime)! % 60
let minutestr : String = String(minute)
let secondstr : String = String(second)
let voicetimestr : String = minutestr + ":" + secondstr
playtimelabel.text = voicetimestr
let playcountstr : String = String(Int((topic?.playcount)!))
playtimesLabel.text = playcountstr + "播放"
}
}
}
| mit | a5d9f8ec442ca3623f00aecaa619efdb | 33.2 | 180 | 0.623977 | 4.373402 | false | false | false | false |
jakubknejzlik/ChipmunkSwiftWrapper | Example/ChipmunkSwiftWrapper/Wall.swift | 1 | 1216 | //
// Platform.swift
// ChipmunkSwiftWrapper
//
// Created by Jakub Knejzlik on 17/11/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import SpriteKit
import ChipmunkSwiftWrapper
class Wall: SKSpriteNode {
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
let platformBody = ChipmunkBody.staticBody()
let platformBox = ChipmunkShape(body: platformBody, size: self.size)
platformBox.elasticity = 1
platformBox.friction = 0.2
platformBox.collisionType = Wall.self
self.chipmunk_body = platformBody
// this is veery slow, don't use this approach in-game
UIGraphicsBeginImageContext(self.size)
let context = UIGraphicsGetCurrentContext();
CGContextDrawTiledImage(context, CGRectMake(0, 0, self.size.width, self.size.height), UIImage(named: "wall")?.CGImage)
let tiledBackground = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let texture = SKTexture(image: tiledBackground)
let changeTexture = SKAction.setTexture(texture)
self.runAction(changeTexture)
print(self.texture)
}
} | mit | b793f7719c6e98cfe87ea68c59ee1c26 | 32.777778 | 126 | 0.677366 | 4.655172 | false | false | false | false |
srn214/Floral | Floral/Pods/SwiftLocation/Sources/Geocoding/Services/OpenStreetGeocoderRequest.swift | 1 | 2988 | //
// SwiftLocation - Efficient Location Tracking for iOS
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
import Foundation
import CoreLocation
public class OpenStreetGeocoderRequest: GeocoderRequest {
// MARK: - Public Properties -
/// Google API Key
public var APIKey: String?
// MARK: - Private Properties -
/// JSON Operation
private var jsonOperation: JSONOperation?
// MARK: - Overriden Functions -
public override func stop() {
jsonOperation?.stop()
super.stop()
}
public override func start() {
guard state != .expired else {
return
}
// Compose the request URL
guard let url = composeURL() else {
dispatch(data: .failure(.generic("Failed to compose valid request's URL.")))
return
}
jsonOperation = JSONOperation(url, timeout: self.timeout?.interval)
jsonOperation?.start { response in
switch response {
case .failure(let error):
self.stop(reason: error, remove: true)
case .success(let json):
var places = [Place]()
if let rawArray = json as? [Any] {
places = rawArray.compactMap { Place(openStreet: $0) }
} else {
places.append(Place(openStreet: json))
}
self.value = places
self.dispatch(data: .success(places), andComplete: true)
}
}
}
// MARK: - Private Helper Functions -
private func composeURL() -> URL? {
var urlComponents = URLComponents(url: baseURL(), resolvingAgainstBaseURL: false)
var serverParams = [URLQueryItem]()
serverParams.append(URLQueryItem(name: "format", value: "json"))
serverParams.append(URLQueryItem(name: "addressdetails", value: "1"))
switch operationType {
case .geocoder:
serverParams.append(URLQueryItem(name: "address", value: address!))
case .reverseGeocoder:
serverParams.append(URLQueryItem(name: "lat", value: "\(coordinates!.latitude)"))
serverParams.append(URLQueryItem(name: "lon", value: "\(coordinates!.longitude)"))
}
serverParams += options?.serverParams() ?? []
urlComponents?.queryItems = serverParams
return urlComponents?.url
}
private func baseURL() -> URL {
switch operationType {
case .geocoder:
return URL(string: "https://nominatim.openstreetmap.org/search/\(address!.urlEncoded)")!
case .reverseGeocoder:
return URL(string: "https://nominatim.openstreetmap.org/reverse")!
}
}
}
| mit | d26d2342bfaea25a981a3715504a3097 | 31.11828 | 100 | 0.580181 | 4.849026 | false | false | false | false |
jregnauld/SwiftyInstagram | Example/Tests/Mock/MockAuthorizationViewController.swift | 1 | 1243 | //
// MockAuthorizationViewController.swift
// SwiftyInstagram
//
// Created by Julien Regnauld on 8/13/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import SwiftyInstagram
class MockAuthorizationViewController : AuthorizationViewController {
let successURL: URL
let failureURL: URL
let fakeAuthorizationURL: URL
init(authorizationURL: URL, redirectURL: String) {
self.successURL = URL(string: redirectURL + "/#access_token=357230059.d19d478.0b0ec3f4ecb0450fa9c7d41821ec68a9")!
self.failureURL = URL(string: redirectURL + "/?error_reason=user_denied&error=access_denied&error_description=The+user+denied+your+request.")!
self.fakeAuthorizationURL = authorizationURL
super.init(authorizationURL: authorizationURL)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
}
override func viewDidAppear(_ animated: Bool) {
}
func successAnswer() {
self.delegate?.getWebViewAnswer(self.successURL)
}
func failureAnswer() {
self.delegate?.getWebViewAnswer(self.failureURL)
}
func authorizationURLAnswer() {
self.delegate?.getWebViewAnswer(self.fakeAuthorizationURL)
}
}
| mit | f6b5c33cb7008fd8de5f906fc4f9d861 | 31.684211 | 146 | 0.750403 | 3.869159 | false | false | false | false |
zhfish/XMMediator | Sources/XMMediator.swift | 1 | 2404 | //
// XMMediator.swift
// XMMediator
//
// Created by 王晨 on 2017/3/5.
// Copyright © 2017年 天星宿命. All rights reserved.
//
import Foundation
public class XMMediator {
/// 单例
public static let shared: XMMediator = {
let instance = XMMediator()
return instance
}()
/// 命名空间,namespace.target
private let namespace : String
/// target缓存
private var targetCache : Dictionary<String, Any>
/// 配置
public var config : XMMediatorConfig
/// 初始化
private init() {
namespace = Bundle.main.infoDictionary!["CFBundleExecutable"] as! String
targetCache = [String:Any]()
config = XMMediatorConfig()
}
/// 本地组件调用入口
///
/// - Parameters:
/// - targetName: 调用的类名
/// - actionName: 调用的方法名
/// - params: 传递的参数
/// - shouldCacheTarget: 是否缓存Target实例
/// - Returns: 返回值,如果没有返回值,则返回nil
public func performWith(targetName: String, actionName: String, params: Dictionary<String,Any>?, shouldCacheTarget: Bool) -> Any! {
let targetString = "Target_\(targetName)"
let actionString = "Action_\(actionName):"
var target = targetCache[targetString] as? NSObject
if target == nil {
guard let targetClass = NSClassFromString("\(namespace).\(targetString)") as? NSObject.Type else {
return nil
}
target = targetClass.init()
}
let action = NSSelectorFromString(actionString)
if shouldCacheTarget {
targetCache[targetString] = target
}
guard target!.responds(to: action) else {
clearTargetCache(with: targetString)
return nil
}
let result = target!.perform(action, with: params)
return result!.takeUnretainedValue()
}
/// 清除单个Target缓存
///
/// - Parameter targetName: 调用的类名
public func clearTargetCache(with targetName: String) {
let targetString = "Target_\(targetName)"
targetCache.removeValue(forKey: targetString)
}
/// 清除所有Target缓存
public func clearTargetCacheWithAll() {
targetCache.removeAll()
}
}
| mit | 46a27a96d4539400628f11496a3e12d4 | 25.951807 | 135 | 0.583818 | 4.602881 | false | false | false | false |
aschwaighofer/swift | test/Driver/Dependencies/fail-with-bad-deps-fine.swift | 2 | 2927 | /// main ==> depends-on-main | bad ==> depends-on-bad
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/fail-with-bad-deps-fine/* %t
// RUN: touch -t 201401240005 %t/*
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST: Handled main.swift
// CHECK-FIRST: Handled bad.swift
// CHECK-FIRST: Handled depends-on-main.swift
// CHECK-FIRST: Handled depends-on-bad.swift
// Reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/fail-with-bad-deps-fine/*.swiftdeps %t
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-NONE %s
// CHECK-NONE-NOT: Handled
// Reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/fail-with-bad-deps-fine/*.swiftdeps %t
// RUN: touch -t 201401240006 %t/bad.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-BUILD-ALL %s
// CHECK-BUILD-ALL-NOT: warning
// CHECK-BUILD-ALL: Handled bad.swift
// CHECK-BUILD-ALL-DAG: Handled main.swift
// CHECK-BUILD-ALL-DAG: Handled depends-on-main.swift
// CHECK-BUILD-ALL-DAG: Handled depends-on-bad.swift
// Reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/fail-with-bad-deps-fine/*.swiftdeps %t
// RUN: touch -t 201401240007 %t/bad.swift %t/main.swift
// RUN: cd %t && not %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies-bad.py" -output-file-map %t/output.json -incremental ./main.swift ./bad.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-WITH-FAIL %s
// RUN: %FileCheck -check-prefix=CHECK-RECORD %s < %t/main~buildrecord.swiftdeps
// CHECK-WITH-FAIL: Handled main.swift
// CHECK-WITH-FAIL-NOT: Handled depends
// CHECK-WITH-FAIL: Handled bad.swift
// CHECK-WITH-FAIL-NOT: Handled depends
// CHECK-RECORD-DAG: "./bad.swift": !private [
// CHECK-RECORD-DAG: "./main.swift": [
// CHECK-RECORD-DAG: "./depends-on-main.swift": !private [
// CHECK-RECORD-DAG: "./depends-on-bad.swift": [
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental ./bad.swift ./main.swift ./depends-on-main.swift ./depends-on-bad.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-BUILD-ALL %s
| apache-2.0 | d47800fcc6dd6c14057c629eafab089f | 57.54 | 306 | 0.701401 | 2.947633 | false | false | false | false |
qualaroo/QualarooSDKiOS | Qualaroo/Filters/TimeFilter.swift | 1 | 1456 | //
// TimeFilter.swift
// Qualaroo
//
// Copyright (c) 2018, Qualaroo, Inc. All Rights Reserved.
//
// Please refer to the LICENSE.md file for the terms and conditions
// under which redistribution and use of this file is permitted.
//
import Foundation
class TimeFilter {
private let minimumTimePassed: TimeInterval = 72 * 60 * 60
init(withSeenSurveyStorage storage: SeenSurveyMemoryProtocol) {
self.storage = storage
}
/// Class that keeps persistent data.
private let storage: SeenSurveyMemoryProtocol
/// Used to determine if user has seen survey with given id in last 72 hours.
///
/// - Parameter surveyID: Unique identifier of survey we want to check.
/// - Returns: True if user has seen survey recently, false if he didn't.
private func enoughTimePassed(forSurveyId surveyId: Int) -> Bool {
guard let lastSeenDate = storage.lastSeenDate(forSurveyWithID: surveyId) else { return true }
let threeDaysAgo = Date(timeIntervalSinceNow: -minimumTimePassed)
let enoughTimePassed = lastSeenDate <= threeDaysAgo
if enoughTimePassed == false {
Qualaroo.log("""
Not showing survey with id: \(surveyId).
At least 72 hours should pass before survey can be re-displayed.
""")
return false
}
return true
}
}
extension TimeFilter: FilterProtocol {
func shouldShow(survey: Survey) -> Bool {
return enoughTimePassed(forSurveyId: survey.surveyId)
}
}
| mit | 0c6c7f7a8c8424da637cf8a1f22c70b9 | 29.333333 | 97 | 0.705357 | 4.148148 | false | false | false | false |
HHuckebein/HorizontalPicker | HorizontalPicker/Classes/CollectionView/HPCollectionVC.swift | 1 | 6330 | //
// HPCollectionVC.swift
// HorizontalPickerDemo
//
// Created by Bernd Rabe on 13.12.15.
// Copyright © 2015 RABE_IT Services. All rights reserved.
//
import UIKit
protocol HPCollectionVCProvider: class {
func numberOfRowsInCollectionViewController (controller: HPCollectionVC) -> Int
func collectionViewController (controller: HPCollectionVC, titleForRow row: Int) -> String
func collectionViewController (controller: HPCollectionVC, didSelectRow row: Int)
}
class HPCollectionVC: UICollectionViewController, UICollectionViewDelegateFlowLayout {
weak var provider: HPCollectionVCProvider?
var maxElementWidth: CGFloat = 0.0
var font: UIFont = UIFont.preferredFont(forTextStyle: .title1)
var useTwoLineMode = true
var textColor = UIColor.lightGray
var selectedCellIndexPath = IndexPath(item: 0, section: 0)
var programmaticallySet: Bool = false
// MARK: - Public API
var selectedRow: Int {
return selectedCellIndexPath.row
}
func selectRow(at indexPath: IndexPath, animated: Bool) {
if let collectionView = collectionView {
selectedCellIndexPath = indexPath
scrollToIndex(indexPath.item, animated: animated)
changeSelectionForCell(at: indexPath, collectionView: collectionView, animated: animated)
}
}
// MARK: - UICollectionViewDelegate/UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return provider?.numberOfRowsInCollectionViewController(controller: self) ?? 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let reuseId = HPCollectionViewCellConstants.reuseIdentifier
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseId, for: indexPath) as! HPCollectionViewCell
configureCollectionViewCell(cell, at: indexPath)
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectRow(at: indexPath, animated: true)
}
// MARK: - UICollectionViewDelegateFlowLayout
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let text = provider?.collectionViewController(controller: self, titleForRow: indexPath.row) ?? " "
let maxHeight = collectionView.bounds.height - collectionView.contentInset.top - collectionView.contentInset.bottom
return sizeForText(text, maxSize: CGSize(width: maxElementWidth, height: maxHeight))
}
// MARK: - UIScrollviewDelegate
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollToPosition(scrollView: scrollView)
}
override func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
if decelerate == false {
scrollToPosition(scrollView: scrollView)
}
}
func scrollToPosition(scrollView: UIScrollView) {
if let collectionView = scrollView as? UICollectionView, let item = indexPathForCenterCellFromCollectionview(collectionView: collectionView) {
scrollToIndex(item.row, animated: true)
changeSelectionForCell(at: item, collectionView: collectionView, animated: true)
}
}
func indexPathForCenterCellFromCollectionview (collectionView: UICollectionView) -> IndexPath? {
let point = collectionView.convert(collectionView.center, from: collectionView.superview)
guard let indexPath = collectionView.indexPathForItem(at: point) else { return collectionView.indexPathsForVisibleItems.first }
return indexPath
}
// MARK: - Helper
func sizeForText(_ text: String, maxSize: CGSize) -> CGSize {
let attr: [NSAttributedStringKey: Any] = [.font : font]
var frame = (text as NSString).boundingRect(with: maxSize, options: .usesLineFragmentOrigin, attributes: attr, context: NSStringDrawingContext())
frame = frame.integral
frame.size.width += 10
frame.size.width = max(frame.width, 30)
frame.size.height = maxSize.height
return frame.size
}
private func configureCollectionViewCell(_ cell: HPCollectionViewCell, at indexPath: IndexPath) {
if let provider = provider {
cell.text = provider.collectionViewController(controller: self, titleForRow: indexPath.row)
cell.isSelected = selectedCellIndexPath == indexPath
cell.delegate = self
}
}
private func scrollToIndex(_ index: Int, animated: Bool) {
let indexPath = IndexPath(item: index, section: 0)
guard let cv = collectionView, let attributes = cv.layoutAttributesForItem(at: indexPath) else {
return
}
let halfWidth = cv.frame.width / CGFloat(2.0)
let offset = CGPoint(x: attributes.frame.midX - halfWidth, y: 0)
cv.setContentOffset(offset, animated: animated)
}
private func changeSelectionForCell(at indexPath: IndexPath, collectionView: UICollectionView, animated: Bool) {
delay(inSeconds: 0.25) {
collectionView.selectItem(at: indexPath, animated: animated, scrollPosition: .centeredHorizontally)
}
if programmaticallySet == false {
provider?.collectionViewController(controller: self, didSelectRow: indexPath.item)
} else {
programmaticallySet = false
}
}
private func delay(inSeconds delay:TimeInterval, closure: @escaping ()->()) {
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
closure()
}
}
}
extension HPCollectionVC: HPCollectionViewCellDelegate {
func useTwolineModeForCollectionViewCell(cvCell: HPCollectionViewCell) -> Bool {
return useTwoLineMode
}
func fontForCollectionViewCell(cvCell: HPCollectionViewCell) -> UIFont {
return font
}
func textColorForCollectionViewCell(cvCell: HPCollectionViewCell) -> UIColor {
return textColor
}
}
| mit | 7257cd4a5f410999a59555be58d372d9 | 39.570513 | 160 | 0.696161 | 5.404782 | false | false | false | false |
chamira/ModelGen | ModelGen/CodeFileSaver.swift | 1 | 3910 | //
// CodeFileSaver.swift
// ModelGen
//
// Created by Chamira Fernando on 15/05/2017.
// Copyright © 2017 Arangaya Apps. All rights reserved.
//
import Foundation
struct CodeFileSaverStatus : CustomStringConvertible {
let fileName:String
let status:(Bool,String?)
var description: String {
let st = self.status.0 == true ? "Done" : ("Fail->" + self.status.1!)
return "Model:"+self.fileName + " Status:" + st
}
}
class CodeFileSaver {
let files:[EntityFileContentHolder]
let language:SupportLanguage
private(set) var path:String!
private(set) var createNewDir:Bool!
private(set) var overwrite:Bool!
private(set) var dirName:String!
static let kDefaultDirName = "ModelObjectsGenerated"
init(files:[EntityFileContentHolder], language:SupportLanguage) {
self.files = files
self.language = language
}
func save(atPath:String, createNewDir:Bool = true, dirName:String? = CodeFileSaver.kDefaultDirName, overwrite:Bool = false) throws -> String {
self.createNewDir = createNewDir
self.path = atPath
self.overwrite = overwrite
self.dirName = dirName
var status:[String] = [String]()
let dirToWrite = getDirToWrite()
if (dirToWrite.0 == false) {
throw ErrorRegistry.fileIO(errorDesc: dirToWrite.1!)
}
for eachEntity in files {
var s:CodeFileSaverStatus!
let _fileName = eachEntity.fileName+"."+language.extension
do {
let _dirToWrite = dirToWrite.1!
let fileName = (_dirToWrite + (_dirToWrite.hasSuffix("/") ? "" :"/") + _fileName).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
var write:Bool = false
if (overwrite) {
write = true
} else {
if !FileManager.default.fileExists(atPath: fileName) {
write = true
}
}
if write {
try eachEntity.content.write(toFile: fileName, atomically: true, encoding: String.Encoding.utf8)
s = CodeFileSaverStatus(fileName: fileName, status: (true,fileName))
} else {
s = CodeFileSaverStatus(fileName: fileName, status: (false,"File does exist, did not overwrite")) //not over write
}
} catch let e {
s = CodeFileSaverStatus(fileName: _fileName, status: (false,e.localizedDescription))
}
status.append(s.description)
}
return status.joined(separator: "\n")
}
func createNewDir(path:String) -> (Bool,String?){
let newPath = (path + (path.hasSuffix("/") ? "" : "/") + getNewDirName()).trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
if FileManager.default.fileExists(atPath: newPath) {
return (true,newPath)
}
do {
try FileManager.default.createDirectory(atPath:newPath, withIntermediateDirectories: true, attributes: nil)
return (true, newPath)
} catch let e {
return (false,e.localizedDescription)
}
}
func getDirToWrite() ->(Bool,String?) {
if createNewDir {
let p = createNewDir(path: self.path)
return p
}
return (true,self.path)
}
func getNewDirName()->String {
if (dirName == CodeFileSaver.kDefaultDirName) {
return CodeFileSaver.kDefaultDirName + "-" + language.rawValue
} else {
return dirName
}
}
}
| mit | 6f04373d3509be6339d468bfdff76d42 | 30.780488 | 157 | 0.547966 | 4.808118 | false | false | false | false |
recisio/IncrementableLabel | Source/UIColor+Blend.swift | 2 | 1916 | // UIColor+Blend.swift
//
// Copyright (c) 2016 Recisio (http://www.recisio.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
extension UIColor{
//From https://stackoverflow.com/a/39779603
func blend(to: UIColor, percent: Double) -> UIColor {
var fR : CGFloat = 0.0
var fG : CGFloat = 0.0
var fB : CGFloat = 0.0
var tR : CGFloat = 0.0
var tG : CGFloat = 0.0
var tB : CGFloat = 0.0
self.getRed(&fR, green: &fG, blue: &fB, alpha: nil)
to.getRed(&tR, green: &tG, blue: &tB, alpha: nil)
let dR = tR - fR
let dG = tG - fG
let dB = tB - fB
let rR = fR + dR * CGFloat(percent)
let rG = fG + dG * CGFloat(percent)
let rB = fB + dB * CGFloat(percent)
return UIColor(red: rR, green: rG, blue: rB, alpha: 1.0)
}
}
| mit | 5347e0fa046f34bcdaf2ed8b887889f8 | 38.916667 | 80 | 0.658664 | 3.801587 | false | false | false | false |
mibaldi/IOS_MIMO_APP | iosAPP/models/Task.swift | 1 | 386 | //
// Task.swift
// iosAPP
//
// Created by mikel balduciel diaz on 17/2/16.
// Copyright © 2016 mikel balduciel diaz. All rights reserved.
//
import Foundation
class Task : NSObject {
var taskId = Int64()
var taskIdServer = Int64()
var name = String()
var photo = String()
var seconds = Int64()
var recipeId = Int64()
var taskDescription = String()
} | apache-2.0 | 6b3aa0f8e9aed12e4b5e3f8e7f007332 | 19.315789 | 63 | 0.638961 | 3.262712 | false | false | false | false |
saagarjha/iina | iina/SidebarTabView.swift | 1 | 1304 | //
// SidebarTabView.swift
// iina
//
// Created by Collider LI on 10/10/2020.
// Copyright © 2020 lhc. All rights reserved.
//
import Cocoa
class SidebarTabView: NSViewController {
var name: String!
var pluginID: String!
weak var quickSettingsView: QuickSettingViewController!
@IBOutlet weak var label: NSTextField!
override var acceptsFirstResponder: Bool {
true
}
var isActive: Bool = false {
didSet {
updateStyle()
}
}
override func viewDidLoad() {
super.viewDidLoad()
view.wantsLayer = true
view.layer?.cornerRadius = 10
updateStyle()
label.stringValue = name
}
override func mouseDown(with event: NSEvent) {
quickSettingsView.pleaseSwitchToTab(.plugin(id: pluginID))
isActive = true
}
private func updateStyle() {
if isActive {
view.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.2).cgColor
label.textColor = .white
} else {
view.layer?.backgroundColor = NSColor.white.withAlphaComponent(0.1).cgColor
label.textColor = NSColor.white.withAlphaComponent(0.5)
}
}
}
class SidebarTabActiveView: NSView {
override var acceptsFirstResponder: Bool {
true
}
override func mouseDown(with event: NSEvent) {
self.nextResponder?.mouseDown(with: event)
}
}
| gpl-3.0 | bc02e2dd13223b168eb8f06f8fdc7250 | 20.716667 | 81 | 0.689946 | 4.189711 | false | false | false | false |
alexhilton/effectivecocoa | APIDemo/CategoryViewController.swift | 1 | 4244 | //
// CategoryViewController.swift
// APIDemo
//
// Created by Alex Hilton on 11/16/14.
// Copyright (c) 2014 Alex Hilton. All rights reserved.
//
import UIKit
class CategoryViewController: UITableViewController {
let categories = ["UITableView", "UICollectionView"]
override func viewDidLoad() {
super.viewDidLoad()
// 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()
self.title = "Examples of API"
tableView!.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return categories.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as UITableViewCell
// Configure the cell...
cell.textLabel.text = categories[indexPath.row]
return cell
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return false
}
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Delegation
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let row = indexPath.row
var view: UIViewController?
if row == 0 {
view = TableViewExamples()
} else {
var layout = UICollectionViewFlowLayout()
layout.scrollDirection = UICollectionViewScrollDirection.Vertical
layout.minimumLineSpacing = 10
layout.minimumInteritemSpacing = 5
view = CollectionViewExample(collectionViewLayout: layout)
}
view!.title = categories[row]
navigationController?.pushViewController(view!, animated: true)
}
/*
// 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.
}
*/
}
| apache-2.0 | a29cebb28eac8cb98f0087c89af1d7b7 | 36.557522 | 157 | 0.683553 | 5.696644 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/ImageCodec/RawBitmap/FastDecode/_fast_decode_alpha_none.swift | 1 | 3868 | //
// _fast_decode_alpha_none.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
@inlinable
@inline(__always)
func _fast_decode_alpha_none<T, P: _FloatComponentPixel>(_ bitmaps: [RawBitmap], _ format: RawBitmap.Format, _ endianness: RawBitmap.Endianness, _ info: _fast_decode_info<P.Model>, _ should_denormalized: Bool, _: T.Type, _ decode: (T) -> P.Scalar) -> Image<P>? {
let channels = bitmaps[0].channels.sorted { $0.bitRange.lowerBound }
let numberOfComponents = P.Model.numberOfComponents
let bitsPerChannel = MemoryLayout<T>.stride << 3
var alpha_none: [RawBitmap.Channel] = []
for i in 0..<numberOfComponents {
let lowerBound = i * bitsPerChannel
let upperBound = lowerBound + bitsPerChannel
alpha_none.append(RawBitmap.Channel(index: i, format: format, endianness: endianness, bitRange: lowerBound..<upperBound))
}
guard channels == alpha_none else { return nil }
var image = Image<P>(width: info.width, height: info.height, resolution: info.resolution, colorSpace: info.colorSpace, fileBacked: info.fileBacked)
image._fast_decode_float(bitmaps, true, should_denormalized, false, T.self) { (destination, source) in
var destination = destination
var source = source
for _ in 0..<numberOfComponents {
destination.pointee = decode(source.pointee)
destination += 1
source += 1
}
destination.pointee = 1
}
return image
}
@inlinable
@inline(__always)
func _fast_decode_alpha_none<T: FixedWidthInteger, P: _FloatComponentPixel>(_ bitmaps: [RawBitmap], _ endianness: RawBitmap.Endianness, _ info: _fast_decode_info<P.Model>, _: T.Type) -> Image<P>? {
switch endianness {
case .big: return _fast_decode_alpha_none(bitmaps, .unsigned, endianness, info, true, T.self) { P.Scalar(T(bigEndian: $0)) / P.Scalar(T.max) }
case .little: return _fast_decode_alpha_none(bitmaps, .unsigned, endianness, info, true, T.self) { P.Scalar(T(littleEndian: $0)) / P.Scalar(T.max) }
}
}
@inlinable
@inline(__always)
func _fast_decode_alpha_none<P: _FloatComponentPixel>(_ bitmaps: [RawBitmap], _ endianness: RawBitmap.Endianness, _ info: _fast_decode_info<P.Model>, _: P.Scalar.Type) -> Image<P>? where P.Scalar: RawBitPattern {
switch endianness {
case .big: return _fast_decode_alpha_none(bitmaps, .float, endianness, info, false, P.Scalar.BitPattern.self) { P.Scalar(bitPattern: P.Scalar.BitPattern(bigEndian: $0)) }
case .little: return _fast_decode_alpha_none(bitmaps, .float, endianness, info, false, P.Scalar.BitPattern.self) { P.Scalar(bitPattern: P.Scalar.BitPattern(littleEndian: $0)) }
}
}
| mit | f4493e3a8b4803683fffe8006943545c | 46.753086 | 262 | 0.691055 | 3.777344 | false | false | false | false |
hedgehog-labs/iOS-firebase_pagination | end/fb pagination/PlayerTableViewCell.swift | 2 | 788 | //
// PlayerTableViewCell.swift
// fb pagination
//
// Created by Ymmanuel on 4/20/17.
// Copyright © 2017 Hedgehog Labs. All rights reserved.
//
import UIKit
class PlayerTableViewCell: UITableViewCell {
@IBOutlet weak var imgAvatar: UIImageView!
@IBOutlet weak var lblName: UILabel!
@IBOutlet weak var lblScore: UILabel!
@IBOutlet weak var view: UIView!
var player:Player!{
didSet {
imgAvatar.image = UIImage(named: player.avatar!)
lblName.text = player.name.uppercased()
lblScore.text = "\(player.score!)"
}
}
override func awakeFromNib() {
super.awakeFromNib()
view.layer.borderWidth = 1.0
view.layer.borderColor = UIColor.white.cgColor
}
}
| mit | 87e6e07789ef4676dfb5e996639ead05 | 22.848485 | 60 | 0.617535 | 4.18617 | false | false | false | false |
fulldecent/FSLineChart | iOS Example/iOS Example/ViewController.swift | 1 | 2022 | //
// ViewController.swift
// iOS Example
//
// Created by Yaroslav Zhurakovskiy on 20.11.2019.
// Copyright © 2019 William Entriken. All rights reserved.
//
import UIKit
import FSLineChart
class ViewController: UIViewController {
@IBOutlet weak var chartWithDates: FSLineChart!
@IBOutlet weak var chartWithZeroes: FSLineChart!
override func viewDidLoad() {
super.viewDidLoad()
setupChartWithDates()
setupChartWithZeroes()
loadChartWithDates()
loadChartWithZeroes()
}
private func loadChartWithDates() {
let chartData = (0..<7).map { Double($0) / 30.0 + Double(Int.random(in: 0...100)) / 500 }
chartWithDates.setChartData(chartData)
}
private func loadChartWithZeroes() {
let chartData = (0..<10).map { _ in Double(0) }
chartWithZeroes.setChartData(chartData)
}
private func setupChartWithDates() {
chartWithDates.verticalGridStep = 6
chartWithDates.horizontalGridStep = 3
chartWithDates.fillColor = nil
chartWithDates.displayDataPoint = true
chartWithDates.dataPointColor = .fsOrange
chartWithDates.dataPointBackgroundColor = UIColor.fsOrange
chartWithDates.dataPointRadius = 2
chartWithDates.color = chartWithDates.dataPointColor.withAlphaComponent(0.3)
chartWithDates.valueLabelPosition = .mirrored
let months = [
"January",
"February",
"March",
"April",
"May",
"June",
"July"
]
chartWithDates.labelForIndex = { months[$0] }
chartWithDates.labelForValue = { String(format: "%.02f €", $0) }
}
private func setupChartWithZeroes() {
chartWithZeroes.verticalGridStep = 5
chartWithZeroes.horizontalGridStep = 9
chartWithZeroes.labelForIndex = { "\($0)" }
chartWithZeroes.labelForValue = { String(format: "%.f", $0) }
}
}
| apache-2.0 | c320437a31a0b272101e904dd05fd8a7 | 29.134328 | 98 | 0.619118 | 4.351293 | false | false | false | false |
apple/swift-syntax | Tests/SwiftParserTest/translated/DelayedExtensionTests.swift | 1 | 796 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 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
//
//===----------------------------------------------------------------------===//
// This test file has been translated from swift/test/Parse/delayed_extension.swift
import XCTest
final class DelayedExtensionTests: XCTestCase {
func testDelayedExtension1() {
AssertParse(
"""
extension X { }
_ = 1
f()
"""
)
}
}
| apache-2.0 | 491691e846c857d0aadb749af46c363b | 27.428571 | 83 | 0.546482 | 4.975 | false | true | false | false |
wojoin/swift-ascii-art | SwiftAsciiArt/Pixel.swift | 2 | 1771 | //
// Pixel.swift
// SwiftAsciiArt
//
// Created by Joshua Smith on 4/25/15.
// Copyright (c) 2015 iJoshSmith. All rights reserved.
//
import Foundation
/** Represents the memory address of a pixel. */
typealias PixelPointer = UnsafePointer<UInt8>
/** A point in an image converted to an ASCII character. */
struct Pixel
{
/** The number of bytes a pixel occupies. 1 byte per channel (RGBA). */
static let bytesPerPixel = 4
private let offset: Int
private init(_ offset: Int) { self.offset = offset }
static func createPixelMatrix(width: Int, _ height: Int) -> [[Pixel]]
{
return map(0..<height) { row in
map(0..<width) { col in
let offset = (width * row + col) * Pixel.bytesPerPixel
return Pixel(offset)
}
}
}
func intensityFromPixelPointer(pointer: PixelPointer) -> Double
{
let
red = pointer[offset + 0],
green = pointer[offset + 1],
blue = pointer[offset + 2]
return Pixel.calculateIntensity(red, green, blue)
}
private static func calculateIntensity(r: UInt8, _ g: UInt8, _ b: UInt8) -> Double
{
// Normalize the pixel's grayscale value to between 0 and 1.
// Weights from http://en.wikipedia.org/wiki/Grayscale#Luma_coding_in_video_systems
let
redWeight = 0.229,
greenWeight = 0.587,
blueWeight = 0.114,
weightedMax = 255.0 * redWeight +
255.0 * greenWeight +
255.0 * blueWeight,
weightedSum = Double(r) * redWeight +
Double(g) * greenWeight +
Double(b) * blueWeight
return weightedSum / weightedMax
}
}
| mit | 5fae63702d918d3a963a17e401bfc04e | 29.534483 | 91 | 0.570299 | 4.043379 | false | false | false | false |
tonyli508/ObjectMapperDeep | ObjectMapperTests/ClassClusterTests.swift | 5 | 2232 | //
// ClassClusterTests.swift
// ObjectMapper
//
// Created by Tristan Himmelman on 2015-09-18.
// Copyright © 2015 hearst. All rights reserved.
//
import Foundation
import XCTest
import ObjectMapper
class ClassClusterTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testClassClusters() {
let carName = "Honda"
let JSON = ["name": carName, "type": "car"]
if let vehicle = Mapper<Vehicle>().map(JSON){
XCTAssertNotNil(vehicle)
XCTAssertNotNil(vehicle as? Car)
XCTAssertEqual((vehicle as? Car)?.name, carName)
}
}
func testClassClustersFromJSONString() {
let carName = "Honda"
let JSON = "{\"name\": \"\(carName)\", \"type\": \"car\"}"
if let vehicle = Mapper<Vehicle>().map(JSON){
XCTAssertNotNil(vehicle)
XCTAssertNotNil(vehicle as? Car)
XCTAssertEqual((vehicle as? Car)?.name, carName)
}
}
func testClassClusterArray() {
let carName = "Honda"
let JSON = [["name": carName, "type": "car"], ["type": "bus"], ["type": "vehicle"]]
if let vehicles = Mapper<Vehicle>().mapArray(JSON){
XCTAssertNotNil(vehicles)
XCTAssertTrue(vehicles.count == 3)
XCTAssertNotNil(vehicles[0] as? Car)
XCTAssertNotNil(vehicles[1] as? Bus)
XCTAssertNotNil(vehicles[2])
XCTAssertEqual((vehicles[0] as? Car)?.name, carName)
}
}
}
class Vehicle: MappableCluster {
var type: String?
static func objectForMapping(map: Map) -> Mappable? {
if let type: String = map["type"].value() {
switch type {
case "car":
return Car(map)
case "bus":
return Bus(map)
default:
return nil
}
}
return nil
}
required init?(_ map: Map){
}
func mapping(map: Map) {
type <- map["type"]
}
}
class Car: Vehicle {
var name: String?
override func mapping(map: Map) {
super.mapping(map)
name <- map["name"]
}
}
class Bus: Vehicle {
override func mapping(map: Map) {
super.mapping(map)
}
}
| mit | fb788811fefc563433a4cdfea9bf3528 | 20.247619 | 111 | 0.639623 | 3.45356 | false | true | false | false |
huonw/swift | test/stmt/errors.swift | 4 | 3604 | // RUN: %target-swift-frontend -typecheck -verify %s
enum MSV : Error {
case Foo, Bar, Baz
var _domain: String { return "" }
var _code: Int { return 0 }
}
func a() {}
func b() {}
func c() {}
func d() {}
func e() {}
func thrower() throws {}
func opaque_error() -> Error { return MSV.Foo }
func one() {
throw MSV.Foo // expected-error {{error is not handled because the enclosing function is not declared 'throws'}}
}
func two() {
throw opaque_error() // expected-error {{error is not handled because the enclosing function is not declared 'throws'}}
}
func three() {
do {
throw opaque_error() // expected-error {{error is not handled because the enclosing catch is not exhaustive}}
} catch let e as MSV {
_ = e
}
}
func four() {
do {
throw opaque_error()
} catch let e {
_ = e
}
}
func five() {
do {
throw opaque_error()
} catch let e as MSV {
_ = e
} catch _ {
}
}
func six() {
do {
do {
throw opaque_error()
} catch let e as MSV {
_ = e
}
} catch _ {
}
}
func seven_helper() throws -> Int { throw MSV.Baz }
struct seven {
var x: Int {
do {
return try seven_helper()
} catch {
return 0
}
}
var y: Int {
return try! seven_helper()
}
var z: Int {
return (try? seven_helper()) ?? 0
}
}
class eight {
lazy var x: Int = {
do {
return try seven_helper()
} catch {
return 0
}
}()
lazy var y: Int = {
return try! seven_helper()
}()
lazy var z: Int = {
return (try? seven_helper()) ?? 0
}()
}
protocol ThrowingProto {
func foo() throws
static func bar() throws
}
func testExistential(_ p : ThrowingProto) throws {
try p.foo()
try type(of: p).bar()
}
func testGeneric<P : ThrowingProto>(p : P) throws {
try p.foo()
try P.bar()
}
// Don't warn about the "useless" try in these cases.
func nine_helper(_ x: Int, y: Int) throws {} // expected-note {{'nine_helper(_:y:)' declared here}}
func nine() throws {
try nine_helper(y: 0) // expected-error {{missing argument for parameter #1 in call}}
}
func ten_helper(_ x: Int) {}
func ten_helper(_ x: Int, y: Int) throws {}
func ten() throws {
try ten_helper(y: 0) // expected-error {{extraneous argument label 'y:' in call}} {{18-21=}}
}
// rdar://21074857
func eleven_helper(_ fn: () -> ()) {}
func eleven_one() {
eleven_helper {
do {
try thrower()
// FIXME: suppress the double-emission of the 'always true' warning
} catch let e as Error { // expected-warning {{immutable value 'e' was never used}} {{17-18=_}} expected-warning 2 {{'as' test is always true}}
}
}
}
func eleven_two() {
eleven_helper { // expected-error {{invalid conversion from throwing function of type '() throws -> ()' to non-throwing function type '() -> ()'}}
do {
try thrower()
} catch let e as MSV {
}
}
}
enum Twelve { case Payload(Int) }
func twelve_helper(_ fn: (Int, Int) -> ()) {}
func twelve() {
twelve_helper { (a, b) in // expected-error {{invalid conversion from throwing function of type '(_, _) throws -> ()' to non-throwing function type '(Int, Int) -> ()'}}
do {
try thrower()
} catch Twelve.Payload(a...b) {
}
}
}
struct Thirteen : Error, Equatable {}
func ==(a: Thirteen, b: Thirteen) -> Bool { return true }
func thirteen_helper(_ fn: (Thirteen) -> ()) {}
func thirteen() {
thirteen_helper { (a) in // expected-error {{invalid conversion from throwing function of type '(_) throws -> ()' to non-throwing function type '(Thirteen) -> ()'}}
do {
try thrower()
} catch a {
}
}
}
| apache-2.0 | 2a9f729c7036e957a8e3a6c25c386760 | 20.580838 | 170 | 0.586016 | 3.403211 | false | false | false | false |
jackTang11/TlySina | TlySina/TlySina/Classes/View(视图和控制器)/Main/TLYMainViewController.swift | 1 | 3972 | //
// TLYMainViewController.swift
// TlySina
//
// Created by jack_tang on 17/4/28.
// Copyright © 2017年 jack_tang. All rights reserved.
//
import UIKit
class TLYMainViewController: UITabBarController {
lazy var composeButton : UIButton = UIButton.cz_imageButton("tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button")
override func viewDidLoad() {
super.viewDidLoad()
setChildController()
setupComposeButton()
setupNewFeatuerView()
}
@objc fileprivate func middleClick(){
print("....")
}
}
extension TLYMainViewController{
var isNewVersion : Bool {
//获取当前版本号
let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
///取出保存在用户偏好中的版本号
let path : String = ("version" as NSString).cz_appendDocumentDir()
let sandboxVersion = try? String(contentsOfFile: path, encoding: .utf8)
_ = try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
print(currentVersion)
return currentVersion == sandboxVersion
}
func setupNewFeatuerView(){
let v = isNewVersion ? WBNewFeatureView.newFeature() : WBWelcomView.welcomView()
view.addSubview(v)
}
}
extension TLYMainViewController {
//添加中间按钮
fileprivate func setupComposeButton(){
tabBar.addSubview(composeButton)
let count = CGFloat(childViewControllers.count)
let w = tabBar.bounds.width / count-1
composeButton.frame = tabBar.bounds.insetBy(dx: w*2, dy: 0)
composeButton.addTarget(self, action: #selector(middleClick), for: .touchUpInside)
}
//准备自控制器
fileprivate func setChildController(){
let doucdir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
let jsonPath = (doucdir as NSString).appendingPathComponent("main.json")
var data = NSData(contentsOfFile: jsonPath)
if data == nil {
let path = Bundle.main.path(forResource: "main.json", ofType: nil)
data = NSData(contentsOfFile: path!)
}
guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String:AnyObject]]
else {
return
}
var arrayM : [UIViewController] = [UIViewController]()
for dict in array! {
arrayM.append(controller(dict: dict))
}
viewControllers = arrayM
}
//创建控制器
private func controller(dict : [String : Any]) -> UIViewController{
guard let clsName = dict["clsName"] as? String,
let titleName = dict["titleName"] as? String,
let imageName = dict["imageName"] as? String,
let visiDict = dict["visiInfos"] as? [String : String],
let cls = NSClassFromString(Bundle.main.nameSpace + "." + clsName) as? TLYBaseViewController.Type
else {
return UIViewController();
}
//创建控制器
let vc = cls.init()
vc.title = titleName
vc.visinfos = visiDict
//设置图像
vc.tabBarItem.image = UIImage(named: ("tabbar_" + imageName))
vc.tabBarItem.selectedImage = UIImage(named: ("tabbar_" + imageName+"_selected"))?.withRenderingMode(.alwaysOriginal);
vc.tabBarItem.setTitleTextAttributes(
[NSForegroundColorAttributeName : UIColor.orange], for: .highlighted)
vc.tabBarItem.setTitleTextAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 12)], for: .normal)
let nav = TLYNavController(rootViewController: vc)
return nav;
}
}
| apache-2.0 | ca037c315298815d0239d44cfe3e58dc | 25.182432 | 136 | 0.602581 | 4.760442 | false | false | false | false |
chatappcodepath/ChatAppSwift | LZChat/Models/LZUser.swift | 1 | 2231 | //
// LZUser.swift
// LZChat
//
// Created by Kevin Balvantkumar Patel on 12/17/16.
//
// License
// Copyright (c) 2017 chatappcodepath
// Released under an MIT license: http://opensource.org/licenses/MIT
//
//
// Sample
/*
"kI9OZDu4SFRktlrZu6LJZrfvXOv1" : {
"email" : "[email protected]",
"id" : "kI9OZDu4SFRktlrZu6LJZrfvXOv1",
"name" : "Yqa phonereg",
"photoUrl" : "https://lh4.googleusercontent.com/-6v5FaHf_KOc/AAAAAAAAAAI/AAAAAAAAAAA/AKTaeK8xIk_DrmSpOgbk-P7pCYgGsbZHow/s96-c/photo.jpg"
}
*/
import Foundation
import FirebaseDatabase
import Firebase
struct LZUser {
var email: String?
var id: String?
var name: String?
var photoUrl: String?
public init(withFIRUser firUser: FIRUser?) {
if let currentUser = firUser {
email = currentUser.email
id = currentUser.uid
name = currentUser.displayName
photoUrl = currentUser.photoURL?.absoluteString
}
}
public static func users(withSnapShot snapShot:FIRDataSnapshot) -> [LZUser] {
var retUsers = [LZUser]()
if let usersDict = snapShot.value as? [String: Any] {
for dictionary in usersDict.values {
if let dictionary = dictionary as? [String: Any] {
retUsers.append(LZUser(withDictionary: dictionary))
}
}
}
return retUsers
}
public init(withDictionary dictionary:[String: Any]) {
self.dictionary = dictionary
}
var dictionary: [String: Any] {
get {
var dictionary: [String : Any] = [String: Any]()
dictionary["email"] = email
dictionary["id"] = id
dictionary["name"] = name
dictionary["photoUrl"] = photoUrl
return dictionary;
}
set {
self.email = newValue["email"] as? String
self.id = newValue["id"] as? String
self.name = newValue["name"] as? String
self.photoUrl = newValue["photoUrl"] as? String
}
}
}
extension LZUser: Equatable {
public static func ==(lhs: LZUser, rhs: LZUser) -> Bool {
return lhs.id == rhs.id
}
}
| mit | dce33fe034b91670bc32a4fe5ccb4814 | 24.643678 | 137 | 0.582698 | 3.730769 | false | false | false | false |
ZhiQiang-Yang/pppt | v2exProject 2/Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift | 13 | 6731 | //
// KingfisherOptionsInfo.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/23.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(OSX)
import AppKit
#else
import UIKit
#endif
/**
* KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. You can use the enum of option item with value to control some behaviors of Kingfisher.
*/
public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem]
let KingfisherEmptyOptionsInfo = [KingfisherOptionsInfoItem]()
/**
Items could be added into KingfisherOptionsInfo.
- TargetCache: The associated value of this member should be an ImageCache object. Kingfisher will use the specified cache object when handling related operations, including trying to retrieve the cached images and store the downloaded image to it.
- Downloader: The associated value of this member should be an ImageDownloader object. Kingfisher will use this downloader to download the images.
- Transition: Member for animation transition when using UIImageView. Kingfisher will use the `ImageTransition` of this enum to animate the image in if it is downloaded from web. The transition will not happen when the image is retrieved from either memory or disk cache.
- DownloadPriority: Associated `Float` value will be set as the priority of image download task. The value for it should be between 0.0~1.0. If this option not set, the default value (`NSURLSessionTaskPriorityDefault`) will be used.
- ForceRefresh: If set, `Kingfisher` will ignore the cache and try to fire a download task for the resource.
- CacheMemoryOnly: If set, `Kingfisher` will only cache the value in memory but not in disk.
- BackgroundDecode: Decode the image in background thread before using.
- CallbackDispatchQueue: The associated value of this member will be used as the target queue of dispatch callbacks when retrieving images from cache. If not set, `Kingfisher` will use main quese for callbacks.
- ScaleFactor: The associated value of this member will be used as the scale factor when converting retrieved data to an image.
*/
public enum KingfisherOptionsInfoItem {
case TargetCache(ImageCache?)
case Downloader(ImageDownloader?)
case Transition(ImageTransition)
case DownloadPriority(Float)
case ForceRefresh
case CacheMemoryOnly
case BackgroundDecode
case CallbackDispatchQueue(dispatch_queue_t?)
case ScaleFactor(CGFloat)
}
infix operator <== {
associativity none
precedence 160
}
// This operator returns true if two `KingfisherOptionsInfoItem` enum is the same, without considering the associated values.
func <== (lhs: KingfisherOptionsInfoItem, rhs: KingfisherOptionsInfoItem) -> Bool {
switch (lhs, rhs) {
case (.TargetCache(_), .TargetCache(_)): return true
case (.Downloader(_), .Downloader(_)): return true
case (.Transition(_), .Transition(_)): return true
case (.DownloadPriority(_), .DownloadPriority(_)): return true
case (.ForceRefresh, .ForceRefresh): return true
case (.CacheMemoryOnly, .CacheMemoryOnly): return true
case (.BackgroundDecode, .BackgroundDecode): return true
case (.CallbackDispatchQueue(_), .CallbackDispatchQueue(_)): return true
case (.ScaleFactor(_), .ScaleFactor(_)): return true
default: return false
}
}
extension CollectionType where Generator.Element == KingfisherOptionsInfoItem {
func kf_firstMatchIgnoringAssociatedValue(target: Generator.Element) -> Generator.Element? {
return indexOf { $0 <== target }.flatMap { self[$0] }
}
func kf_removeAllMatchesIgnoringAssociatedValue(target: Generator.Element) -> [Generator.Element] {
return self.filter { !($0 <== target) }
}
}
extension CollectionType where Generator.Element == KingfisherOptionsInfoItem {
var targetCache: ImageCache? {
if let item = kf_firstMatchIgnoringAssociatedValue(.TargetCache(nil)),
case .TargetCache(let cache) = item
{
return cache
}
return nil
}
var downloader: ImageDownloader? {
if let item = kf_firstMatchIgnoringAssociatedValue(.Downloader(nil)),
case .Downloader(let downloader) = item
{
return downloader
}
return nil
}
var transition: ImageTransition {
if let item = kf_firstMatchIgnoringAssociatedValue(.Transition(.None)),
case .Transition(let transition) = item
{
return transition
}
return ImageTransition.None
}
var downloadPriority: Float {
if let item = kf_firstMatchIgnoringAssociatedValue(.DownloadPriority(0)),
case .DownloadPriority(let priority) = item
{
return priority
}
return NSURLSessionTaskPriorityDefault
}
var forceRefresh: Bool {
return contains{ $0 <== .ForceRefresh }
}
var cacheMemoryOnly: Bool {
return contains{ $0 <== .CacheMemoryOnly }
}
var backgroundDecode: Bool {
return contains{ $0 <== .BackgroundDecode }
}
var callbackDispatchQueue: dispatch_queue_t {
if let item = kf_firstMatchIgnoringAssociatedValue(.CallbackDispatchQueue(nil)),
case .CallbackDispatchQueue(let queue) = item
{
return queue ?? dispatch_get_main_queue()
}
return dispatch_get_main_queue()
}
var scaleFactor: CGFloat {
if let item = kf_firstMatchIgnoringAssociatedValue(.ScaleFactor(0)),
case .ScaleFactor(let scale) = item
{
return scale
}
return 1.0
}
}
| apache-2.0 | a4752031543e777b3fde931ca2e21398 | 40.549383 | 272 | 0.70777 | 4.982235 | false | false | false | false |
IvoPaunov/selfie-apocalypse | Selfie apocalypse/Frameworks/DCKit/UIViews/DCDashedBorderedView.swift | 1 | 2060 | //
// DCDashedBorderedView.swift
// DCKitSample
//
// Created by Andrey Gordeev on 5/10/15.
// Copyright (c) 2015 Andrey Gordeev. All rights reserved.
//
import UIKit
@IBDesignable
public class DCDashedBorderedView: DCBaseView {
@IBInspectable public var borderColor: UIColor = UIColor.lightGrayColor() {
didSet {
borderLayer.strokeColor = borderColor.CGColor
}
}
@IBInspectable public var borderWidth: CGFloat = 1.0 {
didSet {
borderLayer.lineWidth = borderWidth / UIScreen.mainScreen().scale
}
}
@IBInspectable public var cornerRadius: CGFloat = 0.0 {
didSet {
layoutSubviews()
}
}
@IBInspectable public var dashLength: CGFloat = 4.0 {
didSet {
borderLayer.lineDashPattern = [dashLength, dashSpace]
}
}
@IBInspectable public var dashSpace: CGFloat = 2.0 {
didSet {
borderLayer.lineDashPattern = [dashLength, dashSpace]
}
}
let borderLayer = CAShapeLayer()
public override func layoutSubviews() {
super.layoutSubviews()
borderLayer.path = UIBezierPath(roundedRect: bounds, cornerRadius: cornerRadius).CGPath
borderLayer.frame = bounds
}
// MARK: - Build control
override public func customInit() {
super.customInit()
addBorder()
}
public func addBorder() {
borderLayer.strokeColor = borderColor.CGColor
borderLayer.fillColor = UIColor.clearColor().CGColor
borderLayer.lineDashPattern = [dashLength, dashSpace]
borderLayer.lineWidth = borderWidth / UIScreen.mainScreen().scale
// http://stackoverflow.com/questions/4735623/uilabel-layer-cornerradius-negatively-impacting-performance
borderLayer.masksToBounds = true
borderLayer.rasterizationScale = UIScreen.mainScreen().scale
borderLayer.shouldRasterize = true
layer.addSublayer(borderLayer)
}
}
| mit | b8e3544d1e417f5680ddec1b099365a4 | 26.466667 | 113 | 0.630097 | 5.124378 | false | false | false | false |
Prosumma/Guise | Tests/GuiseTests/ErrorTests.swift | 1 | 3732 | //
// ErrorTests.swift
// GuiseTests
//
// Created by Gregory Higley on 2022-10-03.
//
import XCTest
@testable import Guise
final class ErrorTests: XCTestCase {
override func setUp() {
super.setUp()
prepareForGuiseTests()
}
func test_error_same_key_sync() throws {
// Given
let key = Key(String.self)
let container = Container()
container.register(instance: "error")
Entry.testResolutionError = ResolutionError(key: key, reason: .notFound)
// When
do {
_ = try container.resolve(String.self)
XCTFail("Expected to throw an error.")
} catch let error as ResolutionError {
guard
error.key == key,
case .notFound = error.reason
else {
throw error
}
}
}
func test_error_different_key_sync() throws {
// Given
let key = Key(String.self)
let container = Container()
container.register(instance: "error")
container.register(instance: 7)
Entry.testResolutionError = ResolutionError(key: key, reason: .notFound)
// When
do {
_ = try container.resolve(Int.self)
XCTFail("Expected to throw an error.")
} catch let error as ResolutionError {
guard
error.key == Key(Int.self),
case .error(let nestedError as ResolutionError) = error.reason,
nestedError.key == Key(String.self),
case .notFound = nestedError.reason
else {
throw error
}
}
}
func test_arbitrary_error_sync() throws {
// Given
enum Foo: Error { case foo }
let key = Key(String.self)
let container = Container()
container.register(instance: "error")
Entry.testResolutionError = Foo.foo
do {
_ = try container.resolve(String.self)
XCTFail("Expected to throw an error.")
} catch let error as ResolutionError {
guard
error.key == key,
case .error(Foo.foo) = error.reason
else {
throw error
}
}
}
func test_error_same_key_async() async throws {
// Given
let key = Key(String.self)
let container = Container()
container.register(instance: "error")
Entry.testResolutionError = ResolutionError(key: key, reason: .notFound)
// When
do {
_ = try await container.resolve(String.self)
XCTFail("Expected to throw an error.")
} catch let error as ResolutionError {
guard
error.key == key,
case .notFound = error.reason
else {
throw error
}
}
}
func test_error_different_key_async() async throws {
// Given
let key = Key(String.self)
let container = Container()
container.register(instance: "error")
container.register(instance: 7)
Entry.testResolutionError = ResolutionError(key: key, reason: .notFound)
// When
do {
_ = try await container.resolve(Int.self)
XCTFail("Expected to throw an error.")
} catch let error as ResolutionError {
guard
error.key == Key(Int.self),
case .error(let nestedError as ResolutionError) = error.reason,
nestedError.key == Key(String.self),
case .notFound = nestedError.reason
else {
throw error
}
}
}
func test_arbitrary_error_async() async throws {
// Given
enum Foo: Error { case foo }
let key = Key(String.self)
let container = Container()
container.register(instance: "error")
Entry.testResolutionError = Foo.foo
do {
_ = try await container.resolve(String.self)
XCTFail("Expected to throw an error.")
} catch let error as ResolutionError {
guard
error.key == key,
case .error(Foo.foo) = error.reason
else {
throw error
}
}
}
}
| mit | 431b5da48b10279b5d1aca00ac63c261 | 24.216216 | 76 | 0.612004 | 4.030238 | false | true | false | false |
seamgen/SeamgenKit-Swift | SeamgenKit/Classes/UI/UIColor+Extensions.swift | 1 | 1968 | //
// UIColor+Extensions.swift
// SeamgenKit
//
// Created by Sam Gerardi on 12/12/16.
// Copyright © 2016 Seamgen. All rights reserved.
//
import UIKit
extension UIColor {
/// Initializes the color with values between 0 and 254
///
/// - Parameters:
/// - r: The red component.
/// - g: The green component.
/// - b: The blue component.
/// - alpha: The alpha component (between 0.0 and 1.0)
public convenience init(r: Int, g: Int, b: Int, alpha: CGFloat) {
precondition(r >= 0 && r <= 255)
precondition(g >= 0 && g <= 255)
precondition(b >= 0 && b <= 255)
precondition(alpha >= 0 && alpha <= 1)
self.init(red: CGFloat(r)/255.0, green: CGFloat(g)/255.0, blue: CGFloat(b)/255.0, alpha: alpha)
}
/// Initializes the color with a hex string.
///
/// - Parameter string: A hex string with the format #DEF, #FF00FF, #FF00FF00. The '#' is not required.
public convenience init(hex string: String) {
var hex = string.hasPrefix("#")
? String(string.characters.dropFirst())
: string
guard hex.characters.count == 3 || hex.characters.count == 6 || hex.characters.count == 8 else {
self.init(white: 0, alpha: 0)
return
}
if hex.characters.count == 3 {
for (index, char) in hex.characters.enumerated() {
hex.insert(char, at: hex.characters.index(hex.startIndex, offsetBy: index * 2))
}
}
if hex.characters.count == 6 {
hex += "FF"
}
self.init(
red: CGFloat((uint(hex, radix: 16)! >> 24) & 0xFF) / 255.0,
green: CGFloat((uint(hex, radix: 16)! >> 16) & 0xFF) / 255.0,
blue: CGFloat((uint(hex, radix: 16)! >> 8) & 0xFF) / 255.0,
alpha: CGFloat((uint(hex, radix: 16)!) & 0xFF) / 255.0)
}
}
| mit | cfc22a3ab35dbb14d6e97c432be3bf64 | 31.245902 | 108 | 0.524657 | 3.676636 | false | false | false | false |
manavgabhawala/swift | test/SILGen/opaque_values_silgen_lib.swift | 1 | 2370 | // RUN: %target-swift-frontend -enable-sil-opaque-values -emit-sorted-sil -Xllvm -new-mangling-for-tests -Xllvm -sil-full-demangle -parse-stdlib -parse-as-library -emit-silgen -module-name Swift %s | %FileCheck %s
// UNSUPPORTED: resilient_stdlib
precedencegroup AssignmentPrecedence { assignment: true }
enum Optional<Wrapped> {
case none
case some(Wrapped)
}
protocol EmptyP {}
struct String { var ptr: Builtin.NativeObject }
// Init of Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value)
// ---
// CHECK-LABEL: sil shared [transparent] [thunk] @_TFOs9PAndSEnum1AFMS_FTPs6EmptyP_SS_S_ : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_owned (@in EmptyP, @owned String) -> @out PAndSEnum {
// CHECK: bb0([[ARG:%.*]] : $@thin PAndSEnum.Type):
// CHECK: [[RETVAL:%.*]] = partial_apply {{.*}}([[ARG]]) : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum
// CHECK: return [[RETVAL]] : $@callee_owned (@in EmptyP, @owned String) -> @out PAndSEnum
// CHECK-LABEL: } // end sil function '_TFOs9PAndSEnum1AFMS_FTPs6EmptyP_SS_S_'
// CHECK-LABEL: sil shared [transparent] @_TFOs9PAndSEnum1AfMS_FTPs6EmptyP_SS_S_ : $@convention(method) (@in EmptyP, @owned String, @thin PAndSEnum.Type) -> @out PAndSEnum {
// CHECK: bb0([[ARG0:%.*]] : $EmptyP, [[ARG1:%.*]] : $String, [[ARG2:%.*]] : $@thin PAndSEnum.Type):
// CHECK: [[RTUPLE:%.*]] = tuple ([[ARG0]] : $EmptyP, [[ARG1]] : $String)
// CHECK: [[RETVAL:%.*]] = enum $PAndSEnum, #PAndSEnum.A!enumelt.1, [[RTUPLE]] : $(EmptyP, String)
// CHECK: return [[RETVAL]] : $PAndSEnum
// CHECK-LABEL: } // end sil function '_TFOs9PAndSEnum1AfMS_FTPs6EmptyP_SS_S_'
enum PAndSEnum { case A(EmptyP, String) }
// Tests Empty protocol + Builtin.NativeObject enum (including opaque tuples as a return value)
// ---
// CHECK-LABEL: sil hidden @_TFs21s010______PAndS_casesFT_T_ : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: [[MTYPE:%.*]] = metatype $@thin PAndSEnum.Type
// CHECK: [[EAPPLY:%.*]] = apply {{.*}}([[MTYPE]]) : $@convention(thin) (@thin PAndSEnum.Type) -> @owned @callee_owned (@in EmptyP, @owned String) -> @out PAndSEnum
// CHECK: destroy_value [[EAPPLY]]
// CHECK: return %{{.*}} : $()
// CHECK-LABEL: } // end sil function '_TFs21s010______PAndS_casesFT_T_'
func s010______PAndS_cases() {
_ = PAndSEnum.A
}
| apache-2.0 | c04762425940fc41465445534d851e99 | 56.804878 | 213 | 0.654852 | 3.376068 | false | false | false | false |
EthanGit/UIFilmLabel | UIFilmLabel/UIFilmLabel.swift | 1 | 2124 | //
// UIFilmLabel.swift
// DingOKMovie
//
// Created by Ethan on 2015/6/12.
// Copyright (c) 2015年 Ethan. All rights reserved.
//
import UIKit
//MARK: UIColor
extension UIColor {
public class func colorFromCode(_ code: Int) -> UIColor {
let red = CGFloat((code & 0xFF0000) >> 16) / 255.0 as CGFloat
let green = CGFloat((code & 0xFF00) >> 8) / 255.0 as CGFloat
let blue = CGFloat(code & 0xFF) / 255.0 as CGFloat
return UIColor(red: red, green: green, blue: blue, alpha: 1.0)
}
}
//MARK: UIFilmLabel
open class UIFilmLabel: UILabel {
/**
instance UIFilmLabel
*/
public override init(frame: CGRect) {
super.init(frame: frame)
// Initialization code
self.textColor = UIColor.white
self.textAlignment = .center
self.font = UIFont.boldSystemFont(ofSize: 14)
}
/**
instance UIFilmLabel
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// Initialization code
self.textColor = UIColor.white
self.textAlignment = .center
self.font = UIFont.boldSystemFont(ofSize: 14)
}
/**
setFilmLevelStr
*/
open func setFilmLevelStr(_ filmLevelStr:String) {
switch filmLevelStr {
case "G", "普":
self.text = filmLevelStr
self.backgroundColor = UIColor.colorFromCode(0x4CB503)
case "P", "護":
self.text = filmLevelStr
self.backgroundColor = UIColor.blue
case "PG", "輔":
self.text = filmLevelStr
self.backgroundColor = UIColor.orange
case "R", "限":
self.text = filmLevelStr
self.backgroundColor = UIColor.red
default:
self.text = ""
self.backgroundColor = UIColor.clear
}
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| mit | 2f96f463c9c9948e232938b8939c14b4 | 24.780488 | 78 | 0.581362 | 4.161417 | false | false | false | false |
zambelz48/swift-sample-dependency-injection | SampleDI/Core/Reusables/NavigationBar/Entities/NavigationBarViewItem.swift | 1 | 510 | //
// NavigationBarViewItem.swift
// My Blue Bird
//
// Created by Nanda Julianda Akbar on 8/23/17.
// Copyright © 2017 Nanda Julianda Akbar. All rights reserved.
//
import Foundation
import UIKit
struct NavigationBarViewItem: NavigationBarItem {
var view: UIView?
var enabled: Bool
var onTapEvent: (() -> Void)?
init(_ view: UIView? = nil,
enabled: Bool = true,
onTapEvent: (() -> Void)? = nil) {
self.view = view
self.enabled = enabled
self.onTapEvent = onTapEvent
}
}
| mit | 7cab2ff223def80de5801d392b1c93c7 | 17.851852 | 63 | 0.660118 | 3.305195 | false | false | false | false |
apple/swift | test/SILGen/guaranteed_self.swift | 5 | 24522 |
// RUN: %target-swift-emit-silgen -module-name guaranteed_self -Xllvm -sil-full-demangle %s -disable-objc-attr-requires-foundation-module -enable-objc-interop | %FileCheck %s
protocol Fooable {
init()
func foo(_ x: Int)
mutating func bar()
mutating func bas()
var prop1: Int { get set }
var prop2: Int { get set }
var prop3: Int { get nonmutating set }
}
protocol Barrable: class {
init()
func foo(_ x: Int)
func bar()
func bas()
var prop1: Int { get set }
var prop2: Int { get set }
var prop3: Int { get set }
}
struct S: Fooable {
var x: C? // Make the type nontrivial, so +0/+1 is observable.
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thin S.Type) -> @owned S
init() {}
// TODO: Way too many redundant r/r pairs here. Should use +0 rvalues.
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed S) -> () {
// CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: copy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
func foo(_ x: Int) {
self.foo(x)
}
func foooo(_ x: (Int, Bool)) {
self.foooo(x)
}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV3bar{{[_0-9a-zA-Z]*}}F : $@convention(method) (@inout S) -> ()
// CHECK: bb0([[SELF:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF]]
mutating func bar() {
self.bar()
}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed S) -> ()
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: copy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
func bas() {
self.bas()
}
var prop1: Int = 0
// Getter for prop1
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s15guaranteed_self1SV5prop1Sivg : $@convention(method) (@guaranteed S) -> Int
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
// Setter for prop1
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s15guaranteed_self1SV5prop1Sivs : $@convention(method) (Int, @inout S) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: load [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// modify for prop1
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s15guaranteed_self1SV5prop1SivM : $@yield_once @convention(method) (@inout S) -> @yields @inout Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: load [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
var prop2: Int {
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV5prop2Sivg : $@convention(method) (@guaranteed S) -> Int
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
get { return 0 }
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV5prop2Sivs : $@convention(method) (Int, @inout S) -> ()
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s15guaranteed_self1SV5prop2SivM : $@yield_once @convention(method) (@inout S) -> @yields @inout Int
set { }
}
var prop3: Int {
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV5prop3Sivg : $@convention(method) (@guaranteed S) -> Int
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
get { return 0 }
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1SV5prop3Sivs : $@convention(method) (Int, @guaranteed S) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s15guaranteed_self1SV5prop3SivM : $@yield_once @convention(method) (@guaranteed S) -> @yields @inout Int
// CHECK: bb0([[SELF:%.*]] : @guaranteed $S):
// CHECK-NOT: destroy_value [[SELF]]
nonmutating set { }
}
}
// Witness thunk for nonmutating 'foo'
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP3foo{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for mutating 'bar'
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP3bar{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: load [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for 'bas', which is mutating in the protocol, but nonmutating
// in the implementation
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP3bas{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK: end_borrow [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
// Witness thunk for prop1 getter
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop1SivgTW :
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF]]
// Witness thunk for prop1 setter
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop1SivsTW :
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop1 modify
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop1SivMTW :
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 getter
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop2SivgTW :
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 setter
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop2SivsTW :
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop2 modify
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop2SivMTW :
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 getter
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop3SivgTW :
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 nonmutating setter
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop3SivsTW :
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness thunk for prop3 nonmutating modify
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1SVAA7FooableA2aDP5prop3SivMTW :
// CHECK: bb0([[SELF_ADDR:%.*]] : $*S):
// CHECK: [[SELF:%.*]] = load_borrow [[SELF_ADDR]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK: } // end sil function '$s15guaranteed_self1SVAA7FooableA2aDP5prop3SivMTW'
//
// TODO: Expected output for the other cases
//
struct AO<T>: Fooable {
var x: T?
init() {}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self2AOV3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK: apply {{.*}} [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK: }
func foo(_ x: Int) {
self.foo(x)
}
mutating func bar() {
self.bar()
}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self2AOV3bas{{[_0-9a-zA-Z]*}}F : $@convention(method) <T> (@in_guaranteed AO<T>) -> ()
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
func bas() {
self.bas()
}
var prop1: Int = 0
var prop2: Int {
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self2AOV5prop2Sivg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int {
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
get { return 0 }
set { }
}
var prop3: Int {
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self2AOV5prop3Sivg : $@convention(method) <T> (@in_guaranteed AO<T>) -> Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
get { return 0 }
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self2AOV5prop3Sivs : $@convention(method) <T> (Int, @in_guaranteed AO<T>) -> ()
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK-LABEL: sil hidden [transparent] [ossa] @$s15guaranteed_self2AOV5prop3SivM : $@yield_once @convention(method) <T> (@in_guaranteed AO<T>) -> @yields @inout Int
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<T>):
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// CHECK: }
nonmutating set { }
}
}
// Witness for nonmutating 'foo'
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self2AOVyxGAA7FooableA2aEP3foo{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0({{.*}} [[SELF_ADDR:%.*]] : $*AO<τ_0_0>):
// CHECK: apply {{.*}} [[SELF_ADDR]]
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
// Witness for 'bar', which is mutating in protocol but nonmutating in impl
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self2AOVyxGAA7FooableA2aEP3bar{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0([[SELF_ADDR:%.*]] : $*AO<τ_0_0>):
// -- NB: This copy is not necessary, since we're willing to assume an inout
// parameter is not mutably aliased.
// CHECK: apply {{.*}}([[SELF_ADDR]])
// CHECK-NOT: destroy_addr [[SELF_ADDR]]
class C: Fooable, Barrable {
// Allocating initializer
// CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick C.Type) -> @owned C
// CHECK: [[SELF1:%.*]] = alloc_ref $C
// CHECK-NOT: [[SELF1]]
// CHECK: [[SELF2:%.*]] = apply {{.*}}([[SELF1]])
// CHECK-NOT: [[SELF2]]
// CHECK: return [[SELF2]]
// Initializing constructors still have the +1 in, +1 out convention.
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned C) -> @owned C {
// CHECK: bb0([[SELF:%.*]] : @owned $C):
// CHECK: [[MARKED_SELF:%.*]] = mark_uninitialized [rootself] [[SELF]]
// CHECK: [[MARKED_SELF_RESULT:%.*]] = copy_value [[MARKED_SELF]]
// CHECK: destroy_value [[MARKED_SELF]]
// CHECK: return [[MARKED_SELF_RESULT]]
// CHECK: } // end sil function '$s15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fc'
// @objc thunk for initializing constructor
// CHECK-LABEL: sil private [thunk] [ossa] @$s15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo : $@convention(objc_method) (@owned C) -> @owned C
// CHECK: bb0([[SELF:%.*]] : @owned $C):
// CHECK-NOT: copy_value [[SELF]]
// CHECK: [[SELF2:%.*]] = apply {{%.*}}([[SELF]])
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF2]]
// CHECK: return [[SELF2]]
// CHECK: } // end sil function '$s15guaranteed_self1CC{{[_0-9a-zA-Z]*}}fcTo'
@objc required init() {}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed C) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $C):
// CHECK-NOT: copy_value
// CHECK-NOT: destroy_value
// CHECK: } // end sil function '$s15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}F'
// CHECK-LABEL: sil private [thunk] [ossa] @$s15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (Int, C) -> () {
// CHECK: bb0({{.*}} [[SELF:%.*]] : @unowned $C):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: apply {{.*}}({{.*}}, [[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: } // end sil function '$s15guaranteed_self1CC3foo{{[_0-9a-zA-Z]*}}FTo'
@objc func foo(_ x: Int) {
self.foo(x)
}
@objc func bar() {
self.bar()
}
@objc func bas() {
self.bas()
}
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1CC5prop1SivgTo : $@convention(objc_method) (C) -> Int
// CHECK: bb0([[SELF:%.*]] : @unowned $C):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: apply {{.*}}([[BORROWED_SELF_COPY]])
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-LABEL: sil private [transparent] [thunk] [ossa] @$s15guaranteed_self1CC5prop1SivsTo : $@convention(objc_method) (Int, C) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : @unowned $C):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: apply {{.*}} [[BORROWED_SELF_COPY]]
// CHECK: end_borrow [[BORROWED_SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: }
@objc var prop1: Int = 0
@objc var prop2: Int {
get { return 0 }
set {}
}
@objc var prop3: Int {
get { return 0 }
set {}
}
}
class D: C {
// CHECK-LABEL: sil hidden [exact_self_class] [ossa] @$s15guaranteed_self1DC{{[_0-9a-zA-Z]*}}fC : $@convention(method) (@thick D.Type) -> @owned D
// CHECK: [[SELF1:%.*]] = alloc_ref $D
// CHECK-NOT: [[SELF1]]
// CHECK: [[SELF2:%.*]] = apply {{.*}}([[SELF1]])
// CHECK-NOT: [[SELF1]]
// CHECK-NOT: [[SELF2]]
// CHECK: return [[SELF2]]
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self1DC{{[_0-9a-zA-Z]*}}fc : $@convention(method) (@owned D) -> @owned D
// CHECK: bb0([[SELF:%.*]] : @owned $D):
// CHECK: [[SELF_BOX:%.*]] = alloc_box ${ var D }
// CHECK-NEXT: [[MARKED_SELF_BOX:%.*]] = mark_uninitialized [derivedself] [[SELF_BOX]]
// CHECK-NEXT: [[LIFETIME:%.+]] = begin_borrow [lexical] [[MARKED_SELF_BOX]]
// CHECK-NEXT: [[PB:%.*]] = project_box [[LIFETIME]]
// CHECK-NEXT: store [[SELF]] to [init] [[PB]]
// CHECK-NOT: [[PB]]
// CHECK: [[SELF1:%.*]] = load [take] [[PB]]
// CHECK-NEXT: [[SUPER1:%.*]] = upcast [[SELF1]]
// CHECK-NOT: [[PB]]
// CHECK: [[SUPER2:%.*]] = apply {{.*}}([[SUPER1]])
// CHECK-NEXT: [[SELF2:%.*]] = unchecked_ref_cast [[SUPER2]]
// CHECK-NEXT: store [[SELF2]] to [init] [[PB]]
// CHECK-NOT: [[PB]]
// CHECK-NOT: [[SELF1]]
// CHECK-NOT: [[SUPER1]]
// CHECK-NOT: [[SELF2]]
// CHECK-NOT: [[SUPER2]]
// CHECK: [[SELF_FINAL:%.*]] = load [copy] [[PB]]
// CHECK-NEXT: end_borrow [[LIFETIME]]
// CHECK-NEXT: destroy_value [[MARKED_SELF_BOX]]
// CHECK-NEXT: return [[SELF_FINAL]]
required init() {
super.init()
}
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] [ossa] @$s15guaranteed_self1DC3foo{{[_0-9a-zA-Z]*}}FTD : $@convention(method) (Int, @guaranteed D) -> ()
// CHECK: bb0({{.*}} [[SELF:%.*]] : @guaranteed $D):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF_COPY]]
// CHECK-NOT: destroy_value [[SELF]]
// CHECK: }
dynamic override func foo(_ x: Int) {
self.foo(x)
}
}
func S_curryThunk(_ s: S) -> ((S) -> (Int) -> ()/*, Int -> ()*/) {
return (S.foo /*, s.foo*/)
}
func AO_curryThunk<T>(_ ao: AO<T>) -> ((AO<T>) -> (Int) -> ()/*, Int -> ()*/) {
return (AO.foo /*, ao.foo*/)
}
// ----------------------------------------------------------------------------
// Make sure that we properly translate in_guaranteed parameters
// correctly if we are asked to.
// ----------------------------------------------------------------------------
// CHECK-LABEL: sil shared [transparent] [serialized] [thunk] [ossa] @$s15guaranteed_self9FakeArrayVAA8SequenceA2aDP17_constrainElement{{[_0-9a-zA-Z]*}}FTW :
// CHECK: bb0([[ARG0_PTR:%.*]] : $*FakeElement, [[ARG1_PTR:%.*]] : $*FakeArray):
// CHECK: [[ARG0:%.*]] = load [trivial] [[ARG0_PTR]]
// CHECK: function_ref (extension in guaranteed_self):guaranteed_self.SequenceDefaults._constrainElement
// CHECK: [[FUN:%.*]] = function_ref @{{.*}}
// CHECK: apply [[FUN]]<FakeArray>([[ARG0]], [[ARG1_PTR]])
class Z {}
public struct FakeGenerator {}
public struct FakeArray {
var z = Z()
}
public struct FakeElement {}
public protocol FakeGeneratorProtocol {
associatedtype Element
}
extension FakeGenerator : FakeGeneratorProtocol {
public typealias Element = FakeElement
}
public protocol SequenceDefaults {
associatedtype Element
associatedtype Generator : FakeGeneratorProtocol
}
extension SequenceDefaults {
public func _constrainElement(_: FakeGenerator.Element) {}
}
public protocol Sequence : SequenceDefaults {
func _constrainElement(_: Element)
}
extension FakeArray : Sequence {
public typealias Element = FakeElement
public typealias Generator = FakeGenerator
func _containsElement(_: Element) {}
}
// -----------------------------------------------------------------------------
// Make sure that we do not emit extra copy_values when accessing let fields of
// guaranteed parameters.
// -----------------------------------------------------------------------------
class Kraken {
func enrage() {}
}
func destroyShip(_ k: Kraken) {}
class LetFieldClass {
let letk = Kraken()
var vark = Kraken()
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self13LetFieldClassC10letkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () {
// CHECK: bb0([[CLS:%.*]] : @guaranteed $LetFieldClass):
// CHECK: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
// CHECK-NEXT: [[KRAKEN:%.*]] = load [copy] [[KRAKEN_ADDR]]
// CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[KRAKEN]]
// CHECK-NEXT: apply [[KRAKEN_METH]]([[KRAKEN]])
// CHECK: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
// CHECK-NEXT: [[KRAKEN:%.*]] = load [copy] [[KRAKEN_ADDR]]
// CHECK: [[REBORROWED_KRAKEN:%.*]] = begin_borrow [lexical] [[KRAKEN]]
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$s15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@guaranteed Kraken) -> ()
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[REBORROWED_KRAKEN]])
// CHECK-NEXT: end_borrow [[REBORROWED_KRAKEN]]
// CHECK-NEXT: destroy_value [[KRAKEN]]
// CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken }
// CHECK-NEXT: [[KRAKEN_LIFETIME:%.+]] = begin_borrow [lexical] [[KRAKEN_BOX]]
// CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_LIFETIME]]
// CHECK-NEXT: [[KRAKEN_ADDR:%.*]] = ref_element_addr [[CLS]] : $LetFieldClass, #LetFieldClass.letk
// CHECK-NEXT: [[KRAKEN:%.*]] = load [copy] [[KRAKEN_ADDR]]
// CHECK-NEXT: store [[KRAKEN]] to [init] [[PB]]
// CHECK-NEXT: [[READ:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken
// CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[READ]]
// CHECK-NEXT: end_access [[READ]] : $*Kraken
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$s15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@guaranteed Kraken) -> ()
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
// CHECK-NEXT: destroy_value [[KRAKEN_COPY]]
// CHECK-NEXT: end_borrow [[KRAKEN_LIFETIME]]
// CHECK-NEXT: destroy_value [[KRAKEN_BOX]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
// CHECK: } // end sil function
func letkMethod() {
do {
letk.enrage()
}
do {
let ll = letk
destroyShip(ll)
}
do {
var lv = letk
destroyShip(lv)
}
}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self13LetFieldClassC10varkMethod{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed LetFieldClass) -> () {
// CHECK: bb0([[CLS:%.*]] : @guaranteed $LetFieldClass):
// CHECK: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
// CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
// CHECK-NEXT: [[KRAKEN_METH:%.*]] = class_method [[KRAKEN]]
// CHECK-NEXT: apply [[KRAKEN_METH]]([[KRAKEN]])
// CHECK-NEXT: destroy_value [[KRAKEN]]
// CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
// CHECK-NEXT: [[KRAKEN:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
// CHECK: [[BORROWED_KRAKEN:%.*]] = begin_borrow [lexical] [[KRAKEN]]
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$s15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@guaranteed Kraken) -> ()
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[BORROWED_KRAKEN]])
// CHECK-NEXT: [[KRAKEN_BOX:%.*]] = alloc_box ${ var Kraken }
// CHECK-NEXT: [[KRAKEN_LIFETIME:%.+]] = begin_borrow [lexical] [[KRAKEN_BOX]]
// CHECK-NEXT: [[PB:%.*]] = project_box [[KRAKEN_LIFETIME]]
// CHECK-NEXT: [[KRAKEN_GETTER_FUN:%.*]] = class_method [[CLS]] : $LetFieldClass, #LetFieldClass.vark!getter : (LetFieldClass) -> () -> Kraken, $@convention(method) (@guaranteed LetFieldClass) -> @owned Kraken
// CHECK-NEXT: [[KRAKEN2:%.*]] = apply [[KRAKEN_GETTER_FUN]]([[CLS]])
// CHECK-NEXT: store [[KRAKEN2]] to [init] [[PB]]
// CHECK-NEXT: [[WRITE:%.*]] = begin_access [read] [unknown] [[PB]] : $*Kraken
// CHECK-NEXT: [[KRAKEN_COPY:%.*]] = load [copy] [[WRITE]]
// CHECK-NEXT: end_access [[WRITE]] : $*Kraken
// CHECK: [[DESTROY_SHIP_FUN:%.*]] = function_ref @$s15guaranteed_self11destroyShipyyAA6KrakenCF : $@convention(thin) (@guaranteed Kraken) -> ()
// CHECK-NEXT: apply [[DESTROY_SHIP_FUN]]([[KRAKEN_COPY]])
// CHECK-NEXT: destroy_value [[KRAKEN_COPY]]
// CHECK-NEXT: end_borrow [[KRAKEN_LIFETIME]]
// CHECK-NEXT: destroy_value [[KRAKEN_BOX]]
// CHECK-NEXT: end_borrow [[BORROWED_KRAKEN]]
// CHECK-NEXT: destroy_value [[KRAKEN]]
// CHECK-NEXT: tuple
// CHECK-NEXT: return
func varkMethod() {
vark.enrage()
let vl = vark
destroyShip(vl)
var vv = vark
destroyShip(vv)
}
}
// -----------------------------------------------------------------------------
// Make sure that in all of the following cases find has only one copy_value in it.
// -----------------------------------------------------------------------------
class ClassIntTreeNode {
let value : Int
let left, right : ClassIntTreeNode
init() {}
// CHECK-LABEL: sil hidden [ossa] @$s15guaranteed_self16ClassIntTreeNodeC4find{{[_0-9a-zA-Z]*}}F : $@convention(method) (Int, @guaranteed ClassIntTreeNode) -> @owned ClassIntTreeNode {
// CHECK-NOT: destroy_value
// CHECK: copy_value
// CHECK-NOT: copy_value
// CHECK: destroy_value
// CHECK: destroy_value
// CHECK-NOT: destroy_value
// CHECK: return
func find(_ v : Int) -> ClassIntTreeNode {
if v == value { return self }
if v < value { return left.find(v) }
return right.find(v)
}
}
| apache-2.0 | 135e18cf37ef9c9f3abfe21c23909119 | 42.707665 | 211 | 0.580873 | 3.361206 | false | false | false | false |
danielsaidi/KeyboardKit | Tests/KeyboardKitTests/Keyboard/StandardKeyboardBehaviorTests.swift | 1 | 6544 | //
// StandardKeyboardBehaviorTests.swift
// KeyboardKit
//
// Created by Daniel Saidi on 2019-05-06.
// Copyright © 2021 Daniel Saidi. All rights reserved.
//
import Quick
import Nimble
import MockingKit
import UIKit
@testable import KeyboardKit
class StandardKeyboardBehaviorTests: QuickSpec {
override func spec() {
var behavior: StandardKeyboardBehavior!
var context: MockKeyboardContext!
var proxy: MockTextDocumentProxy!
beforeEach {
proxy = MockTextDocumentProxy()
context = MockKeyboardContext()
context.textDocumentProxy = proxy
behavior = StandardKeyboardBehavior(context: context)
}
describe("preferred keyboard type after gesture on action") {
func result(after gesture: KeyboardGesture, on action: KeyboardAction) -> KeyboardType {
behavior.preferredKeyboardType(after: gesture, on: action)
}
it("is by default the context preferred keyboard type") {
proxy.documentContextBeforeInput = "Hello!"
proxy.autocapitalizationType = .allCharacters
context.keyboardType = .alphabetic(.lowercased)
expect(result(after: .tap, on: .character("i"))).to(equal(.alphabetic(.uppercased)))
}
it("is context preferred keyboard type if shift is double-tapped too slowly") {
context.keyboardType = .alphabetic(.uppercased)
behavior.lastShiftCheck = .distantPast
expect(result(after: .tap, on: .shift(currentState: .uppercased))).to(equal(.alphabetic(.uppercased)))
}
it("is context preferred keyboard type if non-shift is double-tapped") {
context.keyboardType = .alphabetic(.uppercased)
expect(result(after: .tap, on: .command)).to(equal(.alphabetic(.lowercased)))
}
it("is context preferred keyboard type if current keyboard type is not upper-cased") {
context.keyboardType = .alphabetic(.lowercased)
expect(result(after: .tap, on: .command)).to(equal(.alphabetic(.lowercased)))
}
it("is caps-locked if shift is double-tapped quickly") {
context.keyboardType = .alphabetic(.uppercased)
expect(result(after: .tap, on: .shift(currentState: .uppercased))).to(equal(.alphabetic(.capsLocked)))
}
}
describe("should end sentence") {
func result(after gesture: KeyboardGesture, on action: KeyboardAction) -> Bool {
behavior.shouldEndSentence(after: gesture, on: action)
}
it("is only true for space after a previous space") {
proxy.documentContextBeforeInput = "hej "
expect(result(after: .tap, on: .space)).to(beTrue())
expect(result(after: .tap, on: .character(" "))).to(beFalse())
expect(result(after: .tap, on: .command)).to(beFalse())
proxy.documentContextBeforeInput = "hej. "
expect(result(after: .tap, on: .space)).to(beFalse())
expect(result(after: .tap, on: .character(" "))).to(beFalse())
proxy.documentContextBeforeInput = "hej. "
expect(result(after: .tap, on: .space)).to(beFalse())
expect(result(after: .tap, on: .character(" "))).to(beFalse())
}
}
describe("should switch to caps lock") {
func result(after gesture: KeyboardGesture, on action: KeyboardAction) -> Bool {
behavior.shouldSwitchToCapsLock(after: gesture, on: action)
}
it("is true if the action is shift") {
expect(result(after: .tap, on: .shift(currentState: .capsLocked))).to(beTrue())
expect(result(after: .tap, on: .shift(currentState: .lowercased))).to(beTrue())
expect(result(after: .tap, on: .shift(currentState: .uppercased))).to(beTrue())
}
}
describe("should switch to preferred keyboard type after gesture on action") {
func result(after gesture: KeyboardGesture, on action: KeyboardAction) -> Bool {
behavior.shouldSwitchToPreferredKeyboardType(after: gesture, on: action)
}
it("is true if the action is shift") {
expect(result(after: .tap, on: .shift(currentState: .capsLocked))).to(beTrue())
expect(result(after: .tap, on: .shift(currentState: .lowercased))).to(beTrue())
expect(result(after: .tap, on: .shift(currentState: .uppercased))).to(beTrue())
}
it("is true is the current keyboard type differs from the preferred one") {
proxy.documentContextBeforeInput = "Hello!"
proxy.autocapitalizationType = .allCharacters
context.keyboardType = .alphabetic(.lowercased)
expect(result(after: .tap, on: .character("i"))).to(beTrue())
}
it("is false is the current keyboard type is the same as the preferred one") {
proxy.documentContextBeforeInput = "Hello!"
proxy.autocapitalizationType = .none
context.keyboardType = .alphabetic(.lowercased)
expect(result(after: .tap, on: .character("i"))).to(beFalse())
}
}
describe("should switch to preferred keyboard type after text did change") {
beforeEach {
proxy.autocapitalizationType = .sentences
proxy.documentContextBeforeInput = "foo. "
}
func result() -> Bool {
behavior.shouldSwitchToPreferredKeyboardTypeAfterTextDidChange()
}
it("is true if the the current keyboard type is not the preferred one") {
expect(result()).to(beTrue())
}
it("is not true if the current keyboard type is the preferred one") {
context.keyboardType = .alphabetic(.uppercased)
expect(result()).to(beFalse())
}
}
}
}
| mit | d527caba1f18cdf250c919e3f319b76b | 42.331126 | 118 | 0.555556 | 5.213546 | false | false | false | false |
contentful/ManagedObjectModelSerializer | Code/XMLTools.swift | 1 | 2147 | //
// XMLTools.swift
// ManagedObjectModelSerializer
//
// Created by Boris Bügling on 11/11/14.
// Copyright (c) 2014 Boris Bügling. All rights reserved.
//
import Foundation
func temporaryFileURL(filename : String) -> NSURL {
let fileName = NSString(format: "%@_%@", NSProcessInfo.processInfo().globallyUniqueString, filename)
return NSURL(fileURLWithPath: (NSTemporaryDirectory() as NSString).stringByAppendingPathComponent(fileName as String))
}
func temporaryURLForString(string : String, filename : String) -> NSURL {
let temporaryURL = temporaryFileURL("out.xml")
do {
try string.writeToURL(temporaryURL, atomically: true, encoding: NSUTF8StringEncoding)
} catch _ {
}
return temporaryURL
}
func xmllint(xmlString : String, options : String) -> String {
let temporaryURL = temporaryURLForString(xmlString, filename: "out.xml")
let result = $(NSString(format: "xmllint %@ %@", options, temporaryURL.path!) as String)
do {
try NSFileManager().removeItemAtURL(temporaryURL)
} catch _ {
}
return result
}
func canonicalizeXML(xmlString : String) -> String {
let result = xmllint(xmlString, options: "--c14n")
return xmllint(result, options: "--format")
}
func diff(oneString : String, anotherString: String) -> String {
let temporaryURL1 = temporaryURLForString(oneString, filename: "1.xml")
let temporaryURL2 = temporaryURLForString(anotherString, filename: "2.xml")
let result = $(NSString(format: "diff -w %@ %@", temporaryURL1.path!, temporaryURL2.path!) as String)
do {
try NSFileManager().removeItemAtURL(temporaryURL1)
} catch _ {
}
do {
try NSFileManager().removeItemAtURL(temporaryURL2)
} catch _ {
}
return result
}
public class XMLTools {
public class func compareXML(xmlString : String, withXMLAtPath : String) -> String {
var compareXML = try! NSString(contentsOfFile: withXMLAtPath, encoding: NSUTF8StringEncoding)
compareXML = canonicalizeXML(compareXML as String)
return diff(canonicalizeXML(xmlString), anotherString: compareXML as String)
}
}
| mit | db11143008fb55d4b23b886b88fb29f4 | 31.5 | 122 | 0.697436 | 4.23913 | false | false | false | false |
N26-OpenSource/bob | Sources/Bob/Commands/Travis Script/TravisScriptCommand.swift | 1 | 5552 | /*
* Copyright (c) 2017 N26 GmbH.
*
* This file is part of Bob.
*
* Bob is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Bob is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Bob. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
import Vapor
/// Struct used to map targets to scripts
public struct TravisTarget {
/// Name used in the command parameters
public let name: String
/// Script to trigger
public let script: Script
public init(name: String, script: Script) {
self.name = name
self.script = script
}
}
/// Command executing a script on TravisCI
/// Script are provided via `TravisTarget`s. In case
/// only 1 traget is provided, the user does not have
/// to type in the target name
public class TravisScriptCommand {
public let name: String
fileprivate let travis: TravisCI
fileprivate let targets: [TravisTarget]
fileprivate let defaultBranch: BranchName
fileprivate let gitHub: GitHub?
/// Initializer for the command
///
/// - Parameters:
/// - name: Command name to use
/// - travis: TravisCI instance
/// - targets: Array of possible targets the user can use
/// - gitHub: If GitHub config is provided, the command will perform a branch check before invoking TravisCI api
public init(name: String, travis: TravisCI, targets: [TravisTarget], defaultBranch: BranchName, gitHub: GitHub? = nil) {
self.name = name
self.travis = travis
self.targets = targets
self.defaultBranch = defaultBranch
self.gitHub = gitHub
}
}
extension TravisScriptCommand: Command {
enum Constants {
static let branchSpecifier: String = "-b"
}
public var usage: String {
let target = self.targets.count == 1 ? "" : " {{target}}"
var message = "Triger a script by saying `\(self.name + target) \(Constants.branchSpecifier) {{branch}}`. I'll do the job for you. `branch` parameter is optional and it defaults to `\(self.defaultBranch)`"
if self.targets.count != 1 {
message += "\nAvailable targets:"
self.targets.forEach({ message += "\n• " + $0.name })
}
return message
}
public func execute(with parameters: [String], replyingTo sender: MessageSender) throws {
var params = parameters
/// Resolve target
var target: TravisTarget!
if self.targets.count == 1 {
/// Only 1 possible target, the user doesn't have to specify
target = self.targets[0]
} else {
/// More possible targets, resolve which one needs to be used
guard params.count > 0 else { throw "No parameters provided. See `\(self.name) usage` for instructions on how to use this command" }
let targetName = params[0]
params.remove(at: 0)
guard let existingTarget = self.targets.first(where: { $0.name == targetName }) else { throw "Unknown target `\(targetName)`." }
target = existingTarget
}
/// Resolve branch
var branch: BranchName = self.defaultBranch
if let branchSpecifierIndex = params.index(where: { $0 == Constants.branchSpecifier }) {
guard params.count > branchSpecifierIndex + 1 else { throw "Branch name not specified after `\(Constants.branchSpecifier)`" }
branch = BranchName(params[branchSpecifierIndex + 1])
params.remove(at: branchSpecifierIndex + 1)
params.remove(at: branchSpecifierIndex)
}
guard params.count == 0 else { throw "To many parameters. See `\(self.name) usage` for instructions on how to use this command" }
_ = try self.assertGitHubBranchIfPossible(branch).flatMap {
return try self.travis.execute(target.script, on: branch)
}.flatMap(to: TravisCI.Request.self) { response in
sender.send("Got it! Executing target *" + target.name + "* success.")
return try self.travis.request(id: response.request.id)
}.flatMap { buildRequest in
return try self.travis.poll(requestId: buildRequest.id, until: { request -> TravisCI.Poll<TravisCI.Request.Complete> in
switch request.state {
case .pending:
return .continue
case .complete(let completedRequest):
return .stop(completedRequest)
}
})
}.map { completedRequest in
let urls = completedRequest.builds.map { self.travis.buildURL(from: $0) }
let message = urls.reduce("Build URL: ") { $0 + "\n \($1.absoluteString)" }
sender.send(message)
}
.catch { error in
sender.send("Executing target *" + target.name + "* failed: `\(error)`")
}
}
private func assertGitHubBranchIfPossible(_ branch: BranchName) throws -> Future<Void> {
guard let gitHub = self.gitHub else {
return travis.worker.future()
}
return try gitHub.assertBranchExists(branch)
}
}
| gpl-3.0 | efd2063c882b507ec20385c977b0c0df | 39.808824 | 213 | 0.631892 | 4.479419 | false | false | false | false |
PurpleSweetPotatoes/customControl | SwiftKit/extension/CALayer+extension.swift | 1 | 1581 | //
// CALayer+extension.swift
// HJLBusiness
//
// Created by MrBai on 2017/5/18.
// Copyright © 2017年 baiqiang. All rights reserved.
//
import Foundation
import UIKit
extension CALayer {
class func lineLayer(frame: CGRect) -> CAShapeLayer {
let line = CAShapeLayer()
line.frame = frame
line.backgroundColor = UIColor.lineColor.cgColor
return line
}
var left : CGFloat {
get {
return self.frame.origin.x
}
set(left) {
self.frame.origin = CGPoint(x: left, y: self.frame.origin.y)
}
}
var right : CGFloat {
get {
return self.frame.origin.x + self.width
}
set(right) {
self.left = right - self.width
}
}
var top : CGFloat {
get {
return self.frame.origin.y
}
set(top) {
self.frame.origin = CGPoint(x: self.frame.origin.x, y: top)
}
}
var bottom : CGFloat {
get {
return self.frame.origin.y + self.height
}
set(bottom) {
self.top = bottom - self.height
}
}
var width : CGFloat {
get {
return self.bounds.size.width
}
set(width) {
self.frame.size = CGSize(width: width, height: self.frame.height)
}
}
var height : CGFloat {
get {
return self.bounds.size.height
}
set(height) {
self.frame.size = CGSize(width: self.width, height: height)
}
}
}
| apache-2.0 | 26730430252a858deb83e216bfcb7cf6 | 21.869565 | 77 | 0.508238 | 4.005076 | false | false | false | false |
DimensionSrl/Desman | Desman/Remote/Controllers/AppsTableViewController.swift | 1 | 4953 | //
// AppsTableViewController.swift
// Desman
//
// Created by Matteo Gavagnin on 31/10/15.
// Copyright © 2015 DIMENSION S.r.l. All rights reserved.
//
import UIKit
#if !DESMAN_AS_COCOAPOD
import Desman
#endif
private var desmanAppsContext = 0
public class RemoteController {
}
class AppsTableViewController: UITableViewController {
var objectToObserve = RemoteManager.sharedInstance
var apps = [App]()
override func viewDidLoad() {
super.viewDidLoad()
self.splitViewController?.preferredDisplayMode = .AllVisible
objectToObserve.addObserver(self, forKeyPath: "apps", options: .New, context: &desmanAppsContext)
self.apps = Array(RemoteManager.sharedInstance.apps)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
RemoteManager.sharedInstance.fetchApps()
}
func previewingContext(previewingContext: UIViewControllerPreviewing, commitViewController viewControllerToCommit: UIViewController) {
showViewController(viewControllerToCommit, sender: self)
}
@IBAction func dismissController(sender: UIBarButtonItem) {
self.navigationController?.dismissViewControllerAnimated(true, completion: nil)
}
override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if context == &desmanAppsContext {
if keyPath == "apps" {
if let updatedApps = change?[NSKeyValueChangeNewKey] as? [App] {
let removedApps = apps.removeObjectsInArray(updatedApps)
let addedApps = updatedApps.removeObjectsInArray(apps)
var removeIndexPaths = [NSIndexPath]()
var index = 1
let appsCount = apps.count
for _ in removedApps {
let indexPath = NSIndexPath(forRow: appsCount - index, inSection: 0)
removeIndexPaths.append(indexPath)
index += 1
}
var addedIndexPaths = [NSIndexPath]()
index = 0
for _ in addedApps {
let indexPath = NSIndexPath(forRow: index, inSection: 0)
addedIndexPaths.append(indexPath)
index += 1
}
var rowAnimation : UITableViewRowAnimation = .Right
if apps.count == 0 {
rowAnimation = .None
}
apps = Array(updatedApps)
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths(removeIndexPaths, withRowAnimation: .Left)
tableView.insertRowsAtIndexPaths(addedIndexPaths, withRowAnimation: rowAnimation)
tableView.endUpdates()
}
}
} else {
super.observeValueForKeyPath(keyPath, ofObject: object, change: change, context: context)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return apps.count
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let selectedApp = apps[indexPath.row]
RemoteManager.sharedInstance.fetchUsers(selectedApp)
self.performSegueWithIdentifier("showUsersSegue", sender: selectedApp)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("appCell", forIndexPath: indexPath) as! Desman.AppTableViewCell
let app = apps[indexPath.row]
cell.appTitleLabel.text = app.title
cell.appImageView.isIcon()
if let iconUrl = app.iconUrl {
cell.appImageView.loadFromURL(iconUrl)
}
return cell
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showUsersSegue" {
if let detailController = segue.destinationViewController as? UsersTableViewController {
if let sender = sender as? App {
detailController.app = sender
}
}
}
}
deinit {
objectToObserve.removeObserver(self, forKeyPath: "apps", context: &desmanAppsContext)
}
}
| mit | 17a7c64ad1f2df32dde7526785780813 | 36.515152 | 157 | 0.607835 | 5.652968 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.