repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
thesecretlab/Swift-iOS-Workshops-2014 | refs/heads/master | Swift/3. Classes.playground/section-1.swift | mit | 1 | // Playground - noun: a place where people can play
import UIKit
// MARK: Classes
// Classes define the 'blueprint' for an object
class Vehicle {
var colour: String?
var maxSpeed = 80
func description() -> String {
return "A \(self.colour) vehicle"
}
func travel() {
println("Travelling at \(maxSpeed) kph")
}
}
var redVehicle = Vehicle()
redVehicle.colour = "Red"
redVehicle.maxSpeed = 90
redVehicle.travel() // prints "Travelling at 90 kph"
redVehicle.description() // = "A Red vehicle"
// MARK: Inheritance
// Classes can inherit from other classes
class Car: Vehicle {
// Inherited classes can override functions
override func description() -> String {
var description = super.description()
return description + ", which is a car"
}
}
// MARK: Initialisers
// Classes have a special 'init' function
class Motorcycle : Vehicle {
var manufacturer : String
override func description() -> String {
return "A \(colour) \(manufacturer) bike"
}
// By the end of the init function, all variables that are not optional must have a value
init(manufacturer: String = "No-Name Brand™") {
self.manufacturer = manufacturer
// The superclass' init function must be called after all properties defined in this subclass have a value
super.init()
self.colour = "Blue"
}
// 'convenience' init functions let you set up default values, and must call the main init method first
convenience init (colour : String) {
self.init()
self.colour = colour
}
}
var firstBike = Motorcycle(manufacturer: "Yamaha")
firstBike.description() // = "A Blue Yamaha bike"
var secondBike = Motorcycle(colour: "Red")
secondBike.description() // = "A Red No-Name Brand™ bike"
// MARK: Properties
// Properties can be simple stored variables
class SimplePropertyExample {
var number: Int = 0
}
var test1 = SimplePropertyExample()
test1.number = 2
// MARK: Computed properties
// Properties can be computed
class Rectangle {
var width: Double = 0.0
var height: Double = 0.0
var area : Double {
// computed getter
get {
return width * height
}
// computed setter
set {
// Assume equal dimensions (ie a square)
width = sqrt(newValue)
height = sqrt(newValue)
}
}
}
var rect = Rectangle()
rect.width = 3.0
rect.height = 4.5
rect.area // = 13.5
rect.area = 9 // width & height now both 3.0
// MARK: Property observers
// You can run code when a property changes
class PropertyObserverExample {
var number : Int = 0 {
willSet(newNumber) {
println("About to change to \(newNumber)")
}
didSet(oldNumber) {
println("Just changed from \(oldNumber) to \(self.number)!")
}
}
}
var observer = PropertyObserverExample()
observer.number = 4
// prints "About to change to 4", then "Just changed from 0 to 5!"
// MARK: Lazy properties
// Properties can be made 'lazy': they aren't set up until they're first called
class SomeExpensiveClass {
init(id : Int) {
println("Expensive class \(id) created!")
}
}
class LazyPropertyExample {
var expensiveClass1 = SomeExpensiveClass(id: 1)
// note that we're actually constructing a class,
// but it's labelled as lazy
lazy var expensiveClass2 = SomeExpensiveClass(id: 2)
init() {
println("First class created!")
}
}
var lazyExample = LazyPropertyExample() // prints "Expensive class 1 created", then "First class created!"
lazyExample.expensiveClass1 // prints nothing, it's already created
lazyExample.expensiveClass2 // prints "Expensive class 2 created!"
// MARK: Protocols
// Protocols are lists of methods and properties that classes can contain
protocol Blinking {
// This property must be (at least) gettable
var isBlinking : Bool { get }
// This property must be gettable and settable
var blinkSpeed: Double { get set }
// This function must exist, but what it does is up to the implementor
func startBlinking(blinkSpeed: Double) -> Void
}
class Light : Blinking {
var isBlinking: Bool = false
var blinkSpeed : Double = 0.0
func startBlinking(blinkSpeed : Double) {
println("I am now blinking")
isBlinking = true
self.blinkSpeed = blinkSpeed
}
}
var aBlinkingThing : Blinking?
// can be ANY object that has the Blinking protocol
aBlinkingThing = Light()
aBlinkingThing!.startBlinking(4.0) // prints "I am now blinking"
aBlinkingThing!.blinkSpeed // = 4.0
// MARK: Extensions
// Types can be extended to include new properties and methods
extension Int {
var doubled : Int {
return self * 2
}
func multiplyWith(anotherNumber: Int) -> Int {
return self * anotherNumber
}
}
2.doubled // = 4
4.multiplyWith(32) // = 128
// Types can also be made to conform to a protocol
extension Int : Blinking {
var isBlinking : Bool {
return false;
}
var blinkSpeed : Double {
get {
return 0.0;
}
set {
// Do nothing
}
}
func startBlinking(blinkSpeed : Double) {
println("I am the integer \(self). I do not blink.")
}
}
2.isBlinking // = false
2.startBlinking(2.0) // prints "I am the integer 2. I do not blink."
// MARK: Access control
// This class is visible to everyone
public class AccessControl {
// Accessible to this module only
// 'internal' here is the default and can be omitted
internal var internalProperty = 123
// Accessible to everyone
public var publicProperty = 123
// Only accessible in this source file
private var privateProperty = 123
// The setter is private, so other files can't modify it
private(set) var privateSetterProperty = 123
}
// MARK: Interoperating with Objective-C
// Creating Objective-C objects
var view = UIView(frame: CGRect(x: 0,y: 0,width: 100,height: 100))
// Working with Objective-C properties
view.bounds
// Calling Objective-C methods
view.pointInside(CGPoint(x: 20, y: 20), withEvent:nil) // = true
// MARK: Modules
import AVFoundation
| 13a5467dc10c89ddd32deb1d352efdf1 | 22.966165 | 114 | 0.641255 | false | false | false | false |
eonil/BTree | refs/heads/master | Sources/BTreeCursor.swift | mit | 2 | //
// BTreeCursor.swift
// BTree
//
// Created by Károly Lőrentey on 2016-02-12.
// Copyright © 2015–2017 Károly Lőrentey.
//
extension BTree {
//MARK: Cursors
public typealias Cursor = BTreeCursor<Key, Value>
/// Call `body` with a cursor at `offset` in this tree.
///
/// - Warning: Do not rely on anything about `self` (the `BTree` that is the target of this method) during the
/// execution of body: it will not appear to have the correct value.
/// Instead, use only the supplied cursor to manipulate the tree.
///
public mutating func withCursor<R>(atOffset offset: Int, body: (Cursor) throws -> R) rethrows -> R {
precondition(offset >= 0 && offset <= count)
makeUnique()
let cursor = BTreeCursor(BTreeCursorPath(root: root, offset: offset))
root = Node(order: self.order)
defer { self.root = cursor.finish() }
return try body(cursor)
}
/// Call `body` with a cursor at the start of this tree.
///
/// - Warning: Do not rely on anything about `self` (the `BTree` that is the target of this method) during the
/// execution of body: it will not appear to have the correct value.
/// Instead, use only the supplied cursor to manipulate the tree.
///
public mutating func withCursorAtStart<R>(_ body: (Cursor) throws -> R) rethrows -> R {
return try withCursor(atOffset: 0, body: body)
}
/// Call `body` with a cursor at the end of this tree.
///
/// - Warning: Do not rely on anything about `self` (the `BTree` that is the target of this method) during the
/// execution of body: it will not appear to have the correct value.
/// Instead, use only the supplied cursor to manipulate the tree.
///
public mutating func withCursorAtEnd<R>(_ body: (Cursor) throws -> R) rethrows -> R {
makeUnique()
let cursor = BTreeCursor(BTreeCursorPath(endOf: root))
root = Node(order: self.order)
defer { self.root = cursor.finish() }
return try body(cursor)
}
/// Call `body` with a cursor positioned on `key` in this tree.
/// If there are multiple elements with the same key, `selector` indicates which matching element to find.
///
/// - Warning: Do not rely on anything about `self` (the `BTree` that is the target of this method) during the
/// execution of body: it will not appear to have the correct value.
/// Instead, use only the supplied cursor to manipulate the tree.
///
public mutating func withCursor<R>(onKey key: Key, choosing selector: BTreeKeySelector = .any, body: (Cursor) throws -> R) rethrows -> R {
makeUnique()
let cursor = BTreeCursor(BTreeCursorPath(root: root, key: key, choosing: selector))
root = Node(order: self.order)
defer { self.root = cursor.finish() }
return try body(cursor)
}
/// Call `body` with a cursor positioned on `index` in this tree.
///
/// - Warning: Do not rely on anything about `self` (the `BTree` that is the target of this method) during the
/// execution of body: it will not appear to have the correct value.
/// Instead, use only the supplied cursor to manipulate the tree.
///
public mutating func withCursor<R>(at index: Index, body: (Cursor) throws -> R) rethrows -> R {
index.state.expectRoot(root)
makeUnique()
let cursor = BTreeCursor(BTreeCursorPath(root: root, slotsFrom: index.state))
root = Node(order: self.order)
defer { self.root = cursor.finish() }
return try body(cursor)
}
}
/// A mutable path in a B-tree, holding strong references to nodes on the path.
/// This path variant supports modification of the tree itself.
///
/// To speed up operations inserting/removing individual elements from the tree, this path keeps the tree in a
/// special editing state, with element counts of nodes on the current path subtracted from their ancestors' counts.
/// The counts are restored when the path ascends back towards the root.
///
/// Because this preparation breaks the tree's invariants, there should not be references to the tree's root outside of
/// the cursor. Creating a `BTreeCursorPath` for a tree takes exclusive ownership of its root for the duration of the
/// editing. (I.e., until `finish()` is called.) If the root isn't uniquely held, you'll need to clone it before
/// creating a cursor path on it. (The path clones internal nodes on its own, as needed.)
///
internal struct BTreeCursorPath<Key: Comparable, Value>: BTreePath {
typealias Tree = BTree<Key, Value>
typealias Node = BTreeNode<Key, Value>
typealias Element = (Key, Value)
/// The root node in the tree that is being edited. Note that this isn't a valid B-tree while the cursor is active:
/// each node on the current path has an invalid `count` field. (Other B-tree invariants are kept, though.)
var root: Node
/// The current count of elements in the tree. This is always kept up to date, while `root.count` is usually invalid.
var count: Int
/// The offset of the currently focused element in the tree.
var offset: Int
/// The current path in the tree that is being edited.
///
/// Only the last node on the path has correct `count`; the element count of the currently focused descendant
/// subtree is subtracted from each ancestor's count.
/// I.e., `path[i].count = realCount(path[i]) - realCount(path[i+1])`.
var _path: [Node]
var node: Node
/// The slots on the path to the currently focused part of the tree.
var _slots: [Int]
var slot: Int?
init(root: Node) {
self.root = root
self.offset = root.count
self.count = root.count
self._path = []
self.node = root
self._slots = []
self.slot = nil
}
var length: Int { return _path.count + 1}
var element: Element {
get { return node.elements[slot!] }
set { node.elements[slot!] = newValue }
}
var key: Key {
get { return node.elements[slot!].0 }
set { node.elements[slot!].0 = newValue }
}
var value: Value {
get { return node.elements[slot!].1 }
set { node.elements[slot!].1 = newValue }
}
func setValue(_ value: Value) -> Value {
precondition(!isAtEnd)
let old = node.elements[slot!].1
node.elements[slot!].1 = value
return old
}
/// Invalidate this cursor.
mutating func invalidate() {
root = BTreeNode<Key, Value>(order: root.order)
count = 0
offset = 0
_path = []
node = root
_slots = []
slot = nil
}
mutating func popFromSlots() {
assert(self.slot != nil)
offset += node.count - node.offset(ofSlot: slot!)
slot = nil
}
mutating func popFromPath() {
assert(_path.count > 0 && slot == nil)
let child = node
node = _path.removeLast()
node.count += child.count
slot = _slots.removeLast()
}
mutating func pushToPath() {
assert(self.slot != nil)
let parent = node
_path.append(parent)
node = parent.makeChildUnique(self.slot!)
parent.count -= node.count
_slots.append(slot!)
slot = nil
}
mutating func pushToSlots(_ slot: Int, offsetOfSlot: Int) {
assert(self.slot == nil)
offset -= node.count - offsetOfSlot
self.slot = slot
}
func forEach(ascending: Bool, body: (Node, Int) -> Void) {
if ascending {
body(node, slot!)
for i in (0 ..< _path.count).reversed() {
body(_path[i], _slots[i])
}
}
else {
for i in 0 ..< _path.count {
body(_path[i], _slots[i])
}
body(node, slot!)
}
}
func forEachSlot(ascending: Bool, body: (Int) -> Void) {
if ascending {
body(slot!)
_slots.reversed().forEach(body)
}
else {
_slots.forEach(body)
body(slot!)
}
}
mutating func finish() -> Node {
var childCount = self.node.count
while !_path.isEmpty {
let node = _path.removeLast()
node.count += childCount
childCount = node.count
}
assert(root.count == count)
defer { invalidate() }
return root
}
/// Restore B-tree invariants after a single-element insertion produced an oversize leaf node.
fileprivate mutating func fixupAfterInsert() {
guard node.isTooLarge else { return }
_path.append(self.node)
_slots.append(self.slot!)
// Split nodes on the way to the root until we restore the B-tree's size constraints.
var i = _path.count - 1
while _path[i].isTooLarge {
// Split path[i], which must have correct count.
let left = _path[i]
let slot = _slots[i]
let splinter = left.split()
let right = splinter.node
if slot > left.elements.count {
// Focused element is in the new branch; adjust self accordingly.
_slots[i] = slot - left.elements.count - 1
_path[i] = right
}
else if slot == left.elements.count && i == _path.count - 1 {
// Focused element is the new separator; adjust self accordingly.
_path.removeLast()
_slots.removeLast()
}
if i > 0 {
// Insert splinter into parent node and fix its count field.
let parent = _path[i - 1]
let pslot = _slots[i - 1]
parent.insert(splinter, inSlot: pslot)
parent.count += left.count + right.count + 1
if slot > left.elements.count {
// Focused element is in the new branch; update parent slot accordingly.
_slots[i - 1] = pslot + 1
}
i -= 1
}
else {
// Create new root node.
self.root = BTreeNode<Key, Value>(left: left, separator: splinter.separator, right: right)
_path.insert(self.root, at: 0)
_slots.insert(slot > left.elements.count ? 1 : 0, at: 0)
}
}
// Size constraints are now OK, but counts on path have become valid, so we need to restore
// cursor state by subtracting focused children.
while i < _path.count - 1 {
_path[i].count -= _path[i + 1].count
i += 1
}
node = _path.removeLast()
slot = _slots.removeLast()
}
}
/// A stateful editing interface for efficiently inserting/removing/updating a range of elements in a B-tree.
///
/// Creating a cursor over a tree takes exclusive ownership of it; the tree is in a transient invalid state
/// while the cursor is active. (In particular, element counts are not finalized until the cursor is deactivated.)
///
/// The cursor always focuses on a particular spot on the tree: either a particular element, or the empty spot after
/// the last element. There are methods to move the cursor to the next or previous element, to modify the currently
/// focused element, to insert a new element before the current position, and to remove the currently focused element
/// from the tree.
///
/// Note that the cursor does not verify that keys you insert/modify uphold tree invariants -- it is your responsibility
/// to guarantee keys remain in ascending order while you're working with the cursor.
///
/// Creating a cursor takes O(log(*n*)) steps; once the cursor has been created, the complexity of most manipulations
/// is amortized O(1). For example, appending *k* new elements without a cursor takes O(*k* * log(*n*)) steps;
/// using a cursor to do the same only takes O(log(*n*) + *k*).
public final class BTreeCursor<Key: Comparable, Value> {
public typealias Element = (Key, Value)
public typealias Tree = BTree<Key, Value>
internal typealias Node = BTreeNode<Key, Value>
internal typealias State = BTreeCursorPath<Key, Value>
fileprivate var state: State
/// The number of elements in the tree currently being edited.
public var count: Int { return state.count }
/// The offset of the currently focused element in the tree.
///
/// - Complexity: O(1) for the getter, O(log(`count`)) for the setter.
public var offset: Int {
get {
return state.offset
}
set {
state.move(toOffset: newValue)
}
}
//MARK: Simple properties
/// Return true iff this is a valid cursor.
internal var isValid: Bool { return state.isValid }
/// Return true iff the cursor is focused on the initial element.
public var isAtStart: Bool { return state.isAtStart }
/// Return true iff the cursor is focused on the spot beyond the last element.
public var isAtEnd: Bool { return state.isAtEnd }
//MARK: Initializers
internal init(_ state: BTreeCursorPath<Key, Value>) {
self.state = state
}
//MARK: Finishing
/// Finalize editing the tree and return it, deactivating this cursor.
/// You'll need to create a new cursor to continue editing the tree.
///
/// - Complexity: O(log(`count`))
internal func finish() -> Node {
return state.finish()
}
//MARK: Navigation
/// Position the cursor on the next element in the B-tree.
///
/// - Requires: `!isAtEnd`
/// - Complexity: Amortized O(1)
public func moveForward() {
state.moveForward()
}
/// Position this cursor on the previous element in the B-tree.
///
/// - Requires: `!isAtStart`
/// - Complexity: Amortized O(1)
public func moveBackward() {
state.moveBackward()
}
/// Position this cursor on the start of the B-tree.
///
/// - Complexity: O(log(`offset`))
public func moveToStart() {
state.moveToStart()
}
/// Position this cursor on the end of the B-tree, i.e., at the offset after the last element.
///
/// - Complexity: O(log(`count` - `offset`))
public func moveToEnd() {
state.moveToEnd()
}
/// Move this cursor to the specified offset in the B-tree.
///
/// - Complexity: O(log(*distance*)), where *distance* is the absolute difference between the desired and current
/// offsets.
public func move(toOffset offset: Int) {
state.move(toOffset: offset)
}
/// Move this cursor to an element with the specified key.
/// If there are no such elements, the cursor is moved to the first element after `key` (or at the end of tree).
/// If there are multiple such elements, `selector` specifies which one to find.
///
/// - Complexity: O(log(`count`))
public func move(to key: Key, choosing selector: BTreeKeySelector = .any) {
state.move(to: key, choosing: selector)
}
//MARK: Editing
/// Get or replace the currently focused element.
///
/// - Warning: Changing the key is potentially dangerous; it is the caller's responsibility to ensure that
/// keys remain in ascending order. This is not verified at runtime.
/// - Complexity: O(1)
public var element: Element {
get { return state.element }
set { state.element = newValue }
}
/// Get or set the key of the currently focused element.
///
/// - Warning: Changing the key is potentially dangerous; it is the caller's responsibility to ensure that
/// keys remain in ascending order. This is not verified at runtime.
/// - Complexity: O(1)
public var key: Key {
get { return state.key }
set { state.key = newValue }
}
/// Get or set the value of the currently focused element.
///
/// - Complexity: O(1)
public var value: Value {
get { return state.value }
set { state.value = newValue }
}
/// Update the value stored at the cursor's current position and return the previous value.
/// This method does not change the cursor's position.
///
/// - Complexity: O(1)
public func setValue(_ value: Value) -> Value {
return state.setValue(value)
}
/// Insert a new element after the cursor's current position, and position the cursor on the new element.
///
/// - Complexity: amortized O(1)
public func insertAfter(_ element: Element) {
precondition(!self.isAtEnd)
state.count += 1
if state.node.isLeaf {
let slot = state.slot!
state.node.insert(element, inSlot: slot + 1)
state.slot = slot + 1
state.offset += 1
}
else {
moveForward()
assert(state.node.isLeaf && state.slot == 0)
state.node.insert(element, inSlot: 0)
}
state.fixupAfterInsert()
}
/// Insert a new element at the cursor's current offset, and leave the cursor positioned on the original element.
///
/// - Complexity: amortized O(1)
public func insert(_ element: Element) {
precondition(self.isValid)
state.count += 1
if state.node.isLeaf {
state.node.insert(element, inSlot: state.slot!)
}
else {
moveBackward()
assert(state.node.isLeaf && state.slot == state.node.elements.count - 1)
state.node.append(element)
state.slot = state.node.elements.count - 1
state.offset += 1
}
state.fixupAfterInsert()
moveForward()
}
/// Insert the contents of `tree` before the currently focused element, keeping the cursor's position on it.
///
/// - Complexity: O(log(`count + tree.count`))
public func insert(_ tree: Tree) {
insert(tree.root)
}
/// Insert the contents of `node` before the currently focused element, keeping the cursor's position on it.
///
/// - Complexity: O(log(`count + node.count`))
internal func insert(_ node: Node) {
insertWithoutCloning(node.clone())
}
/// Insert all elements in a sequence before the currently focused element, keeping the cursor's position on it.
///
/// - Requires: `self.isValid` and `elements` is sorted by key.
/// - Complexity: O(log(`count`) + *c*), where *c* is the number of elements in the sequence.
public func insert<S: Sequence>(_ elements: S) where S.Element == Element {
insertWithoutCloning(BTree(sortedElements: elements).root)
}
internal func insertWithoutCloning(_ root: Node) {
precondition(isValid)
let c = root.count
if c == 0 { return }
if c == 1 {
insert(root.elements[0])
return
}
if self.count == 0 {
state = State(endOf: root)
return
}
let offset = self.offset
if offset == self.count {
// Append
moveBackward()
let separator = remove()
let j = Node.join(left: finish(), separator: separator, right: root)
state = State(endOf: j)
}
else if offset == 0 {
// Prepend
let separator = remove()
let j = Node.join(left: root, separator: separator, right: finish())
state = State(root: j, offset: offset + c)
}
else {
// Insert in middle
moveBackward()
let sep1 = remove()
let (prefix, sep2, suffix) = state.split()
state.invalidate()
let t1 = Node.join(left: prefix.root, separator: sep1, right: root)
let t2 = Node.join(left: t1, separator: sep2, right: suffix.root)
state = State(root: t2, offset: offset + c)
}
}
/// Remove and return the element at the cursor's current position, and position the cursor on its successor.
///
/// - Complexity: O(log(`count`))
@discardableResult
public func remove() -> Element {
precondition(!isAtEnd)
let result = state.element
if !state.node.isLeaf {
// For internal nodes, remove the (leaf) predecessor instead, then put it back in place of the element
// that we actually want to remove.
moveBackward()
let surrogate = remove()
self.key = surrogate.0
self.value = surrogate.1
moveForward()
return result
}
let targetOffset = self.offset
state.node.elements.remove(at: state.slot!)
state.node.count -= 1
state.count -= 1
state.popFromSlots()
while state.node !== state.root && state.node.isTooSmall {
state.popFromPath()
let slot = state.slot!
state.popFromSlots()
state.node.fixDeficiency(slot)
}
while targetOffset != count && targetOffset == self.offset && state.node !== state.root {
state.popFromPath()
state.popFromSlots()
}
if state.node === state.root && state.node.elements.count == 0 && state.node.children.count == 1 {
assert(state.length == 1 && state.slot == nil)
state.root = state.node.makeChildUnique(0)
state.node = state.root
}
state.descend(toOffset: targetOffset)
return result
}
/// Remove `n` elements starting at the cursor's current position, and position the cursor on the successor of
/// the last element that was removed.
///
/// - Complexity: O(log(`count`))
public func remove(_ n: Int) {
precondition(isValid && n >= 0 && self.offset + n <= count)
if n == 0 { return }
if n == 1 { remove(); return }
if n == count { removeAll(); return }
let offset = self.offset
if offset == 0 {
state.move(toOffset: n - 1)
state = State(startOf: state.suffix().root)
}
else if offset == count - n {
state = State(endOf: state.prefix().root)
}
else {
let left = state.prefix()
state.move(toOffset: offset + n)
let separator = state.element
let right = state.suffix()
state.invalidate()
let j = Node.join(left: left.root, separator: separator, right: right.root)
state = State(root: j, offset: offset)
}
}
/// Remove all elements.
///
/// - Complexity: O(log(`count`)) if nodes of this tree are shared with other trees; O(`count`) otherwise.
public func removeAll() {
state = State(startOf: Node(order: state.root.order))
}
/// Remove all elements before (and if `inclusive` is true, including) the current position, and
/// position the cursor at the start of the remaining tree.
///
/// - Complexity: O(log(`count`)) if nodes of this tree are shared with other trees; O(`count`) otherwise.
public func removeAllBefore(includingCurrent inclusive: Bool) {
if isAtEnd {
assert(!inclusive)
removeAll()
return
}
if !inclusive {
if isAtStart {
return
}
moveBackward()
}
state = State(startOf: state.suffix().root)
}
/// Remove all elements before (and if `inclusive` is true, including) the current position, and
/// position the cursor on the end of the remaining tree.
///
/// - Complexity: O(log(`count`)) if nodes of this tree are shared with other trees; O(`count`) otherwise.
public func removeAllAfter(includingCurrent inclusive: Bool) {
if isAtEnd {
assert(!inclusive)
return
}
if !inclusive {
moveForward()
if isAtEnd {
return
}
}
if isAtStart {
removeAll()
return
}
state = State(endOf: state.prefix().root)
}
/// Extract `n` elements starting at the cursor's current position, and position the cursor on the successor of
/// the last element that was removed.
///
/// - Returns: The extracted elements as a new B-tree.
/// - Complexity: O(log(`count`))
public func extract(_ n: Int) -> Tree {
precondition(isValid && n >= 0 && self.offset + n <= count)
if n == 0 {
return Tree(order: state.root.order)
}
if n == 1 {
let element = remove()
var tree = Tree(order: state.root.order)
tree.insert(element)
return tree
}
if n == count {
let node = state.finish()
state = State(startOf: Node(order: node.order))
return Tree(node)
}
let offset = self.offset
if offset == count - n {
var split = state.split()
state = State(root: split.prefix.root, offset: offset)
split.suffix.insert(split.separator, atOffset: 0)
return split.suffix
}
let (left, sep1, tail) = state.split()
state = State(root: tail.root, offset: n - 1)
var (mid, sep2, right) = state.split()
state.invalidate()
let j = Node.join(left: left.root, separator: sep2, right: right.root)
state = State(root: j, offset: offset)
mid.insert(sep1, atOffset: 0)
return mid
}
}
| 3841cd388ea15557ac4911e8a179bdd5 | 35.395745 | 142 | 0.587825 | false | false | false | false |
firebase/SwiftLint | refs/heads/master | Source/SwiftLintFramework/Rules/OverriddenSuperCallRule.swift | mit | 2 | //
// OverriddenSuperCallRule.swift
// SwiftLint
//
// Created by Angel Garcia on 04/09/16.
// Copyright © 2016 Realm. All rights reserved.
//
import SourceKittenFramework
public struct OverriddenSuperCallRule: ConfigurationProviderRule, ASTRule, OptInRule {
public var configuration = OverridenSuperCallConfiguration()
public init() {}
public static let description = RuleDescription(
identifier: "overridden_super_call",
name: "Overridden methods call super",
description: "Some overridden methods should always call super",
nonTriggeringExamples: [
"class VC: UIViewController {\n" +
"\toverride func viewWillAppear(_ animated: Bool) {\n" +
"\t\tsuper.viewWillAppear(animated)\n" +
"\t}\n" +
"}\n",
"class VC: UIViewController {\n" +
"\toverride func viewWillAppear(_ animated: Bool) {\n" +
"\t\tself.method1()\n" +
"\t\tsuper.viewWillAppear(animated)\n" +
"\t\tself.method2()\n" +
"\t}\n" +
"}\n",
"class VC: UIViewController {\n" +
"\toverride func loadView() {\n" +
"\t}\n" +
"}\n",
"class Some {\n" +
"\tfunc viewWillAppear(_ animated: Bool) {\n" +
"\t}\n" +
"}\n",
"class VC: UIViewController {\n" +
"\toverride func viewDidLoad() {\n" +
"\t\tdefer {\n" +
"\t\t\tsuper.viewDidLoad()\n" +
"\t\t}\n" +
"\t}\n" +
"}\n"
],
triggeringExamples: [
"class VC: UIViewController {\n" +
"\toverride func viewWillAppear(_ animated: Bool) {↓\n" +
"\t\t//Not calling to super\n" +
"\t\tself.method()\n" +
"\t}\n" +
"}\n",
"class VC: UIViewController {\n" +
"\toverride func viewWillAppear(_ animated: Bool) {↓\n" +
"\t\tsuper.viewWillAppear(animated)\n" +
"\t\t//Other code\n" +
"\t\tsuper.viewWillAppear(animated)\n" +
"\t}\n" +
"}\n",
"class VC: UIViewController {\n" +
"\toverride func didReceiveMemoryWarning() {↓\n" +
"\t}\n" +
"}\n"
]
)
public func validate(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard let offset = dictionary.bodyOffset,
let name = dictionary.name,
kind == .functionMethodInstance,
configuration.resolvedMethodNames.contains(name),
dictionary.enclosedSwiftAttributes.contains("source.decl.attribute.override")
else { return [] }
let callsToSuper = dictionary.extractCallsToSuper(methodName: name)
if callsToSuper.isEmpty {
return [StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset),
reason: "Method '\(name)' should call to super function")]
} else if callsToSuper.count > 1 {
return [StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, byteOffset: offset),
reason: "Method '\(name)' should call to super only once")]
}
return []
}
}
| f2e3e4ba557dda5f719265955ac2babf | 38.404255 | 92 | 0.514579 | false | true | false | false |
xcode-coffee/JSONFeed | refs/heads/master | Sources/JSONFeed/JSONFeed+Validation.swift | mit | 1 | //
// JSONFeed+Validation.swift
// JSONFeed
//
// Created by Phillip Harris on 6/27/17.
//
import Foundation
public extension JSONFeed {
public enum Violation {
case missingParameter(String)
case atLeastOnePropertyMustBePresent(Author)
case atLeastOneContentPropertyMustBePresent(Item)
case nextUrlMustNotBeTheSameAsFeedUrl
}
public func validate() -> [Violation] {
var violations = [Violation]()
if version == nil { violations.append(.missingParameter("version")) }
if title == nil { violations.append(.missingParameter("title")) }
if let author = author {
violations.append(contentsOf: author.validate())
}
if let items = items {
violations.append(contentsOf: (items.flatMap { $0.validate() }) )
} else {
violations.append(.missingParameter("items"))
}
if let hubs = hubs {
violations.append(contentsOf: (hubs.flatMap { $0.validate() }) )
}
if let nextUrl = nextUrl, let feedUrl = feedUrl, nextUrl == feedUrl {
violations.append(.nextUrlMustNotBeTheSameAsFeedUrl)
}
return violations
}
}
public extension JSONFeed.Item {
public func validate() -> [JSONFeed.Violation] {
var violations = Array<JSONFeed.Violation>()
if contentHtml == nil && contentText == nil {
violations.append(.atLeastOneContentPropertyMustBePresent(self))
}
if let author = author {
violations.append(contentsOf: author.validate())
}
if let attachments = attachments {
violations.append(contentsOf: (attachments.flatMap { $0.validate() }) )
}
return violations
}
}
public extension JSONFeed.Author {
public func validate() -> [JSONFeed.Violation] {
if name == nil && url == nil && avatar == nil {
return [.atLeastOnePropertyMustBePresent(self)]
} else {
return []
}
}
}
public extension JSONFeed.Item.Attachment {
public func validate() -> [JSONFeed.Violation] {
var violations = Array<JSONFeed.Violation>()
if url == nil { violations.append(.missingParameter("url")) }
if mimeType == nil { violations.append(.missingParameter("mimeType")) }
return violations
}
}
public extension JSONFeed.Hub {
public func validate() -> [JSONFeed.Violation] {
var violations = Array<JSONFeed.Violation>()
if type == nil { violations.append(.missingParameter("type")) }
if url == nil { violations.append(.missingParameter("url")) }
return violations
}
}
| 3b8ff9e3c34f03bc31f6ea78bd588ff5 | 26.132075 | 83 | 0.57128 | false | false | false | false |
oarrabi/RangeSliderView | refs/heads/master | Pod/Classes/SliderKnobViewiOS.swift | mit | 1 | //
// SliderKnobViewiOS.swift
// Pods
//
// Created by Omar Abdelhafith on 07/02/2016.
//
//
#if os(iOS)
import UIKit
class SliderKnobView: UIView {
var boundRange: BoundRange = BoundRange.emptyRange {
didSet {
setNeedsDisplay()
}
}
var knobFrame: CGRect {
get {
return knobView.frame
}
set {
knobView.frame = SliderKnobViewImpl.adjustKnobFrame(newValue, viewFrame: self.frame, boundRange: boundRange)
}
}
var knobView: KnobView!
var knobMovementCallback : (CGRect -> ())?
init() {
super.init(frame: CGRectZero)
commonInit()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
commonInit()
}
func commonInit() {
knobView = KnobView()
knobView.frame = CGRectMake(0, 0, 30, 30)
self.addSubview(knobView)
}
override func hitTest(point: CGPoint, withEvent event: UIEvent?) -> UIView? {
let isIn = CGRectContainsPoint(knobView.frame, point)
return isIn ? knobView : nil
}
var draggingPoint: CGFloat = 0
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
let pointInKnob = touches.first!.locationInView(knobView)
draggingPoint = RectUtil.pointHorizontalDistanceFromCenter(forRect: knobFrame, point: pointInKnob)
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
let point = touches.first!.locationInView(self)
knobFrame =
knobFrame
|> RectUtil.updateRectHorizontalCenter(xCenter: point.x)
|> RectUtil.moveRect(toLeft: draggingPoint)
knobMovementCallback?(knobView.frame)
}
}
extension SliderKnobView: SliderKnob {
var view: SliderKnobView { return self }
}
#endif
| 1c7b973f74384737cf70d29e38e18014 | 22.575 | 116 | 0.61877 | false | false | false | false |
wanliming11/MurlocAlgorithms | refs/heads/master | Last/Algorithms/插入排序/insertionSort/insertionSort/InsertionSort.swift | mit | 1 | //
// Created by FlyingPuPu on 02/12/2016.
// Copyright (c) 2016 ___FULLUSERNAME___. All rights reserved.
//
import Foundation
public class InsertionSort<T> {
public var sortArray: [T] = [T]()
public func swapSorted(_ sort: (T, T) -> Bool) -> [T] {
guard sortArray.count > 1 else {
return sortArray
}
for x in 1 ..< sortArray.count {
var y = x
//不断的同以前的一个数进行对比,如果满足反向输入条件情况则交换,直到到达最左边。
//简单的说,不满足条件就交换,但是是拿不满足的情况冒泡了一把
while y > 0 && sort(sortArray[y], sortArray[y - 1]) {
swap(&sortArray[y], &sortArray[y - 1])
y -= 1
}
}
return sortArray
}
public func moveSorted(_ sort: (T, T) -> Bool) -> [T] {
guard sortArray.count > 1 else {
return sortArray
}
for x in 1 ..< sortArray.count {
var y = x
let temp = sortArray[x]
//拿temp与前面的数比较,如果发现满足条件,则继续前移,直到找到不满足的情况
//例如2,1, ----- 4 , 比较条件是> ,则1,4
while y > 0 && sort(temp, sortArray[y - 1]) {
sortArray[y] = sortArray[y - 1]
y -= 1
}
sortArray[y] = temp
}
return sortArray
}
}
| e0b3e3bb6433c82214b6ab4e8edc710d | 26.326087 | 65 | 0.481305 | false | false | false | false |
ali-rantakari/Punos | refs/heads/master | Sources/PunosHTTPServer.swift | mit | 1 | //
// PunosHTTPServer.swift
// Punos
//
// Created by Ali Rantakari on 13.2.16.
// Copyright © 2016 Ali Rantakari. All rights reserved.
//
// This implementation is based on:
// Swifter by Damian Kołakowski -- https://github.com/glock45/swifter
// GCDWebServer by Pierre-Olivier Latour -- https://github.com/swisspol/GCDWebServer
//
import Foundation
typealias Logger = (String) -> Void
class PunosHTTPServer {
let queue: DispatchQueue
private let log: Logger
init(queue: DispatchQueue, logger: @escaping Logger = { _ in }) {
self.log = logger
self.queue = queue
}
private var sourceGroup: DispatchGroup?
private var dispatchSource: DispatchSourceProtocol?
private var clientSockets: Set<Socket> = []
private let clientSocketsLock = NSLock()
private func createDispatchSource(_ listeningSocket: Socket) -> DispatchSourceProtocol? {
guard let sourceGroup = sourceGroup else { return nil }
let listeningSocketFD = listeningSocket.socketFileDescriptor
sourceGroup.enter()
let source = DispatchSource.makeReadSource(fileDescriptor: listeningSocketFD, queue: queue)
source.setCancelHandler {
do {
try Socket.release(listeningSocketFD)
self.log("Closed listening socket \(listeningSocketFD)")
} catch (let error) {
self.log("Failed to close listening socket \(listeningSocketFD): \(error)")
}
sourceGroup.leave()
}
source.setEventHandler {
autoreleasepool {
do {
let clientSocket = try listeningSocket.acceptClientSocket()
self.clientSocketsLock.with {
self.clientSockets.insert(clientSocket)
}
self.queue.async {
self.handleConnection(clientSocket) {
_ = self.clientSocketsLock.with {
self.clientSockets.remove(clientSocket)
}
}
}
} catch let error {
self.log("Failed to accept socket. Error: \(error)")
}
}
}
log("Started dispatch source for listening socket \(listeningSocketFD)")
return source
}
private(set) var port: in_port_t?
func start(portsToTry: [in_port_t]) throws {
if dispatchSource != nil {
throw punosError(0, "Already running")
}
var maybeSocket: Socket? = nil
for port in portsToTry {
log("Attempting to bind to port \(port)")
do {
maybeSocket = try Socket.tcpSocketForListen(port)
} catch let error {
if case SocketError.bindFailedAddressAlreadyInUse(_) = error {
log("Could not bind to port \(port)")
continue
}
throw error
}
log("Assigning port \(port)")
self.port = port
break
}
guard let socket = maybeSocket else {
throw punosError(0, "Could not bind to any given port")
}
sourceGroup = DispatchGroup()
dispatchSource = createDispatchSource(socket)
guard let source = dispatchSource else {
throw punosError(0, "Could not create dispatch source")
}
source.resume()
}
func stop() {
guard let source = dispatchSource, let group = sourceGroup else {
return
}
log("Stopping server at port \(port ?? 0)")
// These properties are our implicit "are we running" state:
//
dispatchSource = nil
sourceGroup = nil
// Shut down all the client sockets, so that our dispatch
// source can be cancelled:
//
for socket in clientSockets {
socket.shutdown()
}
clientSockets.removeAll(keepingCapacity: true)
// Cancel the main listening socket dispatch source (the
// cancellation handler is responsible for closing the
// socket):
//
source.cancel()
// Wait until the cancellation handler has been called, which
// guarantees that the listening socket is closed:
//
_ = group.wait(timeout: DispatchTime.distantFuture)
port = nil
}
var responder: ((HTTPRequest, @escaping (HttpResponse) -> Void) -> Void)?
var defaultResponse = HttpResponse(200, nil, nil)
private func respondToRequestAsync(_ request: HTTPRequest, responseCallback: @escaping (HttpResponse) -> Void) {
if let responder = responder {
responder(request, responseCallback)
} else {
responseCallback(defaultResponse)
}
}
private func handleConnection(_ socket: Socket, doneCallback: @escaping () -> Void) {
guard let request = try? readHttpRequest(socket) else {
socket.releaseIgnoringErrors()
doneCallback()
return
}
respondToRequestAsync(request) { response in
do {
_ = try self.respond(socket, response: response, keepAlive: false)
} catch {
self.log("Failed to send response: \(error)")
}
socket.releaseIgnoringErrors()
doneCallback()
}
}
private struct InnerWriteContext: HttpResponseBodyWriter {
let socket: Socket
let log: Logger
func write(_ data: [UInt8]) {
do {
try socket.writeUInt8(data)
} catch {
log("Error writing to socket \(socket.socketFileDescriptor): \(error)")
}
}
}
private func respond(_ socket: Socket, response: HttpResponse, keepAlive: Bool) throws -> Bool {
try socket.writeUTF8AndCRLF("HTTP/1.1 \(response.statusCode) \(response.reasonPhrase)")
let content = response.content
if 0 <= content.length {
try socket.writeUTF8AndCRLF("Content-Length: \(content.length)")
}
let respondKeepAlive = keepAlive && content.length != -1
if !response.headers.contains(name: "Connection") { // Allow the response to override this
if respondKeepAlive {
try socket.writeUTF8AndCRLF("Connection: keep-alive")
} else {
try socket.writeUTF8AndCRLF("Connection: close")
}
}
for (name, value) in response.headers.pairs {
try socket.writeUTF8AndCRLF("\(name): \(value)")
}
try socket.writeUTF8AndCRLF("")
if let writeClosure = content.write {
let context = InnerWriteContext(socket: socket, log: log)
try writeClosure(context)
}
return respondKeepAlive
}
}
| c0448891fcc3a20baf1be6240eaede84 | 32.054795 | 116 | 0.547589 | false | false | false | false |
bkmunar/firefox-ios | refs/heads/master | Client/Frontend/Widgets/SiteTableViewController.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Storage
struct SiteTableViewControllerUX {
static let HeaderHeight = CGFloat(25)
static let RowHeight = CGFloat(58)
static let HeaderBorderColor = UIColor(rgb: 0xCFD5D9).colorWithAlphaComponent(0.8)
static let HeaderTextColor = UIColor(rgb: 0x232323)
static let HeaderBackgroundColor = UIColor(rgb: 0xECF0F3).colorWithAlphaComponent(0.3)
}
private class SiteTableViewHeader : UITableViewHeaderFooterView {
// I can't get drawRect to play nicely with the glass background. As a fallback
// we just use views for the top and bottom borders.
let topBorder = UIView()
let bottomBorder = UIView()
override init(frame: CGRect) {
super.init(frame: frame)
didLoad()
}
override init(reuseIdentifier: String?) {
super.init(reuseIdentifier: reuseIdentifier)
}
private func didLoad() {
addSubview(topBorder)
addSubview(bottomBorder)
backgroundView = UIVisualEffectView(effect: UIBlurEffect(style: .ExtraLight))
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
topBorder.frame = CGRect(x: 0, y: -0.5, width: frame.width, height: 0.5)
bottomBorder.frame = CGRect(x: 0, y: frame.height, width: frame.width, height: 0.5)
topBorder.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
bottomBorder.backgroundColor = SiteTableViewControllerUX.HeaderBorderColor
super.layoutSubviews()
textLabel.font = UIFont(name: UIAccessibilityIsBoldTextEnabled() ? "HelveticaNeue-Bold" : "HelveticaNeue-Medium", size: 11)
textLabel.textColor = UIAccessibilityDarkerSystemColorsEnabled() ? UIColor.blackColor() : SiteTableViewControllerUX.HeaderTextColor
textLabel.textAlignment = .Center
contentView.backgroundColor = SiteTableViewControllerUX.HeaderBackgroundColor
}
}
/**
* Provides base shared functionality for site rows and headers.
*/
class SiteTableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private let CellIdentifier = "CellIdentifier"
private let HeaderIdentifier = "HeaderIdentifier"
var profile: Profile! {
didSet {
reloadData()
}
}
var data: Cursor<Site> = Cursor<Site>(status: .Success, msg: "No data set")
var tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(tableView)
tableView.snp_makeConstraints { make in
make.edges.equalTo(self.view)
return
}
tableView.delegate = self
tableView.dataSource = self
tableView.registerClass(TwoLineTableViewCell.self, forCellReuseIdentifier: CellIdentifier)
tableView.registerClass(SiteTableViewHeader.self, forHeaderFooterViewReuseIdentifier: HeaderIdentifier)
tableView.layoutMargins = UIEdgeInsetsZero
tableView.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
tableView.backgroundColor = AppConstants.PanelBackgroundColor
tableView.separatorColor = AppConstants.SeparatorColor
tableView.accessibilityIdentifier = "SiteTable"
// Set an empty footer to prevent empty cells from appearing in the list.
tableView.tableFooterView = UIView()
}
func reloadData() {
if data.status != .Success {
println("Err: \(data.statusMessage)")
} else {
self.tableView.reloadData()
}
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return data.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
return tableView.dequeueReusableCellWithIdentifier(CellIdentifier) as! UITableViewCell
// Callers should override this to fill in the cell returned here
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return tableView.dequeueReusableHeaderFooterViewWithIdentifier(HeaderIdentifier) as? UIView
// Callers should override this to fill in the cell returned here
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return SiteTableViewControllerUX.HeaderHeight
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return SiteTableViewControllerUX.RowHeight
}
}
| ba21488a2290c734d290d4397351132a | 38.479339 | 139 | 0.711116 | false | false | false | false |
randymarsh77/crystal | refs/heads/master | Sources/Crystal/utility.swift | mit | 1 | import Foundation
import AudioToolbox
public class Utility
{
public static func GetDefaultInputDeviceSampleRate() -> (OSStatus, Float64)
{
var sampleRate = 0
#if TARGET_OS_MAC
var propertySize = UInt32(sizeof(AudioDeviceID))
var propertyAddress = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDefaultInputDevice,
mScope: kAudioObjectPropertyScopeGlobal,
mElement: 0)
let propertyAddressPointer = UnsafeMutablePointer<AudioObjectPropertyAddress>.alloc(1)
propertyAddressPointer.initialize(propertyAddress)
let deviceIdPointer = UnsafeMutablePointer<AudioDeviceID>.alloc(1)
deviceIdPointer.initialize(AudioDeviceID(kAudioObjectSystemObject))
let propertySizePointer = UnsafeMutablePointer<UInt32>.alloc(1)
propertySizePointer.initialize(propertySize)
let dataSize: UnsafeMutablePointer<Void> = nil
var error = AudioHardwareServiceGetPropertyData(
deviceIdPointer.memory,
propertyAddressPointer,
0,
dataSize,
propertySizePointer,
deviceIdPointer)
if (error == 0)
{
propertyAddress.mSelector = kAudioDevicePropertyNominalSampleRate
propertyAddress.mScope = kAudioObjectPropertyScopeGlobal
propertyAddress.mElement = 0;
propertySize = UInt32(sizeof(Float64))
propertyAddressPointer.initialize(propertyAddress)
propertySizePointer.initialize(propertySize)
let sampleRatePointer = UnsafeMutablePointer<Float64>.alloc(1)
sampleRatePointer.initialize(sampleRate)
error = AudioHardwareServiceGetPropertyData(
deviceIdPointer.memory,
propertyAddressPointer,
0,
dataSize,
propertySizePointer,
sampleRatePointer);
sampleRate = sampleRatePointer.memory
}
return ( error, sampleRate )
#else
return ( OSStatus(0), 44100 )
#endif
}
public static func ComputeBufferSize(formatPointer: UnsafePointer<AudioStreamBasicDescription>, queue: AudioQueueRef, seconds: Float64) -> UInt32
{
var bytes: UInt32 = 0
let format = formatPointer.pointee
let frames = UInt32(ceil(seconds * format.mSampleRate))
if (format.mBytesPerFrame > 0)
{
bytes = frames * format.mBytesPerFrame
}
else
{
let maxPacketSize = UnsafeMutablePointer<UInt32>.allocate(capacity: 1)
maxPacketSize.initialize(to: format.mBytesPerPacket)
if (format.mBytesPerPacket == 0)
{
let propertyDataSize = UnsafeMutablePointer<UInt32>.allocate(capacity: 1)
propertyDataSize.initialize(to: UInt32(MemoryLayout<UInt32>.size))
AudioQueueGetProperty(queue, kAudioConverterPropertyMaximumOutputPacketSize, maxPacketSize, propertyDataSize)
}
var packets = format.mFramesPerPacket > 0 ?
frames / format.mFramesPerPacket :
frames
packets = packets == 0 ? 1 : packets
bytes = packets * maxPacketSize.pointee
}
return bytes > 6144 ? 6144 : 6144;
}
}
| 8fc7216d9ac103b796543117ad6d1ea1 | 27.783505 | 146 | 0.770774 | false | false | false | false |
HabitRPG/habitrpg-ios | refs/heads/develop | HabitRPG/TableViewDataSources/TodoTableViewDataSource.swift | gpl-3.0 | 1 | //
// TodoTableViewDataSource.swift
// Habitica
//
// Created by Phillip Thelen on 07.03.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
class TodoTableViewDataSource: TaskTableViewDataSource {
let dateFormatter = DateFormatter()
init(predicate: NSPredicate) {
super.init(predicate: predicate, taskType: TaskType.todo)
dateFormatter.dateStyle = .medium
dateFormatter.timeStyle = .none
}
override func configure(cell: TaskTableViewCell, indexPath: IndexPath, task: TaskProtocol) {
if let todocell = cell as? ToDoTableViewCell {
todocell.taskDetailLine.dateFormatter = dateFormatter
todocell.checkboxTouched = {[weak self] in
if !task.isValid { return }
self?.scoreTask(task: task, direction: task.completed ? .down : .up, soundEffect: .todoCompleted)
}
todocell.checklistItemTouched = {[weak self] checklistItem in
if !task.isValid { return }
self?.disposable.add(self?.repository.score(checklistItem: checklistItem, task: task).observeCompleted {})
}
todocell.checklistIndicatorTouched = {[weak self] in
if !task.isValid { return }
self?.expandSelectedCell(indexPath: indexPath)
}
}
super.configure(cell: cell, indexPath: indexPath, task: task)
}
override func predicates(filterType: Int) -> [NSPredicate] {
var predicates = super.predicates(filterType: filterType)
switch filterType {
case 0:
predicates.append(NSPredicate(format: "completed == false"))
case 1:
predicates.append(NSPredicate(format: "completed == false && duedate != nil"))
case 2:
predicates.append(NSPredicate(format: "completed == true"))
default:
break
}
return predicates
}
}
| 10c12de127236688f88efff203210fa2 | 34.839286 | 122 | 0.618834 | false | false | false | false |
CanBeMyQueen/DouYuZB | refs/heads/master | DouYu/DouYu/Classes/Main/View/PageTitleView.swift | mit | 1 | //
// PageTitleView.swift
// DouYu
//
// Created by 张萌 on 2017/9/12.
// Copyright © 2017年 JiaYin. All rights reserved.
//
import UIKit
protocol PageTitleViewDelegate : class {
func changePageTitleView(titleView : PageTitleView, selectedIndex index : Int)
}
private let kNormalColor : (CGFloat, CGFloat, CGFloat) = (85/255.0, 85/255.0, 85/255.0)
private let kSelectedColor : (CGFloat, CGFloat, CGFloat) = (255/255.0, 128/255.0, 0/255.0)
private var isForbitScrollDelegate = false
class PageTitleView: UIView {
//定义属性
var titles: [String]
let kScrollLineH : CGFloat = 2
var currentTag : Int = 0
weak var delegate : PageTitleViewDelegate?
let scrollLine : UIView = {
let scrollLine = UIView()
return scrollLine
}()
// 懒加载一个 label 数组,用于存放 title 的 label
lazy var labels : [UILabel] = [UILabel]()
//懒加载属性
lazy var scrollView : UIScrollView = {
let scrollView = UIScrollView()
scrollView.showsHorizontalScrollIndicator = false
scrollView.scrollsToTop = false
scrollView.bounces = false
return scrollView
}()
// 1.自定义一个构造函数
init(frame: CGRect, titles: [String]) {
self.titles = titles
super.init(frame: frame)
//设置 UI 界面
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageTitleView {
public func setupUI() {
// 1.添加 UIScrollView
addSubview(scrollView)
scrollView.frame = bounds
// 2.添加titles对应的label
setupTitlesLabel()
// 3.设置底部线条和滚动滑块
setupBottomLineAndSrcollLine()
}
private func setupTitlesLabel() {
let labelW = frame.width / CGFloat(titles.count)
let labelH = frame.height - kScrollLineH
let labelY = 0
for (index, title) in titles.enumerated() {
let label = UILabel()
label.text = title
label.textAlignment = .center
label.tag = index
label.font = UIFont.systemFont(ofSize: 16.0)
label.textColor = UIColor(red: kNormalColor.0, green: kNormalColor.1, blue: kNormalColor.2, alpha: 1)
let LabelX = labelW * CGFloat(index)
label.frame = CGRect(x: LabelX, y: CGFloat(labelY), width: labelW, height: labelH)
labels.append(label)
scrollView.addSubview(label)
//给 label 添加手势
label.isUserInteractionEnabled = true
let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.titleLabelClick(tapGes:)))
label.addGestureRecognizer(tapGes)
}
}
private func setupBottomLineAndSrcollLine() {
// 添加底部线
let bottomLine = UIView()
let lineH : CGFloat = 0.5
bottomLine.backgroundColor = UIColor.lightGray
bottomLine.frame = CGRect(x: 0, y: frame.height - lineH, width: frame.width, height: lineH)
addSubview(bottomLine)
//添加滚动条
self.scrollLine.backgroundColor = UIColor(red: kSelectedColor.0, green: kSelectedColor.1, blue: kSelectedColor.2, alpha: 1)
// guard swift 语法
guard let firstLabel = labels.first else { return }
firstLabel.textColor = UIColor(red: kSelectedColor.0, green: kSelectedColor.1, blue: kSelectedColor.2, alpha: 1)
scrollLine.frame = CGRect(x: firstLabel.frame.origin.x, y: frame.height - kScrollLineH, width: firstLabel.frame.size.width, height: kScrollLineH)
scrollView.addSubview(scrollLine)
}
}
// 监听 label 的点击事件
extension PageTitleView {
@objc public func titleLabelClick( tapGes : UITapGestureRecognizer) {
print("====");
// 获取当前点击的 label 并设置成选中色
guard let currentLabel = tapGes.view as? UILabel else {return}
currentLabel.textColor = UIColor(red: kSelectedColor.0, green: kSelectedColor.1, blue: kSelectedColor.2, alpha: 1)
// 获取之前选中的 label 并改变颜色
let oldlabel = labels[currentTag] as UILabel
currentTag = currentLabel.tag
oldlabel.textColor = UIColor(red: kNormalColor.0, green: kNormalColor.1, blue: kNormalColor.2, alpha: 1)
// 设置滚动条:
let scrollLineX = CGFloat(currentLabel.tag) * scrollLine.frame.width
UIView.animate(withDuration: 0.15) {
self.scrollLine.frame.origin.x = scrollLineX
}
// 通知代理
delegate?.changePageTitleView(titleView: self, selectedIndex: currentTag)
}
}
// 设置对外暴露的方法
extension PageTitleView {
func setTitleView(progress : CGFloat, currentIndex: Int, targetIndex: Int) {
// 1.获取当前 label 和目标 label
let currentLabel = labels[currentIndex]
let targetLabel = labels[targetIndex]
// 2.处理滑块逻辑
let totalX = targetLabel.frame.origin.x - currentLabel.frame.origin.x
let moveX = totalX * CGFloat(progress)
print("----- \(moveX)")
scrollLine.frame.origin.x = currentLabel.frame.origin.x + moveX
//3.处理文字颜色渐变
//3.1 取出变化范围
let colorDelta = (kSelectedColor.0 - kNormalColor.0, kSelectedColor.1 - kNormalColor.1, kSelectedColor.2 - kNormalColor.2)
currentLabel.textColor = UIColor(red: kSelectedColor.0 - (colorDelta.0 * progress), green: kSelectedColor.1 - colorDelta.1 * progress, blue: kSelectedColor.2 - colorDelta.2 * progress, alpha: 1)
targetLabel.textColor = UIColor(red: kNormalColor.0 + (colorDelta.0 * progress), green: kNormalColor.1 + colorDelta.1 * progress, blue: kNormalColor.2 + colorDelta.2 * progress, alpha: 1)
currentTag = targetIndex
}
}
| 85ebd59e74d5585af0e1a8f3575d526e | 32.318182 | 202 | 0.618179 | false | false | false | false |
dpricha89/DrApp | refs/heads/master | Source/TableCells/MapCell.swift | apache-2.0 | 1 | //
// MapCell.swift
// Venga
//
// Created by David Richards on 7/22/17.
// Copyright © 2017 David Richards. All rights reserved.
//
import UIKit
import MapKit
import SnapKit
open class MapCell: UITableViewCell, MKMapViewDelegate {
let map = MKMapView()
public override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// Setup the delegate
self.map.delegate = self
// Make the select color none
self.selectionStyle = .none
self.backgroundColor = .clear
// size the map to the same size as the cell
self.contentView.addSubview(self.map)
self.map.snp.makeConstraints { (make) -> Void in
make.edges.equalTo(self.contentView)
}
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open func addAnnotation(lat: Float, lng: Float) {
let annotation = MKPointAnnotation()
annotation.coordinate.latitude = CLLocationDegrees(lat)
annotation.coordinate.longitude = CLLocationDegrees(lng)
self.map.addAnnotation(annotation)
self.map.showAnnotations(self.map.annotations, animated: true)
}
open func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
if !(annotation is MKPointAnnotation) {
return nil
}
var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: "demo")
if annotationView == nil {
annotationView = MKAnnotationView(annotation: annotation, reuseIdentifier: "demo")
annotationView!.canShowCallout = true
}
else {
annotationView!.annotation = annotation
}
// Add custom annotation
if let annotationView = annotationView {
//annotationView.image = UIImage.fontAwesomeIcon(name: .mapMarker, textColor: FlatMint(), size: CGSize(width: 50, height: 50))
}
return annotationView
}
}
| 6b0cd0a44368a8f997c44f0208a4425c | 31.119403 | 138 | 0.637082 | false | false | false | false |
zskyfly/bootcamp-github | refs/heads/master | GithubDemo/RepoResultsViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// GithubDemo
//
// Created by Nhan Nguyen on 5/12/15.
// Copyright (c) 2015 codepath. All rights reserved.
//
import UIKit
import MBProgressHUD
// Main ViewController
class RepoResultsViewController: UIViewController, UITableViewDelegate {
@IBOutlet weak var repoResultsTableView: UITableView!
var searchBar: UISearchBar!
var searchSettings = GithubRepoSearchSettings()
var repos: [GithubRepo]!
override func viewDidLoad() {
super.viewDidLoad()
repoResultsTableView.delegate = self
repoResultsTableView.dataSource = self
repoResultsTableView.estimatedRowHeight = 170
repoResultsTableView.rowHeight = UITableViewAutomaticDimension
// Initialize the UISearchBar
searchBar = UISearchBar()
searchBar.delegate = self
// Add SearchBar to the NavigationBar
searchBar.sizeToFit()
navigationItem.titleView = searchBar
// Perform the first search when the view controller first loads
doSearch()
}
// Perform the search.
private func doSearch() {
MBProgressHUD.showHUDAddedTo(self.view, animated: true)
// Perform request to GitHub API to get the list of repositories
GithubRepo.fetchRepos(searchSettings, successCallback: { (newRepos) in
// Print the returned repositories to the output window
for repo in newRepos {
print(repo)
}
self.repos = newRepos
self.repoResultsTableView.reloadData()
MBProgressHUD.hideHUDForView(self.view, animated: true)
}, error: { (error) -> Void in
print(error)
})
}
}
// SearchBar methods
extension RepoResultsViewController: UISearchBarDelegate {
func searchBarShouldBeginEditing(searchBar: UISearchBar) -> Bool {
searchBar.setShowsCancelButton(true, animated: true)
return true;
}
func searchBarShouldEndEditing(searchBar: UISearchBar) -> Bool {
searchBar.setShowsCancelButton(false, animated: true)
return true;
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
searchBar.text = ""
searchBar.resignFirstResponder()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchSettings.searchString = searchBar.text
searchBar.resignFirstResponder()
doSearch()
}
}
extension RepoResultsViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let repos = self.repos {
return repos.count
} else {
return 0
}
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("RepoResultTableViewCell", forIndexPath: indexPath) as! RepoResultTableViewCell
cell.githubRepo = self.repos[indexPath.row]
return cell
}
} | 9482c7f84bdd0a86108d0b53002aab48 | 28.423077 | 142 | 0.67375 | false | false | false | false |
GraphQLSwift/Graphiti | refs/heads/main | Sources/Graphiti/Enum/Enum.swift | mit | 1 | import GraphQL
public final class Enum<
Resolver,
Context,
EnumType: Encodable & RawRepresentable
>: Component<
Resolver,
Context
> where EnumType.RawValue == String {
private let values: [Value<EnumType>]
override func update(typeProvider: SchemaTypeProvider, coders _: Coders) throws {
let enumType = try GraphQLEnumType(
name: name,
description: description,
values: values.reduce(into: [:]) { result, value in
result[value.value.rawValue] = GraphQLEnumValue(
value: try MapEncoder().encode(value.value),
description: value.description,
deprecationReason: value.deprecationReason
)
}
)
try typeProvider.map(EnumType.self, to: enumType)
typeProvider.types.append(enumType)
}
private init(
type _: EnumType.Type,
name: String?,
values: [Value<EnumType>]
) {
self.values = values
super.init(name: name ?? Reflection.name(for: EnumType.self))
}
}
public extension Enum {
convenience init(
_ type: EnumType.Type,
as name: String? = nil,
@ValueBuilder<EnumType> _ values: () -> Value<EnumType>
) {
self.init(type: type, name: name, values: [values()])
}
convenience init(
_ type: EnumType.Type,
as name: String? = nil,
@ValueBuilder<EnumType> _ values: () -> [Value<EnumType>]
) {
self.init(type: type, name: name, values: values())
}
}
| 3bfee5f1ce8e4edddcbaa27fac847d88 | 27.285714 | 85 | 0.575126 | false | false | false | false |
apple/swift-corelibs-foundation | refs/heads/main | Sources/Foundation/NSCFArray.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
@_implementationOnly import CoreFoundation
internal final class _NSCFArray : NSMutableArray {
deinit {
_CFDeinit(self)
_CFZeroUnsafeIvars(&_storage)
}
required init(coder: NSCoder) {
fatalError()
}
required init(objects: UnsafePointer<AnyObject>?, count cnt: Int) {
fatalError()
}
required public convenience init(arrayLiteral elements: Any...) {
fatalError()
}
override var count: Int {
return CFArrayGetCount(_cfObject)
}
override func object(at index: Int) -> Any {
let value = CFArrayGetValueAtIndex(_cfObject, index)
return __SwiftValue.fetch(nonOptional: unsafeBitCast(value, to: AnyObject.self))
}
override func insert(_ value: Any, at index: Int) {
let anObject = __SwiftValue.store(value)
CFArrayInsertValueAtIndex(_cfMutableObject, index, unsafeBitCast(anObject, to: UnsafeRawPointer.self))
}
override func removeObject(at index: Int) {
CFArrayRemoveValueAtIndex(_cfMutableObject, index)
}
override var classForCoder: AnyClass {
return NSMutableArray.self
}
}
internal func _CFSwiftArrayGetCount(_ array: AnyObject) -> CFIndex {
return (array as! NSArray).count
}
internal func _CFSwiftArrayGetValueAtIndex(_ array: AnyObject, _ index: CFIndex) -> Unmanaged<AnyObject> {
let arr = array as! NSArray
if type(of: array) === NSArray.self || type(of: array) === NSMutableArray.self {
return Unmanaged.passUnretained(arr._storage[index])
} else {
let value = __SwiftValue.store(arr.object(at: index))
let container: NSMutableDictionary
if arr._storage.isEmpty {
container = NSMutableDictionary()
arr._storage.append(container)
} else {
container = arr._storage[0] as! NSMutableDictionary
}
container[NSNumber(value: index)] = value
return Unmanaged.passUnretained(value)
}
}
internal func _CFSwiftArrayGetValues(_ array: AnyObject, _ range: CFRange, _ values: UnsafeMutablePointer<Unmanaged<AnyObject>?>) {
let arr = array as! NSArray
if type(of: array) === NSArray.self || type(of: array) === NSMutableArray.self {
for idx in 0..<range.length {
values[idx] = Unmanaged.passUnretained(arr._storage[idx + range.location])
}
} else {
for idx in 0..<range.length {
let index = idx + range.location
let value = __SwiftValue.store(arr.object(at: index))
let container: NSMutableDictionary
if arr._storage.isEmpty {
container = NSMutableDictionary()
arr._storage.append(container)
} else {
container = arr._storage[0] as! NSMutableDictionary
}
container[NSNumber(value: index)] = value
values[idx] = Unmanaged.passUnretained(value)
}
}
}
internal func _CFSwiftArrayAppendValue(_ array: AnyObject, _ value: AnyObject) {
(array as! NSMutableArray).add(value)
}
internal func _CFSwiftArraySetValueAtIndex(_ array: AnyObject, _ value: AnyObject, _ idx: CFIndex) {
(array as! NSMutableArray).replaceObject(at: idx, with: value)
}
internal func _CFSwiftArrayReplaceValueAtIndex(_ array: AnyObject, _ idx: CFIndex, _ value: AnyObject) {
(array as! NSMutableArray).replaceObject(at: idx, with: value)
}
internal func _CFSwiftArrayInsertValueAtIndex(_ array: AnyObject, _ idx: CFIndex, _ value: AnyObject) {
(array as! NSMutableArray).insert(value, at: idx)
}
internal func _CFSwiftArrayExchangeValuesAtIndices(_ array: AnyObject, _ idx1: CFIndex, _ idx2: CFIndex) {
(array as! NSMutableArray).exchangeObject(at: idx1, withObjectAt: idx2)
}
internal func _CFSwiftArrayRemoveValueAtIndex(_ array: AnyObject, _ idx: CFIndex) {
(array as! NSMutableArray).removeObject(at: idx)
}
internal func _CFSwiftArrayRemoveAllValues(_ array: AnyObject) {
(array as! NSMutableArray).removeAllObjects()
}
internal func _CFSwiftArrayReplaceValues(_ array: AnyObject, _ range: CFRange, _ newValues: UnsafeMutablePointer<Unmanaged<AnyObject>>, _ newCount: CFIndex) {
let buffer: UnsafeBufferPointer<Unmanaged<AnyObject>> = UnsafeBufferPointer(start: newValues, count: newCount)
let replacements = Array(buffer).map { $0.takeUnretainedValue() }
(array as! NSMutableArray).replaceObjects(in: NSRange(location: range.location, length: range.length), withObjectsFrom: replacements)
}
internal func _CFSwiftArrayIsSubclassOfNSMutableArray(_ array: AnyObject) -> _DarwinCompatibleBoolean {
return array is NSMutableArray ? true : false
}
| 5055dde9e4bde138ba7bf1ba5e3fee7a | 36.377778 | 158 | 0.675386 | false | false | false | false |
Ticketmaster/Task | refs/heads/master | Example-iOS/Example-iOS/Controllers/WorkflowViewController.swift | mit | 1 | //
// WorkflowViewController.swift
// Example-iOS
//
// Created by Prachi Gauriar on 8/28/2016.
// Copyright © 2016 Ticketmaster Entertainment, Inc. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Task
import UIKit
class WorkflowViewController : UIViewController, TSKWorkflowDelegate, UITableViewDataSource, UITableViewDelegate {
private static let kTaskCellReuseIdentifier = "TSKTaskViewController.TaskCell"
private let workflow: TSKWorkflow = TSKWorkflow(name: "Order Product Workflow")
private var tasks: [TSKTask] = []
private var taskStateObservers: [KeyValueObserver<TSKTask>] = []
private var cellControllers: [TaskCellController] = []
@IBOutlet weak var tableView: UITableView!
override func viewDidLoad() {
super.viewDidLoad()
title = workflow.name
initializeWorkflow()
// Create a cell controller for each task
cellControllers = tasks.map { (task: TSKTask) -> TaskCellController in
switch task {
case let task as TimeSlicedTask:
return TimeSlicedTaskCellController(task: task)
case let task as TSKExternalConditionTask:
return ExternalConditionTaskCellController(task: task)
default:
return TaskCellController(task: task)
}
}
// Create the task state observers after the cell controllers, since the task state observer
// will update the cell
taskStateObservers = tasks.map { (task: TSKTask) -> KeyValueObserver<TSKTask> in
KeyValueObserver(object: task, keyPath: #keyPath(TSKTask.state)) { [unowned self] (task) in
OperationQueue.main.addOperation {
self.updateCell(for: task)
for dependentTask in task.dependentTasks {
self.updateCell(for: dependentTask)
}
}
}
}
// Set up our table view
tableView.register(TaskTableViewCell.nib, forCellReuseIdentifier: WorkflowViewController.kTaskCellReuseIdentifier)
tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 120
}
func initializeWorkflow() {
workflow.delegate = self
// This task is completely independent of other tasks. Imagine that this creates a server resource that
// we are going to update with additional data
let createProjectTask = TimeSlicedTask(name: "Create Project", timeRequired: 2.0)
createProjectTask.probabilityOfFailure = 0.1;
workflow.add(createProjectTask, prerequisites: nil)
// This is an external condition task that indicates that a photo is available. Imagine that this is
// fulfilled when the user takes a photo or chooses a photo from their library for this project.
let photo1AvailableCondition = TSKExternalConditionTask(name: "Photo 1 Available")
workflow.add(photo1AvailableCondition, prerequisites: nil)
// This uploads the first photo. It can’t run until the project is created and the photo is available
let uploadPhoto1Task = TimeSlicedTask(name: "Upload Photo 1", timeRequired: 5.0)
uploadPhoto1Task.probabilityOfFailure = 0.15;
workflow.add(uploadPhoto1Task, prerequisites: [createProjectTask, photo1AvailableCondition]);
// These are analagous to the previous two tasks, but for a second photo
let photo2AvailableCondition = TSKExternalConditionTask(name: "Photo 2 Available")
let uploadPhoto2Task = TimeSlicedTask(name: "Upload Photo 2", timeRequired: 6.0)
uploadPhoto2Task.probabilityOfFailure = 0.15;
workflow.add(photo2AvailableCondition, prerequisites: nil)
workflow.add(uploadPhoto2Task, prerequisites: [createProjectTask, photo2AvailableCondition])
// This is an external condition task that indicates that some metadata has been entered. Imagine that
// once the two photos are uploaded, the user is asked to name the project.
let metadataAvailableCondition = TSKExternalConditionTask(name: "Metadata Available")
workflow.add(metadataAvailableCondition, prerequisites: nil)
// This submits an order. It can’t run until the photos are uploaded and the metadata is provided.
let submitOrderTask = TimeSlicedTask(name: "Submit Order", timeRequired: 2.0)
submitOrderTask.probabilityOfFailure = 0.1;
workflow.add(submitOrderTask, prerequisites: [uploadPhoto1Task, uploadPhoto2Task, metadataAvailableCondition])
tasks = [createProjectTask,
photo1AvailableCondition, uploadPhoto1Task,
photo2AvailableCondition, uploadPhoto2Task,
metadataAvailableCondition,
submitOrderTask]
}
func updateCell(for task: TSKTask) {
guard let index = tasks.index(of: task) else {
return
}
let cellController = cellControllers[index]
guard let cell = cellController.cell else {
return
}
cellController.configure(cell)
}
// MARK: - Table view data source and delegate
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return cellControllers.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: WorkflowViewController.kTaskCellReuseIdentifier, for: indexPath) as! TaskTableViewCell
let controller = self.cellControllers[indexPath.row];
controller.cell = cell;
controller.configure(cell)
return cell;
}
func tableView(_ tableView: UITableView, didEndDisplaying cell: UITableViewCell, forRowAt indexPath: IndexPath) {
cellControllers[indexPath.row].cell = nil
}
// MARK: - Workflow delegate
func workflowDidFinish(_ workflow: TSKWorkflow) {
OperationQueue.main.addOperation {
let alertController = UIAlertController(title: "Tasks Finished", message: "All tasks finished successfully.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alertController, animated: true, completion: nil)
}
}
func workflow(_ workflow: TSKWorkflow, task: TSKTask, didFailWith error: Error?) {
guard task as? TSKExternalConditionTask == nil else {
return
}
OperationQueue.main.addOperation {
let alertController = UIAlertController(title: "Task Failed", message: "\(task.name ?? "Unknown task") failed.", preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
alertController.addAction(UIAlertAction(title: "Retry", style: .default) { [task] (_) in
task.retry()
})
self.present(alertController, animated: true, completion: nil)
}
}
}
| c8e25954b2b311d2995b0b2084958541 | 42.962366 | 151 | 0.68815 | false | false | false | false |
YevheniiPylypenko/FontKit | refs/heads/master | FontKit/Enum.swift | mit | 1 | //
// Enum.swift
// FontKit
//
// Created by Ievhenii Pylypenko on 30.06.16.
// Copyright © 2016 Ievhenii Pylypenko. All rights reserved.
//
public enum FKWeatherIcon: String {
case WiDaySunny = "\u{f00d}"
case WiDayCloudy = "\u{f002}"
case WiDayCloudyGusts = "\u{f000}"
case WiDayCloudyWindy = "\u{f001}"
case WiDayFog = "\u{f003}"
case WiDayHail = "\u{f004}"
case WiDayHaze = "\u{f0b6}"
case WiDayLightning = "\u{f005}"
case WiDayRain = "\u{f008}"
case WiDayRainMix = "\u{f006}"
case WiDayRainWind = "\u{f007}"
case WiDayShowers = "\u{f009}"
case WiDaySleet = "\u{f0b2}"
case WiDaySleetStorm = "\u{f068}"
case WiDaySnow = "\u{f00a}"
case WiDaySnowThunderstorm = "\u{f06b}"
case WiDaySnowWind = "\u{f065}"
case WiDaySprinkle = "\u{f00b}"
case WiDayStormShowers = "\u{f00e}"
case WiDaySunnyOvercast = "\u{f00c}"
case WiDayThunderstorm = "\u{f010}"
case WiDayWindy = "\u{f085}"
case WiSolarEclipse = "\u{f06e}"
case WiHot = "\u{f072}"
case WiDayCloudyHigh = "\u{f07d}"
case WiDayLightWind = "\u{f0c4}"
case WiNightClear = "\u{f02e}"
case WiNightAltCloudy = "\u{f086}"
case WiNightAltCloudyGusts = "\u{f022}"
case WiNightAltCloudyWindy = "\u{f023}"
case WiNightAltHail = "\u{f024}"
case WiNightAltLightning = "\u{f025}"
case WiNightAltRain = "\u{f028}"
case WiNightAltRainMix = "\u{f026}"
case WiNightAltRainWind = "\u{f027}"
case WiNightAltShowers = "\u{f029}"
case WiWightAltSleet = "\u{f0b4}"
case WiMightAltSleetStorm = "\u{f06a}"
case WiNightAltSnow = "\u{f02a}"
case WiNightAltSnowThunderstorm = "\u{f06d}"
case WiNightAltSnowWind = "\u{f067}"
case WiNightAltSprinkle = "\u{f02b}"
case WiMightAltStormShowers = "\u{f02c}"
case WiNightAltThunderstorm = "\u{f02d}"
case WiNightCloudy = "\u{f031}"
case WiNightCloudyGusts = "\u{f02f}"
case WiNightCloudyWindy = "\u{f030}"
case WiNightFog = "\u{f04a}"
case WiNightHail = "\u{f032}"
case WiNightLightning = "\u{f033}"
case WiNightPartlyCloudy = "\u{f083}"
case WiNightRain = "\u{f036}"
case WiNightRainMix = "\u{f034}"
case WiNightRainWind = "\u{f035}"
case WiNightShowers = "\u{f037}"
case WiNightSleet = "\u{f0b3}"
case WiNightSleetStorm = "\u{f069}"
case WiNightSnow = "\u{f038}"
case WiNightSnowThunderstorm = "\u{f06c}"
case WiNightSnowWind = "\u{f066}"
case WiNightSprinkle = "\u{f039}"
case WiNightStormShowers = "\u{f03a}"
case WiNightThunderstorm = "\u{f03b}"
case WiLunarEclipse = "\u{f070}"
case WiStars = "\u{f077}"
case WiStormShowers = "\u{f01d}"
case WiThunderstorm = "\u{f01e}"
case WiNightAltCloudyHigh = "\u{f07e}"
case WiNightCloudyHigh = "\u{f080}"
case WiNightAltPartlyCloudy = "\u{f081}"
case WiAlien = "\u{f075}"
case WiCelsius = "\u{f03c}"
case WiFahrenheit = "\u{f045}"
case WiDegrees = "\u{f042}"
case WiThermometer = "\u{f055}"
case WiThermometerExterior = "\u{f053}"
case WiThermometerInternal = "\u{f054}"
case WiCloudDown = "\u{f03d}"
case WiCloudUp = "\u{f040}"
case WiCloudRefresh = "\u{f03e}"
case WiHorizon = "\u{f047}"
case WiHorizonAlt = "\u{f046}"
case WiSunrise = "\u{f051}"
case WiSunset = "\u{f052}"
case WiMoonrise = "\u{f0c9}"
case WiMoonset = "\u{f0ca}"
case WiRefresh = "\u{f04c}"
case WiRefreshAlt = "\u{f04b}"
case WiUmbrella = "\u{f084}"
case WiBarometer = "\u{f079}"
case WiHumidity = "\u{f07a}"
case WiNa = "\u{f07b}"
case WiTrain = "\u{f0cb}"
case WiCloud = "\u{f041}"
case WiCloudy = "\u{f013}"
case WiCloudyGusts = "\u{f011}"
case WiCloudyWindy = "\u{f012}"
case WiFog = "\u{f014}"
case WiHail = "\u{f015}"
case WiRain = "\u{f019}"
case WiRainMix = "\u{f017}"
case WiRainWind = "\u{f018}"
case WiShowers = "\u{f01a}"
case WiSleet = "\u{f0b5}"
case WiSnow = "\u{f01b}"
case WiSprinkle = "\u{f01c}"
case WiSnowWind = "\u{f064}"
case WiSmog = "\u{f074}"
case WiSmoke = "\u{f062}"
case WiLightning = "\u{f016}"
case WiRaindrops = "\u{f04e}"
case WiRaindrop = "\u{f078}"
case WiDust = "\u{f063}"
case WiSnowflakeCold = "\u{f076}"
case WiWindy = "\u{f021}"
case WiStrongWind = "\u{f050}"
case WiSandstorm = "\u{f082}"
case WiEarthquake = "\u{f0c6}"
case WiFire = "\u{f0c7}"
case WiFlood = "\u{f07c}"
case WiMeteor = "\u{f071}"
case WiTsunami = "\u{f0c5}"
case WiVolcano = "\u{f0c8}"
case WiHurricane = "\u{f073}"
case WiTornado = "\u{f056}"
case WiSmallCraftAdvisory = "\u{f0cc}"
case WiGaleWarning = "\u{f0cd}"
case WiStormWarning = "\u{f0ce}"
case WiHurricaneWarning = "\u{f0cf}"
case WiWindDirection = "\u{f0b1}"
case WiDirectionUp = "\u{f058}"
case WiDirectionUpRight = "\u{f057}"
case WiDirectionRight = "\u{f04d}"
case WiDirectionDownRight = "\u{f088}"
case WiDirectionDown = "\u{f044}"
case WiDirectionDownLeft = "\u{f043}"
case WiDirectionLeft = "\u{f048}"
case WiDirectionUpLeft = "\u{f087}"
public static func fromCode(code: String) -> FKWeatherIcon? {
guard let raw = FKWeacherIcons[code], icon = FKWeatherIcon(rawValue: raw) else {
return nil
}
return icon
}
}
public let FKWeacherIcons = [
"wi-day-sunny" : "\u{f00d}",
"wi-day-cloudy" : "\u{f002}",
"wi-day-cloudy-gusts" : "\u{f000}",
"wi-day-cloudy-windy" : "\u{f001}",
"wi-day-fog" : "\u{f003}",
"wi-day-hail" : "\u{f004}",
"wi-day-haze" : "\u{f0b6}",
"wi-day-lightning" : "\u{f005}",
"wi-day-rain" : "\u{f008}",
"wi-day-rain-mix" : "\u{f006}",
"wi-day-rain-wind" : "\u{f007}",
"wi-day-showers" : "\u{f009}",
"wi-day-sleet" : "\u{f0b2}",
"wi-day-sleet-storm" : "\u{f068}",
"wi-day-snow" : "\u{f00a}",
"wi-day-snow-thunderstorm" : "\u{f06b}",
"wi-day-snow-wind" : "\u{f065}",
"wi-day-sprinkle" : "\u{f00b}",
"wi-day-storm-showers" : "\u{f00e}",
"wi-day-sunny-overcast" : "\u{f00c}",
"wi-day-thunderstorm" : "\u{f010}",
"wi-day-windy" : "\u{f085}",
"wi-solar-eclipse" : "\u{f06e}",
"wi-hot" : "\u{f072}",
"wi-day-cloudy-high" : "\u{f07d}",
"wi-day-light-wind" : "\u{f0c4}",
"wi-night-clear" : "\u{f02e}",
"wi-night-alt-cloudy" : "\u{f086}",
"wi-night-alt-cloudy-gusts" : "\u{f022}",
"wi-night-alt-cloudy-windy" : "\u{f023}",
"wi-night-alt-hail" : "\u{f024}",
"wi-night-alt-lightning" : "\u{f025}",
"wi-night-alt-rain" : "\u{f028}",
"wi-night-alt-rain-mix" : "\u{f026}",
"wi-night-alt-rain-wind" : "\u{f027}",
"wi-night-alt-showers" : "\u{f029}",
"wi-night-alt-sleet" : "\u{f0b4}",
"wi-night-alt-sleet-storm" : "\u{f06a}",
"wi-night-alt-snow" : "\u{f02a}",
"wi-night-alt-snow-thunderstorm" : "\u{f06d}",
"wi-night-alt-snow-wind" : "\u{f067}",
"wi-night-alt-sprinkle" : "\u{f02b}",
"wi-night-alt-storm-showers" : "\u{f02c}",
"wi-night-alt-thunderstorm" : "\u{f02d}",
"wi-night-cloudy" : "\u{f031}",
"wi-night-cloudy-gusts" : "\u{f02f}",
"wi-night-cloudy-windy" : "\u{f030}",
"wi-night-fog" : "\u{f04a}",
"wi-night-hail" : "\u{f032}",
"wi-night-lightning" : "\u{f033}",
"wi-night-partly-cloudy" : "\u{f083}",
"wi-night-rain" : "\u{f036}",
"wi-night-rain-mix" : "\u{f034}",
"wi-night-rain-wind" : "\u{f035}",
"wi-night-showers" : "\u{f037}",
"wi-night-sleet" : "\u{f0b3}",
"wi-night-sleet-storm" : "\u{f069}",
"wi-night-snow" : "\u{f038}",
"wi-night-snow-thunderstorm" : "\u{f06c}",
"wi-night-snow-wind" : "\u{f066}",
"wi-night-sprinkle" : "\u{f039}",
"wi-night-storm-showers" : "\u{f03a}",
"wi-night-thunderstorm" : "\u{f03b}",
"wi-lunar-eclipse" : "\u{f070}",
"wi-stars" : "\u{f077}",
"wi-storm-showers" : "\u{f01d}",
"wi-thunderstorm" : "\u{f01e}",
"wi-night-alt-cloudy-high" : "\u{f07e}",
"wi-night-cloudy-high" : "\u{f080}",
"wi-night-alt-partly-cloudy" : "\u{f081}",
"wi-alien" : "\u{f075}",
"wi-celsius" : "\u{f03c}",
"wi-fahrenheit" : "\u{f045}",
"wi-degrees" : "\u{f042}",
"wi-thermometer" : "\u{f055}",
"wi-thermometer-exterior" : "\u{f053}",
"wi-thermometer-internal" : "\u{f054}",
"wi-cloud-down" : "\u{f03d}",
"wi-cloud-up" : "\u{f040}",
"wi-cloud-refresh" : "\u{f03e}",
"wi-horizon" : "\u{f047}",
"wi-horizon-alt" : "\u{f046}",
"wi-sunrise" : "\u{f051}",
"wi-sunset" : "\u{f052}",
"wi-moonrise" : "\u{f0c9}",
"wi-moonset" : "\u{f0ca}",
"wi-refresh" : "\u{f04c}",
"wi-refresh-alt" : "\u{f04b}",
"wi-umbrella" : "\u{f084}",
"wi-barometer" : "\u{f079}",
"wi-humidity" : "\u{f07a}",
"wi-na" : "\u{f07b}",
"wi-train" : "\u{f0cb}",
"wi-cloud" : "\u{f041}",
"wi-cloudy" : "\u{f013}",
"wi-cloudy-gusts" : "\u{f011}",
"wi-cloudy-windy" : "\u{f012}",
"wi-fog" : "\u{f014}",
"wi-hail" : "\u{f015}",
"wi-rain" : "\u{f019}",
"wi-rain-mix" : "\u{f017}",
"wi-rain-wind" : "\u{f018}",
"wi-showers" : "\u{f01a}",
"wi-sleet" : "\u{f0b5}",
"wi-snow" : "\u{f01b}",
"wi-sprinkle" : "\u{f01c}",
"wi-snow-wind" : "\u{f064}",
"wi-smog" : "\u{f074}",
"wi-smoke" : "\u{f062}",
"wi-lightning" : "\u{f016}",
"wi-raindrops" : "\u{f04e}",
"wi-raindrop" : "\u{f078}",
"wi-dust" : "\u{f063}",
"wi-snowflake-cold" : "\u{f076}",
"wi-windy" : "\u{f021}",
"wi-strong-wind" : "\u{f050}",
"wi-sandstorm" : "\u{f082}",
"wi-earthquake" : "\u{f0c6}",
"wi-fire" : "\u{f0c7}",
"wi-flood" : "\u{f07c}",
"wi-meteor" : "\u{f071}",
"wi-tsunami" : "\u{f0c5}",
"wi-volcano" : "\u{f0c8}",
"wi-hurricane" : "\u{f073}",
"wi-tornado" : "\u{f056}",
"wi-small-craft-advisory" : "\u{f0cc}",
"wi-gale-warning" : "\u{f0cd}",
"wi-storm-warning" : "\u{f0ce}",
"wi-hurricane-warning" : "\u{f0cf}",
"wi-wind-direction" : "\u{f0b1}",
"wi-direction-up" : "\u{f058}",
"wi-direction-up-right" : "\u{f057}",
"wi-direction-right" : "\u{f04d}",
"wi-direction-down-right" : "\u{f088}",
"wi-direction-down" : "\u{f044}",
"wi-direction-down-left" : "\u{f043}",
"wi-direction-left" : "\u{f048}",
"wi-direction-up-left" : "\u{f087}"
]
| 9742702c819827e3ab16d63c9ef4dc05 | 33.68 | 88 | 0.55767 | false | false | false | false |
typesprite/JESlideMenu | refs/heads/master | Sources/JESlideMenuController.swift | mit | 1 | //
// JESlideMenu.swift
// JESlideMenu
//
// Created by Jasmin Eilers on 02.08.17.
// Copyright © 2017 Jasmin Eilers. All rights reserved.
//
import UIKit
protocol JESlideMenuDelegate: class {
func toggleMenu()
func setViewControllerAtIndexPath(indexPath: IndexPath)
}
class JESlideMenuController: UIViewController {
// Menu Items can be set in storyboard or here
internal var menuItems: [NSString]!
private var iconImages: [UIImage?]!
@IBInspectable public var darkMode: Bool = false
@IBInspectable public var lightStatusBar: Bool = false
@IBInspectable public var menuItem1: NSString!
@IBInspectable public var menuItem2: NSString!
@IBInspectable public var menuItem3: NSString!
@IBInspectable public var menuItem4: NSString!
@IBInspectable public var menuItem5: NSString!
@IBInspectable public var menuItem6: NSString!
@IBInspectable public var menuItem7: NSString!
@IBInspectable public var menuItem8: NSString!
@IBInspectable public var menuItem9: NSString!
@IBInspectable public var menuItem10: NSString!
@IBInspectable public var iconImage1: UIImage!
@IBInspectable public var iconImage2: UIImage!
@IBInspectable public var iconImage3: UIImage!
@IBInspectable public var iconImage4: UIImage!
@IBInspectable public var iconImage5: UIImage!
@IBInspectable public var iconImage6: UIImage!
@IBInspectable public var iconImage7: UIImage!
@IBInspectable public var iconImage8: UIImage!
@IBInspectable public var iconImage9: UIImage!
@IBInspectable public var iconImage10: UIImage!
@IBInspectable public var buttonImage: UIImage?
@IBInspectable public var buttonColor: UIColor?
@IBInspectable public var titleColor: UIColor?
@IBInspectable public var barColor: UIColor?
@IBInspectable public var headerText: String = ""
@IBInspectable public var headerTextColor: UIColor = UIColor.black
@IBInspectable public var headerFont: String = "AvenirNextCondensed-Bold"
@IBInspectable public var headerFontSize: CGFloat = 28.0
@IBInspectable public var headerBorder: Bool = false
@IBInspectable public var centerHeader: Bool = false
@IBInspectable public var headerImage: UIImage?
@IBInspectable public var headerHeight: CGFloat = 40.0
@IBInspectable public var iconHeight: CGFloat = 20.0
@IBInspectable public var iconWidth: CGFloat = 20.0
@IBInspectable public var paddingLeft: CGFloat = 22.0
@IBInspectable public var paddingTopBottom: CGFloat = 16.0
private var iconTextGap: CGFloat = 14.0
@IBInspectable public var textFontName: String?
@IBInspectable public var textSize: CGFloat = 17.0
@IBInspectable public var textColor: UIColor = UIColor.black
@IBInspectable public var backgroundColor: UIColor = UIColor.clear
internal var menuNavigationController: JESlideNavigationController!
private var menuTableView: JESlideMenuTableViewController!
internal var tapAreaView: UIView!
internal var leadingConstraint: NSLayoutConstraint!
internal var menuIsOpenConstant: CGFloat = 0.0
internal var menuIsOpenAlpha: CGFloat = 0.2
internal var isMenuOpen = false
internal var visibleViewControllerID: NSString = ""
internal var viewcontrollerCache = NSCache<NSString, UIViewController>()
private var startPoint = CGPoint(x: 0, y: 0)
private var edgeLocation = CGPoint(x: 0, y: 0)
override func viewDidLoad() {
super.viewDidLoad()
calculateMenuConstant()
setupMenuItems()
setupIconImages()
if menuItems.count != 0 {
setupMenuTableViewWithItems(menuItems: menuItems,
iconImages: iconImages)
setupNavigationController()
setupGestureRecognizer()
}
}
// calculate the menu width for iPhone/iPad
private func calculateMenuConstant() {
let width = self.view.bounds.width
let adjustedWidth: CGFloat = (width * 0.8)
menuIsOpenConstant = adjustedWidth > 280.0 ? 280.0 : adjustedWidth
}
// MARK: - Setup Menu and NavigationController
// create array for all Storyboard IDs
private func setupMenuItems() {
if menuItems == nil {
menuItems = [NSString]()
let items = [menuItem1,
menuItem2,
menuItem3,
menuItem4,
menuItem5,
menuItem6,
menuItem7,
menuItem8,
menuItem9,
menuItem10]
for item in items {
if let i = item {
menuItems.append(i)
}
}
}
}
private func setupIconImages() {
if iconImages == nil {
iconImages = [iconImage1,
iconImage2,
iconImage3,
iconImage4,
iconImage5,
iconImage6,
iconImage7,
iconImage8,
iconImage9,
iconImage10
]
let count = iconImages.filter({$0 != nil}).count
// no icons -> discard imageWidth
if count == 0 {
iconWidth = 0.0
}
}
}
// menu tableViewController added to view and add autolayout
private func setupMenuTableViewWithItems(menuItems: [NSString], iconImages: [UIImage?]) {
if darkMode {
textColor = UIColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0)
backgroundColor = UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1.0)
}
// system blue for all buttons by default
buttonColor = buttonColor == nil ? view.tintColor : buttonColor
let menuConfig = createMenuConfiguration(menuItemNames: menuItems, iconImages: iconImages)
menuTableView = JESlideMenuTableViewController(configuration: menuConfig)
menuTableView.view.translatesAutoresizingMaskIntoConstraints = false
self.addChildViewController(menuTableView)
view.addSubview(menuTableView.view)
// set delegate for switching viewControllers
menuTableView.delegate = self
// add fullscreen autolayout
NSLayoutConstraint.activate([
menuTableView.view.leadingAnchor.constraint(equalTo: view.leadingAnchor),
menuTableView.view.topAnchor.constraint(equalTo: view.topAnchor),
menuTableView.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
menuTableView.view.widthAnchor.constraint(equalToConstant: (menuIsOpenConstant + 2.0))
])
menuTableView.didMove(toParentViewController: self)
}
// configure menu tableView controller
private func createMenuConfiguration(menuItemNames: [NSString],
iconImages: [UIImage?]) -> MenuConfiguration {
let menuConfig = MenuConfiguration()
menuConfig.menuItemNames = menuItemNames
menuConfig.iconImages = iconImages
menuConfig.headerText = headerText
menuConfig.headerTextColor = headerTextColor
menuConfig.headerFont = headerFont
menuConfig.headerFontSize = headerFontSize
menuConfig.headerImage = headerImage
menuConfig.headerHeight = headerHeight
menuConfig.headerBorder = headerBorder
menuConfig.cellPadding = paddingTopBottom
menuConfig.cellPaddingLeft = paddingLeft
menuConfig.iconTextGap = iconTextGap
menuConfig.iconHeight = iconHeight
menuConfig.iconWidth = iconWidth
menuConfig.textFontName = textFontName
menuConfig.textSize = textSize
menuConfig.textColor = textColor
menuConfig.backgroundColor = backgroundColor
menuConfig.centerHeader = centerHeader
return menuConfig
}
// access navigationbar
private func setupNavigationController() {
if menuItems != nil {
// get the first item & instantiate as rootViewController
if let identifier = menuItems.first,
let homeController = instantiateViewControllerFromIdentifier(identifier: identifier) {
homeController.title = NSLocalizedString(identifier as String, comment: "translated title")
menuNavigationController = JESlideNavigationController(rootViewController: homeController)
menuNavigationController.view.translatesAutoresizingMaskIntoConstraints = false
visibleViewControllerID = identifier
self.addChildViewController(menuNavigationController)
view.addSubview(menuNavigationController.view)
// customize navigationbar (color)
menuNavigationController.toggleButtonColor = buttonColor
menuNavigationController.barTitleColor = titleColor
menuNavigationController.barTintColor = barColor
menuNavigationController.setBarButtonItemWith(image: buttonImage)
// set delegate for toggle action
menuNavigationController.menuDelegate = self
// add autolayout for Animation
leadingConstraint = menuNavigationController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor)
NSLayoutConstraint.activate([
menuNavigationController.view.widthAnchor.constraint(equalTo: view.widthAnchor),
menuNavigationController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor),
menuNavigationController.view.topAnchor.constraint(equalTo: view.topAnchor),
leadingConstraint
])
// border on the left
let border = UIView()
border.backgroundColor = UIColor.black
border.alpha = 0.3
view.addSubview(border)
border.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
border.widthAnchor.constraint(equalToConstant: 1.0),
border.heightAnchor.constraint(equalTo: menuNavigationController.view.heightAnchor),
border.trailingAnchor.constraint(equalTo: menuNavigationController.view.leadingAnchor),
border.centerYAnchor.constraint(equalTo: menuNavigationController.view.centerYAnchor)
])
menuNavigationController.didMove(toParentViewController: self)
}
}
}
// pan & tap gesture recognizer for the slider
private func setupGestureRecognizer() {
let swipeGestureAreaView = UIView()
swipeGestureAreaView.backgroundColor = UIColor.clear
swipeGestureAreaView.translatesAutoresizingMaskIntoConstraints = false
menuNavigationController.view.addSubview(swipeGestureAreaView)
let tapAreaView = UIView()
tapAreaView.alpha = 0.0
tapAreaView.backgroundColor = UIColor.black
tapAreaView.translatesAutoresizingMaskIntoConstraints = false
menuNavigationController.view.addSubview(tapAreaView)
let topConstant: CGFloat = 60.0
// autolayout
NSLayoutConstraint.activate([
swipeGestureAreaView.widthAnchor.constraint(equalToConstant: 22.0),
swipeGestureAreaView.topAnchor.constraint(equalTo: menuNavigationController.view.topAnchor,
constant: topConstant),
swipeGestureAreaView.leadingAnchor.constraint(equalTo: menuNavigationController.view.leadingAnchor),
swipeGestureAreaView.bottomAnchor.constraint(equalTo: menuNavigationController.view.bottomAnchor),
tapAreaView.leadingAnchor.constraint(equalTo: menuNavigationController.view.leadingAnchor),
tapAreaView.topAnchor.constraint(equalTo: menuNavigationController.view.topAnchor),
tapAreaView.trailingAnchor.constraint(equalTo: menuNavigationController.view.trailingAnchor),
tapAreaView.bottomAnchor.constraint(equalTo: menuNavigationController.view.bottomAnchor)
])
let edgeGestureRecognizer = UIPanGestureRecognizer(target: self,
action: #selector(edgePanGestureRecognized(recognizer:)))
let tapGestureRecognizer = UITapGestureRecognizer(target: self,
action: #selector(tapGestureRecognized(recognizer:)))
let swipeGestureRecognizer = UIPanGestureRecognizer(target: self,
action: #selector(edgePanGestureRecognized(recognizer:)))
swipeGestureAreaView.addGestureRecognizer(edgeGestureRecognizer)
tapAreaView.addGestureRecognizer(tapGestureRecognizer)
tapAreaView.addGestureRecognizer(swipeGestureRecognizer)
self.tapAreaView = tapAreaView
}
// instantiate viewcontroller from storyboard and set the title
private func instantiateViewControllerFromIdentifier(identifier: NSString) -> UIViewController? {
if let controller = self.storyboard?.instantiateViewController(withIdentifier: identifier as String) {
if let navigation = controller as? UINavigationController,
let root = navigation.topViewController {
viewcontrollerCache.setObject(root, forKey: identifier)
return root
}
viewcontrollerCache.setObject(controller, forKey: identifier)
return controller
}
return nil
}
// open and close menu
@objc private func edgePanGestureRecognized(recognizer: UIPanGestureRecognizer) {
let currentPoint = recognizer.location(in: view)
switch recognizer.state {
case .began:
startPoint = currentPoint
edgeLocation.x = self.leadingConstraint.constant
case .changed:
let difference = round(currentPoint.x - startPoint.x)
let newConstant = round(edgeLocation.x + difference)
if newConstant >= 0 && newConstant <= menuIsOpenConstant {
self.leadingConstraint.constant = round(edgeLocation.x + difference)
// min: 0.0 max: 0.5
let alpha = round(round(edgeLocation.x + difference) /
menuIsOpenConstant * menuIsOpenAlpha * 10.0) / 10.0
self.tapAreaView.alpha = alpha
}
case .ended:
animateOpenCloseGesture(recognizer: recognizer)
default:
print("default")
}
}
// close menu when it's open
@objc private func tapGestureRecognized(recognizer: UITapGestureRecognizer) {
switch recognizer.state {
case .ended:
toggleMenu()
default:
print("default")
}
}
private func animateOpenCloseGesture(recognizer: UIPanGestureRecognizer) {
let velocity = recognizer.velocity(in: view)
let locationX = self.leadingConstraint.constant
let percent: CGFloat = 0.4 * menuIsOpenConstant
// menu was closed
if !isMenuOpen && velocity.x < 100.0 && locationX < percent { // close when opened too slowly
isMenuOpen = true
toggleMenu()
} else if !isMenuOpen && velocity.x > 0 { // open it
toggleMenu()
} else if !isMenuOpen && velocity.x < 0 { // close it
isMenuOpen = true
toggleMenu()
} else if isMenuOpen && velocity.x > 0 { // open it
isMenuOpen = false
toggleMenu()
} else { // close it
isMenuOpen = true
toggleMenu()
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
if lightStatusBar {
return .lightContent
}
return .default
}
// forward rotation notification
override func willTransition(to newCollection: UITraitCollection,
with coordinator: UIViewControllerTransitionCoordinator) {
super.willTransition(to: newCollection, with: coordinator)
menuNavigationController.willTransition(to: newCollection, with: coordinator)
}
}
| 2e2f7fcbe9f08d4e8dbcb4ff66b26bbb | 40.68262 | 119 | 0.645274 | false | true | false | false |
ben-ng/swift | refs/heads/master | validation-test/compiler_crashers_fixed/01694-void.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
enum S<e<T -> : d {
func a(f: C = B, length: (A.Iterator.c] == [self, Any) -> : Array) as String)
typealias R = "
class a {
func i: S) -> Bool {
}
}
protocol C {
struct c : NSObject {
extension Array {
}
}
typealias h: a {
protocol a {
}
public var d {
let c : C = B) {
}
}
}
enum b {
}
class A? {
}
func b(c<T.in
| 6bc567a0bf1a9b81fea42b34a6a4e721 | 20.575758 | 79 | 0.664326 | false | false | false | false |
safx/Cron-Swift | refs/heads/master | Sources/Cron/DateGenerator.swift | mit | 1 | //
// DateGenerator.swift
// Cronexpr
//
// Created by Safx Developer on 2015/12/06.
// Copyright © 2015年 Safx Developers. All rights reserved.
//
import Foundation
public struct DateGenerator {
let pattern: DatePattern
let hash: Int64
let date: CronDate
internal init(pattern: DatePattern, hash: Int64, date: CronDate) {
self.pattern = pattern
self.hash = hash
self.date = date
}
public init(pattern: DatePattern, hash: Int64 = 0, date: Foundation.Date = Foundation.Date()) {
self.init(pattern: pattern, hash: hash, date: CronDate(date: date))
}
}
extension DateGenerator: IteratorProtocol {
public typealias Element = Foundation.Date
mutating public func next() -> Element? {
guard let next = pattern.next(date) else {
return nil
}
self = DateGenerator(pattern: self.pattern, hash: self.hash, date: next)
return next.date
}
}
| 8d936d973b0f308f692975069c994bf4 | 24.131579 | 99 | 0.646073 | false | false | false | false |
DrabWeb/Komikan | refs/heads/master | Komikan/Komikan/KMImageUtilities.swift | gpl-3.0 | 1 | //
// KMImageUtilities.swift
// Komikan
//
// Created by Seth on 2016-02-03.
//
import Foundation
import AppKit
extension NSImage {
/// Resizes the image to the width and height specified
func resizeImage(_ width: CGFloat, _ height: CGFloat) -> NSImage {
// Thanks to http://stackoverflow.com/questions/11949250/how-to-resize-nsimage/30422317#30422317 for the solution
// Create a variable to store the resized image, with the size we specified above
let resizedImage = NSImage(size: NSSize(width: width, height: height));
// Lock draing focus on the image
resizedImage.lockFocus();
// Set the current graphics contexts image interpolation to high for maximum quality
NSGraphicsContext.current()!.imageInterpolation = NSImageInterpolation.high;
// Draw this image into the size that we want
self.draw(in: NSMakeRect(0, 0, width, height), from: NSMakeRect(0, 0, size.width, size.height), operation: NSCompositingOperation.copy, fraction: 1);
// Unlock drawing focus
resizedImage.unlockFocus();
// Return the resized image
return resizedImage;
}
/// Resizes the image by multiplying its size by the factor. Factor should be above zero, or you will get nothing.
func resizeByFactor(_ factor : CGFloat) -> NSImage {
// Get the width the we will resize it to
let width : CGFloat = self.size.width * factor;
// Get the height that we will resize it to
let height : CGFloat = self.size.height * factor;
// Resize the image to the width and height we got
let resizedImage : NSImage = self.resizeImage(width, height);
// Return the resized image
return resizedImage;
}
/// Resizes the image to the specified height while maintaining the aspect ratio
func resizeToHeight(_ height : CGFloat) -> NSImage {
// Calculate the aspect ratio of this image(width/height)
let aspectRatio = self.size.width / self.size.height;
// Get the width(aspect ratio * desired height)
let width = aspectRatio * height;
// Get the resized image by using the resizeImage function with the passed height and the calcuated width
let resizedImage = self.resizeImage(width, height);
// Return the resized image
return resizedImage;
}
}
| fc3ba541f37020d1769b3a38b9ddd9c3 | 37.90625 | 157 | 0.643373 | false | false | false | false |
Zahzi/DMX-DIP-Converter | refs/heads/master | DMX-DIP Converter/DMX-DIP Converter/ColorSelectorViewController.swift | gpl-3.0 | 1 | //
// ColorSelectorViewController.swift
// DMX-DIP Converter
//
// Created by Eben Collins on 16/07/26.
// Copyright © 2016 Eben Collins. All rights reserved.
//
import UIKit
protocol ColorSelectedViewDelegate{
func setColor(main:UIColor, text:UIColor)
}
class ColorSelectorViewController: UIViewController {
private let defaults = UserDefaults(suiteName: "group.com.ebencollins.DMXDIPConverter.share")!
var delegate: ColorSelectedViewDelegate?
var colorKeys:(main: String, text: String)?
var mainColorSelector: ColorSelector?
var textColorSelector: ColorSelector?
override func viewDidLoad() {
super.viewDidLoad()
mainColorSelector = ColorSelector(frame: CGRect(x: 0, y: 0, width: 0, height: 0), startColor: defaults.color(forKey: (colorKeys?.main)!)!)
textColorSelector = ColorSelector(frame: CGRect(x: 0, y: 0, width: 0, height: 0), startColor: defaults.color(forKey: (colorKeys?.text)!)!)
for cs in [mainColorSelector, textColorSelector]{
cs?.addTarget(nil, action: #selector(colorSelectorValueChanged(sender:)), for: .valueChanged)
self.view.addSubview(cs!)
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true);
if(defaults.value(forKey: "enableHaptics") as! Bool){
let generator = UIImpactFeedbackGenerator(style: .medium)
generator.prepare()
generator.impactOccurred();
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(true)
if(defaults.value(forKey: "enableHaptics") as! Bool){
let generator = UISelectionFeedbackGenerator()
generator.prepare()
generator.selectionChanged()
}
defaults.setColor(color: mainColorSelector?.color, forKey: (colorKeys?.main)!)
defaults.setColor(color: textColorSelector?.color, forKey: (colorKeys?.text)!)
self.delegate?.setColor(main: (mainColorSelector?.color)!, text: (textColorSelector?.color)!)
}
override func viewDidLayoutSubviews() {
self.preferredContentSize.width = UIScreen.main.bounds.width * 1.0
self.preferredContentSize.height = UIScreen.main.bounds.height * 0.3
mainColorSelector?.frame = CGRect(x: 0, y: 0, width: self.view.frame.width, height: self.view.frame.height/2)
textColorSelector?.frame = CGRect(x: 0, y: self.view.frame.height/2, width: self.view.frame.width, height: self.view.frame.height/2)
drawLineFromPoint(start: CGPoint(x: 0, y: self.view.bounds.height/2), end: CGPoint(x: self.view.bounds.width, y: self.view.bounds.height/2), lineColor: UIColor.black, view: self.view)
}
func colorSelectorValueChanged(sender: ColorSelector){
self.delegate?.setColor(main: (mainColorSelector?.color)!, text: (textColorSelector?.color)!)
}
func drawLineFromPoint(start : CGPoint, end:CGPoint, lineColor: UIColor, view:UIView) {
//design the path
let path = UIBezierPath()
path.move(to: start)
path.addLine(to: end)
//design path in layer
let shapeLayer = CAShapeLayer()
shapeLayer.path = path.cgPath
shapeLayer.strokeColor = lineColor.cgColor
shapeLayer.lineWidth = 1.0
view.layer.addSublayer(shapeLayer)
}
}
| dc04ab28221a41ff568a7f7a5a38e0be | 37.808989 | 191 | 0.65663 | false | false | false | false |
asharijuang/playground-collection | refs/heads/master | Conditionals.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
// Basic condition using if else
var umur = 18
if umur >= 17 {
print("Kamu sudah beranjak dewasa")
}else {
print("Saat ini kamu terlalu muda")
}
// equal
var nama = "juang"
if nama == "septi" {
print("hi \(nama)")
}else {
print("Saya yakin namamu bukan juang")
}
// 2 statement
if nama == "juang" && umur >= 17 {
print("Hi \(nama), kamu sudah beranjak dewasa")
}else {
print("Maaf saya sedang mencari juang")
}
// statemen or menggunakan tanda ||
// statement with boolean
var keputusan = true
if keputusan {
print("Ini yang terbaik buat kamu")
}
// else if
var username = "admin"
var pass = "password"
if username == "admin" && pass == "" {
print("Password anda salah atau password tidak boleh kosong")
}else if username == "" && pass == "password" {
print("Username tidak boleh kosong")
}else {
print("Selamat datang")
} | 473d61990866df025120547b1dfc609e | 18.5625 | 65 | 0.641791 | false | false | false | false |
ricardopereira/PremierKit | refs/heads/main | PremierKitTests/KVOTests.swift | mit | 1 | //
// KVOTests.swift
// PremierKitTests
//
// Created by Ricardo Pereira on 08/10/2019.
// Copyright © 2019 Ricardo Pereira. All rights reserved.
//
import XCTest
@testable import PremierKit
class KVOTests: 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 testNewKey() {
let op1 = Operation()
var cancelled = false
let kvoToken = op1.addObserver(for: \.isCancelled, options:[.new]) { object, change in
cancelled = change.newValue ?? false
XCTAssertEqual(change.kind, .setting)
XCTAssertEqual(change.newValue, true)
XCTAssertNil(change.oldValue)
XCTAssertNil(change.indexes)
XCTAssertEqual(change.isPrior, false)
}
op1.cancel()
kvoToken.invalidate()
XCTAssertTrue(cancelled)
}
func testNewAndOldKey() {
let op1 = Operation()
var cancelled = false
let kvoToken = op1.addObserver(for: \.isCancelled, options:[.new, .old]) { object, change in
cancelled = true
XCTAssertEqual(change.kind, .setting)
XCTAssertEqual(change.newValue, true)
XCTAssertEqual(change.oldValue, false)
XCTAssertNil(change.indexes)
XCTAssertEqual(change.isPrior, false)
}
op1.cancel()
kvoToken.invalidate()
XCTAssertTrue(cancelled)
}
func testInvalidate() {
let op1 = Operation()
var cancelled = false
let kvoToken = op1.addObserver(for: \.isCancelled, options:[.new]) { object, change in
cancelled = true
}
kvoToken.invalidate()
op1.cancel()
XCTAssertFalse(cancelled)
}
}
| 206e5dffbd7bc41cde9d6a8553de6226 | 29 | 111 | 0.609453 | false | true | false | false |
panyam/SwiftHTTP | refs/heads/master | Sources/Core/HttpRequest.swift | apache-2.0 | 2 |
import SwiftIO
public class HttpRequest : HttpMessage, CustomStringConvertible {
public var method = "GET"
public var version = "HTTP 1.1"
private var fullPath : String = ""
public var resourcePath : String = ""
public var fragment : String = ""
public var queryParams = StringMultiMap(caseSensitiveKeys: true)
public override func reset()
{
super.reset()
}
public var requestTarget : String {
get {
return fullPath
}
set (value) {
fullPath = requestTarget
if let urlComponents = NSURLComponents(string: value)
{
resourcePath = ""
fragment = ""
if urlComponents.path != nil
{
resourcePath = urlComponents.path!
}
if urlComponents.fragment != nil
{
fragment = urlComponents.fragment!
}
queryParams.removeAll()
if let queryItems = urlComponents.queryItems
{
queryItems.forEach({ (queryItem) -> () in
if queryItem.value != nil
{
queryParams.forKey(queryItem.name, create: true)?.addValue(queryItem.value!)
}
})
}
}
}
}
public var description : String {
return "\(method) \(requestTarget) \(version)\(CRLF)\(headers)"
}
}
| b0b4dd105d39105bb1cee839f0fee97f | 28.980769 | 104 | 0.481719 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/ViewRelated/What's New/Views/AnnouncementCell.swift | gpl-2.0 | 1 |
class AnnouncementCell: UITableViewCell {
// MARK: - View elements
private lazy var headingLabel: UILabel = {
return makeLabel(font: Appearance.headingFont)
}()
private lazy var subHeadingLabel: UILabel = {
return makeLabel(font: Appearance.subHeadingFont, color: .textSubtle)
}()
private lazy var descriptionStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [headingLabel, subHeadingLabel])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .vertical
return stackView
}()
private lazy var announcementImageView: UIImageView = {
return UIImageView()
}()
private lazy var mainStackView: UIStackView = {
let stackView = UIStackView(arrangedSubviews: [announcementImageView, descriptionStackView])
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.axis = .horizontal
stackView.alignment = .center
stackView.setCustomSpacing(Appearance.imageTextSpacing, after: announcementImageView)
return stackView
}()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
contentView.addSubview(mainStackView)
contentView.pinSubviewToSafeArea(mainStackView, insets: Appearance.mainStackViewInsets)
NSLayoutConstraint.activate([
announcementImageView.heightAnchor.constraint(equalToConstant: Appearance.announcementImageSize),
announcementImageView.widthAnchor.constraint(equalToConstant: Appearance.announcementImageSize)
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Configures the labels and image views using the data from a `WordPressKit.Feature` object.
/// - Parameter feature: The `feature` containing the information to fill the cell with.
func configure(feature: WordPressKit.Feature) {
if let iconBase64Components = feature.iconBase64,
!iconBase64Components.isEmpty,
let base64Image = iconBase64Components.components(separatedBy: ";base64,")[safe: 1],
let imageData = Data(base64Encoded: base64Image, options: .ignoreUnknownCharacters),
let icon = UIImage(data: imageData) {
announcementImageView.image = icon
}
else if let url = URL(string: feature.iconUrl) {
announcementImageView.af_setImage(withURL: url)
}
headingLabel.text = feature.title
subHeadingLabel.text = feature.subtitle
}
/// Configures the labels and image views using the data passed as parameters.
/// - Parameters:
/// - title: The title string to use for the heading.
/// - description: The description string to use for the sub heading.
/// - image: The image to use for the image view.
func configure(title: String, description: String, image: UIImage?) {
headingLabel.text = title
subHeadingLabel.text = description
announcementImageView.image = image
announcementImageView.isHidden = image == nil
}
}
// MARK: Helpers
private extension AnnouncementCell {
func makeLabel(font: UIFont, color: UIColor? = nil) -> UILabel {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.numberOfLines = 0
label.font = font
if let color = color {
label.textColor = color
}
return label
}
}
// MARK: - Appearance
private extension AnnouncementCell {
enum Appearance {
// heading
static let headingFont = UIFont(descriptor: UIFontDescriptor.preferredFontDescriptor(withTextStyle: .headline), size: 17)
// sub-heading
static let subHeadingFont = UIFont(descriptor: UIFontDescriptor.preferredFontDescriptor(withTextStyle: .subheadline), size: 15)
// announcement image
static let announcementImageSize: CGFloat = 48
// main stack view
static let imageTextSpacing: CGFloat = 16
static let mainStackViewInsets = UIEdgeInsets(top: 0, left: 0, bottom: 24, right: 0)
}
}
| 376fdc468de91237592ea02412d2e223 | 35.793103 | 135 | 0.683458 | false | false | false | false |
Synchronized-TV/cordova-plugin-parse | refs/heads/master | src/ios/Parse.swift | mit | 2 |
import Foundation
import Parse
@objc protocol SNSUtils {
class func unlinkUserInBackground(user: PFUser!, block: PFBooleanResultBlock!)
class func unlinkUserInBackground(user: PFUser!, target: AnyObject!, selector: Selector)
}
@objc(CDVParse) class CDVParse : CDVPlugin {
// catches FB oauth
override func handleOpenURL(notification: NSNotification!) {
super.handleOpenURL(notification);
var sourceApplication = "test";
var wasHandled:AnyObject = FBAppCall.handleOpenURL(notification.object as NSURL, sourceApplication:nil, withSession:PFFacebookUtils.session());
NSLog("wasHandled \(wasHandled)");
}
private func getPluginResult(success: Bool, message: String) -> CDVPluginResult {
NSLog("pluginResult(\(success)): \(message)");
return CDVPluginResult(status: (success ? CDVCommandStatus_OK : CDVCommandStatus_ERROR), messageAsString: message);
}
private func getPluginResult(success: Bool, message: String, data: Dictionary<String, AnyObject>) -> CDVPluginResult {
NSLog("pluginResult(\(success)): \(message)");
return CDVPluginResult(status: (success ? CDVCommandStatus_OK : CDVCommandStatus_ERROR), messageAsDictionary: data);
}
// store keys for the client
var appKeys = [String: String]();
// setup accounts on startup
override func pluginInitialize() {
NSLog("pluginInitialize");
var plist = NSBundle.mainBundle();
// store some keys for the client SDKs
appKeys["ParseApplicationId"] = plist.objectForInfoDictionaryKey("ParseApplicationId") as String!
//appKeys["ParseClientKey"] = plist.objectForInfoDictionaryKey("ParseClientKey") as String!
// not needed (yet) because twitter not included in the Parse client SDK
// appKeys["TwitterConsumerKey"] = plist.objectForInfoDictionaryKey("TwitterConsumerKey") as? String
appKeys["FacebookAppID"] = plist.objectForInfoDictionaryKey("FacebookAppID") as String!
Parse.setApplicationId(
appKeys["ParseApplicationId"],
clientKey: appKeys["ParseClientKey"]
)
PFFacebookUtils.initializeFacebook()
PFTwitterUtils.initializeWithConsumerKey(
plist.objectForInfoDictionaryKey("TwitterConsumerKey") as String!,
consumerSecret: plist.objectForInfoDictionaryKey("TwitterConsumerSecret") as String!
)
let enableAutomaticUser: AnyObject! = plist.objectForInfoDictionaryKey("ParseEnableAutomaticUser");
if enableAutomaticUser===true {
PFUser.enableAutomaticUser();
}
}
// return user status
func getStatus(command: CDVInvokedUrlCommand) -> Void {
var pluginResult = CDVPluginResult()
var currentUser = PFUser.currentUser()
var userStatus = [
"isNew": true,
"isAuthenticated": false,
"facebook": false,
"twitter": false,
"username": "",
"email": "",
"emailVerified": false
];
if (currentUser != nil) {
// force refresh user data
currentUser.fetchInBackgroundWithBlock {
(user:PFObject!, error: NSError!) -> Void in
if (error == nil) {
// update with logged in user data
userStatus["sessionToken"] = currentUser.sessionToken
userStatus["isNew"] = currentUser.isNew
userStatus["username"] = currentUser.username
userStatus["email"] = currentUser.email
userStatus["isAuthenticated"] = currentUser.isAuthenticated()
userStatus["facebook"] = PFFacebookUtils.isLinkedWithUser(currentUser)
userStatus["twitter"] = PFTwitterUtils.isLinkedWithUser(currentUser)
userStatus["keys"] = self.appKeys
if (currentUser.objectForKey("emailVerified") != nil) {
userStatus["emailVerified"] = currentUser["emailVerified"] as Bool
}
for item in user.allKeys() {
let key = item as String
userStatus[key] = user[key] as? NSObject
}
pluginResult = self.getPluginResult(true, message: "getStatus", data:userStatus)
} else {
let errorString = error.userInfo!["error"] as NSString
pluginResult = self.getPluginResult(false, message: errorString)
}
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
}
}
func unlinkFacebook(command: CDVInvokedUrlCommand) -> Void {
var result = self.unlinkNetwork("facebook");
commandDelegate.sendPluginResult(result, callbackId:command.callbackId)
}
func unlinkTwitter(command: CDVInvokedUrlCommand) -> Void {
var result = self.unlinkNetwork("twitter");
commandDelegate.sendPluginResult(result, callbackId:command.callbackId)
}
private func getNetworkClass(network: String) -> AnyClass {
var networks: Dictionary<String, AnyClass> = [
"facebook": PFFacebookUtils.self,
"twitter": PFTwitterUtils.self
];
return networks[network]!;
}
private func unlinkNetwork(network: String) -> CDVPluginResult {
var pluginResult = CDVPluginResult();
var currentUser = PFUser.currentUser();
let networkCls: AnyClass = getNetworkClass(network);
if (networkCls.isLinkedWithUser(currentUser)) {
networkCls.unlinkUserInBackground(currentUser as PFUser!, {
(succeeded: Bool, error: NSError!) -> Void in
if succeeded {
pluginResult = self.getPluginResult(true, message: "The user is no longer associated with their \(network) account.");
} else {
pluginResult = self.getPluginResult(false, message: "Cannot unlink user to their \(network) account.");
}
})
} else {
pluginResult = self.getPluginResult(false, message: "User not linked to \(network)");
}
return pluginResult;
}
private func loginWith(network: String, permissions: Array<String>=[]) -> CDVPluginResult {
// handle both FB and Twitter login processes
// handle existing and new account
var pluginResult = CDVPluginResult();
var currentUser = PFUser.currentUser();
let networkCls: AnyClass = getNetworkClass(network);
// PFUser already exists
if (currentUser != nil) {
if (networkCls.isLinkedWithUser(currentUser)) {
pluginResult = self.getPluginResult(true, message: "user already logged in with \(network)!");
} else {
if (network == "facebook") {
// facebook needs special permissions
PFFacebookUtils.linkUser(currentUser, permissions: permissions as Array, {
(succeeded: Bool, error: NSError!) -> Void in
if succeeded {
// fetch user details with FB api
FBRequestConnection.startForMeWithCompletionHandler({connection, result, error in
if (error === nil)
{
currentUser["fbId"] = result.objectID as String;
currentUser["fbName"] = result.name as String;
currentUser["fbEmail"] = result.email as String;
currentUser.saveEventually()
pluginResult = self.getPluginResult(true, message: "user logged in with \(network)!");
} else {
pluginResult = self.getPluginResult(false, message: "Cannot fetch \(network) account details :/");
}
})
} else {
pluginResult = self.getPluginResult(false, message: "Error linking \(network) account :/");
}
})
} else if (network == "twitter") {
PFTwitterUtils.linkUser(currentUser, {
(succeeded: Bool, error: NSError!) -> Void in
if succeeded {
// store twitter handle
currentUser["twitterHandle"] = PFTwitterUtils.twitter().screenName;
currentUser.saveEventually()
pluginResult = self.getPluginResult(true, message: "user logged in with \(network)!");
} else {
pluginResult = self.getPluginResult(false, message: "Error linking \(network) account :/");
}
})
}
}
// user not logged, create a new account from FB
} else {
if (network == "facebook") {
// create a new user using FB
PFFacebookUtils.logInWithPermissions(permissions as Array, {
(user: PFUser!, error: NSError!) -> Void in
if user == nil {
pluginResult = self.getPluginResult(false, message: "Uh oh. The user cancelled the \(network) login.");
} else if user.isNew {
pluginResult = self.getPluginResult(true, message: "User signed up and logged in through \(network)!");
} else {
pluginResult = self.getPluginResult(true, message: "User logged in through \(network)!");
}
})
} else if (network == "twitter") {
// create a new user using twitter
PFTwitterUtils.logInWithBlock {
(user: PFUser!, error: NSError!) -> Void in
if user == nil {
pluginResult = self.getPluginResult(false, message: "Uh oh. The user cancelled the \(network) login.");
} else if user.isNew {
pluginResult = self.getPluginResult(true, message: "User signed up and logged in through \(network)!");
} else {
pluginResult = self.getPluginResult(true, message: "User logged in through \(network)!");
}
}
}
}
return pluginResult
}
// start FB login process
func loginWithFacebook(command: CDVInvokedUrlCommand) -> Void {
var options = command.arguments[0] as [String: AnyObject];
if (options["permissions"] === nil) {
options["permissions"] = ["public_profile", "email"];
}
var result = self.loginWith("facebook", permissions: options["permissions"] as Array);
self.commandDelegate.sendPluginResult(result, callbackId:command.callbackId)
}
// start Twitter login process
func loginWithTwitter(command: CDVInvokedUrlCommand) -> Void {
var result = self.loginWith("twitter");
self.commandDelegate.sendPluginResult(result, callbackId:command.callbackId)
}
func logout(command: CDVInvokedUrlCommand) -> Void {
var pluginResult = self.getPluginResult(true, message: "user logged out");
PFUser.logOut();
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
// create a new Parse account
func signUp(command: CDVInvokedUrlCommand) -> Void {
var email = command.arguments[0] as String
var password = command.arguments[1] as String
var pluginResult = CDVPluginResult()
var user = PFUser()
user.username = email
user.password = password
user.email = email
user.signUpInBackgroundWithBlock {
(succeeded: Bool!, error: NSError!) -> Void in
if error == nil {
pluginResult = self.getPluginResult(true, message: "user signed up successfully");
} else {
let errorString = error.userInfo!["error"] as NSString
pluginResult = self.getPluginResult(false, message: errorString);
}
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
}
// login to a new Parse account
func logIn(command: CDVInvokedUrlCommand) -> Void {
var email = command.arguments[0] as String
var password = command.arguments[1] as String
var pluginResult = CDVPluginResult()
PFUser.logInWithUsernameInBackground(email, password:password) {
(user: PFUser!, error: NSError!) -> Void in
if user != nil {
pluginResult = self.getPluginResult(true, message: "user logged in successfully");
} else {
let errorString = error.userInfo!["error"] as NSString
pluginResult = self.getPluginResult(false, message: errorString);
}
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
}
// launch Parse password receovery process
func resetPassword(command: CDVInvokedUrlCommand) -> Void {
var email = command.arguments[0] as String
var pluginResult = CDVPluginResult()
PFUser.requestPasswordResetForEmailInBackground(email) {
(succeeded: Bool!, error: NSError!) -> Void in
if error == nil {
pluginResult = self.getPluginResult(true, message: "password reset email sent");
} else {
let errorString = error.userInfo!["error"] as NSString
pluginResult = self.getPluginResult(false, message: errorString);
}
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
}
func setUserKey(command: CDVInvokedUrlCommand) -> Void {
var key = command.arguments[0] as String
var value = command.arguments[1] as String
var currentUser = PFUser.currentUser()
currentUser[key] = value
currentUser.saveEventually();
var pluginResult = self.getPluginResult(true, message: "user updated successfully");
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
// create a decente Twitter API call
private func getTwitterRequest(url: String, method: String = "POST", bodyData: String = "") -> NSMutableURLRequest {
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
request.HTTPMethod = method
if bodyData != "" {
request.HTTPBody = bodyData.dataUsingEncoding(NSUTF8StringEncoding);
}
PFTwitterUtils.twitter().signRequest(request)
return request
}
// parse errors if any
private func handleTwitterResponse(data: NSData) -> CDVPluginResult {
var pluginResult = CDVPluginResult()
var jsonResult: NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: nil) as NSDictionary
if let errors = jsonResult["errors"]? as? NSArray {
if errors.count > 0 {
pluginResult = self.getPluginResult(false, message: errors[0]["message"] as String);
} else {
pluginResult = self.getPluginResult(true, message: "success");
}
} else {
pluginResult = self.getPluginResult(true, message: "success");
}
return pluginResult
}
// create/destroy retweet
private func twitterRetweetStatus(command: CDVInvokedUrlCommand, enable: Bool) -> Void {
let tweetId = command.arguments[0] as String
let action: String = enable ? "retweet" : "destroy";
let url = "https://api.twitter.com/1.1/statuses/\(action)/\(tweetId).json"
var request = self.getTwitterRequest(url, method: "POST")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
let pluginResult: CDVPluginResult = self.handleTwitterResponse(data);
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
}
func twitterRetweet(command: CDVInvokedUrlCommand) -> Void {
self.twitterRetweetStatus(command, enable: true);
}
func twitterCancelRetweet(command: CDVInvokedUrlCommand) -> Void {
self.twitterRetweetStatus(command, enable: false);
}
// create/destroy favorite
private func twitterFavoriteStatus(command: CDVInvokedUrlCommand, enable: Bool) -> Void {
let tweetId = command.arguments[0] as String
let action: String = enable ? "create" : "destroy";
let url = "https://api.twitter.com/1.1/favorites/\(action).json"
var request = self.getTwitterRequest(url, method: "POST", bodyData: "id=\(tweetId)")
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) {(response, data, error) in
let pluginResult: CDVPluginResult = self.handleTwitterResponse(data);
self.commandDelegate.sendPluginResult(pluginResult, callbackId:command.callbackId)
}
}
func twitterFavorite(command: CDVInvokedUrlCommand) -> Void {
self.twitterFavoriteStatus(command, enable: true);
}
func twitterCancelFavorite(command: CDVInvokedUrlCommand) -> Void {
self.twitterFavoriteStatus(command, enable: false);
}
}
| 18f9a5711e35631e654e65133c867831 | 45.834646 | 160 | 0.599305 | false | false | false | false |
CoderXpert/Weather | refs/heads/master | Weather/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// Weather
//
// Created by Adnan Aftab on 3/7/16.
// Copyright © 2016 CX. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var updateDateTimeLabel: UILabel!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var spinner: UIActivityIndicatorView!
@IBOutlet weak var weatherConditionIcon: UILabel!
@IBOutlet weak var currentTempLabel: UILabel!
@IBOutlet weak var futureForecastScrollView: UIScrollView!
@IBOutlet weak var todayForecastScrollView: UIScrollView!
@IBOutlet weak var errorTextLabel: UILabel!
@IBOutlet weak var refreshButton: UIButton!
private var alreadyPopulatedCurrentWeather = false
private var alreadyPopulatedForecastInfo = false
var viewModel:CurrentWeatherForecastViewModelType?
override func viewDidLoad() {
super.viewDidLoad()
registerForViewModelNotificaitons()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
@IBAction func onTapRefreshButton(sender: AnyObject) {
viewModel!.updateWeatherData()
}
private func clearCurrentWeatherUI(){
self.locationLabel.text = ""
self.updateDateTimeLabel.text = ""
self.weatherConditionIcon.text = ""
self.currentTempLabel.text = ""
}
private func clearForecastUI(){
for v in self.todayForecastScrollView.subviews {
v.removeFromSuperview()
}
for v in self.futureForecastScrollView.subviews {
v.removeFromSuperview()
}
}
}
//: ViewModel notificaitons
extension ViewController {
func registerForViewModelNotificaitons() {
viewModel = CurrentWeatherForecastViewModel()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "updateCurrentWeatherUI", name: ForecastViewModelNotificaitons.GotNewCurrentWeatherData.rawValue, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "udpateForecastUI", name: ForecastViewModelNotificaitons.GotNewForecastData.rawValue, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onNoForecastInfo", name: ForecastViewModelNotificaitons.GotNoForecasts.rawValue, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onNoCurrentWeatherInfo", name: ForecastViewModelNotificaitons.GotNoCurrentWeatherData.rawValue, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "onStartLoadingWeatherInfo", name: ForecastViewModelNotificaitons.StartLoadingCurrentWeatherInfo.rawValue, object: nil)
}
func onStartLoadingWeatherInfo(){
self.refreshButton.hidden = true
self.clearCurrentWeatherUI()
self.errorTextLabel.hidden = true
self.spinner.startAnimating()
}
func onNoCurrentWeatherInfo(){
self.spinner.stopAnimating()
self.refreshButton.hidden = false
if !alreadyPopulatedCurrentWeather {
clearCurrentWeatherUI()
self.errorTextLabel.hidden = false
}
else {
updateCurrentWeatherUI()
}
}
func onNoForecastInfo(){
if !alreadyPopulatedForecastInfo {
clearForecastUI()
self.todayForecastScrollView.hidden = true
self.futureForecastScrollView.hidden = true
}
}
func updateCurrentWeatherUI() {
self.spinner.stopAnimating()
self.refreshButton.hidden = false
self.errorTextLabel.hidden = true
locationLabel.text = viewModel!.currentLocationName
updateDateTimeLabel.text = viewModel!.lastUpdateDateAndTimeString
currentTempLabel.text = viewModel!.currentTemperatureString
weatherConditionIcon.text = viewModel!.currentWeatherConditionIconText
alreadyPopulatedCurrentWeather = true
}
func updateTodayForecastUI(){
var xPos = 0
for index in 0..<viewModel!.totalNumberOfTodaysForecasts {
let frame = CGRectMake(CGFloat(xPos), 0.0, 80.0, 114.0)
let fv = ForecastView(frame: frame)
fv.temperature = viewModel?.todayForecastTemperatureStringForIndex(index)
fv.icon = viewModel?.todayForecastWeatherConditionIconTextForIndex(index)
fv.time = viewModel?.todayForecastShortDateTimeStringForIndex(index)
self.todayForecastScrollView.addSubview(fv)
xPos += 80
}
self.todayForecastScrollView.contentSize = CGSizeMake(CGFloat(xPos), 114.0)
}
func updateFutureForecastUI(){
var xPos = 0
for index in 0..<viewModel!.totalNumberOfFutureForecastsExcludingToday {
let frame = CGRectMake(CGFloat(xPos), 0.0, 80.0, 114.0)
let fv = ForecastView(frame: frame)
fv.temperature = viewModel?.futureForecastTemperatureStringForIndex(index)
fv.icon = viewModel?.futureForecastWeatherConditionIconTextForIndex(index)
fv.time = viewModel?.futureForecastShortDateTimeStringForIndex(index)
xPos += 80
self.futureForecastScrollView.addSubview(fv)
}
self.futureForecastScrollView.contentSize = CGSizeMake(CGFloat(xPos), 114.0)
}
func udpateForecastUI() {
clearForecastUI()
self.todayForecastScrollView.hidden = false
self.futureForecastScrollView.hidden = false
updateTodayForecastUI()
updateFutureForecastUI()
alreadyPopulatedForecastInfo = true
}
}
| 6d85aaf8eea32bdca1e5a12afb004009 | 40.42963 | 192 | 0.699803 | false | false | false | false |
Leo19/swift_begin | refs/heads/master | test-swift/SliderApp/SliderApp/ViewController.swift | gpl-2.0 | 1 | //
// ViewController.swift
// SliderApp
//
// Created by liushun on 15/11/6.
// Copyright © 2015年 liushun. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 手动创建一个slider
let slider = UISlider(frame: CGRectMake(100,300,100,30))
slider.minimumValue = 10
slider.maximumValue = 200
slider.value = 50
slider.continuous = true
slider.minimumTrackTintColor = UIColor.redColor()
slider.maximumTrackTintColor = UIColor.greenColor()
slider.thumbTintColor = UIColor.brownColor()
slider.addTarget(self, action: "didChanged:", forControlEvents: .ValueChanged)
self.view.addSubview(slider)
// 手动创建一个switch 位置x,y坐标起作用,后面的大小设置了也不起作用
let sw = UISwitch(frame: CGRectMake(100,400,100,30))
sw.addTarget(self, action: "didSwitched:", forControlEvents: .ValueChanged)
sw.onTintColor = UIColor.blueColor()
sw.tintColor = UIColor.greenColor()
sw.thumbTintColor = UIColor.redColor()
self.view.addSubview(sw)
}
// 滑动和滑动结束的时候都会触发这个事件,这个value是浮点数
@IBAction func didChanged(sender: UISlider) {
print("\(sender.value)")
}
@IBAction func didSwitched(sender: UISwitch) {
print("\(sender.on)")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 5d20976e221b777c58ad1bca8772f171 | 29.58 | 86 | 0.64552 | false | false | false | false |
darren90/Gankoo_Swift | refs/heads/master | Gankoo/Gankoo/Classes/Main/Base/BaseTableViewController.swift | apache-2.0 | 1 | //
// BaseTableViewController.swift
// iTVshows
//
// Created by Fengtf on 2016/11/21.
// Copyright © 2016年 tengfei. All rights reserved.
//
import UIKit
class BaseTableViewController: BaseViewController,UITableViewDelegate,UITableViewDataSource {
public var tableView:UITableView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
addTableView()
// addLoadingView()
}
func addTableView() {
let rect = CGRect(x: 0, y: 64, width: self.view.bounds.width, height: self.view.bounds.height-64)
tableView = UITableView.init(frame: rect, style: .plain)
self.view .addSubview(tableView)
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = .none
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1;
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 0;
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var cell = tableView .dequeueReusableCell(withIdentifier: "cell")
if cell == nil {
cell = UITableViewCell.init(style: .default, reuseIdentifier: "cell")
}
return cell!;
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
/// 移除选中的状态
tableView.deselectRow(at: indexPath, animated: true)
}
}
| 47168fb92d5977f1926a860cf7329734 | 23.758065 | 105 | 0.652117 | false | false | false | false |
exoplatform/exo-ios | refs/heads/acceptance | eXo/Sources/Models/Cookies/CookiesFromAuthorizationFetcher.swift | lgpl-3.0 | 1 | //
// CookiesFromAuthorizationFetcher.swift
// eXo
//
// Created by Paweł Walczak on 07.02.2018.
// Copyright © 2018 eXo. All rights reserved.
//
import Foundation
class CookiesFromAuthorizationFetcher {
func fetch(headerValue: String?) -> [String: String] {
guard let headerValue = headerValue else { return [:] }
var result = [String: String]()
let cookies = headerValue.split(separator: ";")
for c in cookies {
let keyValue = c.split(separator: "=")
guard keyValue.count == 2 else { continue }
let key = String(keyValue[0])
let value = String(keyValue[1])
guard !key.withoutWhitespaces.isEmpty, !value.withoutWhitespaces.isEmpty else { continue }
result[key.withoutWhitespaces] = value.withoutWhitespaces
}
return result
}
func fetch(headerValue: String?, url: URL) -> [HTTPCookie] {
let cookies = self.fetch(headerValue: headerValue)
guard !cookies.isEmpty else { return [] }
var result = [HTTPCookie]()
for c in cookies {
guard let cookie = fromKeyValueToCookie(cookie: c, url: url) else { continue }
result.append(cookie)
}
return result
}
private func fromKeyValueToCookie(cookie: (key: String, value: String), url: URL) -> HTTPCookie? {
return HTTPCookie(properties: [
HTTPCookiePropertyKey.name: cookie.key,
HTTPCookiePropertyKey.value: cookie.value,
HTTPCookiePropertyKey.domain: url.absoluteString.serverDomainWithProtocolAndPort ?? "",
HTTPCookiePropertyKey.originURL: url,
HTTPCookiePropertyKey.path: "/",
HTTPCookiePropertyKey.secure: true
]
)
}
}
extension String {
var withoutWhitespaces: String {
return self.trimmingCharacters(in: .whitespaces)
}
}
| d4f6c15a56d9a60a9ec6ed987e96b9ca | 33.732143 | 103 | 0.611825 | false | false | false | false |
LDlalala/LDZBLiving | refs/heads/master | LDZBLiving/LDZBLiving/Classes/Main/LDPageView/LDPageStyle.swift | mit | 1 | //
// LDPageStyle.swift
// LDPageView
//
// Created by 李丹 on 17/8/2.
// Copyright © 2017年 LD. All rights reserved.
//
import UIKit
class LDPageStyle {
var titleHeight : CGFloat = 44;
var normalColor : UIColor = UIColor(r: 255, g: 255, b: 255)
var selectColor : UIColor = UIColor(r: 255, g: 127, b: 0)
var font : UIFont = UIFont.systemFont(ofSize: 15)
var margin : CGFloat = 20
var isScrollEnadle : Bool = false
}
| c4ca207c938368ef935db52577a25793 | 22.578947 | 63 | 0.636161 | false | false | false | false |
FullMetalFist/buzzlr | refs/heads/master | OAuthSwiftDemo/ViewController.swift | mit | 10 | //
// ViewController.swift
// OAuthSwift
//
// Created by Dongri Jin on 6/21/14.
// Copyright (c) 2014 Dongri Jin. All rights reserved.
//
import UIKit
import OAuthSwift
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var services = ["Twitter", "Flickr", "Github", "Instagram", "Foursquare", "Fitbit", "Withings", "Linkedin", "Linkedin2", "Dropbox", "Dribbble", "Salesforce", "BitBucket", "GoogleDrive", "Smugmug", "Intuit", "Zaim", "Tumblr", "Slack"]
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "OAuth"
let tableView: UITableView = UITableView(frame: self.view.bounds, style: .Plain)
tableView.delegate = self
tableView.dataSource = self
self.view.addSubview(tableView)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func doOAuthTwitter(){
let oauthswift = OAuth1Swift(
consumerKey: Twitter["consumerKey"]!,
consumerSecret: Twitter["consumerSecret"]!,
requestTokenUrl: "https://api.twitter.com/oauth/request_token",
authorizeUrl: "https://api.twitter.com/oauth/authorize",
accessTokenUrl: "https://api.twitter.com/oauth/access_token"
)
//oauthswift.authorize_url_handler = WebViewController()
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/twitter")!, success: {
credential, response in
self.showAlertView("Twitter", message: "auth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
var parameters = Dictionary<String, AnyObject>()
oauthswift.client.get("https://api.twitter.com/1.1/statuses/mentions_timeline.json", parameters: parameters,
success: {
data, response in
let jsonDict: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
println(jsonDict)
}, failure: {(error:NSError!) -> Void in
println(error)
})
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
}
)
}
func doOAuthFlickr(){
let oauthswift = OAuth1Swift(
consumerKey: Flickr["consumerKey"]!,
consumerSecret: Flickr["consumerSecret"]!,
requestTokenUrl: "https://www.flickr.com/services/oauth/request_token",
authorizeUrl: "https://www.flickr.com/services/oauth/authorize",
accessTokenUrl: "https://www.flickr.com/services/oauth/access_token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/flickr")!, success: {
credential, response in
self.showAlertView("Flickr", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
let url :String = "https://api.flickr.com/services/rest/"
let parameters :Dictionary = [
"method" : "flickr.photos.search",
"api_key" : Flickr["consumerKey"]!,
"user_id" : "128483205@N08",
"format" : "json",
"nojsoncallback" : "1",
"extras" : "url_q,url_z"
]
oauthswift.client.get(url, parameters: parameters,
success: {
data, response in
let jsonDict: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
println(jsonDict)
}, failure: {(error:NSError!) -> Void in
println(error)
})
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthGithub(){
let oauthswift = OAuth2Swift(
consumerKey: Github["consumerKey"]!,
consumerSecret: Github["consumerSecret"]!,
authorizeUrl: "https://github.com/login/oauth/authorize",
accessTokenUrl: "https://github.com/login/oauth/access_token",
responseType: "code"
)
let state: String = generateStateWithLength(20) as String
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/github")!, scope: "user,repo", state: state, success: {
credential, response, parameters in
self.showAlertView("Github", message: "oauth_token:\(credential.oauth_token)")
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthSalesforce(){
let oauthswift = OAuth2Swift(
consumerKey: Salesforce["consumerKey"]!,
consumerSecret: Salesforce["consumerSecret"]!,
authorizeUrl: "https://login.salesforce.com/services/oauth2/authorize",
accessTokenUrl: "https://login.salesforce.com/services/oauth2/token",
responseType: "code"
)
let state: String = generateStateWithLength(20) as String
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/salesforce")!, scope: "full", state: state, success: {
credential, response, parameters in
self.showAlertView("Salesforce", message: "oauth_token:\(credential.oauth_token)")
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthInstagram(){
let oauthswift = OAuth2Swift(
consumerKey: Instagram["consumerKey"]!,
consumerSecret: Instagram["consumerSecret"]!,
authorizeUrl: "https://api.instagram.com/oauth/authorize",
responseType: "token"
)
let state: String = generateStateWithLength(20) as String
oauthswift.authorize_url_handler = WebViewController()
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/instagram")!, scope: "likes+comments", state:state, success: {
credential, response, parameters in
self.showAlertView("Instagram", message: "oauth_token:\(credential.oauth_token)")
let url :String = "https://api.instagram.com/v1/users/1574083/?access_token=\(credential.oauth_token)"
let parameters :Dictionary = Dictionary<String, AnyObject>()
oauthswift.client.get(url, parameters: parameters,
success: {
data, response in
let jsonDict: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
println(jsonDict)
}, failure: {(error:NSError!) -> Void in
println(error)
})
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthFoursquare(){
let oauthswift = OAuth2Swift(
consumerKey: Foursquare["consumerKey"]!,
consumerSecret: Foursquare["consumerSecret"]!,
authorizeUrl: "https://foursquare.com/oauth2/authorize",
responseType: "token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/foursquare")!, scope: "", state: "", success: {
credential, response, parameters in
self.showAlertView("Foursquare", message: "oauth_token:\(credential.oauth_token)")
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthFitbit(){
let oauthswift = OAuth1Swift(
consumerKey: Fitbit["consumerKey"]!,
consumerSecret: Fitbit["consumerSecret"]!,
requestTokenUrl: "https://api.fitbit.com/oauth/request_token",
authorizeUrl: "https://www.fitbit.com/oauth/authorize?display=touch",
accessTokenUrl: "https://api.fitbit.com/oauth/access_token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/fitbit")!, success: {
credential, response in
self.showAlertView("Fitbit", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthWithings(){
let oauthswift = OAuth1Swift(
consumerKey: Withings["consumerKey"]!,
consumerSecret: Withings["consumerSecret"]!,
requestTokenUrl: "https://oauth.withings.com/account/request_token",
authorizeUrl: "https://oauth.withings.com/account/authorize",
accessTokenUrl: "https://oauth.withings.com/account/access_token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/withings")!, success: {
credential, response in
self.showAlertView("Withings", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthLinkedin(){
let oauthswift = OAuth1Swift(
consumerKey: Linkedin["consumerKey"]!,
consumerSecret: Linkedin["consumerSecret"]!,
requestTokenUrl: "https://api.linkedin.com/uas/oauth/requestToken",
authorizeUrl: "https://api.linkedin.com/uas/oauth/authenticate",
accessTokenUrl: "https://api.linkedin.com/uas/oauth/accessToken"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/linkedin")!, success: {
credential, response in
self.showAlertView("Linkedin", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
var parameters = Dictionary<String, AnyObject>()
oauthswift.client.get("https://api.linkedin.com/v1/people/~", parameters: parameters,
success: {
data, response in
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(dataString)
}, failure: {(error:NSError!) -> Void in
println(error)
})
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthLinkedin2(){
let oauthswift = OAuth2Swift(
consumerKey: Linkedin2["consumerKey"]!,
consumerSecret: Linkedin2["consumerSecret"]!,
authorizeUrl: "https://www.linkedin.com/uas/oauth2/authorization",
accessTokenUrl: "https://www.linkedin.com/uas/oauth2/accessToken",
responseType: "code"
)
let state: String = generateStateWithLength(20) as String
oauthswift.authorizeWithCallbackURL( NSURL(string: "http://oauthswift.herokuapp.com/callback/linkedin2")!, scope: "r_fullprofile", state: state, success: {
credential, response, parameters in
self.showAlertView("Linkedin2", message: "oauth_token:\(credential.oauth_token)")
var parameters = Dictionary<String, AnyObject>()
oauthswift.client.get("https://api.linkedin.com/v1/people/~?format=json", parameters: parameters,
success: {
data, response in
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(dataString)
}, failure: {(error:NSError!) -> Void in
println(error)
})
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthSmugmug(){
let oauthswift = OAuth1Swift(
consumerKey: Smugmug["consumerKey"]!,
consumerSecret: Smugmug["consumerSecret"]!,
requestTokenUrl: "http://api.smugmug.com/services/oauth/getRequestToken.mg",
authorizeUrl: "http://api.smugmug.com/services/oauth/authorize.mg",
accessTokenUrl: "http://api.smugmug.com/services/oauth/getAccessToken.mg"
)
oauthswift.allowMissingOauthVerifier = true
// NOTE: Smugmug's callback URL is configured on their site and the one passed in is ignored.
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/smugmug")!, success: {
credential, response in
self.showAlertView("Smugmug", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthDropbox(){
let oauthswift = OAuth2Swift(
consumerKey: Dropbox["consumerKey"]!,
consumerSecret: Dropbox["consumerSecret"]!,
authorizeUrl: "https://www.dropbox.com/1/oauth2/authorize",
accessTokenUrl: "https://api.dropbox.com/1/oauth2/token",
responseType: "token"
)
oauthswift.authorize_url_handler = WebViewController()
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/dropbox")!, scope: "", state: "", success: {
credential, response, parameters in
self.showAlertView("Dropbox", message: "oauth_token:\(credential.oauth_token)")
// Get Dropbox Account Info
var parameters = Dictionary<String, AnyObject>()
oauthswift.client.get("https://api.dropbox.com/1/account/info?access_token=\(credential.oauth_token)", parameters: parameters,
success: {
data, response in
let jsonDict: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
println(jsonDict)
}, failure: {(error:NSError!) -> Void in
println(error)
})
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthDribbble(){
let oauthswift = OAuth2Swift(
consumerKey: Dribbble["consumerKey"]!,
consumerSecret: Dribbble["consumerSecret"]!,
authorizeUrl: "https://dribbble.com/oauth/authorize",
accessTokenUrl: "https://dribbble.com/oauth/token",
responseType: "code"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/dribbble")!, scope: "", state: "", success: {
credential, response, parameters in
self.showAlertView("Dribbble", message: "oauth_token:\(credential.oauth_token)")
// Get User
var parameters = Dictionary<String, AnyObject>()
oauthswift.client.get("https://api.dribbble.com/v1/user?access_token=\(credential.oauth_token)", parameters: parameters,
success: {
data, response in
let jsonDict: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
println(jsonDict)
}, failure: {(error:NSError!) -> Void in
println(error)
})
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthBitBucket(){
let oauthswift = OAuth1Swift(
consumerKey: BitBucket["consumerKey"]!,
consumerSecret: BitBucket["consumerSecret"]!,
requestTokenUrl: "https://bitbucket.org/api/1.0/oauth/request_token",
authorizeUrl: "https://bitbucket.org/api/1.0/oauth/authenticate",
accessTokenUrl: "https://bitbucket.org/api/1.0/oauth/access_token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/bitbucket")!, success: {
credential, response in
self.showAlertView("BitBucket", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
var parameters = Dictionary<String, AnyObject>()
oauthswift.client.get("https://bitbucket.org/api/1.0/user", parameters: parameters,
success: {
data, response in
let dataString = NSString(data: data, encoding: NSUTF8StringEncoding)
println(dataString)
}, failure: {(error:NSError!) -> Void in
println(error)
})
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthGoogle(){
let oauthswift = OAuth2Swift(
consumerKey: GoogleDrive["consumerKey"]!,
consumerSecret: GoogleDrive["consumerSecret"]!,
authorizeUrl: "https://accounts.google.com/o/oauth2/auth",
accessTokenUrl: "https://accounts.google.com/o/oauth2/token",
responseType: "code"
)
// For googgle the redirect_uri should match your this syntax: your.bundle.id:/oauth2Callback
// in plist define a url schem with: your.bundle.id:
oauthswift.authorizeWithCallbackURL( NSURL(string: "https://oauthswift.herokuapp.com/callback/google")!, scope: "https://www.googleapis.com/auth/drive", state: "", success: {
credential, response, parameters in
self.showAlertView("Github", message: "oauth_token:\(credential.oauth_token)")
var parameters = Dictionary<String, AnyObject>()
// Multi-part upload
oauthswift.client.postImage("https://www.googleapis.com/upload/drive/v2/files", parameters: parameters, image: self.snapshot(),
success: {
data, response in
let jsonDict: AnyObject! = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil)
println("SUCCESS: \(jsonDict)")
}, failure: {(error:NSError!) -> Void in
println(error)
})
}, failure: {(error:NSError!) -> Void in
println("ERROR: \(error.localizedDescription)")
})
}
func doOAuthIntuit(){
let oauthswift = OAuth1Swift(
consumerKey: Intuit["consumerKey"]!,
consumerSecret: Intuit["consumerSecret"]!,
requestTokenUrl: "https://oauth.intuit.com/oauth/v1/get_request_token",
authorizeUrl: "https://appcenter.intuit.com/Connect/Begin",
accessTokenUrl: "https://oauth.intuit.com/oauth/v1/get_access_token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/intuit")!, success: {
credential, response in
self.showAlertView("Intuit", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthZaim(){
let oauthswift = OAuth1Swift(
consumerKey: Zaim["consumerKey"]!,
consumerSecret: Zaim["consumerSecret"]!,
requestTokenUrl: "https://api.zaim.net/v2/auth/request",
authorizeUrl: "https://auth.zaim.net/users/auth",
accessTokenUrl: "https://api.zaim.net/v2/auth/access"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/zaim")!, success: {
credential, response in
self.showAlertView("Zaim", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthTumblr(){
let oauthswift = OAuth1Swift(
consumerKey: Tumblr["consumerKey"]!,
consumerSecret: Tumblr["consumerSecret"]!,
requestTokenUrl: "http://www.tumblr.com/oauth/request_token",
authorizeUrl: "http://www.tumblr.com/oauth/authorize",
accessTokenUrl: "http://www.tumblr.com/oauth/access_token"
)
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/tumblr")!, success: {
credential, response in
self.showAlertView("Tumblr", message: "oauth_token:\(credential.oauth_token)\n\noauth_toke_secret:\(credential.oauth_token_secret)")
}, failure: {(error:NSError!) -> Void in
println(error.localizedDescription)
})
}
func doOAuthSlack(){
let oauthswift = OAuth2Swift(
consumerKey: Slack["consumerKey"]!,
consumerSecret: Slack["consumerSecret"]!,
authorizeUrl: "https://slack.com/oauth/authorize",
accessTokenUrl: "https://slack.com/api/oauth.access",
responseType: "code"
)
let state: String = generateStateWithLength(20) as String
oauthswift.authorizeWithCallbackURL( NSURL(string: "oauth-swift://oauth-callback/slack")!, scope: "", state: state, success: {
credential, response, parameters in
self.showAlertView("Slack", message: "oauth_token:\(credential.oauth_token)")
}, failure: {(error:NSError!) -> Void in
print(error.localizedDescription)
})
}
func snapshot() -> NSData {
UIGraphicsBeginImageContext(self.view.frame.size)
self.view.layer.renderInContext(UIGraphicsGetCurrentContext())
let fullScreenshot = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
UIImageWriteToSavedPhotosAlbum(fullScreenshot, nil, nil, nil)
return UIImageJPEGRepresentation(fullScreenshot, 0.5)
}
func showAlertView(title: String, message: String) {
var alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return services.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath:NSIndexPath) -> UITableViewCell {
let cell: UITableViewCell = UITableViewCell(style: UITableViewCellStyle.Subtitle, reuseIdentifier: "Cell")
cell.textLabel?.text = services[indexPath.row]
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) {
var service: String = services[indexPath.row]
switch service {
case "Twitter":
doOAuthTwitter()
case "Flickr":
doOAuthFlickr()
case "Github":
doOAuthGithub()
case "Instagram":
doOAuthInstagram()
case "Foursquare":
doOAuthFoursquare()
case "Fitbit":
doOAuthFitbit()
case "Withings":
doOAuthWithings()
case "Linkedin":
doOAuthLinkedin()
case "Linkedin2":
doOAuthLinkedin2()
case "Dropbox":
doOAuthDropbox()
case "Dribbble":
doOAuthDribbble()
case "Salesforce":
doOAuthSalesforce()
case "BitBucket":
doOAuthBitBucket()
case "GoogleDrive":
doOAuthGoogle()
case "Smugmug":
doOAuthSmugmug()
case "Intuit":
doOAuthIntuit()
case "Zaim":
doOAuthZaim()
case "Tumblr":
doOAuthTumblr()
case "Slack":
doOAuthSlack()
default:
println("default (check ViewController tableView)")
}
tableView.deselectRowAtIndexPath(indexPath, animated:true)
}
}
| bd4e6cae9ccd14fb993e26ca4b2a25cd | 47.836327 | 237 | 0.602975 | false | false | false | false |
Ares42/Portfolio | refs/heads/master | HackerRankMobile/Models/FirebaseUser.swift | mit | 1 | //
// FirebaseUser.swift
// HackerRankMobile
//
// Created by Luke Solomon on 6/26/17.
// Copyright © 2017 Solomon Stuff. All rights reserved.
//
import Foundation
import FirebaseDatabase.FIRDataSnapshot
class FirebaseUser: NSObject {
// MARK: - Singleton
private static var _current: FirebaseUser?
var isFollowed = false
static var current: FirebaseUser {
guard let currentUser = _current else {
fatalError("Error: current user doesn't exist")
}
return currentUser
}
// MARK: - Class Methods
static func setCurrent(_ user: FirebaseUser, writeToUserDefaults: Bool) {
if writeToUserDefaults {
let data = NSKeyedArchiver.archivedData(withRootObject: user)
UserDefaults.standard.set(data, forKey: Constants.UserDefaults.currentUser)
}
_current = user
}
// MARK: - Properties
let uid: String
let username: String
// MARK: - Init
init(uid: String, username: String) {
self.uid = uid
self.username = username
super.init()
}
init?(snapshot: DataSnapshot) {
guard let dict = snapshot.value as? [String : Any],
let username = dict["username"] as? String
else { return nil }
self.uid = snapshot.key
self.username = username
super.init()
}
required init?(coder aDecoder: NSCoder) {
guard let uid = aDecoder.decodeObject(forKey: Constants.UserDefaults.uid) as? String,
let username = aDecoder.decodeObject(forKey: Constants.UserDefaults.username) as? String
else { return nil }
self.uid = uid
self.username = username
super.init()
}
}
extension FirebaseUser: NSCoding {
func encode(with aCoder: NSCoder) {
aCoder.encode(uid, forKey: Constants.UserDefaults.uid)
aCoder.encode(username, forKey: Constants.UserDefaults.username)
}
}
| 8dda2ebae0c6a364bb8eb4207b0d3e56 | 25.115385 | 100 | 0.605302 | false | false | false | false |
jairoeli/Instasheep | refs/heads/master | InstagramFirebase/InstagramFirebase/UserProfileHeader/UserProfilePhotoCell.swift | mit | 1 | //
// UserProfilePhotoCell.swift
// InstagramFirebase
//
// Created by Jairo Eli de Leon on 4/6/17.
// Copyright © 2017 DevMountain. All rights reserved.
//
import UIKit
class UserProfilePhotoCell: UICollectionViewCell {
var post: Post? {
didSet {
guard let imageURL = post?.imageURL else { return }
photoImageView.loadImage(urlString: imageURL)
}
}
let photoImageView = CustomImageView() <== {
$0.backgroundColor = .lightGray
$0.contentMode = .scaleAspectFill
$0.clipsToBounds = true
}
override init(frame: CGRect) {
super.init(frame: frame)
addSubview(photoImageView)
setupLayout()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension UserProfilePhotoCell {
fileprivate func setupLayout() {
photoImageView.anchor(top: topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, paddingTop: 0, paddingLeft: 0, paddingBottom: 0, paddingRight: 0, width: 0, height: 0)
}
}
| 61a612d18a41166000a77ef8692c5ae8 | 20.87234 | 188 | 0.692607 | false | false | false | false |
isRaining/Swift30days | refs/heads/master | 1_day/007可选项的判断/007可选项的判断/ViewController.swift | mit | 1 | //
// ViewController.swift
// 007可选项的判断
//
// Created by 张正雨 on 2017/5/16.
// Copyright © 2017年 张正雨. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
demo()
demo1(x: 10, y: 100)
demo2(x: 10, y: nil)
demo3(x: 10, y: nil)
demo3(x: nil, y: nil)
let name:String? = "老王"
print((name ?? "") + "你好")
//?? 运算优先级比较低 在使用的时候最好最好加上小括号
print(name ?? "" + "你好")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func demo() -> () {
let x:Int? = 10
let y:Int? = 20
print(x! + y!)
}
func demo1(x:Int? ,y:Int?) {
print(x! + y!)
}
func demo2(x:Int? ,y:Int?) {
if x != nil && y != nil {
print(x! + y!)
} else {
print("x或者y中有nil")
}
}
func demo3(x:Int? ,y:Int?) {
/**
?? 是一个简单的三目运算
如果x或者y有值,则取值计算
否则,则为0
*/
print((x ?? 0) + (y ?? 0))
}
}
| 643f5ff47257b75261803cd6685d8182 | 19.822581 | 80 | 0.466305 | false | false | false | false |
zhugejunwei/Algorithms-in-Java-Swift-CPP | refs/heads/master | Isomorphism & Girth/sourceCode/Girth of G.playground/Contents.swift | mit | 1 | import Foundation
struct girth {
static let case1 = [[0, 0, 0, 1, 0, 1],
[0, 0, 0, 1, 1, 1],
[0, 0, 0, 1, 0, 0],
[1, 1, 1, 0, 0, 0],
[0, 1, 0, 0, 0, 0],
[1, 1, 0, 0, 0, 0]]
static let case2 =
[[0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1],
[1, 0, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1, 1, 0, 1],
[1, 0, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 0],
[1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 0, 0, 0, 1, 1, 0, 1, 0, 1, 0, 1],
[0, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1, 1, 0, 1, 0],
[1, 0, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 0, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0, 1, 1],
[1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1],
[1, 1, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1, 1, 0],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1],
[1, 1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 0, 1, 1, 1],
[0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 1, 0, 0, 1],
[1, 0, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 0, 1],
[1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1, 1, 0]]
}
public class Node {
public var vertex: Int
public var depth: Int
init(_ vertex: Int, _ depth: Int) {
self.vertex = vertex
self.depth = depth
}
}
func FindGirth(_ graph: [[Int]]) -> Int
{
let n = graph.count
// shortest cycle length
var short = n - 1
var queue = [Node]()
var root = 0
while (root < n - 2 && short > 3)
{
var label = Array(repeating: -1, count: n)
label[root] = 0
queue.append(Node(root, 0))
var node = queue.removeFirst()
while (!queue.isEmpty && short > 3 && (node.depth + 1) * 2 - 1 < short)
{
let depth = node.depth + 1
// check all neighbours
for neighbour in getNeighbours(graph, node.vertex)
{
// haven't seen this neighbour before
if label[neighbour] < 0 {
queue.append(Node(neighbour, depth))
label[neighbour] = depth
} else if label[neighbour] == depth - 1 {
// odd number of edges
if depth * 2 - 1 < short {
short = depth * 2 - 1
}
} else if label[neighbour] == depth {
// even number of edges
if (depth * 2 < short) {
short = depth * 2
}
}
}
node = queue.removeFirst()
}
queue.removeAll()
root += 1
}
return short > 0 ? short : 1
}
func getNeighbours(_ graph: [[Int]], _ vertex: Int) -> [Int]
{
var res = [Int]()
for i in 0..<graph.count {
if graph[vertex][i] != 0 {
res.append(i)
}
}
return res
}
/* test case1
let graph = girth.case1
let result = FindGirth(graph)
print(result)
// 4
*/
// test case2
let graph = girth.case2
let result = FindGirth(graph)
print(result)
// 14
| ac3268de6f08f2a37a9da9bbd634898d | 27.132743 | 79 | 0.386285 | false | false | false | false |
bm842/Brokers | refs/heads/master | Sources/Random.swift | mit | 2 | //
// CwlRandom.swift
// CwlUtils
//
// Created by Matt Gallagher on 2016/05/17.
// Copyright © 2016 Matt Gallagher ( http://cocoawithlove.com ). All rights reserved.
//
// Permission to use, copy, modify, and/or distribute this software for any
// purpose with or without fee is hereby granted, provided that the above
// copyright notice and this permission notice appear in all copies.
//
// THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
// WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
// SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
// WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
// ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
// IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
//
import Foundation
public protocol RandomGenerator {
init()
/// Initializes the provided buffer with randomness
mutating func randomize(buffer: UnsafeMutableRawPointer, size: Int)
// Generates 64 bits of randomness
mutating func random64() -> UInt64
// Generates 32 bits of randomness
mutating func random32() -> UInt32
// Generates a uniform distribution with a maximum value no more than `max`
mutating func random64(max: UInt64) -> UInt64
// Generates a uniform distribution with a maximum value no more than `max`
mutating func random32(max: UInt32) -> UInt32
/// Generates a double with a random 52 bit significand on the half open range [0, 1)
mutating func randomHalfOpen() -> Double
/// Generates a double with a random 52 bit significand on the closed range [0, 1]
mutating func randomClosed() -> Double
/// Generates a double with a random 51 bit significand on the open range (0, 1)
mutating func randomOpen() -> Double
}
public extension RandomGenerator {
mutating func random64() -> UInt64 {
var bits: UInt64 = 0
randomize(buffer: &bits, size: MemoryLayout<UInt64>.size)
return bits
}
mutating func random32() -> UInt32 {
var bits: UInt32 = 0
randomize(buffer: &bits, size: MemoryLayout<UInt32>.size)
return bits
}
mutating func random64(max: UInt64) -> UInt64 {
switch max {
case UInt64.max: return random64()
case 0: return 0
default:
var result: UInt64
repeat {
result = random64()
} while result < UInt64.max % (max + 1)
return result % (max + 1)
}
}
mutating func random32(max: UInt32) -> UInt32 {
switch max {
case UInt32.max: return random32()
case 0: return 0
default:
var result: UInt32
repeat {
result = random32()
} while result < UInt32.max % (max + 1)
return result % (max + 1)
}
}
mutating func randomHalfOpen() -> Double {
return halfOpenDoubleFrom64(bits: random64())
}
mutating func randomClosed() -> Double {
return closedDoubleFrom64(bits: random64())
}
mutating func randomOpen() -> Double {
return openDoubleFrom64(bits: random64())
}
}
public func halfOpenDoubleFrom64(bits: UInt64) -> Double {
return Double(bits & 0x001f_ffff_ffff_ffff) * (1.0 / 9007199254740992.0)
}
public func closedDoubleFrom64(bits: UInt64) -> Double {
return Double(bits & 0x001f_ffff_ffff_ffff) * (1.0 / 9007199254740991.0)
}
public func openDoubleFrom64(bits: UInt64) -> Double {
return (Double(bits & 0x000f_ffff_ffff_ffff) + 0.5) * (1.0 / 9007199254740991.0)
}
public protocol RandomWordGenerator: RandomGenerator {
associatedtype WordType
mutating func randomWord() -> WordType
}
extension RandomWordGenerator {
public mutating func randomize(buffer: UnsafeMutableRawPointer, size: Int) {
let b = buffer.assumingMemoryBound(to: WordType.self)
for i in 0..<(size / MemoryLayout<WordType>.size) {
b[i] = randomWord()
}
let remainder = size % MemoryLayout<WordType>.size
if remainder > 0 {
var final = randomWord()
let b2 = buffer.assumingMemoryBound(to: UInt8.self)
withUnsafePointer(to: &final) { (fin: UnsafePointer<WordType>) in
fin.withMemoryRebound(to: UInt8.self, capacity: remainder) { f in
for i in 0..<remainder {
b2[size - i - 1] = f[i]
}
}
}
}
}
}
public struct DevRandom: RandomGenerator {
class FileDescriptor {
let value: CInt
init() {
value = open("/dev/urandom", O_RDONLY)
precondition(value >= 0)
}
deinit {
close(value)
}
}
let fd: FileDescriptor
public init() {
fd = FileDescriptor()
}
public mutating func randomize(buffer: UnsafeMutableRawPointer, size: Int) {
let result = read(fd.value, buffer, size)
precondition(result == size)
}
public static func random64() -> UInt64 {
var r = DevRandom()
return r.random64()
}
public static func randomize(buffer: UnsafeMutableRawPointer, size: Int) {
var r = DevRandom()
r.randomize(buffer: buffer, size: size)
}
}
public struct Arc4Random: RandomGenerator {
public init() {
}
public mutating func randomize(buffer: UnsafeMutableRawPointer, size: Int) {
arc4random_buf(buffer, size)
}
public mutating func random64() -> UInt64 {
// Generating 2x32-bit appears to be faster than using arc4random_buf on a 64-bit value
var value: UInt64 = 0
arc4random_buf(&value, MemoryLayout<UInt64>.size)
return value
}
public mutating func random32() -> UInt32 {
return arc4random()
}
}
public struct Lfsr258: RandomWordGenerator {
public typealias WordType = UInt64
public typealias StateType = (UInt64, UInt64, UInt64, UInt64, UInt64)
static let k: (UInt64, UInt64, UInt64, UInt64, UInt64) = (1, 9, 12, 17, 23)
static let q: (UInt64, UInt64, UInt64, UInt64, UInt64) = (1, 24, 3, 5, 3)
static let s: (UInt64, UInt64, UInt64, UInt64, UInt64) = (10, 5, 29, 23, 8)
var state: StateType = (0, 0, 0, 0, 0)
public init() {
var r = DevRandom()
repeat {
r.randomize(buffer: &state.0, size: MemoryLayout<UInt64>.size)
} while state.0 < Lfsr258.k.0
repeat {
r.randomize(buffer: &state.1, size: MemoryLayout<UInt64>.size)
} while state.1 < Lfsr258.k.1
repeat {
r.randomize(buffer: &state.2, size: MemoryLayout<UInt64>.size)
} while state.2 < Lfsr258.k.2
repeat {
r.randomize(buffer: &state.3, size: MemoryLayout<UInt64>.size)
} while state.3 < Lfsr258.k.3
repeat {
r.randomize(buffer: &state.4, size: MemoryLayout<UInt64>.size)
} while state.4 < Lfsr258.k.4
}
public init(seed: StateType) {
self.state = seed
}
public mutating func randomWord() -> UInt64 {
return random64()
}
public mutating func random64() -> UInt64 {
// Constants from "Tables of Maximally-Equidistributed Combined LFSR Generators" by Pierre L'Ecuyer:
// http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps
let l: UInt64 = 64
let x0 = (((state.0 << Lfsr258.q.0) ^ state.0) >> (l - Lfsr258.k.0 - Lfsr258.s.0))
state.0 = ((state.0 & (UInt64.max << Lfsr258.k.0)) << Lfsr258.s.0) | x0
let x1 = (((state.1 << Lfsr258.q.1) ^ state.1) >> (l - Lfsr258.k.1 - Lfsr258.s.1))
state.1 = ((state.1 & (UInt64.max << Lfsr258.k.1)) << Lfsr258.s.1) | x1
let x2 = (((state.2 << Lfsr258.q.2) ^ state.2) >> (l - Lfsr258.k.2 - Lfsr258.s.2))
state.2 = ((state.2 & (UInt64.max << Lfsr258.k.2)) << Lfsr258.s.2) | x2
let x3 = (((state.3 << Lfsr258.q.3) ^ state.3) >> (l - Lfsr258.k.3 - Lfsr258.s.3))
state.3 = ((state.3 & (UInt64.max << Lfsr258.k.3)) << Lfsr258.s.3) | x3
let x4 = (((state.4 << Lfsr258.q.4) ^ state.4) >> (l - Lfsr258.k.4 - Lfsr258.s.4))
state.4 = ((state.4 & (UInt64.max << Lfsr258.k.4)) << Lfsr258.s.4) | x4
return (state.0 ^ state.1 ^ state.2 ^ state.3 ^ state.4)
}
}
public struct Lfsr176: RandomWordGenerator {
public typealias WordType = UInt64
public typealias StateType = (UInt64, UInt64, UInt64)
static let k: (UInt64, UInt64, UInt64) = (1, 6, 9)
static let q: (UInt64, UInt64, UInt64) = (5, 19, 24)
static let s: (UInt64, UInt64, UInt64) = (24, 13, 17)
var state: StateType = (0, 0, 0)
public init() {
var r = DevRandom()
repeat {
r.randomize(buffer: &state.0, size: MemoryLayout<UInt64>.size)
} while state.0 < Lfsr176.k.0
repeat {
r.randomize(buffer: &state.1, size: MemoryLayout<UInt64>.size)
} while state.1 < Lfsr176.k.1
repeat {
r.randomize(buffer: &state.2, size: MemoryLayout<UInt64>.size)
} while state.2 < Lfsr176.k.2
}
public init(seed: StateType) {
self.state = seed
}
public mutating func random64() -> UInt64 {
return randomWord()
}
public mutating func randomWord() -> UInt64 {
// Constants from "Tables of Maximally-Equidistributed Combined LFSR Generators" by Pierre L'Ecuyer:
// http://www.iro.umontreal.ca/~lecuyer/myftp/papers/tausme2.ps
let l: UInt64 = 64
let x0 = (((state.0 << Lfsr176.q.0) ^ state.0) >> (l - Lfsr176.k.0 - Lfsr176.s.0))
state.0 = ((state.0 & (UInt64.max << Lfsr176.k.0)) << Lfsr176.s.0) | x0
let x1 = (((state.1 << Lfsr176.q.1) ^ state.1) >> (l - Lfsr176.k.1 - Lfsr176.s.1))
state.1 = ((state.1 & (UInt64.max << Lfsr176.k.1)) << Lfsr176.s.1) | x1
let x2 = (((state.2 << Lfsr176.q.2) ^ state.2) >> (l - Lfsr176.k.2 - Lfsr176.s.2))
state.2 = ((state.2 & (UInt64.max << Lfsr176.k.2)) << Lfsr176.s.2) | x2
return (state.0 ^ state.1 ^ state.2)
}
}
public struct Xoroshiro: RandomWordGenerator {
public typealias WordType = UInt64
public typealias StateType = (UInt64, UInt64)
var state: StateType = (0, 0)
public init() {
DevRandom.randomize(buffer: &state, size: MemoryLayout<StateType>.size)
}
public init(seed: StateType) {
self.state = seed
}
public mutating func random64() -> UInt64 {
return randomWord()
}
public mutating func randomWord() -> UInt64 {
// Directly inspired by public domain implementation here:
// http://xoroshiro.di.unimi.it
// by David Blackman and Sebastiano Vigna
let (l, k0, k1, k2): (UInt64, UInt64, UInt64, UInt64) = (64, 55, 14, 36)
let result = state.0 &+ state.1
let x = state.0 ^ state.1
state.0 = ((state.0 << k0) | (state.0 >> (l - k0))) ^ x ^ (x << k1)
state.1 = (x << k2) | (x >> (l - k2))
return result
}
}
public struct ConstantNonRandom: RandomWordGenerator {
public typealias WordType = UInt64
var state: UInt64 = DevRandom.random64()
public init() {
}
public init(seed: UInt64) {
self.state = seed
}
public mutating func random64() -> UInt64 {
return randomWord()
}
public mutating func randomWord() -> UInt64 {
return state
}
}
public struct MersenneTwister: RandomWordGenerator {
public typealias WordType = UInt64
// 312 is 13 x 6 x 4
private var state_internal: (
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64,
UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64, UInt64
) = (
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
)
private var index: Int
private static let stateCount: Int = 312
public init() {
self.init(seed: DevRandom.random64())
}
public init(seed: UInt64) {
index = MersenneTwister.stateCount
withUnsafeMutablePointer(to: &state_internal) { $0.withMemoryRebound(to: UInt64.self, capacity: MersenneTwister.stateCount) { state in
state[0] = seed
for i in 1..<MersenneTwister.stateCount {
state[i] = 6364136223846793005 &* (state[i &- 1] ^ (state[i &- 1] >> 62)) &+ UInt64(i)
}
} }
}
public mutating func randomWord() -> UInt64 {
return random64()
}
private mutating func twist() {
}
public mutating func random64() -> UInt64 {
if index == MersenneTwister.stateCount {
// Really dirty leaking of unsafe pointer outside its closure to ensure inlining in Swift 3 preview 1
let state = withUnsafeMutablePointer(to: &state_internal) { $0.withMemoryRebound(to: UInt64.self, capacity: MersenneTwister.stateCount) { $0 } }
let n = MersenneTwister.stateCount
let m = n / 2
let a: UInt64 = 0xB5026F5AA96619E9
let lowerMask: UInt64 = (1 << 31) - 1
let upperMask: UInt64 = ~lowerMask
var (i, j, stateM) = (0, m, state[m])
repeat {
let x1 = (state[i] & upperMask) | (state[i &+ 1] & lowerMask)
state[i] = state[i &+ m] ^ (x1 >> 1) ^ ((state[i &+ 1] & 1) &* a)
let x2 = (state[j] & upperMask) | (state[j &+ 1] & lowerMask)
state[j] = state[j &- m] ^ (x2 >> 1) ^ ((state[j &+ 1] & 1) &* a)
(i, j) = (i &+ 1, j &+ 1)
} while i != m &- 1
let x3 = (state[m &- 1] & upperMask) | (stateM & lowerMask)
state[m &- 1] = state[n &- 1] ^ (x3 >> 1) ^ ((stateM & 1) &* a)
let x4 = (state[n &- 1] & upperMask) | (state[0] & lowerMask)
state[n &- 1] = state[m &- 1] ^ (x4 >> 1) ^ ((state[0] & 1) &* a)
index = 0
}
var result = withUnsafePointer(to: &state_internal) { $0.withMemoryRebound(to: UInt64.self, capacity: MersenneTwister.stateCount) { ptr in
return ptr[index]
} }
index = index &+ 1
result ^= (result >> 29) & 0x5555555555555555
result ^= (result << 17) & 0x71D67FFFEDA60000
result ^= (result << 37) & 0xFFF7EEE000000000
result ^= result >> 43
return result
}
}
| b3ee962eb6412c54704a9f72d54609a0 | 38.43617 | 156 | 0.57092 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/Parse/init_deinit.swift | apache-2.0 | 2 | // RUN: %target-typecheck-verify-swift
struct FooStructConstructorA {
init // expected-error {{expected '('}}
}
struct FooStructConstructorB {
init() // expected-error {{initializer requires a body}}
}
struct FooStructConstructorC {
init {} // expected-error {{expected '('}}{{7-7=()}}
init<T> {} // expected-error {{expected '('}} {{10-10=()}}
init? { self.init() } // expected-error {{expected '('}} {{8-8=()}}
}
struct FooStructDeinitializerA {
deinit // expected-error {{expected '{' for deinitializer}}
deinit x // expected-error {{deinitializers cannot have a name}} {{10-12=}}
deinit x() // expected-error {{deinitializers cannot have a name}} {{10-11=}}
}
struct FooStructDeinitializerB {
deinit // expected-error {{expected '{' for deinitializer}}
}
struct FooStructDeinitializerC {
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
class FooClassDeinitializerA {
deinit(a : Int) {} // expected-error{{no parameter clause allowed on deinitializer}}{{9-18=}}
}
class FooClassDeinitializerB {
deinit { }
}
init {} // expected-error {{initializers may only be declared within a type}} expected-error {{expected '('}} {{5-5=()}}
init() // expected-error {{initializers may only be declared within a type}}
init() {} // expected-error {{initializers may only be declared within a type}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
deinit // expected-error {{expected '{' for deinitializer}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
struct BarStruct {
init() {}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
extension BarStruct {
init(x : Int) {}
// When/if we allow 'var' in extensions, then we should also allow dtors
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
enum BarUnion {
init() {}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
extension BarUnion {
init(x : Int) {}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
class BarClass {
init() {}
deinit {}
}
extension BarClass {
convenience init(x : Int) { self.init() }
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
protocol BarProtocol {
init() {} // expected-error {{protocol initializers may not have bodies}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
extension BarProtocol {
init(x : Int) {}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
func fooFunc() {
init() {} // expected-error {{initializers may only be declared within a type}}
deinit {} // expected-error {{deinitializers may only be declared within a class}}
}
func barFunc() {
var x : () = { () -> () in
init() {} // expected-error {{initializers may only be declared within a type}}
return
} ()
var y : () = { () -> () in
deinit {} // expected-error {{deinitializers may only be declared within a class}}
return
} ()
}
// SR-852
class Aaron {
init(x: Int) {}
convenience init() { init(x: 1) } // expected-error {{missing 'self.' at initializer invocation}} {{24-24=self.}}
}
class Theodosia: Aaron {
init() {
init(x: 2) // expected-error {{missing 'super.' at initializer invocation}} {{5-5=super.}}
}
}
struct AaronStruct {
init(x: Int) {}
init() { init(x: 1) } // expected-error {{missing 'self.' at initializer invocation}} {{12-12=self.}}
}
enum AaronEnum: Int {
case A = 1
init(x: Int) { init(rawValue: x)! } // expected-error {{missing 'self.' at initializer invocation}} {{18-18=self.}}
}
| 97d5bd6155ddc5b65fa0dc4dc27aa52f | 28.480315 | 120 | 0.665331 | false | false | false | false |
ProjectDent/ARKit-CoreLocation | refs/heads/develop | Sources/ARKit-CoreLocation/Nodes/LocationAnnotationNode.swift | mit | 1 | //
// LocationNode.swift
// ARKit+CoreLocation
//
// Created by Andrew Hart on 02/07/2017.
// Copyright © 2017 Project Dent. All rights reserved.
//
import Foundation
import SceneKit
import CoreLocation
/// A `LocationNode` which has an attached `AnnotationNode`.
open class LocationAnnotationNode: LocationNode {
/// Subnodes and adjustments should be applied to this subnode
/// Required to allow scaling at the same time as having a 2D 'billboard' appearance
public let annotationNode: AnnotationNode
/// Parameter to raise or lower the label's rendering position relative to the node's actual project location.
/// The default value of 1.1 places the label at a pleasing height above the node.
/// To draw the label exactly on the true location, use a value of 0. To draw it below the true location,
/// use a negative value.
public var annotationHeightAdjustmentFactor = 1.1
public init(location: CLLocation?, image: UIImage) {
let plane = SCNPlane(width: image.size.width / 100, height: image.size.height / 100)
plane.firstMaterial?.diffuse.contents = image
plane.firstMaterial?.lightingModel = .constant
annotationNode = AnnotationNode(view: nil, image: image)
annotationNode.geometry = plane
annotationNode.removeFlicker()
super.init(location: location)
let billboardConstraint = SCNBillboardConstraint()
billboardConstraint.freeAxes = SCNBillboardAxis.Y
constraints = [billboardConstraint]
addChildNode(annotationNode)
}
@available(iOS 10.0, *)
/// Use this constructor to add a UIView as an annotation. Keep in mind that it is not live, instead
/// it's a "snapshot" of that UIView. UIView is more configurable then a UIImage, allowing you to add
/// background image, labels, etc.
///
/// - Parameters:
/// - location:The location of the node in the world.
/// - view:The view to display at the specified location.
public convenience init(location: CLLocation?, view: UIView) {
self.init(location: location, image: view.image)
}
public init(location: CLLocation?, layer: CALayer) {
let plane = SCNPlane(width: layer.bounds.size.width / 100, height: layer.bounds.size.height / 100)
plane.firstMaterial?.diffuse.contents = layer
plane.firstMaterial?.lightingModel = .constant
annotationNode = AnnotationNode(view: nil, image: nil, layer: layer)
annotationNode.geometry = plane
annotationNode.removeFlicker()
super.init(location: location)
let billboardConstraint = SCNBillboardConstraint()
billboardConstraint.freeAxes = SCNBillboardAxis.Y
constraints = [billboardConstraint]
addChildNode(annotationNode)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/// Note: we repeat code from `LocationNode`'s implementation of this function. Is this because of the use of `SCNTransaction`
/// to wrap the changes? It's legal to nest the calls, should consider this if any more changes to
/// `LocationNode`'s implementation are needed.
override func updatePositionAndScale(setup: Bool = false, scenePosition: SCNVector3?,
locationNodeLocation nodeLocation: CLLocation,
locationManager: SceneLocationManager,
onCompletion: (() -> Void)) {
guard let position = scenePosition, let location = locationManager.currentLocation else { return }
SCNTransaction.begin()
SCNTransaction.animationDuration = setup ? 0.0 : 0.1
let distance = self.location(locationManager.bestLocationEstimate).distance(from: location)
childNodes.first?.renderingOrder = renderingOrder(fromDistance: distance)
let adjustedDistance = self.adjustedDistance(setup: setup, position: position,
locationNodeLocation: nodeLocation, locationManager: locationManager)
// The scale of a node with a billboard constraint applied is ignored
// The annotation subnode itself, as a subnode, has the scale applied to it
let appliedScale = self.scale
self.scale = SCNVector3(x: 1, y: 1, z: 1)
var scale: Float
if scaleRelativeToDistance {
scale = appliedScale.y
annotationNode.scale = appliedScale
annotationNode.childNodes.forEach { child in
child.scale = appliedScale
}
} else {
let scaleFunc = scalingScheme.getScheme()
scale = scaleFunc(distance, adjustedDistance)
annotationNode.scale = SCNVector3(x: scale, y: scale, z: scale)
annotationNode.childNodes.forEach { node in
node.scale = SCNVector3(x: scale, y: scale, z: scale)
}
}
// Translate the pivot's Y coordinate so the label will show above or below the actual node location.
self.pivot = SCNMatrix4MakeTranslation(0, Float(-1 * annotationHeightAdjustmentFactor) * scale, 0)
SCNTransaction.commit()
onCompletion()
}
}
// MARK: - Image from View
public extension UIView {
@available(iOS 10.0, *)
/// Gets you an image from the view.
var image: UIImage {
let renderer = UIGraphicsImageRenderer(bounds: bounds)
return renderer.image { rendererContext in
layer.render(in: rendererContext.cgContext)
}
}
}
| b5d0c68a8fe9a51e1beaf2d8974214cc | 39.510791 | 130 | 0.662049 | false | false | false | false |
gontovnik/Periscope-VideoViewController | refs/heads/master | VideoViewController/TimelineView.swift | mit | 1 | // TimelineView.swift
//
// Copyright (c) 2016 Danil Gontovnik (http://gontovnik.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
open class TimelineView: UIView {
// MARK: - Vars
/// The duration of the video in seconds.
open var duration: TimeInterval = 0.0 {
didSet { setNeedsDisplay() }
}
/// Time in seconds when rewind began.
open var initialTime: TimeInterval = 0.0 {
didSet {
currentTime = initialTime
}
}
/// Current timeline time in seconds.
open var currentTime: TimeInterval = 0.0 {
didSet {
setNeedsDisplay()
currentTimeDidChange?(currentTime)
}
}
/// Internal zoom variable.
fileprivate var _zoom: CGFloat = 1.0 {
didSet { setNeedsDisplay() }
}
/// The zoom of the timeline view. The higher zoom value, the more accurate rewind is. Default is 1.0.
open var zoom: CGFloat {
get { return _zoom }
set { _zoom = max(min(newValue, maxZoom), minZoom) }
}
/// Indicates minimum zoom value. Default is 1.0.
open var minZoom: CGFloat = 1.0 {
didSet { zoom = _zoom }
}
/// Indicates maximum zoom value. Default is 3.5.
open var maxZoom: CGFloat = 3.5 {
didSet { zoom = _zoom }
}
/// The width of a line representing a specific time interval on a timeline. If zoom is not equal 1, then actual interval width equals to intervalWidth * zoom. Value will be used during rewind for calculations — for example, if zoom is 1, intervalWidth is 30 and intervalDuration is 15, then when user moves 10pixels left or right we will rewind by +5 or -5 seconds;
open var intervalWidth: CGFloat = 24.0 {
didSet { setNeedsDisplay() }
}
/// The duration of an interval in seconds. If video is 55 seconds and interval is 15 seconds — then we will have 3 full intervals and one not full interval. Value will be used during rewind for calculations.
open var intervalDuration: CGFloat = 15.0 {
didSet { setNeedsDisplay() }
}
/// Block which will be triggered everytime currentTime value changes.
open var currentTimeDidChange: ((TimeInterval) -> ())?
// MARK: - Constructors
public init() {
super.init(frame: .zero)
isOpaque = false
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Methods
/**
Calculate current interval width. It takes two variables in count - intervalWidth and zoom.
*/
fileprivate func currentIntervalWidth() -> CGFloat {
return intervalWidth * zoom
}
/**
Calculates time interval in seconds from passed width.
- Parameter width: The distance.
*/
open func timeIntervalFromDistance(_ distance: CGFloat) -> TimeInterval {
return TimeInterval(distance * intervalDuration / currentIntervalWidth())
}
/**
Calculates distance from given time interval.
- Parameter duration: The duration of an interval.
*/
open func distanceFromTimeInterval(_ timeInterval: TimeInterval) -> CGFloat {
return currentIntervalWidth() * CGFloat(timeInterval) / intervalDuration
}
/**
Rewinds by distance. Calculates interval width and adds it to the current time.
- Parameter distance: The distance how far it should rewind by.
*/
open func rewindByDistance(_ distance: CGFloat) {
let newCurrentTime = currentTime + timeIntervalFromDistance(distance)
currentTime = max(min(newCurrentTime, duration), 0.0)
}
// MARK: - Draw
override open func draw(_ rect: CGRect) {
super.draw(rect)
let intervalWidth = currentIntervalWidth()
let originX: CGFloat = bounds.width / 2.0 - distanceFromTimeInterval(currentTime)
let context = UIGraphicsGetCurrentContext()
let lineHeight: CGFloat = 5.0
// Calculate how many intervals it contains
let intervalsCount = CGFloat(duration) / intervalDuration
// Draw full line
context?.setFillColor(UIColor(white: 0.45, alpha: 1.0).cgColor)
let totalPath = UIBezierPath(roundedRect: CGRect(x: originX, y: 0.0, width: intervalWidth * intervalsCount, height: lineHeight), cornerRadius: lineHeight).cgPath
context?.addPath(totalPath)
context?.fillPath()
// Draw elapsed line
context?.setFillColor(UIColor.white.cgColor)
let elapsedPath = UIBezierPath(roundedRect: CGRect(x: originX, y: 0.0, width: distanceFromTimeInterval(currentTime), height: lineHeight), cornerRadius: lineHeight).cgPath
context?.addPath(elapsedPath)
context?.fillPath()
// Draw current time dot
context?.fillEllipse(in: CGRect(x: originX + distanceFromTimeInterval(initialTime), y: 7.0, width: 3.0, height: 3.0))
// Draw full line separators
context?.setFillColor(UIColor(white: 0.0, alpha: 0.5).cgColor)
var intervalIdx: CGFloat = 0.0
repeat {
intervalIdx += 1.0
if intervalsCount - intervalIdx > 0.0 {
context?.fill(CGRect(x: originX + intervalWidth * intervalIdx, y: 0.0, width: 1.0, height: lineHeight))
}
} while intervalIdx < intervalsCount
}
}
| 67847dc2abc608f422152d7ec2752456 | 36.297143 | 370 | 0.652061 | false | false | false | false |
Alan007/iOS-Study-Demo | refs/heads/master | Swift版的FMDB和CoreData学习_转/SwiftCoreData/CoreData/CoreDataDAO.swift | apache-2.0 | 28 | //
// CoreDataDAO.swift
//
//
// Created by Limin Du on 1/22/15.
// Copyright (c) 2015 . All rights reserved.
//
import Foundation
import CoreData
class CoreDataDAO {
var context:CoreDataContext!
init() {
context = CoreDataContext()
}
func getEntities()->[NSManagedObject] {
var entity = [NSManagedObject]()
let managedContext = context.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName:"Person")
//3
var error: NSError?
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]?
if let results = fetchedResults {
entity = results
} else {
//println("Could not fetch \(error), \(error!.userInfo)")
}
return entity
}
func queryEntityByName(name:String)->NSManagedObject?{
var entity = [NSManagedObject]()
let managedContext = context.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName:"Person")
let predicate = NSPredicate(format: "%K = %@", "name", name)
fetchRequest.predicate = predicate
var error: NSError?
let fetchedResults = managedContext.executeFetchRequest(fetchRequest, error: &error) as [NSManagedObject]?
if let results = fetchedResults {
if results.count == 0 {
return nil
}
entity = results
} else {
//println("Could not fetch \(error), \(error!.userInfo)")
return nil
}
return entity[0]
}
func saveEntity(name:String)->NSManagedObject? {
if let _ = queryEntityByName(name) {
return nil
}
let managedContext = context.managedObjectContext!
let entity = NSEntityDescription.entityForName("Person", inManagedObjectContext:managedContext)
let person = NSManagedObject(entity: entity!, insertIntoManagedObjectContext:managedContext)
person.setValue(name, forKey: "name")
var error: NSError?
if !managedContext.save(&error) {
println("Could not save \(error), \(error?.userInfo)")
return nil
}
return person
}
func deleteEntity(name:String)->Bool {
let managedContext = context.managedObjectContext!
let entityToDelete = queryEntityByName(name)
if let entity = entityToDelete {
managedContext.deleteObject(entity)
var error:NSError?
if managedContext.save(&error) != true {
println("Delete error: " + error!.localizedDescription)
return false
}
return true
}
return false
}
func saveContext() {
context.saveContext()
}
} | ce7316c18e64e8c38ded47006b82df82 | 26.779817 | 114 | 0.55963 | false | false | false | false |
prey/prey-ios-client | refs/heads/master | Prey/Classes/PreyDevice.swift | gpl-3.0 | 1 | //
// PreyDevice.swift
// Prey
//
// Created by Javier Cala Uribe on 15/03/16.
// Copyright © 2016 Prey, Inc. All rights reserved.
//
import Foundation
import UIKit
class PreyDevice {
// MARK: Properties
var deviceKey: String?
var name: String?
var type: String?
var model: String?
var vendor: String?
var os: String?
var version: String?
var macAddress: String?
var uuid: String?
var cpuModel: String?
var cpuSpeed: String?
var cpuCores: String?
var ramSize: String?
// MARK: Functions
// Init function
fileprivate init() {
name = UIDevice.current.name
type = (IS_IPAD) ? "Tablet" : "Phone"
os = "iOS"
vendor = "Apple"
model = UIDevice.current.deviceModel.rawValue
version = UIDevice.current.systemVersion
uuid = UIDevice.current.identifierForVendor?.uuidString
macAddress = "02:00:00:00:00:00" // iOS default
ramSize = UIDevice.current.ramSize
cpuModel = UIDevice.current.cpuModel
cpuSpeed = UIDevice.current.cpuSpeed
cpuCores = UIDevice.current.cpuCores
}
// Add new device to Panel Prey
class func addDeviceWith(_ onCompletion:@escaping (_ isSuccess: Bool) -> Void) {
let preyDevice = PreyDevice()
let hardwareInfo : [String:String] = [
"uuid" : preyDevice.uuid!,
"serial_number": preyDevice.uuid!,
"cpu_model" : preyDevice.cpuModel!,
"cpu_speed" : preyDevice.cpuSpeed!,
"cpu_cores" : preyDevice.cpuCores!,
"ram_size" : preyDevice.ramSize!]
let params:[String:Any] = [
"name" : preyDevice.name!,
"device_type" : preyDevice.type!,
"os_version" : preyDevice.version!,
"model_name" : preyDevice.model!,
"vendor_name" : preyDevice.vendor!,
"os" : preyDevice.os!,
"physical_address" : preyDevice.macAddress!,
"hardware_attributes" : hardwareInfo]
// Check userApiKey isn't empty
if let username = PreyConfig.sharedInstance.userApiKey {
PreyHTTPClient.sharedInstance.userRegisterToPrey(username, password:"x", params:params, messageId:nil, httpMethod:Method.POST.rawValue, endPoint:devicesEndpoint, onCompletion:PreyHTTPResponse.checkResponse(RequestType.addDevice, preyAction:nil, onCompletion:onCompletion))
} else {
let titleMsg = "Couldn't add your device".localized
let alertMsg = "Error user ID".localized
displayErrorAlert(alertMsg, titleMessage:titleMsg)
onCompletion(false)
}
}
class func renameDevice(_ newName: String, onCompletion:@escaping (_ isSuccess: Bool) -> Void) {
let language:String = Locale.preferredLanguages[0] as String
let languageES = (language as NSString).substring(to: 2)
let params:[String: Any] = [
"name" : newName,
"lang" : languageES]
if let username = PreyConfig.sharedInstance.userApiKey {
PreyHTTPClient.sharedInstance.userRegisterToPrey(username, password:"x", params:params, messageId:nil, httpMethod:Method.PUT.rawValue, endPoint:actionsDeviceEndpoint, onCompletion:PreyHTTPResponse.checkResponse(RequestType.signUp, preyAction:nil, onCompletion:onCompletion))
}else{
PreyLogger("Error renameDevice")
}
}
class func infoDevice(_ onCompletion:@escaping (_ isSuccess: Bool) -> Void) {
if let username = PreyConfig.sharedInstance.userApiKey {
PreyHTTPClient.sharedInstance.userRegisterToPrey(username, password:"x", params:nil, messageId:nil, httpMethod:Method.GET.rawValue, endPoint:infoEndpoint, onCompletion:PreyHTTPResponse.checkResponse(RequestType.infoDevice, preyAction:nil, onCompletion:onCompletion))
}else{
PreyLogger("Error infoDevice")
}
}
}
| 11b863839143773e0a44ae3aa9172ee1 | 39.745283 | 286 | 0.588331 | false | false | false | false |
luowei/Swift-Samples | refs/heads/master | LWPickerLabel/LWAddressService.swift | apache-2.0 | 1 | //
// LWAddressService.swift
// ACERepair
//
// Created by luowei on 16/8/4.
// Copyright © 2016年 2345.com. All rights reserved.
//
import UIKit
class LWAddress {
var ownId: String
var name: String
var superId: String
init(ownId: String, name: String, superId: String) {
self.ownId = ownId
self.name = name
self.superId = superId
}
}
enum SQLiteError: ErrorType {
case OpenDatabase(message:String)
case Prepare(message:String)
case Step(message:String)
case Bind(message:String)
}
class LWAddressService {
private let dbPointer: COpaquePointer
static func open() throws -> LWAddressService? {
var db: COpaquePointer = nil
guard let path = NSBundle.mainBundle().pathForResource("app_address", ofType: "sqlite") as String? else{
//throw SQLiteError.OpenDatabase(message: "Address db not found")
print("Address db not found")
return nil
}
if sqlite3_open(path, &db) == SQLITE_OK {
return LWAddressService(dbPointer: db) as LWAddressService?
} else {
defer {
if db != nil {
sqlite3_close(db)
}
}
if let message = String.fromCString(sqlite3_errmsg(db)) {
//throw SQLiteError.OpenDatabase(message: message)
print(message)
return nil
} else {
//throw SQLiteError.OpenDatabase(message: "No error message provided from sqlite.")
print("No error message provided from sqlite.")
return nil
}
}
}
private init(dbPointer: COpaquePointer) {
self.dbPointer = dbPointer
}
deinit {
sqlite3_close(dbPointer)
}
private var errorMessage: String {
if let errorMessage = String.fromCString(sqlite3_errmsg(dbPointer)) {
return errorMessage
} else {
return "No error message provided from sqlite."
}
}
}
//Preparing Statements
extension LWAddressService {
func prepareStatement(sql: String) throws -> COpaquePointer {
var statement: COpaquePointer = nil
guard sqlite3_prepare_v2(dbPointer, sql, -1, &statement, nil) == SQLITE_OK else {
throw SQLiteError.Prepare(message: errorMessage)
}
return statement
}
}
//read
extension LWAddressService {
func address(id: String) -> LWAddress? {
let querySql = "SELECT * FROM address WHERE ownId = '\(id)'"
return self.queryOne(querySql)
}
func superAddress(id:String) -> LWAddress? {
let querySql = "SELECT * FROM address WHERE superId = '\(id)'"
return self.queryOne(querySql)
}
func queryOne(sql: String) -> LWAddress? {
guard let statement = try? prepareStatement(sql) else {
return nil
}
defer {
sqlite3_finalize(statement)
}
// guard let param = id as String? where sqlite3_bind_text(statement, 1, param, -1, nil) == SQLITE_OK else {
// return nil
// }
guard sqlite3_step(statement) == SQLITE_ROW else {
return nil
}
let col1 = sqlite3_column_text(statement, 0)
guard let ownId = String.fromCString(UnsafePointer<CChar>(col1)) else{
return nil
}
let col2 = sqlite3_column_text(statement, 1)
guard let name = String.fromCString(UnsafePointer<CChar>(col2)) else{
return nil
}
let col3 = sqlite3_column_text(statement, 1)
guard let superId = String.fromCString(UnsafePointer<CChar>(col3)) else{
return nil
}
return LWAddress(ownId: ownId, name: name, superId: superId)
}
func provinceList() -> [LWAddress]? {
let querySql = "SELECT * FROM address_province"
return self.list(querySql);
}
func cityList(provinceId: String) -> [LWAddress]? {
let querySql = "SELECT * FROM address_city WHERE superId = '\(provinceId)'"
return self.list(querySql);
}
func areaList(cityId: String) -> [LWAddress]? {
let querySql = "SELECT * FROM address_area WHERE superId = '\(cityId)'"
return self.list(querySql);
}
func townList(areaId: String) -> [LWAddress]? {
let querySql = "SELECT * FROM address_town WHERE superId = '\(areaId)'"
return self.list(querySql);
}
func list(sql: String) -> [LWAddress]? {
var list = [LWAddress]()
guard var statement = try? prepareStatement(sql) else {
return nil
}
defer {
sqlite3_finalize(statement)
}
// if id != nil {
// guard let param = id as String? where sqlite3_bind_text(statement, 1, param, -1, nil) == SQLITE_OK else {
// return nil
// }
// }
// guard sqlite3_prepare_v2(dbPointer, sql, -1, &statement, nil) == SQLITE_OK else{
// guard let errmsg = String.fromCString(sqlite3_errmsg(dbPointer)) as String? else{ return nil }
// SQLiteError.Prepare(message: errmsg)
// return nil
// }
while sqlite3_step(statement) == SQLITE_ROW {
let col1 = sqlite3_column_text(statement, 0)
guard let ownId = String.fromCString(UnsafePointer<CChar>(col1)) else{
return nil
}
let col2 = sqlite3_column_text(statement, 1)
guard let name = String.fromCString(UnsafePointer<CChar>(col2)) else{
return nil
}
let col3 = sqlite3_column_text(statement, 2)
guard let superId = String.fromCString(UnsafePointer<CChar>(col3)) else{
return nil
}
let addr = LWAddress(ownId: ownId, name: name, superId: superId)
list.append(addr)
}
return list;
}
}
| 2f1730aace8cc646920a6a2db6fde582 | 27.712264 | 119 | 0.563989 | false | false | false | false |
IsaoTakahashi/iOS-KaraokeSearch | refs/heads/master | KaraokeSearch/FavSongTableViewCell.swift | mit | 1 | //
// FavSongTableViewCell.swift
// KaraokeSearch
//
// Created by 高橋 勲 on 2015/05/10.
// Copyright (c) 2015年 高橋 勲. All rights reserved.
//
import UIKit
import MaterialKit
class FavSongTableViewCell: MKTableViewCell {
@IBOutlet weak var artistLabel: MKLabel!
@IBOutlet weak var songLabel: MKLabel!
@IBOutlet weak var registeredLabel: MKLabel!
var dateFormatter: NSDateFormatter = NSDateFormatter()
override init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
// UILabelとかを追加
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func configureCell(song: FavoredSong, atIndexPath indexPath: NSIndexPath){
artistLabel.textColor = UIColor.MainDarkColor()
songLabel.textColor = UIColor.MainDarkColor()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
artistLabel.text = song.artistName
songLabel.text = song.songTitle
registeredLabel.text = "faved at: " + dateFormatter.stringFromDate(song.favoredAt)
registeredLabel.textColor = UIColor.SubDarkColor()
self.rippleLocation = .TapLocation
self.rippleLayerColor = UIColor.MainLightColor()
self.selectionStyle = .None
}
} | 316805ec6cb00f64d3cfcffc7510785e | 28.652174 | 90 | 0.672781 | false | false | false | false |
rsmoz/swift-corelibs-foundation | refs/heads/master | Foundation/NSXMLElement.swift | apache-2.0 | 1 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
/*!
@class NSXMLElement
@abstract An XML element
@discussion Note: Trying to add a document, namespace, attribute, or node with a parent throws an exception. To add a node with a parent first detach or create a copy of it.
*/
public class NSXMLElement : NSXMLNode {
/*!
@method initWithName:
@abstract Returns an element <tt><name></name></tt>.
*/
public convenience init(name: String) {
self.init(name: name, URI: nil)
}
/*!
@method initWithName:URI:
@abstract Returns an element whose full QName is specified.
*/
public init(name: String, URI: String?) {
super.init(kind: .ElementKind, options: 0)
self.URI = URI
self.name = name
} //primitive
/*!
@method initWithName:stringValue:
@abstract Returns an element with a single text node child <tt><name>string</name></tt>.
*/
public convenience init(name: String, stringValue string: String?) {
self.init(name: name, URI: nil)
if let string = string {
let child = _CFXMLNewTextNode(string)
_CFXMLNodeAddChild(_xmlNode, child)
}
}
/*!
@method initWithXMLString:error:
@abstract Returns an element created from a string. Parse errors are collected in <tt>error</tt>.
*/
public init(XMLString string: String) throws { NSUnimplemented() }
public convenience override init(kind: NSXMLNodeKind, options: Int) {
self.init(name: "", URI: nil)
}
/*!
@method elementsForName:
@abstract Returns all of the child elements that match this name.
*/
public func elementsForName(name: String) -> [NSXMLElement] {
return self.filter({ _CFXMLNodeGetType($0._xmlNode) == _kCFXMLTypeElement }).filter({ $0.name == name }).flatMap({ $0 as? NSXMLElement })
}
/*!
@method elementsForLocalName:URI
@abstract Returns all of the child elements that match this localname URI pair.
*/
public func elementsForLocalName(localName: String, URI: String?) -> [NSXMLElement] { NSUnimplemented() }
/*!
@method addAttribute:
@abstract Adds an attribute. Attributes with duplicate names are not added.
*/
public func addAttribute(attribute: NSXMLNode) {
guard _CFXMLNodeHasProp(_xmlNode, UnsafePointer<UInt8>(_CFXMLNodeGetName(attribute._xmlNode))) == nil else { return }
addChild(attribute)
} //primitive
/*!
@method removeAttributeForName:
@abstract Removes an attribute based on its name.
*/
public func removeAttributeForName(name: String) {
let prop = _CFXMLNodeHasProp(_xmlNode, name)
if prop != nil {
let propNode = NSXMLNode._objectNodeForNode(_CFXMLNodePtr(prop))
_childNodes.remove(propNode)
// We can't use `xmlRemoveProp` because someone else may still have a reference to this attribute
_CFXMLUnlinkNode(_CFXMLNodePtr(prop))
}
} //primitive
/*!
@method setAttributes
@abstract Set the attributes. In the case of duplicate names, the first attribute with the name is used.
*/
public var attributes: [NSXMLNode]? {
get {
var result: [NSXMLNode] = []
var attribute = _CFXMLNodeProperties(_xmlNode)
while attribute != nil {
result.append(NSXMLNode._objectNodeForNode(attribute))
attribute = _CFXMLNodeGetNextSibling(attribute)
}
return result.count > 0 ? result : nil // This appears to be how Darwin does it
}
set {
removeAttributes()
guard let attributes = newValue else {
return
}
for attribute in attributes {
addAttribute(attribute)
}
}
}
private func removeAttributes() {
var attribute = _CFXMLNodeProperties(_xmlNode)
while attribute != nil {
var shouldFreeNode = true
if _CFXMLNodeGetPrivateData(attribute) != nil {
let nodeUnmanagedRef = Unmanaged<NSXMLNode>.fromOpaque(_CFXMLNodeGetPrivateData(attribute))
let node = nodeUnmanagedRef.takeUnretainedValue()
_childNodes.remove(node)
shouldFreeNode = false
}
let temp = _CFXMLNodeGetNextSibling(attribute)
_CFXMLUnlinkNode(attribute)
if shouldFreeNode {
_CFXMLFreeNode(attribute)
}
attribute = temp
}
}
/*!
@method setAttributesWithDictionary:
@abstract Set the attributes based on a name-value dictionary.
*/
public func setAttributesWithDictionary(attributes: [String : String]) {
removeAttributes()
for (name, value) in attributes {
addAttribute(NSXMLNode.attributeWithName(name, stringValue: value) as! NSXMLNode)
}
}
/*!
@method attributeForName:
@abstract Returns an attribute matching this name.
*/
public func attributeForName(name: String) -> NSXMLNode? {
let attribute = _CFXMLNodeHasProp(_xmlNode, name)
return NSXMLNode._objectNodeForNode(attribute)
}
/*!
@method attributeForLocalName:URI:
@abstract Returns an attribute matching this localname URI pair.
*/
public func attributeForLocalName(localName: String, URI: String?) -> NSXMLNode? { NSUnimplemented() } //primitive
/*!
@method addNamespace:URI:
@abstract Adds a namespace. Namespaces with duplicate names are not added.
*/
public func addNamespace(aNamespace: NSXMLNode) { NSUnimplemented() } //primitive
/*!
@method addNamespace:URI:
@abstract Removes a namespace with a particular name.
*/
public func removeNamespaceForPrefix(name: String) { NSUnimplemented() } //primitive
/*!
@method namespaces
@abstract Set the namespaces. In the case of duplicate names, the first namespace with the name is used.
*/
public var namespaces: [NSXMLNode]? { NSUnimplemented() } //primitive
/*!
@method namespaceForPrefix:
@abstract Returns the namespace matching this prefix.
*/
public func namespaceForPrefix(name: String) -> NSXMLNode? { NSUnimplemented() }
/*!
@method resolveNamespaceForName:
@abstract Returns the namespace who matches the prefix of the name given. Looks in the entire namespace chain.
*/
public func resolveNamespaceForName(name: String) -> NSXMLNode? { NSUnimplemented() }
/*!
@method resolvePrefixForNamespaceURI:
@abstract Returns the URI of this prefix. Looks in the entire namespace chain.
*/
public func resolvePrefixForNamespaceURI(namespaceURI: String) -> String? { NSUnimplemented() }
/*!
@method insertChild:atIndex:
@abstract Inserts a child at a particular index.
*/
public func insertChild(child: NSXMLNode, atIndex index: Int) {
_insertChild(child, atIndex: index)
} //primitive
/*!
@method insertChildren:atIndex:
@abstract Insert several children at a particular index.
*/
public func insertChildren(children: [NSXMLNode], atIndex index: Int) {
_insertChildren(children, atIndex: index)
}
/*!
@method removeChildAtIndex:atIndex:
@abstract Removes a child at a particular index.
*/
public func removeChildAtIndex(index: Int) {
_removeChildAtIndex(index)
} //primitive
/*!
@method setChildren:
@abstract Removes all existing children and replaces them with the new children. Set children to nil to simply remove all children.
*/
public func setChildren(children: [NSXMLNode]?) {
_setChildren(children)
} //primitive
/*!
@method addChild:
@abstract Adds a child to the end of the existing children.
*/
public func addChild(child: NSXMLNode) {
_addChild(child)
}
/*!
@method replaceChildAtIndex:withNode:
@abstract Replaces a child at a particular index with another child.
*/
public func replaceChildAtIndex(index: Int, withNode node: NSXMLNode) {
_replaceChildAtIndex(index, withNode: node)
}
/*!
@method normalizeAdjacentTextNodesPreservingCDATA:
@abstract Adjacent text nodes are coalesced. If the node's value is the empty string, it is removed. This should be called with a value of NO before using XQuery or XPath.
*/
public func normalizeAdjacentTextNodesPreservingCDATA(preserve: Bool) { NSUnimplemented() }
internal override class func _objectNodeForNode(node: _CFXMLNodePtr) -> NSXMLElement {
precondition(_CFXMLNodeGetType(node) == _kCFXMLTypeElement)
if _CFXMLNodeGetPrivateData(node) != nil {
let unmanaged = Unmanaged<NSXMLElement>.fromOpaque(_CFXMLNodeGetPrivateData(node))
return unmanaged.takeUnretainedValue()
}
return NSXMLElement(ptr: node)
}
internal override init(ptr: _CFXMLNodePtr) {
super.init(ptr: ptr)
}
}
extension NSXMLElement {
/*!
@method setAttributesAsDictionary:
@abstract Set the attributes base on a name-value dictionary.
@discussion This method is deprecated and does not function correctly. Use -setAttributesWithDictionary: instead.
*/
public func setAttributesAsDictionary(attributes: [NSObject : AnyObject]) { NSUnimplemented() }
}
| 4cf0219c72c534624e0c293dcfd887b3 | 34.116197 | 179 | 0.643036 | false | false | false | false |
niekang/WeiBo | refs/heads/master | WeiBo/Class/Utils/LoadNib/File.swift | apache-2.0 | 1 | //
// File.swift
// WeiBo
//
// Created by 聂康 on 2019/9/10.
// Copyright © 2019 com.nk. All rights reserved.
//
import UIKit
protocol NibLoadable {}
extension NibLoadable where Self: UIView {
static func loadNib(_ nibName: String? = nil) -> Self {
let name = nibName == nil ? "\(self)" : nibName!
return Bundle.main.loadNibNamed(name, owner: nil, options: nil)?.first as! Self
}
}
extension NibLoadable where Self : UIViewController {
static func loadFromStoryboard(_ name: String? = nil, with identifier: String? = nil) -> Self {
let loadName = name == nil ? "\(self)" : name!
guard let id = identifier else {
return UIStoryboard(name: loadName, bundle: nil).instantiateInitialViewController() as! Self
}
return UIStoryboard(name: loadName, bundle: nil).instantiateViewController(withIdentifier: id) as! Self
}
}
extension UIViewController: NibLoadable {}
extension UIView: NibLoadable {}
| 154967fcc2142b113f047a8f9ae870c7 | 26.777778 | 111 | 0.648 | false | false | false | false |
uhnmdi/CCGlucose | refs/heads/master | Example/CCGlucose/GlucoseMeasurementDetailsViewController.swift | mit | 1 | //
// GlucoseMeasurementDetails.swift
// CCBluetooth
//
// Created by Kevin Tallevi on 7/20/16.
// Copyright © 2016 CocoaPods. All rights reserved.
//
import Foundation
import UIKit
import CCGlucose
class GlucoseMeasurementDetailsViewController: UITableViewController {
let cellIdentifier = "DetailsCellIdentifier"
var glucoseMeasurement: GlucoseMeasurement!
override func viewDidLoad() {
super.viewDidLoad()
print("GlucoseMeasurementDetailsViewController#viewDidLoad")
print("glucoseMeasurement: \(glucoseMeasurement)")
}
// MARK: Table data source methods
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return 7
case 1:
return 12
case 2:
return 11
default:
return 0
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath as IndexPath) as UITableViewCell
if(indexPath.section == 0) {
switch indexPath.row {
case 0:
cell.textLabel!.text = glucoseMeasurement.sequenceNumber.description
cell.detailTextLabel!.text = "Sequence number"
case 1:
cell.textLabel!.text = glucoseMeasurement.dateTime?.description
cell.detailTextLabel!.text = "Date/time"
case 2:
cell.textLabel!.text = glucoseMeasurement.timeOffset.description
cell.detailTextLabel!.text = "Time offset"
case 3:
cell.textLabel!.text = glucoseMeasurement.glucoseConcentration.description
cell.detailTextLabel!.text = "Glucose concentration"
case 4:
cell.textLabel!.text = glucoseMeasurement.unit.description
cell.detailTextLabel!.text = "Glucose concentration units"
case 5:
cell.textLabel!.text = glucoseMeasurement.sampleType?.description
cell.detailTextLabel!.text = "Sample type"
case 6:
cell.textLabel!.text = glucoseMeasurement.sampleLocation?.description
cell.detailTextLabel!.text = "Sample location"
default :
cell.textLabel!.text = ""
}
}
if(indexPath.section == 1) {
switch indexPath.row {
case 0:
cell.textLabel!.text = glucoseMeasurement.deviceBatteryLowAtTimeOfMeasurement.description
cell.detailTextLabel!.text = "Device Battery Low At Time Of Measurement"
case 1:
cell.textLabel!.text = glucoseMeasurement.sensorMalfunctionOrFaultingAtTimeOfMeasurement.description
cell.detailTextLabel!.text = "Sensor Malfunction Or Faulting At Time Of Measurement"
case 2:
cell.textLabel!.text = glucoseMeasurement.sampleSizeForBloodOrControlSolutionInsufficientAtTimeOfMeasurement.description
cell.detailTextLabel!.text = "Sample Size For Blood Or Control Solution Insufficient At Time Of Measurement"
case 3:
cell.textLabel!.text = glucoseMeasurement.stripInsertionError.description
cell.detailTextLabel!.text = "Strip Insertion Error"
case 4:
cell.textLabel!.text = glucoseMeasurement.stripTypeIncorrectForDevice.description
cell.detailTextLabel!.text = "Strip Type Incorrect For Device"
case 5:
cell.textLabel!.text = glucoseMeasurement.sensorResultHigherThanTheDeviceCanProcess.description
cell.detailTextLabel!.text = "Sensor Result Higher Than The Device Can Process"
case 6:
cell.textLabel!.text = glucoseMeasurement.sensorResultLowerThanTheDeviceCanProcess.description
cell.detailTextLabel!.text = "Sensor Result Lower Than The Device Can Process"
case 7:
cell.textLabel!.text = glucoseMeasurement.sensorTemperatureTooHighForValidTest.description
cell.detailTextLabel!.text = "Sensor Temperature Too High For Valid Test"
case 8:
cell.textLabel!.text = glucoseMeasurement.sensorTemperatureTooLowForValidTest.description
cell.detailTextLabel!.text = "Sensor Temperature Too Low For Valid Test"
case 9:
cell.textLabel!.text = glucoseMeasurement.sensorReadInterruptedBecauseStripWasPulledTooSoon.description
cell.detailTextLabel!.text = "Sensor Read Interrupted Because Strip Was Pulled Too Soon"
case 10:
cell.textLabel!.text = glucoseMeasurement.generalDeviceFault.description
cell.detailTextLabel!.text = "General Device Fault"
case 11:
cell.textLabel!.text = glucoseMeasurement.timeFaultHasOccurred.description
cell.detailTextLabel!.text = "Time Fault Has Occurred"
default :
cell.textLabel!.text = ""
}
}
if(self.glucoseMeasurement.context != nil) {
if(indexPath.section == 2) {
switch indexPath.row {
case 0:
cell.textLabel!.text = self.glucoseMeasurement.context?.sequenceNumber.description
cell.detailTextLabel!.text = "Sequence number"
case 1:
cell.textLabel!.text = self.glucoseMeasurement.context?.carbohydrateID?.description
cell.detailTextLabel!.text = "Carbohydrate"
case 2:
cell.textLabel!.text = self.glucoseMeasurement.context?.carbohydrateWeight?.description
cell.detailTextLabel!.text = "Carbohydrate weight"
case 3:
cell.textLabel!.text = self.glucoseMeasurement.context?.meal?.description
cell.detailTextLabel!.text = "Meal"
case 4:
cell.textLabel!.text = self.glucoseMeasurement.context?.tester
cell.detailTextLabel!.text = "Tester"
case 5:
cell.textLabel!.text = self.glucoseMeasurement.context?.health
cell.detailTextLabel!.text = "Health"
case 6:
cell.textLabel!.text = self.glucoseMeasurement.context?.exerciseDuration?.description
cell.detailTextLabel!.text = "Exercise duration"
case 7:
cell.textLabel!.text = self.glucoseMeasurement.context?.exerciseIntensity?.description
cell.detailTextLabel!.text = "Exercise intensity"
case 8:
cell.textLabel!.text = self.glucoseMeasurement.context?.medicationID
cell.detailTextLabel!.text = "Medication ID"
case 9:
cell.textLabel!.text = self.glucoseMeasurement.context?.medication?.description
cell.detailTextLabel!.text = "Medication"
case 10:
cell.textLabel!.text = self.glucoseMeasurement.context?.hbA1c?.description
cell.detailTextLabel!.text = "hbA1c"
default :
cell.textLabel!.text = ""
}
}
}
return cell
}
override func numberOfSections(in tableView: UITableView) -> Int {
if(self.glucoseMeasurement.context != nil) {
return 3
} else {
return 2
}
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 75
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
if(self.glucoseMeasurement.context != nil) {
return "Glucose Measurement"
} else {
return "Glucose Measurement (No context)"
}
case 1:
return "Sensor Status Annunciation"
case 2:
return "Glucose Context"
default:
return ""
}
}
}
| c28584bb7932fcdd4e110baece04095c | 44.349727 | 136 | 0.610676 | false | false | false | false |
phimage/MomXML | refs/heads/master | Tests/MomXMLTests.swift | mit | 1 | //
// MomXMLTests.swift
// MomXMLTests
//
// Created by Eric Marchand on 07/06/2017.
// Copyright © 2017 phimage. All rights reserved.
//
import XCTest
@testable import MomXML
import SWXMLHash
class MomXMLTests: 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 testCreateReadEmpty() {
let mom = MomXML()
let xmlString = mom.xml
XCTAssertFalse(xmlString.isEmpty)
let xml = SWXMLHash.parse(xmlString)
let parsedMom = MomXML(xml: xml)
XCTAssertNotNil(parsedMom)
/// XXX Before comparing maybe do an xmlLint or do a better xml compare
XCTAssertEqual(parsedMom!.xml, xmlString)
}
// momXML; userinfo
//entity ; Element; Attribut; model; ; relationship ;
func testMomEntityEmpty(){
var momXML = MomXML()
let entityPersonne = MomEntity(name: "Personne")
let entityStatus = MomEntity(name: "Status")
let entityFunction = MomEntity(name: "Function")
let elementPersonne = MomElement(name: "Personne")
let elementStatus = MomElement(name: "Status")
let elementFunction = MomElement(name: "Function")
momXML.model.entities.append(entityPersonne)
momXML.model.entities.append(entityStatus)
momXML.model.entities.append(entityFunction)
momXML.model.elements.append(elementPersonne)
momXML.model.elements.append(elementStatus)
momXML.model.elements.append(elementFunction)
let xmlString = momXML.xml
print(xmlString)
XCTAssertFalse(xmlString.isEmpty)
let xml = SWXMLHash.parse(xmlString)
let parsedMom = MomXML(xml: xml)
XCTAssertNotNil(parsedMom)
}
func testEntityWithAttribute(){
var momXML = MomXML()
var entitySociete = MomEntity(name: "Societe")
let attrFirstName = MomAttribute(name: "name", attributeType: MomAttribute.AttributeType.string)
let attrlastName = MomAttribute(name: "adresse", attributeType: MomAttribute.AttributeType.string)
let attrIdSociete = MomAttribute(name: "id", attributeType: MomAttribute.AttributeType.integer16)
entitySociete.attributes.append(attrFirstName)
entitySociete.attributes.append(attrlastName)
entitySociete.attributes.append(attrIdSociete)
var entityFournissieur = MomEntity(name: "Fournissieur")
let attrFirstNameFournissieur = MomAttribute(name: "firstname", attributeType: MomAttribute.AttributeType.string)
let attrlastNameFournissieur = MomAttribute(name: "lastname", attributeType: MomAttribute.AttributeType.string)
let attrIdClient = MomAttribute(name: "id", attributeType: MomAttribute.AttributeType.integer16)
entityFournissieur.attributes.append(attrFirstNameFournissieur)
entityFournissieur.attributes.append(attrlastNameFournissieur)
entityFournissieur.attributes.append(attrIdClient)
let elementSociete = MomElement(name: "Societe")
let elementFournissieur = MomElement(name: "Status")
momXML.model.entities.append(entitySociete)
momXML.model.entities.append(entityFournissieur)
momXML.model.elements.append(elementSociete)
momXML.model.elements.append(elementFournissieur)
let xmlString = momXML.xml
print(xmlString)
XCTAssertFalse(xmlString.isEmpty)
let xml = SWXMLHash.parse(xmlString)
let parsedMom = MomXML(xml: xml)
XCTAssertNotNil(parsedMom)
}
func testMomEntityWithRelation() {
var momXML = MomXML()
var entityClient = MomEntity(name: "Client")
let attrFirstName = MomAttribute(name: "firstname", attributeType: MomAttribute.AttributeType.string)
let attrlastName = MomAttribute(name: "lastname", attributeType: MomAttribute.AttributeType.string)
let attrIdClient = MomAttribute(name: "id", attributeType: MomAttribute.AttributeType.integer16)
entityClient.attributes.append(attrFirstName)
entityClient.attributes.append(attrlastName)
entityClient.attributes.append(attrIdClient)
entityClient.userInfo.add(key: "name1", value: "valuename1")
let myrelationshipClient = MomRelationship(name: "client_commande", destinationEntity: "Commande")
entityClient.relationship.append(myrelationshipClient)
var entityCommande = MomEntity(name: "Commande")
let attrDate = MomAttribute(name: "date", attributeType: MomAttribute.AttributeType.date)
let attrDescriptionCommande = MomAttribute(name: "descriptioncommande", attributeType: MomAttribute.AttributeType.string)
let attrIdCommande = MomAttribute(name: "id", attributeType: MomAttribute.AttributeType.integer16)
entityCommande.attributes.append(attrIdCommande)
entityCommande.attributes.append(attrDate)
entityCommande.attributes.append(attrDescriptionCommande)
entityCommande.userInfo.add(key: "name2", value: "valuename2")
let myrelationshipCommande = MomRelationship(name: "commande_client", destinationEntity: "Client")
let myrelationshipCommande2 = MomRelationship(name: "commande_produit", destinationEntity: "Produit")
entityCommande.relationship.append(myrelationshipCommande)
entityCommande.relationship.append(myrelationshipCommande2)
var entityProduit = MomEntity(name: "Produit")
let attrName = MomAttribute(name: "name", attributeType: MomAttribute.AttributeType.string)
let attrPrix = MomAttribute(name: "prix", attributeType: MomAttribute.AttributeType.double)
let attrReference = MomAttribute(name: "reference", attributeType: MomAttribute.AttributeType.string)
let attrIdProduit = MomAttribute(name: "id", attributeType: MomAttribute.AttributeType.integer16)
entityProduit.attributes.append(attrIdProduit)
entityProduit.attributes.append(attrName)
entityProduit.attributes.append(attrPrix)
entityProduit.attributes.append(attrReference)
let myrelationshipProduit = MomRelationship(name: "produit_commande", destinationEntity: "Commande")
entityProduit.relationship.append(myrelationshipProduit)
let elementClient = MomElement(name: "Client", positionX: 106, positionY: -45, width: 128, height: 118)
let elementProduit = MomElement(name: "Produit")
let elementCommande = MomElement(name: "Commande")
var momModel = MomModel()
momModel.entities.append(entityClient)
momModel.entities.append(entityProduit)
momModel.entities.append(entityCommande)
momModel.elements.append(elementClient)
momModel.elements.append(elementCommande)
momModel.elements.append(elementProduit)
XCTAssertEqual(momModel.check(), true)
momModel.moveElements()
momXML.model = momModel
let xmlString = momXML.xml
print(xmlString)
XCTAssertFalse(xmlString.isEmpty)
let xml = SWXMLHash.parse(xmlString)
let parsedMom = MomXML(xml: xml)
XCTAssertNotNil(parsedMom)
}
func testEquatableAttribute(){
//attribut
let attrName = MomAttribute(name: "name", attributeType: .string)
XCTAssertEqual(attrName, attrName)
XCTAssertEqual(attrName, MomAttribute(name: "name", attributeType: .string))
XCTAssertNotEqual(attrName, MomAttribute(name: "name", attributeType: .integer16), "attributeType different")
XCTAssertNotEqual(attrName, MomAttribute(name: "name2", attributeType: .string), "name different")
XCTAssertNotEqual(attrName, MomAttribute(name: "name", attributeType: .string, isOptional: true), "isOptional different")
}
func testEquatableElement(){
//elements
let elementClient = MomElement(name: "Client", positionX: 106, positionY: -45, width: 128, height: 118)
XCTAssertEqual(elementClient, elementClient)
XCTAssertEqual(elementClient, MomElement(name: "Client", positionX: 106, positionY: -45, width: 128, height: 118))
XCTAssertNotEqual(elementClient, MomElement(name: "Client2", positionX: 106, positionY: -45, width: 128, height: 118), "name different")
XCTAssertNotEqual(elementClient, MomElement(name: "Client", positionX: 588, positionY: -45, width: 128, height: 118), "positionX different")
XCTAssertNotEqual(elementClient, MomElement(name: "Client", positionX: 106, positionY: 454, width: 128, height: 118), "positionY different")
XCTAssertNotEqual(elementClient, MomElement(name: "Client", positionX: 106, positionY: -45, width: 44, height: 118), "width different")
XCTAssertNotEqual(elementClient, MomElement(name: "Client", positionX: 106, positionY: -45, width: 128, height: 1), "height different")
}
func testEquatableRelationship(){
//relationship
let myrelationshipProduit = MomRelationship(name: "produit_commande", destinationEntity: "Commande")
XCTAssertEqual(myrelationshipProduit, myrelationshipProduit)
XCTAssertEqual(myrelationshipProduit, MomRelationship(name: "produit_commande", destinationEntity: "Commande"))
XCTAssertNotEqual(myrelationshipProduit, MomRelationship(name: "produit_command", destinationEntity: "Commande"), "name different")
var myrelationshipProduit2 = MomRelationship(name: "produit_commande", destinationEntity: "Commande")
myrelationshipProduit2.deletionRule = .deny
XCTAssertNotEqual(myrelationshipProduit2, myrelationshipProduit, "deletionRule different")
}
func testEquatable(){
//entity
var entityClient = MomEntity(name: "Client")
let attrFirstName = MomAttribute(name: "firstname", attributeType: .string)
let attrlastName = MomAttribute(name: "lastname", attributeType: .string)
let attrIdClient = MomAttribute(name: "id", attributeType: .integer16)
entityClient.attributes.append(attrFirstName)
entityClient.attributes.append(attrlastName)
entityClient.attributes.append(attrIdClient)
entityClient.userInfo.add(key: "name1", value: "valuename1")
let myrelationshipClient = MomRelationship(name: "client_commande", destinationEntity: "Commande")
entityClient.relationship.append(myrelationshipClient)
XCTAssertEqual(entityClient, entityClient)
// fetch
let featchRequest = MomFetchRequest(name: "name", entity: entityClient.name, predicateString: "TRUE")
let emptyFetchRequest = MomFetchRequest(name: "", entity: "", predicateString: "")
XCTAssertEqual(featchRequest, featchRequest)
XCTAssertNotEqual(featchRequest, emptyFetchRequest)
let fetchProperty = MomFetchedProperty(name: "nametest", fetchRequest: featchRequest)
XCTAssertEqual(fetchProperty, fetchProperty)
XCTAssertNotEqual(fetchProperty, MomFetchedProperty(name: "", fetchRequest: emptyFetchRequest))
XCTAssertNotEqual(fetchProperty, MomFetchedProperty(name: "t", fetchRequest: featchRequest))
//model
var momModel = MomModel()
momModel.entities.append(entityClient)
let elementClient = MomElement(name: "Client", positionX: 106, positionY: -45, width: 128, height: 118)
momModel.elements.append(elementClient)
XCTAssertEqual(momModel, momModel)
//MomXML
var momXML = MomXML()
momXML.model.entities.append(entityClient)
momXML.model.elements.append(elementClient)
XCTAssertEqual(momXML, momXML)
var momXML2 = MomXML()
momXML2.model.entities.append(entityClient)
momXML2.model.elements.append(elementClient)
XCTAssertEqual(momXML, momXML2)
let momXML3 = MomXML()
XCTAssertNotEqual(momXML3, momXML)
let momXML4 = MomXML()
momXML2.model.entities.append(MomEntity(name: "Client4"))
momXML2.model.elements.append(MomElement(name: "Client4", positionX: 106, positionY: -45, width: 128, height: 118))
XCTAssertNotEqual(momXML4, momXML)
}
// MARK: test from files
func testXMLToMomModel1() {
if let url = Fixture.url(forResource: "model", withExtension: "xml") {
do {
let xmlString = try String(contentsOf: url)
let xml = SWXMLHash.parse(xmlString)
guard let parsedMom = MomXML(xml: xml) else {
XCTFail("Failed to parse xml")
return
}
let momModel = parsedMom.model
//print(xml)
//print("++++++++")
//print(momModel.xml)
let momEntities = momModel.entities
let momElements = momModel.elements
var entites: [MomEntity] = []
var elements: [MomElement] = []
for entity in momEntities {
entites.append(entity)
print(entity.name)
for attr in entity.attributes {
print("\(attr.name) \(attr.attributeType)")
}
for attr in entity.relationship {
print("\(attr.name) \(attr.destinationEntity)")
}
for attr in entity.fetchProperties {
print("\(attr.name) \(attr.fetchRequest.predicateString)")
}
for attr in entity.fetchIndexes {
print("\(attr.name) \(attr.elements)")
}
if let uniquenessConstraints = entity.uniquenessConstraints {
for uniquenessConstraint in uniquenessConstraints.constraints {
for constraint in uniquenessConstraint.constraints {
print("\(constraint.value)")
}
}
}
}
for element in momElements {
elements.append(element)
print(element.name)
}
XCTAssertEqual(momEntities.count, momElements.count)
/// Important test, check that rendered data it's same as parsed data
let xmlFromParsed = parsedMom.xml
// print(xmlFromParsed)
let recreatedMom = MomXML(xml: SWXMLHash.parse(xmlFromParsed))
XCTAssertEqual(recreatedMom, parsedMom)
} catch {
XCTFail("Unable to read test file Model \(error)")
}
} else {
XCTFail("Unable to get test file Model")
}
}
func testXMLToMomModel2() {
if let url = Fixture.url(forResource: "model2", withExtension: "xml") {
do {
let xmlString = try String(contentsOf: url)
let xml = SWXMLHash.parse(xmlString)
guard let parsedMom = MomXML(xml: xml) else {
XCTFail("Failed to parse xml")
return
}
let momModel = parsedMom.model
let momEntities = momModel.entities
let momElements = momModel.elements
var entites: [MomEntity] = []
var elements: [MomElement] = []
for entity in momEntities {
entites.append(entity)
print(entity.name)
for attr in entity.attributes {
print("\(attr.name) \(attr.attributeType)")
}
for attr in entity.relationship {
print("\(attr.name) \(attr.destinationEntity)")
}
for attr in entity.fetchProperties {
print("\(attr.name) \(attr.fetchRequest.predicateString)")
}
for attr in entity.fetchIndexes {
print("\(attr.name) \(attr.elements)")
}
}
print("+++ elements :")
for element in momElements {
elements.append(element)
print(element.name)
}
XCTAssertEqual(momEntities.count, momElements.count)
/// Important test, check that rendered data it's same as parsed data
let xmlFromParsed = parsedMom.xml
// print(xmlFromParsed)
let recreatedMom = MomXML(xml: SWXMLHash.parse(xmlFromParsed))
XCTAssertEqual(recreatedMom, parsedMom)
} catch {
XCTFail("Unable to read test file Model \(error)")
}
} else {
XCTFail("Unable to get test file Model")
}
}
func testJsonToXML() {
if let url = Fixture.url(forResource: "modelJsonToXML", withExtension: "xml") {
do {
let xmlString = try String(contentsOf: url)
let xml = SWXMLHash.parse(xmlString)
guard let parsedMom = MomXML(xml: xml) else {
XCTFail("Failed to parse xml")
return
}
let momModel = parsedMom.model
let momEntities = momModel.entities
let momElements = momModel.elements
var entites: [MomEntity] = []
var elements: [MomElement] = []
for entity in momEntities {
entites.append(entity)
print(entity.name)
for attr in entity.attributes {
print("\(attr.name) \(attr.attributeType)")
}
for attr in entity.relationship {
print("\(attr.name) \(attr.destinationEntity)")
}
}
for element in momElements {
elements.append(element)
print(element.name)
}
XCTAssertEqual(momEntities.count, momElements.count)
/// Important test, check that rendered data it's same as parsed data
let xmlFromParsed = parsedMom.xml
// print(xmlFromParsed)
let recreatedMom = MomXML(xml: SWXMLHash.parse(xmlFromParsed))
XCTAssertEqual(recreatedMom, parsedMom)
} catch {
XCTFail("Unable to read test file Model \(error)")
}
} else {
XCTFail("Unable to get test file Model")
}
}
func testRelationships() {
let modelString = """
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="14490.99" systemVersion="18F132" minimumToolsVersion="Automatic" sourceLanguage="Swift" userDefinedModelVersionIdentifier="">
<entity name="Entity" representedClassName="Entity" syncable="YES" codeGenerationType="class">
<attribute name="attribute1" optional="YES" attributeType="Integer 16" defaultValueString="0" usesScalarValueType="YES" syncable="YES"/>
<relationship name="relationEntity1" optional="YES" toMany="YES" deletionRule="Cascade" destinationEntity="Entity2" inverseName="relationEntity2" inverseEntity="Entity2" syncable="YES"/>
<uniquenessConstraints>
<uniquenessConstraint>
<constraint value="attribute1"/>
</uniquenessConstraint>
</uniquenessConstraints>
</entity>
<entity name="Entity2" representedClassName="Entity2" syncable="YES" codeGenerationType="class">
<relationship name="relationEntity2" optional="YES" maxCount="1" deletionRule="Nullify" destinationEntity="Entity" inverseName="relationEntity1" inverseEntity="Entity" syncable="YES"/>
</entity>
<elements>
<element name="Entity" positionX="-1697.54296875" positionY="-87.4921875" width="128" height="238"/>
<element name="Entity2" positionX="-403.99609375" positionY="15.84375" width="128" height="58"/>
</elements>
</model>
"""
let xml = SWXMLHash.parse(modelString)
guard let parsedMom = MomXML(xml: xml) else {
XCTFail("Unable to parse String XML model")
return
}
let parsed = parsedMom.model.coreData
let entities = parsed.entities
for entity in entities { //Entity1
let relationships = entity.relationshipsByName
for (_, relation) in relationships { //relationEntity1
XCTAssertNotNil(relation.destinationEntity, "missing destination entity for \(relation) of \(entity)") //Entity2
XCTAssertNotNil(relation.inverseRelationship, "missing inverse relation for \(relation) of \(entity)") //relationEntity2
if let inverseRelationship = relation.inverseRelationship {
XCTAssertEqual(inverseRelationship.inverseRelationship?.name, relation.name, "inverse of inverse is not self for \(relation) of \(entity) : inverseRelationship is \(String(describing: inverseRelationship.inverseRelationship))")
XCTAssertEqual(inverseRelationship.entity.name, relation.destinationEntity?.name, "entity of inverse is not self for \(relation) of \(entity) : inverseRelationship is \(String(describing: inverseRelationship.inverseRelationship))")
if let destination = relation.destinationEntity {
let destinationRelationships = destination.relationshipsByName.values
XCTAssertTrue(destinationRelationships.contains(inverseRelationship))
} // else already asserted
} // else already asserted
}
}
}
}
struct Fixture {
static func url(forResource resource: String, withExtension ext: String) -> URL? {
if let url = Bundle(for: MomXMLTests.self).url(forResource: resource, withExtension: ext) {
return url
}
var url = URL(fileURLWithPath: "Tests/\(resource).\(ext)")
if !FileManager.default.fileExists(atPath: url.path) {
let resourcesURL = URL(fileURLWithPath: #file)
url = resourcesURL.deletingLastPathComponent().appendingPathComponent(resource).appendingPathExtension(ext)
}
return url
}
}
| 0736ce8881abb5dc53ea991284327aa0 | 45.799595 | 251 | 0.624681 | false | true | false | false |
LoopKit/LoopKit | refs/heads/dev | LoopKit/Extensions/NSUserActivity+CarbKit.swift | mit | 2 | //
// NSUserActivity+CarbKit.swift
// LoopKit
//
// Copyright © 2018 LoopKit Authors. All rights reserved.
//
import Foundation
/// Conveniences for activity handoff and restoration of creating a carb entry
extension NSUserActivity {
public static let newCarbEntryActivityType = "NewCarbEntry"
public static let newCarbEntryUserInfoKey = "NewCarbEntry"
public class func forNewCarbEntry() -> NSUserActivity {
let activity = NSUserActivity(activityType: newCarbEntryActivityType)
activity.requiredUserInfoKeys = []
return activity
}
public func update(from entry: NewCarbEntry?) {
if let rawValue = entry?.rawValue {
addUserInfoEntries(from: [
NSUserActivity.newCarbEntryUserInfoKey: rawValue
])
} else {
userInfo = nil
}
}
public var newCarbEntry: NewCarbEntry? {
guard let rawValue = userInfo?[NSUserActivity.newCarbEntryUserInfoKey] as? NewCarbEntry.RawValue else {
return nil
}
return NewCarbEntry(rawValue: rawValue)
}
}
| c4740a8d315f88dc1278e1bda4ab27b0 | 26.6 | 111 | 0.666667 | false | false | false | false |
mihaicris/digi-cloud | refs/heads/develop | Digi Cloud/Models/RootMount.swift | mit | 1 | //
// RootMount.swift
// Digi Cloud
//
// Created by Mihai Cristescu on 20/03/2017.
// Copyright © 2017 Mihai Cristescu. All rights reserved.
//
import Foundation
struct RootMount {
// MARK: - Properties
let identifier: String
let name: String
let path: String
}
extension RootMount {
init?(object: Any?) {
guard
let jsonDictionary = object as? [String: Any],
let identifier = jsonDictionary["id"] as? String,
let name = jsonDictionary["name"] as? String,
let path = jsonDictionary["path"] as? String
else { return nil }
self.identifier = identifier
self.name = name
self.path = path
}
}
| b966e1e536e7bb823f14d89ba093e20d | 21.28125 | 61 | 0.59467 | false | false | false | false |
verticon/VerticonsToolbox | refs/heads/master | VerticonsToolbox/UI/Buttons.swift | mit | 1 | //
// Buttons.swift
//
// Created by Robert Vaessen on 4/15/17.
// Copyright © 2015 Robert Vaessen. All rights reserved.
//
import UIKit
public extension UIButton {
func setBackgroundColor(_ color: UIColor?, forState state: UIControl.State) {
if let color = color {
setBackgroundImage(color.toImage(), for: state)
}
else {
setBackgroundImage(nil, for: state)
}
}
}
@IBDesignable
open class ColoredButton: UIButton {
@IBInspectable open var color: UIColor? {
didSet {
setBackgroundColor(color, forState: .normal)
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(frame: CGRect) {
super.init(frame: frame)
}
}
@IBDesignable
open class ToggleButton: ColoredButton {
open var listener: ((Bool) -> Void)?
@IBInspectable open var selectedColor: UIColor? {
didSet {
setBackgroundColor(selectedColor, forState: .selected)
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
public override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
private func initialize() {
addTarget(self, action: #selector(toggle), for: .touchUpInside)
}
@objc open func toggle() {
isSelected = !isSelected
if let listener = listener { listener(isSelected) }
}
}
@IBDesignable
public class RadioButton: UIButton {
public var listener: ((Bool) -> Void)?
private var bezelLayer = CAShapeLayer()
private var buttonLayer = CAShapeLayer()
@IBInspectable @objc dynamic public var bezelColor: UIColor = UIColor.lightGray {
didSet {
bezelLayer.strokeColor = bezelColor.cgColor
}
}
@IBInspectable @objc dynamic public var bezelWidth: CGFloat = 2.0 {
didSet {
layoutSubLayers()
}
}
@IBInspectable @objc dynamic public var bezelButtonGap: CGFloat = 4.0 {
didSet {
layoutSubLayers()
}
}
@IBInspectable @objc dynamic public var buttonColor: UIColor = UIColor.lightGray {
didSet {
indicateButtonState()
}
}
@IBInspectable public fileprivate(set) var isPressed: Bool = false {
didSet {
indicateButtonState()
}
}
override public init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
// MARK: Initialization
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
bezelLayer.frame = bounds
bezelLayer.lineWidth = bezelWidth
bezelLayer.fillColor = UIColor.clear.cgColor
bezelLayer.strokeColor = bezelColor.cgColor
layer.addSublayer(bezelLayer)
buttonLayer.frame = bounds
buttonLayer.lineWidth = bezelWidth
buttonLayer.fillColor = UIColor.clear.cgColor
buttonLayer.strokeColor = UIColor.clear.cgColor
layer.addSublayer(buttonLayer)
addTarget(self, action: #selector(pressHandler(_:)), for: .touchUpInside)
indicateButtonState()
}
override public func prepareForInterfaceBuilder() {
initialize()
}
@objc private func pressHandler(_ sender: RadioButton) {
isPressed = !isPressed
if let listener = listener { listener(isPressed) }
}
private var bezelInnerRadius: CGFloat {
let width = bounds.width
let height = bounds.height
let maxSide = width > height ? height : width
return (maxSide - bezelWidth) / 2
}
private var bezelInnerFrame: CGRect {
let width = bounds.width
let height = bounds.height
let radius = bezelInnerRadius
let x: CGFloat
let y: CGFloat
if width > height {
y = bezelWidth / 2
x = (width / 2) - radius
} else {
x = bezelWidth / 2
y = (height / 2) - radius
}
let diameter = 2 * radius
return CGRect(x: x, y: y, width: diameter, height: diameter)
}
private var bezelPath: UIBezierPath {
return UIBezierPath(roundedRect: bezelInnerFrame, cornerRadius: bezelInnerRadius)
}
private var buttonPath: UIBezierPath {
let trueGap = bezelButtonGap + (bezelWidth / 2)
return UIBezierPath(roundedRect: bezelInnerFrame.insetBy(dx: trueGap, dy: trueGap), cornerRadius: bezelInnerRadius)
}
private func layoutSubLayers() {
bezelLayer.frame = bounds
bezelLayer.lineWidth = bezelWidth
bezelLayer.path = bezelPath.cgPath
buttonLayer.frame = bounds
buttonLayer.lineWidth = bezelWidth
buttonLayer.path = buttonPath.cgPath
}
private func indicateButtonState() {
buttonLayer.fillColor = isPressed ? buttonColor.cgColor : UIColor.clear.cgColor
}
override public func layoutSubviews() {
super.layoutSubviews()
layoutSubLayers()
}
}
public class RadioButtonGroup {
private let group: [RadioButton]
private let changeHandler: (RadioButton) -> Void
public init(buttons: RadioButton ..., initialSelection: RadioButton, selectionChangedHandler: @escaping (RadioButton) -> Void) {
group = buttons
changeHandler = selectionChangedHandler
group.forEach { button in
button.addTarget(self, action: #selector(pressHandler(_:)), for: .touchUpInside)
}
set(selected: initialSelection)
}
public func set(hidden: Bool) {
group.forEach { $0.isHidden = hidden }
}
public func set(enabled: Bool) {
group.forEach { $0.isEnabled = enabled }
}
public func set(selected: RadioButton) {
group.forEach { $0.isPressed = $0 == selected }
}
@objc private func pressHandler(_ sender: RadioButton) {
group.forEach { $0.isPressed = $0 === sender }
if sender.isPressed { changeHandler(sender) }
}
}
@IBDesignable
public class DropDownButton: UIButton, UIPopoverPresentationControllerDelegate {
public var listBackgroundColor: UIColor = .white
public var itemBackgroundColor: UIColor = .white
public var itemTextColor: UIColor = .black
private var popoverViewController: UIViewController?
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
initialize()
}
fileprivate func initialize() {
if image(for: .normal) == nil {
setImage(UIImage(named: "DropDown", in: Bundle(for: DropDownButton.self), compatibleWith: nil), for: .normal)
}
addTarget(self, action: #selector(toggle), for: .touchUpInside)
sizeToFit()
}
// If the popover has been presented and then the button's view controller is dismissed due to an event other
// than a screen touch, the popover will stay on the screen. Let's detect that and dismiss the popover if it occurs
public override func didMoveToSuperview() {
super.didMoveToSuperview()
if superview == nil, let popover = popoverViewController {
popover.dismiss(animated: true, completion: nil)
}
}
public override func layoutSubviews() {
super.layoutSubviews()
if var imageFrame = imageView?.frame, var labelFrame = titleLabel?.frame, let count = titleLabel?.text?.count {
if (count > 0) {
labelFrame.origin.x = contentEdgeInsets.left
imageFrame.origin.x = labelFrame.origin.x + labelFrame.width + 2
imageView?.frame = imageFrame
titleLabel?.frame = labelFrame
}
}
}
public override func setTitle(_ title: String?, for state: UIControl.State) {
super.setTitle(title, for: state)
sizeToFit()
}
public func trigger() {
toggle(sender: self)
}
@IBInspectable @objc dynamic public var color : UIColor = UIColor.gray {
didSet {
if let image = imageView?.image {
setImage(image.withRenderingMode(.alwaysTemplate), for: .normal)
tintColor = color
}
}
}
public var collapsed: Bool {
return imageView?.transform == CGAffineTransform.identity
}
public var expanded: Bool {
return !collapsed
}
fileprivate func collapse() {
imageView?.transform = CGAffineTransform.identity
}
private func expand() {
imageView?.transform = CGAffineTransform(rotationAngle: .pi)
}
@objc fileprivate func toggle(sender: UIButton) {
if collapsed { expand() } else { collapse() }
if collapsed { return }
guard let viewController = makePopoverViewController() else { return }
viewController.modalPresentationStyle = .popover
viewController.preferredContentSize = CGSize(width: 2 * UIWindow.mainWindow.bounds.width / 3, height: UIWindow.mainWindow.bounds.height / 4)
let presentationController = viewController.popoverPresentationController!
presentationController.delegate = self
if let barButton = outerButton { presentationController.barButtonItem = barButton } else { presentationController.sourceView = self.imageView }
self.viewController?.present(viewController, animated: true, completion: nil)
popoverViewController = viewController
}
fileprivate func makePopoverViewController() -> UIViewController? {
return nil
}
fileprivate var outerButton: DropDownBarButton? // This button might be the custom view of a bar button item (see the UIBarButtonItem subclasses below)
// MARK: UIPopoverPresentationControllerDelegate
public func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
public func popoverPresentationControllerShouldDismissPopover(_ popoverPresentationController: UIPopoverPresentationController) -> Bool {
popoverViewController = nil
collapse()
return true
}
}
@IBDesignable
public class DropDownListButton: DropDownButton {
fileprivate class List {
let items: [CustomStringConvertible]
init(items: [CustomStringConvertible]) {
self.items = items
}
}
fileprivate class ListViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
// The ListCell contains a scroll view which allows text that is wider than the width of the table to be seen.
// That scroll view's contentSize os set in such a way (see ListViewController.cellforRowAt) as that vertical
// scrolling is disabled. The presense of the scroll view prevents rows from being selected (ie. taps do not
// reach the cell). A tap gesture recognizer is used to select the row and invoke the table delegate's didSelectRowAt
// method.
class ListCell : UITableViewCell {
let item = UILabel()
let scrollView = UIScrollView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
item.translatesAutoresizingMaskIntoConstraints = false
scrollView.addSubview(item)
NSLayoutConstraint.activate([
item.leftAnchor.constraint(equalTo: scrollView.leftAnchor, constant: 10),
item.rightAnchor.constraint(equalTo: scrollView.rightAnchor),
item.centerYAnchor.constraint(equalTo: scrollView.centerYAnchor),
])
scrollView.translatesAutoresizingMaskIntoConstraints = false
contentView.addSubview(scrollView)
NSLayoutConstraint.activate([
scrollView.leftAnchor.constraint(equalTo: contentView.leftAnchor),
scrollView.rightAnchor.constraint(equalTo: contentView.rightAnchor),
scrollView.topAnchor.constraint(equalTo: contentView.topAnchor),
scrollView.bottomAnchor.constraint(equalTo: contentView.bottomAnchor),
])
let tapHandler = UITapGestureRecognizer(target: self, action: #selector(selectRow))
scrollView.addGestureRecognizer(tapHandler)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc private func selectRow(_ recognizer: UITapGestureRecognizer) {
switch recognizer.state {
case .ended:
// Traverse the view hierarchy to find first the cell and then the table.
// When they have both been found, invoke the table delegate's didSelectRowAt method
func selectRow(current: UIView, cell: UITableViewCell?) {
if let cell = cell { // We've already found the cell; we're looking for the table
if let table = current as? UITableView {
guard let index = table.indexPath(for: cell) else { fatalError("No index path for the cell that was tapped.") }
//table.delegate?.tableView?(table, didDeselectRowAt: index) Why did this not work???
if let vc = table.delegate as? DropDownListButton.ListViewController {
table.selectRow(at: index, animated: true, scrollPosition: .none)
vc.tableView(table, didSelectRowAt: index)
}
//table.reloadData()
}
else { // Keep looking for the table
guard let next = cell.superview else { fatalError("We reached the top of the view hierarchy without finding the table.") }
selectRow(current: next, cell: cell)
}
}
else { // Keep looking for the cell
guard let next = current.superview else { fatalError("We reached the top of the view hierarchy without finding the cell and the table.") }
selectRow(current: next, cell: current as? UITableViewCell)
}
}
selectRow(current: self, cell: nil)
default: break
}
}
}
let cellBackgroundColor: UIColor
let cellTextColor: UIColor
private var tableView = UITableView()
private var list: List
private let cellId = "DropDownListCell"
init(list: List, title: String?, tableBackgroundColor: UIColor, cellBackgroundColor: UIColor, cellTextColor: UIColor) {
self.list = list
self.cellBackgroundColor = cellBackgroundColor
self.cellTextColor = cellTextColor
super.init(nibName: nil, bundle: nil)
tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tableView)
NSLayoutConstraint.activate([
tableView.leftAnchor.constraint(equalTo: view.leftAnchor),
tableView.rightAnchor.constraint(equalTo: view.rightAnchor),
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
])
tableView.delegate = self
tableView.dataSource = self
if let title = title {
let header = UILabel()
header.frame = CGRect(x: 0, y: 0, width: 0, height: 44)
header.text = title
header.textAlignment = .center
tableView.tableHeaderView = header
}
// tableView.bounces = false
tableView.backgroundColor = tableBackgroundColor
tableView.register(ListCell.self, forCellReuseIdentifier: cellId)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return list.items.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let _cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath)
guard let cell = _cell as? ListCell else { return _cell }
cell.item.textColor = cellTextColor
cell.item.backgroundColor = cellBackgroundColor
cell.item.text = list.items[indexPath.row].description
// Apparently, a height of 0 causes the content view's height to be the height of its content; effectively disabling vertical scrolling.
cell.scrollView.contentSize = CGSize(width: cell.item.intrinsicContentSize.width + 20, height: 0)
cell.scrollView.backgroundColor = cellBackgroundColor
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false)
}
}
private var list: List?
private var title: String?
public init(listBackgroundColor: UIColor = .white, itemBackgroundColor: UIColor = .white, itemTextColor: UIColor = .black) {
super.init(frame: CGRect.zero)
self.listBackgroundColor = listBackgroundColor
self.itemBackgroundColor = itemBackgroundColor
self.itemTextColor = itemTextColor
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public func setList(title: String?, items: [CustomStringConvertible]) {
self.title = title
list = List(items: items)
}
fileprivate override func makePopoverViewController() -> UIViewController? {
guard let list = self.list else { return nil }
return ListViewController(list: list, title: title, tableBackgroundColor: listBackgroundColor, cellBackgroundColor: itemBackgroundColor, cellTextColor: itemTextColor)
}
}
@IBDesignable
public class DropDownMenuButton: DropDownButton {
private class Menu : DropDownListButton.List {
var selection: Int {
didSet {
selectionHandler(items[selection])
}
}
let selectionHandler: ((CustomStringConvertible) -> Void)
init(items: [CustomStringConvertible], initialSelection: Int, selectionHandler: @escaping ((CustomStringConvertible) -> Void)) {
self.selection = initialSelection
self.selectionHandler = selectionHandler
super.init(items: items)
}
public var selectedItem: CustomStringConvertible {
return items[selection]
}
}
private class MenuViewController: DropDownListButton.ListViewController {
private var menu: Menu
init(menu: Menu, title: String?, tableBackgroundColor: UIColor, cellBackgroundColor: UIColor, cellTextColor: UIColor) {
self.menu = menu
super.init(list: menu, title: title, tableBackgroundColor: tableBackgroundColor, cellBackgroundColor: cellBackgroundColor, cellTextColor: cellTextColor)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
cell.accessoryType = indexPath.item == menu.selection ? .checkmark : .none
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
super.tableView(tableView, didSelectRowAt: indexPath)
menu.selection = indexPath.item
self.dismiss(animated: true, completion: nil)
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard let accessory = cell.accessoryView else { return }
accessory.backgroundColor = cellBackgroundColor
accessory.tintColor = cellTextColor
}
}
private var menu: Menu?
private var title: String?
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setTitle("Menu", for: .normal)
}
public func setMenu(title: String?, items: [CustomStringConvertible], initialSelection: Int, selectionHandler: @escaping ((CustomStringConvertible) -> Void)) {
guard items.count > 0 && initialSelection >= 0 && initialSelection < items.count else { return }
self.title = title
menu = Menu(items: items, initialSelection: initialSelection, selectionHandler: { selection in
self.collapse()
self.setTitle(selection.description, for: .normal)
// A situation was encountered wherein the selection handler attempted to present an alert.
// The alert did not appear and the dismissal of the popover was interfered with. Hence we
// delay the invocation of the handler until the popover has been fully dismissed (100 ms
// was too short a time).
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) {
selectionHandler(selection)
}
})
setTitle(menu!.items[initialSelection].description, for: .normal)
}
public var selectedItem: CustomStringConvertible? {
return menu?.selectedItem
}
fileprivate override func makePopoverViewController() -> UIViewController? {
guard let menu = self.menu else { return nil }
return MenuViewController(menu: menu, title: title, tableBackgroundColor: listBackgroundColor, cellBackgroundColor: itemBackgroundColor, cellTextColor: itemTextColor)
}
}
public class DropDownBarButton: UIBarButtonItem {
private let _innerButton = DropDownButton()
fileprivate var innerButton: DropDownButton { return _innerButton }
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
initialize()
}
fileprivate func initialize() {
innerButton.outerButton = self
customView = innerButton
}
public var listBackgroundColor: UIColor {
get { return innerButton.listBackgroundColor }
set { innerButton.listBackgroundColor = newValue }
}
public var itemBackgroundColor: UIColor {
get { return innerButton.itemBackgroundColor }
set { innerButton.itemBackgroundColor = newValue }
}
public var itemTextColor: UIColor {
get { return innerButton.itemTextColor }
set { innerButton.itemTextColor = newValue }
}
public var size : CGSize {
get { return customView!.bounds.size }
set { customView!.bounds.size = newValue }
}
}
public class DropDownListBarButton: DropDownBarButton {
public func setList(title: String?, items: [CustomStringConvertible]) {
innerButton.setList(title: title, items: items)
}
private let _innerButton = DropDownListButton()
fileprivate override var innerButton: DropDownListButton { return _innerButton }
}
public class DropDownMenuBarButton: DropDownBarButton {
public func setMenu(title: String?, items: [CustomStringConvertible], initialSelection: Int, selectionHandler: @escaping ((CustomStringConvertible) -> Void)) {
innerButton.setMenu(title: title, items: items, initialSelection: initialSelection, selectionHandler: selectionHandler)
}
private let _innerButton = DropDownMenuButton()
fileprivate override var innerButton: DropDownMenuButton { return _innerButton }
public var selectedItem: CustomStringConvertible? {
return innerButton.selectedItem
}
}
| 9059f8e327e4632ee62a0e52a39f704d | 34.622003 | 174 | 0.625634 | false | false | false | false |
taoguan/firefox-ios | refs/heads/master | Client/Frontend/Browser/BrowserTrayAnimators.swift | mpl-2.0 | 2 | /* 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
class TrayToBrowserAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
if let bvc = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as? BrowserViewController,
let tabTray = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as? TabTrayController {
transitionFromTray(tabTray, toBrowser: bvc, usingContext: transitionContext)
}
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.4
}
}
private extension TrayToBrowserAnimator {
func transitionFromTray(tabTray: TabTrayController, toBrowser bvc: BrowserViewController, usingContext transitionContext: UIViewControllerContextTransitioning) {
guard let container = transitionContext.containerView() else { return }
guard let selectedTab = bvc.tabManager.selectedTab else { return }
// Bug 1205464 - Top Sites tiles blow up or shrink after rotating
// Force the BVC's frame to match the tab trays since for some reason on iOS 9 the UILayoutContainer in
// the UINavigationController doesn't rotate the presenting view controller
let os = NSProcessInfo().operatingSystemVersion
switch (os.majorVersion, os.minorVersion, os.patchVersion) {
case (9, _, _):
bvc.view.frame = UIWindow().frame
default:
break
}
let tabManager = bvc.tabManager
let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs
guard let expandFromIndex = displayedTabs.indexOf(selectedTab) else { return }
// Hide browser components
bvc.toggleSnackBarVisibility(show: false)
toggleWebViewVisibility(show: false, usingTabManager: bvc.tabManager)
bvc.homePanelController?.view.hidden = true
// Take a snapshot of the collection view that we can scale/fade out. We don't need to wait for screen updates since it's already rendered on the screen
let tabCollectionViewSnapshot = tabTray.collectionView.snapshotViewAfterScreenUpdates(false)
tabTray.collectionView.alpha = 0
tabCollectionViewSnapshot.frame = tabTray.collectionView.frame
container.insertSubview(tabCollectionViewSnapshot, aboveSubview: tabTray.view)
// Create a fake cell to use for the upscaling animation
let startingFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView, atIndex: expandFromIndex)
let cell = createTransitionCellFromBrowser(bvc.tabManager.selectedTab, withFrame: startingFrame)
cell.backgroundHolder.layer.cornerRadius = 0
container.insertSubview(bvc.view, aboveSubview: tabCollectionViewSnapshot)
container.insertSubview(cell, aboveSubview: bvc.view)
// Flush any pending layout/animation code in preperation of the animation call
container.layoutIfNeeded()
let finalFrame = calculateExpandedCellFrameFromBVC(bvc)
bvc.footer.alpha = shouldDisplayFooterForBVC(bvc) ? 1 : 0
bvc.urlBar.isTransitioning = true
// Re-calculate the starting transforms for header/footer views in case we switch orientation
resetTransformsForViews([bvc.header, bvc.headerBackdrop, bvc.readerModeBar, bvc.footer, bvc.footerBackdrop])
transformHeaderFooterForBVC(bvc, toFrame: startingFrame, container: container)
UIView.animateWithDuration(self.transitionDuration(transitionContext),
delay: 0, usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations:
{
// Scale up the cell and reset the transforms for the header/footers
cell.frame = finalFrame
container.layoutIfNeeded()
cell.title.transform = CGAffineTransformMakeTranslation(0, -cell.title.frame.height)
resetTransformsForViews([bvc.header, bvc.footer, bvc.readerModeBar, bvc.footerBackdrop, bvc.headerBackdrop])
bvc.urlBar.updateAlphaForSubviews(1)
tabCollectionViewSnapshot.transform = CGAffineTransformMakeScale(0.9, 0.9)
tabCollectionViewSnapshot.alpha = 0
// Push out the navigation bar buttons
let buttonOffset = tabTray.addTabButton.frame.width + TabTrayControllerUX.ToolbarButtonOffset
tabTray.addTabButton.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, buttonOffset , 0)
tabTray.settingsButton.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, -buttonOffset , 0)
if #available(iOS 9, *) {
tabTray.togglePrivateMode.transform = CGAffineTransformTranslate(CGAffineTransformIdentity, buttonOffset , 0)
}
}, completion: { finished in
// Remove any of the views we used for the animation
cell.removeFromSuperview()
tabCollectionViewSnapshot.removeFromSuperview()
bvc.footer.alpha = 1
bvc.startTrackingAccessibilityStatus()
bvc.toggleSnackBarVisibility(show: true)
toggleWebViewVisibility(show: true, usingTabManager: bvc.tabManager)
bvc.homePanelController?.view.hidden = false
bvc.urlBar.isTransitioning = false
transitionContext.completeTransition(true)
})
}
}
class BrowserToTrayAnimator: NSObject, UIViewControllerAnimatedTransitioning {
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
if let bvc = transitionContext.viewControllerForKey(UITransitionContextFromViewControllerKey) as? BrowserViewController,
let tabTray = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as? TabTrayController {
transitionFromBrowser(bvc, toTabTray: tabTray, usingContext: transitionContext)
}
}
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.4
}
}
private extension BrowserToTrayAnimator {
func transitionFromBrowser(bvc: BrowserViewController, toTabTray tabTray: TabTrayController, usingContext transitionContext: UIViewControllerContextTransitioning) {
guard let container = transitionContext.containerView() else { return }
guard let selectedTab = bvc.tabManager.selectedTab else { return }
let tabManager = bvc.tabManager
let displayedTabs = selectedTab.isPrivate ? tabManager.privateTabs : tabManager.normalTabs
guard let scrollToIndex = displayedTabs.indexOf(selectedTab) else { return }
// Insert tab tray below the browser and force a layout so the collection view can get it's frame right
container.insertSubview(tabTray.view, belowSubview: bvc.view)
// Force subview layout on the collection view so we can calculate the correct end frame for the animation
tabTray.view.layoutSubviews()
tabTray.collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: scrollToIndex, inSection: 0), atScrollPosition: .CenteredVertically, animated: false)
// Build a tab cell that we will use to animate the scaling of the browser to the tab
let expandedFrame = calculateExpandedCellFrameFromBVC(bvc)
let cell = createTransitionCellFromBrowser(bvc.tabManager.selectedTab, withFrame: expandedFrame)
cell.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
cell.innerStroke.hidden = true
// Take a snapshot of the collection view to perform the scaling/alpha effect
let tabCollectionViewSnapshot = tabTray.collectionView.snapshotViewAfterScreenUpdates(true)
tabCollectionViewSnapshot.frame = tabTray.collectionView.frame
tabCollectionViewSnapshot.transform = CGAffineTransformMakeScale(0.9, 0.9)
tabCollectionViewSnapshot.alpha = 0
tabTray.view.addSubview(tabCollectionViewSnapshot)
container.addSubview(cell)
cell.layoutIfNeeded()
cell.title.transform = CGAffineTransformMakeTranslation(0, -cell.title.frame.size.height)
// Hide views we don't want to show during the animation in the BVC
bvc.homePanelController?.view.hidden = true
bvc.toggleSnackBarVisibility(show: false)
toggleWebViewVisibility(show: false, usingTabManager: bvc.tabManager)
bvc.urlBar.isTransitioning = true
// Since we are hiding the collection view and the snapshot API takes the snapshot after the next screen update,
// the screenshot ends up being blank unless we set the collection view hidden after the screen update happens.
// To work around this, we dispatch the setting of collection view to hidden after the screen update is completed.
dispatch_async(dispatch_get_main_queue()) {
tabTray.collectionView.hidden = true
let finalFrame = calculateCollapsedCellFrameUsingCollectionView(tabTray.collectionView,
atIndex: scrollToIndex)
UIView.animateWithDuration(self.transitionDuration(transitionContext),
delay: 0, usingSpringWithDamping: 1,
initialSpringVelocity: 0,
options: UIViewAnimationOptions.CurveEaseInOut,
animations:
{
cell.frame = finalFrame
cell.title.transform = CGAffineTransformIdentity
cell.layoutIfNeeded()
transformHeaderFooterForBVC(bvc, toFrame: finalFrame, container: container)
bvc.urlBar.updateAlphaForSubviews(0)
bvc.footer.alpha = 0
tabCollectionViewSnapshot.alpha = 1
var viewsToReset: [UIView?] = [tabCollectionViewSnapshot, tabTray.addTabButton, tabTray.settingsButton]
if #available(iOS 9, *) {
viewsToReset.append(tabTray.togglePrivateMode)
}
resetTransformsForViews(viewsToReset)
}, completion: { finished in
// Remove any of the views we used for the animation
cell.removeFromSuperview()
tabCollectionViewSnapshot.removeFromSuperview()
tabTray.collectionView.hidden = false
bvc.toggleSnackBarVisibility(show: true)
toggleWebViewVisibility(show: true, usingTabManager: bvc.tabManager)
bvc.homePanelController?.view.hidden = false
bvc.stopTrackingAccessibilityStatus()
bvc.urlBar.isTransitioning = false
transitionContext.completeTransition(true)
})
}
}
}
private func transformHeaderFooterForBVC(bvc: BrowserViewController, toFrame finalFrame: CGRect, container: UIView) {
let footerForTransform = footerTransform(bvc.footer.frame, toFrame: finalFrame, container: container)
let headerForTransform = headerTransform(bvc.header.frame, toFrame: finalFrame, container: container)
bvc.footer.transform = footerForTransform
bvc.footerBackdrop.transform = footerForTransform
bvc.header.transform = headerForTransform
bvc.readerModeBar?.transform = headerForTransform
bvc.headerBackdrop.transform = headerForTransform
}
private func footerTransform(var frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform {
frame = container.convertRect(frame, toView: container)
let endY = CGRectGetMaxY(finalFrame) - (frame.size.height / 2)
let endX = CGRectGetMidX(finalFrame)
let translation = CGPoint(x: endX - CGRectGetMidX(frame), y: endY - CGRectGetMidY(frame))
let scaleX = finalFrame.width / frame.width
var transform = CGAffineTransformIdentity
transform = CGAffineTransformTranslate(transform, translation.x, translation.y)
transform = CGAffineTransformScale(transform, scaleX, scaleX)
return transform
}
private func headerTransform(var frame: CGRect, toFrame finalFrame: CGRect, container: UIView) -> CGAffineTransform {
frame = container.convertRect(frame, toView: container)
let endY = CGRectGetMinY(finalFrame) + (frame.size.height / 2)
let endX = CGRectGetMidX(finalFrame)
let translation = CGPoint(x: endX - CGRectGetMidX(frame), y: endY - CGRectGetMidY(frame))
let scaleX = finalFrame.width / frame.width
var transform = CGAffineTransformIdentity
transform = CGAffineTransformTranslate(transform, translation.x, translation.y)
transform = CGAffineTransformScale(transform, scaleX, scaleX)
return transform
}
//MARK: Private Helper Methods
private func calculateCollapsedCellFrameUsingCollectionView(collectionView: UICollectionView, atIndex index: Int) -> CGRect {
if let attr = collectionView.collectionViewLayout.layoutAttributesForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) {
return collectionView.convertRect(attr.frame, toView: collectionView.superview)
} else {
return CGRectZero
}
}
private func calculateExpandedCellFrameFromBVC(bvc: BrowserViewController) -> CGRect {
var frame = bvc.webViewContainer.frame
// If we're navigating to a home panel and we were expecting to show the toolbar, add more height to end frame since
// there is no toolbar for home panels
if !bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) {
return frame
} else if AboutUtils.isAboutURL(bvc.tabManager.selectedTab?.url) {
frame.size.height += UIConstants.ToolbarHeight
}
return frame
}
private func shouldDisplayFooterForBVC(bvc: BrowserViewController) -> Bool {
return bvc.shouldShowFooterForTraitCollection(bvc.traitCollection) && !AboutUtils.isAboutURL(bvc.tabManager.selectedTab?.url)
}
private func toggleWebViewVisibility(show show: Bool, usingTabManager tabManager: TabManager) {
for i in 0..<tabManager.count {
if let tab = tabManager[i] {
tab.webView?.hidden = !show
}
}
}
private func resetTransformsForViews(views: [UIView?]) {
for view in views {
// Reset back to origin
view?.transform = CGAffineTransformIdentity
}
}
private func transformToolbarsToFrame(toolbars: [UIView?], toRect endRect: CGRect) {
for toolbar in toolbars {
// Reset back to origin
toolbar?.transform = CGAffineTransformIdentity
// Transform from origin to where we want them to end up
if let toolbarFrame = toolbar?.frame {
toolbar?.transform = CGAffineTransformMakeRectToRect(toolbarFrame, toFrame: endRect)
}
}
}
private func createTransitionCellFromBrowser(browser: Browser?, withFrame frame: CGRect) -> TabCell {
let cell = TabCell(frame: frame)
cell.background.image = browser?.screenshot
cell.titleText.text = browser?.displayTitle
if let browser = browser where browser.isPrivate {
cell.style = .Dark
}
if let favIcon = browser?.displayFavicon {
cell.favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!)
} else {
cell.favicon.image = UIImage(named: "defaultFavicon")
}
return cell
}
| 2ea92b716435e9298218ddacb7e6c3c8 | 47.561129 | 168 | 0.717707 | false | false | false | false |
spritesun/MeditationHelper | refs/heads/master | MeditationHelper/MeditationHelper/IJReachability.swift | mit | 1 | //
// IJReachability.swift
// IJReachability
//
// Created by Isuru Nanayakkara on 1/14/15.
// Copyright (c) 2015 Appex. All rights reserved.
//
import Foundation
import SystemConfiguration
public enum IJReachabilityType {
case WWAN,
WiFi,
NotConnected
}
public class IJReachability {
/**
:see: Original post - http://www.chrisdanielson.com/2009/07/22/iphone-network-connectivity-test-example/
*/
public class func isConnectedToNetwork() -> Bool {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return false
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
return (isReachable && !needsConnection) ? true : false
}
public class func isConnectedToNetworkOfType() -> IJReachabilityType {
var zeroAddress = sockaddr_in(sin_len: 0, sin_family: 0, sin_port: 0, sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let defaultRouteReachability = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)).takeRetainedValue()
}
var flags: SCNetworkReachabilityFlags = 0
if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 {
return .NotConnected
}
let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0
let isWWAN = (flags & UInt32(kSCNetworkReachabilityFlagsIsWWAN)) != 0
//let isWifI = (flags & UInt32(kSCNetworkReachabilityFlagsReachable)) != 0
if(isReachable && isWWAN){
return .WWAN
}
if(isReachable && !isWWAN){
return .WiFi
}
return .NotConnected
//let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
//return (isReachable && !needsConnection) ? true : false
}
}
| 92f4e0accc60e57a662d919ad6f9a111 | 31.526316 | 139 | 0.685275 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/SILGen/closures_callee_guaranteed.swift | apache-2.0 | 27 | // RUN: %target-swift-emit-silgen -parse-stdlib -parse-as-library %s | %FileCheck %s
import Swift
// CHECK-LABEL: sil [ossa] @{{.*}}apply{{.*}} : $@convention(thin) (@noescape @callee_guaranteed () -> Int)
// bb0(%0 : $@noescape @callee_guaranteed () -> Int):
// [[B1:%.*]] = begin_borrow %0 : $@noescape @callee_guaranteed () -> Int
// [[C1:%.*]] = copy_value %2 : $@noescape @callee_guaranteed () -> Int
//
// The important part is that the call borrow's the function value -- we are
// @callee_guaranteed.
// [[B2:%.*]] = begin_borrow [[C1]] : $@noescape @callee_guaranteed () -> Int
// [[R:%.*]] = apply [[B2]]() : $@noescape @callee_guaranteed () -> Int
// end_borrow [[B2]] : $@noescape @callee_guaranteed () -> Int
//
// destroy_value [[C1]] : $@noescape @callee_guaranteed () -> Int
// end_borrow [[B1]] : $@noescape @callee_guaranteed () -> Int
// destroy_value %0 : $@noescape @callee_guaranteed () -> Int
// return [[R]] : $Int
public func apply(_ f : () -> Int) -> Int {
return f()
}
// CHECK-LABEL: sil [ossa] @{{.*}}test{{.*}} : $@convention(thin) () -> ()
// CHECK: [[C1:%.*]] = function_ref @{{.*}}test{{.*}} : $@convention(thin) () -> Int
// CHECK: [[C2:%.*]] = convert_function [[C1]] : $@convention(thin) () -> Int to $@convention(thin) @noescape () -> Int
// CHECK: [[C3:%.*]] = thin_to_thick_function [[C2]] : $@convention(thin) @noescape () -> Int to $@noescape @callee_guaranteed () -> Int
// CHECK: [[A:%.*]] = function_ref @{{.*}}apply{{.*}} : $@convention(thin) (@noescape @callee_guaranteed () -> Int) -> Int
// CHECK: apply [[A]]([[C3]]) : $@convention(thin) (@noescape @callee_guaranteed () -> Int) -> Int
public func test() {
let res = apply({ return 1 })
}
| 2f9839b440a37450d48c160cb43ce6e4 | 54.709677 | 138 | 0.561668 | false | true | false | false |
mlilback/rc2SwiftClient | refs/heads/master | MacClient/session/output/ConsoleOutputController.swift | isc | 1 | //
// ConsoleOutputController.swift
//
// Copyright © 2016 Mark Lilback. This file is licensed under the ISC license.
//
import Rc2Common
import Cocoa
import Networking
import MJLLogger
import Model
import ReactiveSwift
enum SessionStateKey: String {
case History = "history"
case Results = "results"
}
///ViewController whose view contains the text view showing the results, and the text field for entering short queries
class ConsoleOutputController: AbstractSessionViewController, OutputController, NSTextViewDelegate, NSTextFieldDelegate, TextViewMenuDelegate
{
// MARK: - properties
@IBOutlet var resultsView: ResultsView?
@IBOutlet var consoleTextField: ConsoleTextField?
@IBOutlet var historyButton: NSSegmentedControl?
@IBOutlet var contextualMenuAdditions: NSMenu?
weak var contextualMenuDelegate: ContextualMenuDelegate?
var outputFont: NSFont = NSFont(name: "Menlo", size: 14)!
let cmdHistory: CommandHistory
@objc dynamic var consoleInputText = "" { didSet { canExecute = consoleInputText.count > 0 } }
@objc dynamic var canExecute = false
var viewFileOrImage: ((_ fileWrapper: FileWrapper) -> Void)?
var currentFontDescriptor: NSFontDescriptor {
didSet {
if let font = NSFont(descriptor: currentFontDescriptor, size: currentFontDescriptor.pointSize) {
outputFont = font
resultsView?.font = font
}
}
}
var supportsSearchBar: Bool { return true }
var searchBarVisible: Bool { return resultsView?.enclosingScrollView?.isFindBarVisible ?? false }
required init?(coder: NSCoder) {
cmdHistory = CommandHistory(target: nil, selector: #selector(ConsoleOutputController.displayHistoryItem(_:)))
// set a default font since required at init. will be changed in viewDidLoad() and restoreSessionState()
currentFontDescriptor = NSFont.userFixedPitchFont(ofSize: 14.0)!.fontDescriptor
super.init(coder: coder)
}
// MARK: - overrides
override func viewDidLoad() {
super.viewDidLoad()
if #available(macOS 10.14, *) {
resultsView?.appearance = NSAppearance(named: .aqua)
}
cmdHistory.target = self
consoleTextField?.adjustContextualMenu = { (editor: NSText, theMenu: NSMenu) in
return theMenu
}
resultsView?.menuDelegate = self
resultsView?.textContainerInset = NSSize(width: 4, height: 4)
restoreFont()
//try switching to Menlo instead of default monospaced font
ThemeManager.shared.activeOutputTheme.signal.observe(on: UIScheduler()).observeValues { [weak self] _ in
self?.themeChanged()
}
}
@objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
guard let action = menuItem.action else { return false }
switch action {
case #selector(ConsoleOutputController.clearConsole(_:)):
return resultsView?.string.count ?? 0 > 0
case #selector(ConsoleOutputController.historyClicked(_:)):
return true
case #selector(displayHistoryItem(_:)):
return true
default:
return false
}
}
// MARK: - internal
private func restoreFont() {
var fdesc: FontDescriptor? = UserDefaults.standard[.consoleOutputFont]
//pick a default font
if fdesc == nil {
fdesc = NSFontDescriptor(name: "Menlo-Regular", size: 14.0)
UserDefaults.standard[.consoleOutputFont] = fdesc
}
var font = NSFont(descriptor: fdesc!, size: fdesc!.pointSize)
if font == nil {
font = NSFont.userFixedPitchFont(ofSize: 14.0)!
fdesc = font!.fontDescriptor
}
currentFontDescriptor = fdesc!
}
func themeChanged() {
let theme = ThemeManager.shared.activeOutputTheme.value
let fullRange = resultsView!.textStorage!.string.fullNSRange
let fontAttrs: [NSAttributedString.Key: Any] = [.font: outputFont, .foregroundColor: theme.color(for: .text)]
resultsView?.textStorage?.addAttributes(fontAttrs, range: fullRange)
theme.update(attributedString: resultsView!.textStorage!)
resultsView?.backgroundColor = theme.color(for: .background)
}
fileprivate func actuallyClearConsole() {
resultsView?.textStorage?.deleteCharacters(in: NSRange(location: 0, length: (resultsView?.textStorage?.length)!))
}
// MARK: - actions
@IBAction func executeQuery(_ sender: Any?) {
guard consoleInputText.count > 0 else { return }
session.executeScript(consoleInputText)
cmdHistory.addToCommandHistory(consoleInputText)
consoleTextField?.stringValue = ""
}
// MARK: - SessionOutputHandler
func append(responseString: ResponseString) {
// swiftlint:disable:next force_cast
let mutStr = responseString.string.mutableCopy() as! NSMutableAttributedString
mutStr.addAttributes([.font: outputFont], range: NSRange(location: 0, length: mutStr.length))
resultsView!.textStorage?.append(mutStr)
resultsView!.scrollToEndOfDocument(nil)
}
func save(state: inout SessionState.OutputControllerState) {
state.commandHistory = cmdHistory.commands
let fullRange = resultsView!.textStorage!.string.fullNSRange
if let rtfd = resultsView?.textStorage?.rtfd(from: fullRange, documentAttributes: [.documentType: NSAttributedString.DocumentType.rtfd])
{
#if DEBUG
_ = try? rtfd.write(to: URL(fileURLWithPath: "/tmp/lastSession.rtfd"))
#endif
state.resultsContent = rtfd
}
}
func restore(state: SessionState.OutputControllerState) {
cmdHistory.commands = state.commandHistory
guard let rtfdData = state.resultsContent else { return }
let resultsView = self.resultsView!
let ts = resultsView.textStorage!
//for some reason, NSLayoutManager is initially making the line with an attachment 32 tall, even though image is 48. On window resize, it corrects itself. so we are going to keep an array of attachment indexes so we can fix this later
var fileIndexes: [Int] = []
resultsView.replaceCharacters(in: NSRange(location: 0, length: ts.length), withRTFD: rtfdData)
themeChanged() //trigger setting attributes
ts.enumerateAttribute(.attachment, in: ts.string.fullNSRange, options: [], using:
{ (value, range, _) -> Void in
guard let attach = value as? NSTextAttachment,
let fw = attach.fileWrapper,
let fname = fw.preferredFilename
else { return }
if fname.hasPrefix("img") {
let cell = NSTextAttachmentCell(imageCell: #imageLiteral(resourceName: "graph"))
cell.image?.size = consoleAttachmentImageSize
ts.removeAttribute(.attachment, range: range)
attach.attachmentCell = cell
ts.addAttribute(.attachment, value: attach, range: range)
} else {
attach.attachmentCell = self.attachmentCellForAttachment(attach)
fileIndexes.append(range.location)
}
})
//now go through all lines with an attachment and insert a space, and then delete it. that forces a layout that uses the correct line height
fileIndexes.forEach {
ts.insert(NSAttributedString(string: " "), at: $0)
ts.deleteCharacters(in: NSRange(location: $0, length: 1))
}
ThemeManager.shared.activeOutputTheme.value.update(attributedString: ts)
//scroll to bottom
resultsView.moveToEndOfDocument(self)
}
func attachmentCellForAttachment(_ attachment: NSTextAttachment) -> NSTextAttachmentCell? {
guard let attach = try? MacConsoleAttachment.from(data: attachment.fileWrapper!.regularFileContents!) else { return nil }
assert(attach.type == .file)
let fileType = FileType.fileType(withExtension: attach.fileExtension!)
let img = NSImage(named: NSImage.Name(fileType?.iconName ?? "file-plain"))
img?.size = consoleAttachmentImageSize
return NSTextAttachmentCell(imageCell: img)
}
// MARK: - command history
@IBAction func historyClicked(_ sender: Any?) {
cmdHistory.adjustCommandHistoryMenu()
let hframe = historyButton?.superview?.convert((historyButton?.frame)!, to: nil)
let rect = view.window?.convertToScreen(hframe!)
cmdHistory.historyMenu.popUp(positioning: nil, at: (rect?.origin)!, in: nil)
}
@IBAction func displayHistoryItem(_ sender: Any?) {
guard let mi = sender as? NSMenuItem, let historyString = mi.representedObject as? String else {
Log.warn("displayHistoryItem only supported from menu item", .app)
return
}
consoleInputText = historyString
canExecute = consoleInputText.count > 0
//the following shouldn't be necessary because they are bound. But sometimes the textfield value does not update
consoleTextField?.stringValue = consoleInputText
view.window?.makeFirstResponder(consoleTextField)
}
@IBAction func clearConsole(_ sender: Any?) {
let defaults = UserDefaults.standard
guard !defaults[.suppressClearImagesWithConsole] else {
actuallyClearConsole()
if defaults[.clearImagesWithConsole] { session.imageCache.clearCache() }
return
}
confirmAction(message: NSLocalizedString("ClearConsoleWarning", comment: ""),
infoText: NSLocalizedString("ClearConsoleInfo", comment: ""),
buttonTitle: NSLocalizedString("ClearImagesButton", comment: ""),
cancelTitle: NSLocalizedString("ClearConsoleOnlyButton", comment: ""),
defaultToCancel: !defaults[.clearImagesWithConsole],
suppressionKey: .suppressClearImagesWithConsole)
{ (clearImages) in
defaults[.clearImagesWithConsole] = clearImages
self.actuallyClearConsole()
if clearImages { self.session.imageCache.clearCache() }
}
}
// MARK: - textfield delegate
func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
if commandSelector == #selector(NSResponder.insertNewline(_:)) {
executeQuery(control)
return true
}
return false
}
// MARK: - textview delegate
func textView(_ textView: NSTextView, clickedOn cell: NSTextAttachmentCellProtocol, in cellFrame: NSRect, at charIndex: Int)
{
let attach = cell.attachment
guard let fw = attach?.fileWrapper else { return }
viewFileOrImage?(fw)
}
// MARK: TextViewMenuDelegate
@objc func additionalContextMenuItems() -> [NSMenuItem]? {
var items = contextualMenuDelegate?.contextMenuItems(for: self) ?? []
for anItem in contextualMenuAdditions?.items ?? [] {
if let dupItem = anItem.copy() as? NSMenuItem,
validateMenuItem(dupItem)
{
items.append(dupItem)
}
}
return items
}
}
extension ConsoleOutputController: Searchable {
func performFind(action: NSTextFinder.Action) {
let menuItem = NSMenuItem(title: "foo", action: #selector(NSTextView.performFindPanelAction(_:)), keyEquivalent: "")
menuItem.tag = action.rawValue
resultsView?.performFindPanelAction(menuItem)
if action == .hideFindInterface {
resultsView?.enclosingScrollView?.isFindBarVisible = false
}
}
}
// MARK: - UsesAdjustableFont
extension ConsoleOutputController: UsesAdjustableFont {
func fontsEnabled() -> Bool {
return true
}
func fontChanged(_ menuItem: NSMenuItem) {
guard let newNameDesc = menuItem.representedObject as? NSFontDescriptor else { return }
let newDesc = newNameDesc.withSize(currentFontDescriptor.pointSize)
currentFontDescriptor = newDesc
resultsView?.font = NSFont(descriptor: newDesc, size: newDesc.pointSize)
}
}
| cf9ce697039b9bf8f2d905c3650ca7d9 | 37.278169 | 236 | 0.746665 | false | false | false | false |
cybertunnel/SplashBuddy | refs/heads/master | SplashBuddy/Software.swift | apache-2.0 | 1 | //
// Software.swift
// SplashBuddy
//
// Created by ftiff on 02/08/16.
// Copyright © 2016 François Levaux-Tiffreau. All rights reserved.
//
import Cocoa
/**
Object that will hold the definition of a software.
The goal here is to:
1. Create a Software object from the plist (MacAdmin supplied Software)
2. Parse the log and either:
- Modify the Software object (if it already exists)
- Create a new Software object.
*/
class Software: NSObject {
/**
Status of the software.
Default is .pending, other cases will be set while parsing the log
*/
@objc enum SoftwareStatus: Int {
case installing = 0
case success = 1
case failed = 2
case pending = 3
}
dynamic var packageName: String
dynamic var packageVersion: String?
dynamic var status: SoftwareStatus
dynamic var icon: NSImage?
dynamic var displayName: String?
dynamic var desc: String?
dynamic var canContinue: Bool
dynamic var displayToUser: Bool
/**
Initializes a Software Object
- note: Only packageName is required to parse, displayName, description and displayToUser will have to be set later to properly show it on the GUI.
- parameter packageName: *packageName*-packageVersion.pkg
- parameter version: Optional
- parameter iconPath: Optional
- parameter displayName: Name displayed to user
- parameter description: Second line underneath name
- parameter canContinue: if set to false, the Software will block the "Continue" button until installed
- parameter displayToUser: set to True to display in GUI
*/
init(packageName: String,
version: String? = nil,
status: SoftwareStatus = .pending,
iconPath: String? = nil,
displayName: String? = nil,
description: String? = nil,
canContinue: Bool = true,
displayToUser: Bool = false) {
self.packageName = packageName
self.packageVersion = version
self.status = status
self.canContinue = canContinue
self.displayToUser = displayToUser
self.displayName = displayName
self.desc = description
if let iconPath = iconPath {
self.icon = NSImage(contentsOfFile: iconPath)
} else {
self.icon = NSImage(named: NSImageNameFolder)
}
}
convenience init?(from line: String) {
var name: String?
var version: String?
var status: SoftwareStatus?
for (regexStatus, regex) in initRegex() {
status = regexStatus
let matches = regex!.matches(in: line, options: [], range: NSMakeRange(0, line.characters.count))
if !matches.isEmpty {
name = (line as NSString).substring(with: matches[0].rangeAt(1))
version = (line as NSString).substring(with: matches[0].rangeAt(2))
break
}
}
if let packageName = name, let packageVersion = version, let packageStatus = status {
self.init(packageName: packageName, version: packageVersion, status: packageStatus)
} else {
return nil
}
}
}
func == (lhs: Software, rhs: Software) -> Bool {
return lhs.packageName == rhs.packageName && lhs.packageVersion == rhs.packageVersion && lhs.status == rhs.status
}
| f12419202dce5820f9069d99748c783d | 27.184 | 152 | 0.609424 | false | false | false | false |
apple/swift-protobuf | refs/heads/main | Sources/SwiftProtobufPluginLibrary/SwiftProtobufNamer.swift | apache-2.0 | 2 | // Sources/SwiftProtobufPluginLibrary/SwiftProtobufNamer.swift - A helper that generates SwiftProtobuf names.
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// A helper that can generate SwiftProtobuf names from types.
///
// -----------------------------------------------------------------------------
import Foundation
public final class SwiftProtobufNamer {
var filePrefixCache = [String:String]()
var enumValueRelativeNameCache = [String:String]()
var mappings: ProtoFileToModuleMappings
var targetModule: String
public var swiftProtobufModuleName: String { return mappings.swiftProtobufModuleName }
public var swiftProtobufModulePrefix: String {
guard targetModule != mappings.swiftProtobufModuleName else {
return ""
}
return "\(mappings.swiftProtobufModuleName)."
}
/// Initializes a a new namer, assuming everything will be in the same Swift module.
public convenience init() {
self.init(protoFileToModuleMappings: ProtoFileToModuleMappings(), targetModule: "")
}
/// Initializes a a new namer. All names will be generated as from the pov of the
/// given file using the provided file to module mapper.
public convenience init(
currentFile file: FileDescriptor,
protoFileToModuleMappings mappings: ProtoFileToModuleMappings
) {
let targetModule = mappings.moduleName(forFile: file) ?? ""
self.init(protoFileToModuleMappings: mappings, targetModule: targetModule)
}
/// Internal initializer.
init(
protoFileToModuleMappings mappings: ProtoFileToModuleMappings,
targetModule: String
) {
self.mappings = mappings
self.targetModule = targetModule
}
/// Calculate the relative name for the given message.
public func relativeName(message: Descriptor) -> String {
if message.containingType != nil {
return NamingUtils.sanitize(messageName: message.name, forbiddenTypeNames: [self.swiftProtobufModuleName])
} else {
let prefix = typePrefix(forFile: message.file)
return NamingUtils.sanitize(messageName: prefix + message.name, forbiddenTypeNames: [self.swiftProtobufModuleName])
}
}
/// Calculate the full name for the given message.
public func fullName(message: Descriptor) -> String {
let relativeName = self.relativeName(message: message)
guard let containingType = message.containingType else {
return modulePrefix(file: message.file) + relativeName
}
return fullName(message:containingType) + "." + relativeName
}
/// Calculate the relative name for the given enum.
public func relativeName(enum e: EnumDescriptor) -> String {
if e.containingType != nil {
return NamingUtils.sanitize(enumName: e.name, forbiddenTypeNames: [self.swiftProtobufModuleName])
} else {
let prefix = typePrefix(forFile: e.file)
return NamingUtils.sanitize(enumName: prefix + e.name, forbiddenTypeNames: [self.swiftProtobufModuleName])
}
}
/// Calculate the full name for the given enum.
public func fullName(enum e: EnumDescriptor) -> String {
let relativeName = self.relativeName(enum: e)
guard let containingType = e.containingType else {
return modulePrefix(file: e.file) + relativeName
}
return fullName(message: containingType) + "." + relativeName
}
/// Compute the short names to use for the values of this enum.
private func computeRelativeNames(enum e: EnumDescriptor) {
let stripper = NamingUtils.PrefixStripper(prefix: e.name)
/// Determine the initial candidate name for the name before
/// doing duplicate checks.
func candidateName(_ enumValue: EnumValueDescriptor) -> String {
let baseName = enumValue.name
if let stripped = stripper.strip(from: baseName) {
return NamingUtils.toLowerCamelCase(stripped)
}
return NamingUtils.toLowerCamelCase(baseName)
}
// Bucketed based on candidate names to check for duplicates.
let candidates :[String:[EnumValueDescriptor]] = e.values.reduce(into: [:]) {
$0[candidateName($1), default:[]].append($1)
}
for (camelCased, enumValues) in candidates {
// If there is only one, sanitize and cache it.
guard enumValues.count > 1 else {
enumValueRelativeNameCache[enumValues.first!.fullName] =
NamingUtils.sanitize(enumCaseName: camelCased)
continue
}
// There are two possible cases:
// 1. There is the main entry and then all aliases for it that
// happen to be the same after the prefix was stripped.
// 2. There are atleast two values (there could also be aliases).
//
// For the first case, there's no need to do anything, we'll go
// with just one Swift version. For the second, append "_#" to
// the names to help make the different Swift versions clear
// which they are.
let firstValue = enumValues.first!.number
let hasMultipleValues = enumValues.contains(where: { return $0.number != firstValue })
guard hasMultipleValues else {
// Was the first case, all one value, just aliases that mapped
// to the same name.
let name = NamingUtils.sanitize(enumCaseName: camelCased)
for e in enumValues {
enumValueRelativeNameCache[e.fullName] = name
}
continue
}
for e in enumValues {
// Can't put a negative size, so use "n" and make the number
// positive.
let suffix = e.number >= 0 ? "_\(e.number)" : "_n\(-e.number)"
enumValueRelativeNameCache[e.fullName] =
NamingUtils.sanitize(enumCaseName: camelCased + suffix)
}
}
}
/// Calculate the relative name for the given enum value.
public func relativeName(enumValue: EnumValueDescriptor) -> String {
if let name = enumValueRelativeNameCache[enumValue.fullName] {
return name
}
computeRelativeNames(enum: enumValue.enumType)
return enumValueRelativeNameCache[enumValue.fullName]!
}
/// Calculate the full name for the given enum value.
public func fullName(enumValue: EnumValueDescriptor) -> String {
return fullName(enum: enumValue.enumType) + "." + relativeName(enumValue: enumValue)
}
/// The relative name with a leading dot so it can be used where
/// the type is known.
public func dottedRelativeName(enumValue: EnumValueDescriptor) -> String {
let relativeName = self.relativeName(enumValue: enumValue)
return "." + NamingUtils.trimBackticks(relativeName)
}
/// Calculate the relative name for the given oneof.
public func relativeName(oneof: OneofDescriptor) -> String {
let camelCase = NamingUtils.toUpperCamelCase(oneof.name)
return NamingUtils.sanitize(oneofName: "OneOf_\(camelCase)", forbiddenTypeNames: [self.swiftProtobufModuleName])
}
/// Calculate the full name for the given oneof.
public func fullName(oneof: OneofDescriptor) -> String {
return fullName(message: oneof.containingType) + "." + relativeName(oneof: oneof)
}
/// Calculate the relative name for the given entension.
///
/// - Precondition: `extensionField` must be FieldDescriptor for an extension.
public func relativeName(extensionField field: FieldDescriptor) -> String {
precondition(field.isExtension)
if field.extensionScope != nil {
return NamingUtils.sanitize(messageScopedExtensionName: field.namingBase)
} else {
let swiftPrefix = typePrefix(forFile: field.file)
return swiftPrefix + "Extensions_" + field.namingBase
}
}
/// Calculate the full name for the given extension.
///
/// - Precondition: `extensionField` must be FieldDescriptor for an extension.
public func fullName(extensionField field: FieldDescriptor) -> String {
precondition(field.isExtension)
let relativeName = self.relativeName(extensionField: field)
guard let extensionScope = field.extensionScope else {
return modulePrefix(file: field.file) + relativeName
}
let extensionScopeSwiftFullName = fullName(message: extensionScope)
let relativeNameNoBackticks = NamingUtils.trimBackticks(relativeName)
return extensionScopeSwiftFullName + ".Extensions." + relativeNameNoBackticks
}
public typealias MessageFieldNames = (name: String, prefixed: String, has: String, clear: String)
/// Calculate the names to use for the Swift fields on the message.
///
/// If `prefixed` is not empty, the name prefixed with that will also be included.
///
/// If `includeHasAndClear` is False, the has:, clear: values in the result will
/// be the empty string.
///
/// - Precondition: `field` must be FieldDescriptor that's isn't for an extension.
public func messagePropertyNames(field: FieldDescriptor,
prefixed: String,
includeHasAndClear: Bool) -> MessageFieldNames {
precondition(!field.isExtension)
let lowerName = NamingUtils.toLowerCamelCase(field.namingBase)
let fieldName = NamingUtils.sanitize(fieldName: lowerName)
let prefixedFieldName =
prefixed.isEmpty ? "" : NamingUtils.sanitize(fieldName: "\(prefixed)\(lowerName)", basedOn: lowerName)
if !includeHasAndClear {
return MessageFieldNames(name: fieldName, prefixed: prefixedFieldName, has: "", clear: "")
}
let upperName = NamingUtils.toUpperCamelCase(field.namingBase)
let hasName = NamingUtils.sanitize(fieldName: "has\(upperName)", basedOn: lowerName)
let clearName = NamingUtils.sanitize(fieldName: "clear\(upperName)", basedOn: lowerName)
return MessageFieldNames(name: fieldName, prefixed: prefixedFieldName, has: hasName, clear: clearName)
}
public typealias OneofFieldNames = (name: String, prefixed: String)
/// Calculate the name to use for the Swift field on the message.
public func messagePropertyName(oneof: OneofDescriptor, prefixed: String = "_") -> OneofFieldNames {
let lowerName = NamingUtils.toLowerCamelCase(oneof.name)
let fieldName = NamingUtils.sanitize(fieldName: lowerName)
let prefixedFieldName = NamingUtils.sanitize(fieldName: "\(prefixed)\(lowerName)", basedOn: lowerName)
return OneofFieldNames(name: fieldName, prefixed: prefixedFieldName)
}
public typealias MessageExtensionNames = (value: String, has: String, clear: String)
/// Calculate the names to use for the Swift Extension on the extended
/// message.
///
/// - Precondition: `extensionField` must be FieldDescriptor for an extension.
public func messagePropertyNames(extensionField field: FieldDescriptor) -> MessageExtensionNames {
precondition(field.isExtension)
let fieldBaseName = NamingUtils.toLowerCamelCase(field.namingBase)
let fieldName: String
let hasName: String
let clearName: String
if let extensionScope = field.extensionScope {
let extensionScopeSwiftFullName = fullName(message: extensionScope)
// Don't worry about any sanitize api on these names; since there is a
// Message name on the front, it should never hit a reserved word.
//
// fieldBaseName is the lowerCase name even though we put more on the
// front, this seems to help make the field name stick out a little
// compared to the message name scoping it on the front.
fieldName = NamingUtils.periodsToUnderscores(extensionScopeSwiftFullName + "_" + fieldBaseName)
let fieldNameFirstUp = NamingUtils.uppercaseFirstCharacter(fieldName)
hasName = "has" + fieldNameFirstUp
clearName = "clear" + fieldNameFirstUp
} else {
// If there was no package and no prefix, fieldBaseName could be a reserved
// word, so sanitize. These's also the slim chance the prefix plus the
// extension name resulted in a reserved word, so the sanitize is always
// needed.
let swiftPrefix = typePrefix(forFile: field.file)
fieldName = NamingUtils.sanitize(fieldName: swiftPrefix + fieldBaseName)
if swiftPrefix.isEmpty {
// No prefix, so got back to UpperCamelCasing the extension name, and then
// sanitize it like we did for the lower form.
let upperCleaned = NamingUtils.sanitize(fieldName: NamingUtils.toUpperCamelCase(field.namingBase),
basedOn: fieldBaseName)
hasName = "has" + upperCleaned
clearName = "clear" + upperCleaned
} else {
// Since there was a prefix, just add has/clear and ensure the first letter
// was capitalized.
let fieldNameFirstUp = NamingUtils.uppercaseFirstCharacter(fieldName)
hasName = "has" + fieldNameFirstUp
clearName = "clear" + fieldNameFirstUp
}
}
return MessageExtensionNames(value: fieldName, has: hasName, clear: clearName)
}
/// Calculate the prefix to use for this file, it is derived from the
/// proto package or swift_prefix file option.
public func typePrefix(forFile file: FileDescriptor) -> String {
if let result = filePrefixCache[file.name] {
return result
}
let result = NamingUtils.typePrefix(protoPackage: file.package,
fileOptions: file.options)
filePrefixCache[file.name] = result
return result
}
/// Internal helper to find the module prefix for a symbol given a file.
func modulePrefix(file: FileDescriptor) -> String {
guard let prefix = mappings.moduleName(forFile: file) else {
return String()
}
if prefix == targetModule {
return String()
}
return "\(prefix)."
}
}
| b2210a5ed8a31a697b2a0f3600e77ffc | 40.39039 | 121 | 0.696147 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | refs/heads/master | Objects/data types/enumerable/CMTrainer.swift | gpl-2.0 | 1 | //
// CMTrainer.swift
// Colosseum Tool
//
// Created by The Steez on 04/06/2018.
//
import Foundation
let kSizeOfTrainerData = 0x34
let kNumberOfTrainerPokemon = 0x06
let kNumberOfTrainerEntries = CommonIndexes.NumberOfTrainers.value // 820
let kTrainerGenderOffset = 0x00
let kTrainerClassOffset = 0x03
let kTrainerFirstPokemonOffset = 0x04
let kTrainerAIOffset = 0x06
let kTrainerNameIDOffset = 0x08
let kTrainerBattleTransitionOffset = 0x0C
let kTrainerClassModelOffset = 0x13
let kTrainerPreBattleTextIDOffset = 0x24
let kTrainerVictoryTextIDOffset = 0x28
let kTrainerDefeatTextIDOffset = 0x2C
let kFirstTrainerLoseText2Offset = 0x32
let kTrainerFirstItemOffset = 0x14
typealias TrainerInfo = (fullname:String,name:String,location:String,hasShadow: Bool,trainerModel:XGTrainerModels,index:Int, deck: XGDecks)
final class XGTrainer: NSObject, Codable {
var index = 0x0
var AI = 0
var cameraEffects = 0 // xd only
var nameID = 0x0
var preBattleTextID = 0x0
var victoryTextID = 0x0
var defeatTextID = 0x0
var shadowMask = 0x0
var pokemon = [XGTrainerPokemon]()
var trainerClass = XGTrainerClasses.none
var trainerModel = XGTrainerModels.wes
var items = [XGItems]()
lazy var battleData: XGBattle? = {
return XGBattle.battleForTrainer(index: self.index)
}()
var startOffset : Int {
get {
return CommonIndexes.Trainers.startOffset + (index * kSizeOfTrainerData)
}
}
var name : XGString {
get {
return XGFiles.common_rel.stringTable.stringSafelyWithID(self.nameID)
}
}
var isPlayer : Bool {
return self.index == 1
}
var prizeMoney : Int {
get {
var maxLevel = 0
for poke in self.pokemon {
maxLevel = poke.level > maxLevel ? poke.level : maxLevel
}
return self.trainerClass.payout * 2 * maxLevel
}
}
var hasShadow : Bool {
get {
for poke in self.pokemon {
if poke.isShadowPokemon {
return true
}
}
return false
}
}
var trainerInfo: TrainerInfo {
return (self.trainerClass.name.string + " " + self.name.unformattedString, self.name.unformattedString,"",self.hasShadow,self.trainerModel,self.index, .DeckStory)
}
init(index: Int) {
super.init()
self.index = index
let start = startOffset
let deck = XGFiles.common_rel.data!
self.nameID = deck.getWordAtOffset(start + kTrainerNameIDOffset).int
self.preBattleTextID = deck.getWordAtOffset(start + kTrainerPreBattleTextIDOffset).int
self.victoryTextID = deck.getWordAtOffset(start + kTrainerVictoryTextIDOffset).int
self.defeatTextID = deck.getWordAtOffset(start + kTrainerDefeatTextIDOffset).int
self.AI = deck.get2BytesAtOffset(start + kTrainerAIOffset)
let tClass = deck.getByteAtOffset(start + kTrainerClassOffset)
let tModel = deck.getByteAtOffset(start + kTrainerClassModelOffset)
self.trainerClass = XGTrainerClasses(rawValue: tClass) ?? .none
self.trainerModel = XGTrainerModels(rawValue: tModel) ?? .wes
self.items = deck.getShortStreamFromOffset(start + kTrainerFirstItemOffset, length: 8).map({ (index) -> XGItems in
return .index(index)
})
let first = deck.get2BytesAtOffset(start + kTrainerFirstPokemonOffset)
if first < CommonIndexes.NumberOfTrainerPokemonData.value {
for i in 0 ..< kNumberOfTrainerPokemon {
self.pokemon.append(XGTrainerPokemon(index: (first + i)))
}
}
}
func save() {
let start = startOffset
let deck = XGFiles.common_rel.data!
deck.replaceWordAtOffset(start + kTrainerNameIDOffset, withBytes: UInt32(self.nameID))
deck.replaceWordAtOffset(start + kTrainerPreBattleTextIDOffset, withBytes: UInt32(self.preBattleTextID))
deck.replaceWordAtOffset(start + kTrainerVictoryTextIDOffset, withBytes: UInt32(self.victoryTextID))
deck.replaceWordAtOffset(start + kTrainerDefeatTextIDOffset, withBytes: UInt32(self.defeatTextID))
deck.replace2BytesAtOffset(start + kTrainerAIOffset, withBytes: self.AI)
deck.replaceByteAtOffset(start + kTrainerClassOffset , withByte: self.trainerClass.rawValue)
deck.replaceByteAtOffset(start + kTrainerClassModelOffset, withByte: self.trainerModel.rawValue)
deck.replaceBytesFromOffset(start + kTrainerFirstItemOffset, withShortStream: items.map({ (item) -> Int in
return item.index
}))
deck.save()
}
func purge(autoSave: Bool) {
for poke in self.pokemon {
poke.purge()
if autoSave {
poke.save()
}
}
}
var fullDescription : String {
let trainerLength = 30
let pokemonLength = 20
var string = ""
let className = self.trainerClass.name.unformattedString
string += (className + " " + name.string).spaceToLength(trainerLength) + "\n\n"
for p in pokemon {
if p.isSet {
string += ((p.isShadowPokemon ? "Shadow " : "") + p.species.name.string).spaceToLength(pokemonLength)
}
}
string += "\n"
for p in self.pokemon {
if p.isSet {
string += ("Level " + p.level.string).spaceToLength(pokemonLength)
}
}
string += "\n"
for p in pokemon {
if p.isSet {
if p.ability == 0xFF {
string += "Random".spaceToLength(pokemonLength)
} else {
string += (p.ability == 0 ? p.species.ability1 : p.species.ability2).spaceToLength(pokemonLength)
}
}
}
string += "\n"
for p in pokemon {
if p.isSet {
string += p.item.name.string.spaceToLength(pokemonLength)
}
}
string += "\n"
for i in 0 ..< 4 {
for p in pokemon {
if p.isSet {
string += p.moves[i].name.string.spaceToLength(pokemonLength)
}
}
string += "\n"
}
string += "\n"
return string
}
}
func allTrainers() -> [XGTrainer] {
var trainers = [XGTrainer]()
for i in 0 ..< kNumberOfTrainerEntries {
trainers.append(XGTrainer(index: i))
}
return trainers
}
extension XGTrainer: XGEnumerable {
var enumerableName: String {
return trainerClass.name.string + " " + name.string
}
var enumerableValue: String? {
return String(format: "%03d", index)
}
static var className: String {
return "Trainers"
}
static var allValues: [XGTrainer] {
var values = [XGTrainer]()
for i in 0 ..< CommonIndexes.NumberOfTrainers.value {
values.append(XGTrainer(index: i))
}
return values
}
}
| 1b46837383d217762b978e3d96b90c8a | 24.465021 | 164 | 0.706044 | false | false | false | false |
cloudant/swift-cloudant | refs/heads/master | Tests/SwiftCloudantTests/DeleteAttachmentTests.swift | apache-2.0 | 1 | //
// DeleteAttachmentTests.swift
// SwiftCloudant
//
// Created by Rhys Short on 17/05/2016.
// Copyright (c) 2016 IBM Corp.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
// except in compliance with the License. You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the
// License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
// either express or implied. See the License for the specific language governing permissions
// and limitations under the License.
//
import Foundation
import XCTest
@testable import SwiftCloudant
class DeleteAttachmentTests : XCTestCase {
static var allTests = {
return [
("testDeleteAttachment", testDeleteAttachment),
("testDeleteAttachmentHTTPOperationProperties",testDeleteAttachmentHTTPOperationProperties),]
}()
var dbName: String? = nil
var client: CouchDBClient? = nil
let docId: String = "PutAttachmentTests"
var revId: String?
override func setUp() {
super.setUp()
dbName = generateDBName()
client = CouchDBClient(url: URL(string: url)!, username: username, password: password)
createDatabase(databaseName: dbName!, client: client!)
let createDoc = PutDocumentOperation(id: docId,
body: createTestDocuments(count: 1).first!,
databaseName: dbName!){[weak self] (response, info, error) in
self?.revId = response?["rev"] as? String
}
let nsCreate = Operation(couchOperation: createDoc)
client?.add(operation: nsCreate)
nsCreate.waitUntilFinished()
let attachment = "This is my awesome essay attachment for my document"
let put = PutAttachmentOperation(name: "myAwesomeAttachment",
contentType: "text/plain",
data: attachment.data(using: String.Encoding.utf8, allowLossyConversion: false)!,
documentID: docId,
revision: revId!,
databaseName: dbName!
)
{[weak self] (response, info, error) in
XCTAssertNil(error)
XCTAssertNotNil(info)
if let info = info {
XCTAssert(info.statusCode / 100 == 2)
}
XCTAssertNotNil(response)
self?.revId = response?["rev"] as? String
}
let nsPut = Operation(couchOperation: put)
client?.add(operation: nsPut)
nsPut.waitUntilFinished()
}
override func tearDown() {
deleteDatabase(databaseName: dbName!, client: client!)
super.tearDown()
}
func testDeleteAttachment(){
let deleteExpectation = self.expectation(description: "Delete expectation")
let delete = DeleteAttachmentOperation(name: "myAwesomeAttachment", documentID: docId, revision: revId!, databaseName: dbName!)
{ (response, info, error) in
XCTAssertNil(error)
XCTAssertNotNil(info)
if let info = info {
XCTAssert(info.statusCode / 100 == 2)
}
XCTAssertNotNil(response)
deleteExpectation.fulfill()
}
client?.add(operation: delete)
self.waitForExpectations(timeout: 10.0, handler: nil)
let getExpectation = self.expectation(description: "Get deleted Attachment")
//make sure that the attachment has been deleted.
let get = ReadAttachmentOperation(name: "myAwesomeAttachment", documentID: docId, databaseName: dbName!){
(response, info, error) in
XCTAssertNotNil(error)
XCTAssertNotNil(info)
XCTAssertNotNil(response)
if let info = info {
XCTAssertEqual(404, info.statusCode)
}
getExpectation.fulfill()
}
client?.add(operation: get)
self.waitForExpectations(timeout: 10.0, handler: nil)
}
func testDeleteAttachmentHTTPOperationProperties(){
let delete = DeleteAttachmentOperation(name: "myAwesomeAttachment", documentID: docId, revision: revId!, databaseName: dbName!)
XCTAssertTrue(delete.validate())
XCTAssertEqual(["rev": revId!], delete.parameters)
XCTAssertEqual("/\(self.dbName!)/\(docId)/myAwesomeAttachment", delete.endpoint)
XCTAssertEqual("DELETE", delete.method)
}
}
| 9005a4ed51fdf36246c33e7bd3485e27 | 38.694215 | 135 | 0.600458 | false | true | false | false |
ShyHornet/SwiftAnyPic | refs/heads/master | SwiftAnyPic/PAPBaseTextCell.swift | cc0-1.0 | 5 | import UIKit
import FormatterKit
import CoreGraphics
import ParseUI
var timeFormatter: TTTTimeIntervalFormatter?
/*! Layout constants */
private let vertBorderSpacing: CGFloat = 8.0
private let vertElemSpacing: CGFloat = 0.0
private let horiBorderSpacing: CGFloat = 8.0
private let horiBorderSpacingBottom: CGFloat = 9.0
private let horiElemSpacing: CGFloat = 5.0
private let vertTextBorderSpacing: CGFloat = 10.0
private let avatarX: CGFloat = horiBorderSpacing
private let avatarY: CGFloat = vertBorderSpacing
private let avatarDim: CGFloat = 33.0
private let nameX: CGFloat = avatarX+avatarDim+horiElemSpacing
private let nameY: CGFloat = vertTextBorderSpacing
private let nameMaxWidth: CGFloat = 200.0
private let timeX: CGFloat = avatarX+avatarDim+horiElemSpacing
class PAPBaseTextCell: PFTableViewCell {
var horizontalTextSpace: Int = 0
var _delegate: PAPBaseTextCellDelegate?
/*!
Unfortunately, objective-c does not allow you to redefine the type of a property,
so we cannot set the type of the delegate here. Doing so would mean that the subclass
of would not be able to define new delegate methods (which we do in PAPActivityCell).
*/
// var delegate: PAPBaseTextCellDelegate? {
// get {
// return _delegate
// }
//
// set {
// _delegate = newValue
// }
// }
/*! The cell's views. These shouldn't be modified but need to be exposed for the subclass */
var mainView: UIView?
var nameButton: UIButton?
var avatarImageButton: UIButton?
var avatarImageView: PAPProfileImageView?
var contentLabel: UILabel?
var timeLabel: UILabel?
var separatorImage: UIImageView?
var hideSeparator: Bool = false // True if the separator shouldn't be shown
// MARK:- NSObject
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
// Initialization code
cellInsetWidth = 0.0
super.init(style: style, reuseIdentifier: reuseIdentifier)
if timeFormatter == nil {
timeFormatter = TTTTimeIntervalFormatter()
}
hideSeparator = false
self.clipsToBounds = true
horizontalTextSpace = Int(PAPBaseTextCell.horizontalTextSpaceForInsetWidth(cellInsetWidth))
self.opaque = true
self.selectionStyle = UITableViewCellSelectionStyle.None
self.accessoryType = UITableViewCellAccessoryType.None
self.backgroundColor = UIColor.clearColor()
mainView = UIView(frame: self.contentView.frame)
mainView!.backgroundColor = UIColor.whiteColor()
self.avatarImageView = PAPProfileImageView()
self.avatarImageView!.backgroundColor = UIColor.clearColor()
self.avatarImageView!.opaque = true
self.avatarImageView!.layer.cornerRadius = 16.0
self.avatarImageView!.layer.masksToBounds = true
mainView!.addSubview(self.avatarImageView!)
self.nameButton = UIButton(type: UIButtonType.Custom)
self.nameButton!.backgroundColor = UIColor.clearColor()
if reuseIdentifier == "ActivityCell" {
self.nameButton!.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
self.nameButton!.setTitleColor(UIColor(red: 114.0/255.0, green: 114.0/255.0, blue: 114.0/255.0, alpha: 1.0), forState: UIControlState.Highlighted)
} else {
self.nameButton!.setTitleColor(UIColor(red: 34.0/255.0, green: 34.0/255.0, blue: 34.0/255.0, alpha: 1.0), forState: UIControlState.Normal)
self.nameButton!.setTitleColor(UIColor(red: 114.0/255.0, green: 114.0/255.0, blue: 114.0/255.0, alpha: 1.0), forState: UIControlState.Highlighted)
}
self.nameButton!.titleLabel!.font = UIFont.boldSystemFontOfSize(13)
self.nameButton!.titleLabel!.lineBreakMode = NSLineBreakMode.ByTruncatingTail
self.nameButton!.addTarget(self, action: Selector("didTapUserButtonAction:"), forControlEvents: UIControlEvents.TouchUpInside)
mainView!.addSubview(self.nameButton!)
self.contentLabel = UILabel()
self.contentLabel!.font = UIFont.systemFontOfSize(13.0)
if reuseIdentifier == "ActivityCell" {
self.contentLabel!.textColor = UIColor.whiteColor()
} else {
self.contentLabel!.textColor = UIColor(red: 34.0/255.0, green: 34.0/255.0, blue: 34.0/255.0, alpha: 1.0)
}
self.contentLabel!.numberOfLines = 0
self.contentLabel!.lineBreakMode = NSLineBreakMode.ByWordWrapping
self.contentLabel!.backgroundColor = UIColor.clearColor()
mainView!.addSubview(self.contentLabel!)
self.timeLabel = UILabel()
self.timeLabel!.font = UIFont.systemFontOfSize(11)
self.timeLabel!.textColor = UIColor(red: 114.0/255.0, green: 114.0/255.0, blue: 114.0/255.0, alpha: 1.0)
self.timeLabel!.backgroundColor = UIColor.clearColor()
mainView!.addSubview(self.timeLabel!)
self.avatarImageButton = UIButton(type: UIButtonType.Custom)
self.avatarImageButton!.backgroundColor = UIColor.clearColor()
self.avatarImageButton!.addTarget(self, action: Selector("didTapUserButtonAction:"), forControlEvents: UIControlEvents.TouchUpInside)
mainView!.addSubview(self.avatarImageButton!)
self.separatorImage = UIImageView(image: UIImage(named: "SeparatorComments.png")!.resizableImageWithCapInsets(UIEdgeInsetsMake(0, 1, 0, 1)))
//[mainView addSubview:separatorImage];
self.contentView.addSubview(mainView!)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- UIView
override func layoutSubviews() {
super.layoutSubviews()
mainView!.frame = CGRectMake(cellInsetWidth, self.contentView.frame.origin.y, self.contentView.frame.size.width-2*cellInsetWidth, self.contentView.frame.size.height)
// Layout avatar image
self.avatarImageView!.frame = CGRectMake(avatarX, avatarY + 5.0, avatarDim, avatarDim)
self.avatarImageButton!.frame = CGRectMake(avatarX, avatarY + 5.0, avatarDim, avatarDim)
// Layout the name button
let nameSize: CGSize = self.nameButton!.titleLabel!.text!.boundingRectWithSize(CGSizeMake(nameMaxWidth, CGFloat.max),
options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin], // word wrap?
attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(13.0)],
context: nil).size
self.nameButton!.frame = CGRectMake(nameX, nameY + 6.0, nameSize.width, nameSize.height)
// Layout the content
let contentSize: CGSize = self.contentLabel!.text!.boundingRectWithSize(CGSizeMake(CGFloat(horizontalTextSpace), CGFloat.max),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: UIFont.systemFontOfSize(13.0)],
context: nil).size
self.contentLabel!.frame = CGRectMake(nameX, vertTextBorderSpacing + 6.0, contentSize.width, contentSize.height)
// Layout the timestamp label
let timeSize: CGSize = self.timeLabel!.text!.boundingRectWithSize(CGSizeMake(CGFloat(horizontalTextSpace), CGFloat.max),
options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin],
attributes: [NSFontAttributeName: UIFont.systemFontOfSize(11.0)],
context: nil).size
self.timeLabel!.frame = CGRectMake(timeX, contentLabel!.frame.origin.y + contentLabel!.frame.size.height + vertElemSpacing, timeSize.width, timeSize.height)
// Layour separator
self.separatorImage!.frame = CGRectMake(0, self.frame.size.height-1, self.frame.size.width-cellInsetWidth*2, 1)
self.separatorImage!.hidden = hideSeparator
}
// MARK:- Delegate methods
/* Inform delegate that a user image or name was tapped */
func didTapUserButtonAction(sender: AnyObject) {
if self.delegate != nil && self.delegate!.respondsToSelector(Selector("cell:didTapUserButton:")) {
self.delegate!.cell(self, didTapUserButton: self.user!)
}
}
// MARK:- PAPBaseTextCell
/* Static helper to get the height for a cell if it had the given name and content */
class func heightForCellWithName(name: String, contentString content: String) -> CGFloat {
return PAPBaseTextCell.heightForCellWithName(name, contentString: content, cellInsetWidth: 0)
}
/* Static helper to get the height for a cell if it had the given name, content and horizontal inset */
class func heightForCellWithName(name: String, contentString content: String, cellInsetWidth cellInset: CGFloat) -> CGFloat {
// FIXME: Why nameSize is used before as the argument at the same time???? let nameSize: CGSize = name.boundingRectWithSize(nameSize,
let nameSize: CGSize = name.boundingRectWithSize(CGSizeMake(nameMaxWidth, CGFloat.max),
options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin],
attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(13.0)],
context: nil).size
let paddedString: String = PAPBaseTextCell.padString(content, withFont: UIFont.systemFontOfSize(13), toWidth: nameSize.width)
let horizontalTextSpace: CGFloat = PAPBaseTextCell.horizontalTextSpaceForInsetWidth(cellInset)
let contentSize: CGSize = paddedString.boundingRectWithSize(CGSizeMake(horizontalTextSpace, CGFloat.max),
options: NSStringDrawingOptions.UsesLineFragmentOrigin, // word wrap?
attributes: [NSFontAttributeName: UIFont.systemFontOfSize(13.0)],
context: nil).size
let singleLineHeight: CGFloat = "test".boundingRectWithSize(CGSizeMake(CGFloat.max, CGFloat.max),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: UIFont.systemFontOfSize(13.0)],
context: nil).size.height
// Calculate the added height necessary for multiline text. Ensure value is not below 0.
let multilineHeightAddition: CGFloat = (contentSize.height - singleLineHeight) > 0 ? (contentSize.height - singleLineHeight) : 0
return horiBorderSpacing + avatarDim + horiBorderSpacingBottom + multilineHeightAddition
}
/* Static helper to obtain the horizontal space left for name and content after taking the inset and image in consideration */
class func horizontalTextSpaceForInsetWidth(insetWidth: CGFloat) -> CGFloat {
return (320-(insetWidth*2)) - (horiBorderSpacing+avatarDim+horiElemSpacing+horiBorderSpacing)
}
/* Static helper to pad a string with spaces to a given beginning offset */
class func padString(string: String, withFont font: UIFont, toWidth width: CGFloat) -> String {
// Find number of spaces to pad
var paddedString = ""
while (true) {
paddedString += " "
let resultSize: CGSize = paddedString.boundingRectWithSize(CGSizeMake(CGFloat.max, CGFloat.max),
options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin],
attributes: [NSFontAttributeName: font],
context: nil).size
if resultSize.width >= width {
break
}
}
// Add final spaces to be ready for first word
paddedString += " \(string)"
return paddedString
}
/*! The user represented in the cell */
var user: PFUser? {
didSet {
// Set name button properties and avatar image
if PAPUtility.userHasProfilePictures(self.user!) {
self.avatarImageView!.setFile(self.user!.objectForKey(kPAPUserProfilePicSmallKey) as? PFFile)
} else {
self.avatarImageView!.setImage(PAPUtility.defaultProfilePicture()!)
}
self.nameButton!.setTitle(self.user!.objectForKey(kPAPUserDisplayNameKey) as? String, forState: UIControlState.Normal)
self.nameButton!.setTitle(self.user!.objectForKey(kPAPUserDisplayNameKey) as? String, forState:UIControlState.Highlighted)
// If user is set after the contentText, we reset the content to include padding
if self.contentLabel!.text != nil {
self.setContentText(self.contentLabel!.text!)
}
self.setNeedsDisplay()
}
}
func setContentText(contentString: String) {
// If we have a user we pad the content with spaces to make room for the name
if self.user != nil {
let nameSize: CGSize = self.nameButton!.titleLabel!.text!.boundingRectWithSize(CGSizeMake(nameMaxWidth, CGFloat.max),
options: [NSStringDrawingOptions.TruncatesLastVisibleLine, NSStringDrawingOptions.UsesLineFragmentOrigin],
attributes: [NSFontAttributeName: UIFont.boldSystemFontOfSize(13.0)],
context: nil).size
let paddedString: String = PAPBaseTextCell.padString(contentString, withFont: UIFont.systemFontOfSize(13), toWidth: nameSize.width)
self.contentLabel!.text = paddedString
} else { // Otherwise we ignore the padding and we'll add it after we set the user
self.contentLabel!.text = contentString
}
self.setNeedsDisplay()
}
func setDate(date: NSDate) {
// Set the label with a human readable time
self.timeLabel!.text = timeFormatter!.stringForTimeIntervalFromDate(NSDate(), toDate: date)
self.setNeedsDisplay()
}
/*! The horizontal inset of the cell */
var cellInsetWidth: CGFloat {
didSet {
// Change the mainView's frame to be insetted by insetWidth and update the content text space
mainView!.frame = CGRectMake(cellInsetWidth, mainView!.frame.origin.y, mainView!.frame.size.width-2*cellInsetWidth, mainView!.frame.size.height)
horizontalTextSpace = Int(PAPBaseTextCell.horizontalTextSpaceForInsetWidth(cellInsetWidth))
self.setNeedsDisplay()
}
}
/* Since we remove the compile-time check for the delegate conforming to the protocol
in order to allow inheritance, we add run-time checks. */
var delegate: PAPBaseTextCellDelegate? {
get {
return _delegate
}
set {
// FIXME: any other way to check?
if _delegate?.hash != newValue!.hash {
_delegate = newValue
}
}
}
func hideSeparator(hide: Bool) {
hideSeparator = hide
}
}
@objc protocol PAPBaseTextCellDelegate: NSObjectProtocol {
/*!
Sent to the delegate when a user button is tapped
@param aUser the PFUser of the user that was tapped
*/
func cell(cellView: PAPBaseTextCell, didTapUserButton aUser: PFUser)
} | 35bd573b5b119abf31686a7b8e997f64 | 49.447205 | 176 | 0.638737 | false | false | false | false |
jalehman/YelpClone | refs/heads/master | YelpClone/SearchResultViewModel.swift | gpl-2.0 | 1 | //
// SearchResultViewModel.swift
// YelpClone
//
// Created by Josh Lehman on 2/12/15.
// Copyright (c) 2015 Josh Lehman. All rights reserved.
//
import Foundation
class SearchResultViewModel: NSObject {
// MARK: Properties
let name: String
let imageURL: NSURL?
let address: String
let rating: Float
let reviewCount: Int
let distance: Double
let ratingImageURL: NSURL?
let categories: [String]
let result: SearchResult
private let services: ViewModelServices
init(services: ViewModelServices, result: SearchResult) {
self.services = services
self.name = result.name
self.imageURL = result.imageURL
self.address = result.address
self.rating = result.rating
self.reviewCount = result.reviewCount
self.distance = result.distance
self.ratingImageURL = result.ratingImageURL
self.categories = result.categories
self.result = result
}
} | e4f42877f942e81d406ede6b96604fbf | 24.384615 | 61 | 0.662285 | false | false | false | false |
SusanDoggie/Doggie | refs/heads/main | Sources/DoggieGraphics/ApplePlatform/Graphic/CGColor.swift | mit | 1 | //
// CGColor.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.
//
#if canImport(CoreGraphics)
extension Color {
public var cgColor: CGColor? {
return colorSpace.cgColorSpace.flatMap { CGColor(colorSpace: $0, components: color.map { CGFloat($0) } + [CGFloat(opacity)]) }
}
}
protocol CGColorConvertibleProtocol {
var cgColor: CGColor? { get }
}
extension Color: CGColorConvertibleProtocol {
}
extension AnyColor {
public init?(cgColor: CGColor) {
guard let colorSpace = cgColor.colorSpace.flatMap(AnyColorSpace.init) else { return nil }
guard let components = cgColor.components, components.count == colorSpace.numberOfComponents + 1 else { return nil }
guard let opacity = components.last else { return nil }
self.init(colorSpace: colorSpace, components: components.dropLast().lazy.map(Double.init), opacity: Double(opacity))
}
}
extension AnyColor {
public var cgColor: CGColor? {
if let base = self.base as? CGColorConvertibleProtocol {
return base.cgColor
}
return nil
}
}
#if canImport(UIKit)
extension CGColor {
public class var clear: CGColor { return UIColor.clear.cgColor }
public class var black: CGColor { return UIColor.black.cgColor }
public class var blue: CGColor { return UIColor.blue.cgColor }
public class var brown: CGColor { return UIColor.brown.cgColor }
public class var cyan: CGColor { return UIColor.cyan.cgColor }
public class var darkGray: CGColor { return UIColor.darkGray.cgColor }
public class var gray: CGColor { return UIColor.gray.cgColor }
public class var green: CGColor { return UIColor.green.cgColor }
public class var lightGray: CGColor { return UIColor.lightGray.cgColor }
public class var magenta: CGColor { return UIColor.magenta.cgColor }
public class var orange: CGColor { return UIColor.orange.cgColor }
public class var purple: CGColor { return UIColor.purple.cgColor }
public class var red: CGColor { return UIColor.red.cgColor }
public class var white: CGColor { return UIColor.white.cgColor }
public class var yellow: CGColor { return UIColor.yellow.cgColor }
}
#elseif canImport(AppKit)
extension CGColor {
public class var clear: CGColor { return NSColor.clear.cgColor }
public class var black: CGColor { return NSColor.black.cgColor }
public class var blue: CGColor { return NSColor.blue.cgColor }
public class var brown: CGColor { return NSColor.brown.cgColor }
public class var cyan: CGColor { return NSColor.cyan.cgColor }
public class var darkGray: CGColor { return NSColor.darkGray.cgColor }
public class var gray: CGColor { return NSColor.gray.cgColor }
public class var green: CGColor { return NSColor.green.cgColor }
public class var lightGray: CGColor { return NSColor.lightGray.cgColor }
public class var magenta: CGColor { return NSColor.magenta.cgColor }
public class var orange: CGColor { return NSColor.orange.cgColor }
public class var purple: CGColor { return NSColor.purple.cgColor }
public class var red: CGColor { return NSColor.red.cgColor }
public class var white: CGColor { return NSColor.white.cgColor }
public class var yellow: CGColor { return NSColor.yellow.cgColor }
}
#endif
#endif
| 01ed37460563bd768e50add131a2152b | 31.865248 | 134 | 0.697238 | false | false | false | false |
GEOSwift/GEOSwift | refs/heads/issue212 | GEOSwift/Codable/CodableGeometry.swift | mit | 2 | protocol CodableGeometry: Codable {
associatedtype Coordinates: Codable
static var geoJSONType: GeoJSONType { get }
var coordinates: Coordinates { get }
init(coordinates: Coordinates) throws
}
enum CodableGeometryCodingKeys: CodingKey {
case type
case coordinates
}
extension CodableGeometry {
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodableGeometryCodingKeys.self)
try container.geoJSONType(forKey: .type, expectedType: Self.geoJSONType)
try self.init(coordinates: container.decode(Coordinates.self, forKey: .coordinates))
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodableGeometryCodingKeys.self)
try container.encode(Self.geoJSONType, forKey: .type)
try container.encode(coordinates, forKey: .coordinates)
}
}
extension KeyedDecodingContainer {
@discardableResult
func geoJSONType(forKey key: K, expectedType: GeoJSONType? = nil) throws -> GeoJSONType {
let type: GeoJSONType
do {
type = try decode(GeoJSONType.self, forKey: key)
} catch {
throw GEOSwiftError.invalidGeoJSONType
}
guard expectedType == nil || expectedType == type else {
throw GEOSwiftError.mismatchedGeoJSONType
}
return type
}
}
| 83c90e9793ca36958d07b791cb698c84 | 33.121951 | 93 | 0.689778 | false | false | false | false |
ShamylZakariya/Squizit | refs/heads/master | Squizit/Util/CancelableAction.swift | mit | 1 | //
// CancelableAction.swift
// Squizit
//
// Created by Shamyl Zakariya on 9/22/14.
// Copyright (c) 2014 Shamyl Zakariya. All rights reserved.
//
import UIKit
class CancelableAction<T> {
typealias Done = ( result:T )->()
typealias Canceled = ()->Bool
typealias Action = ( done:Done, canceled:Canceled )->()
private var _canceled:Bool = false
private var _result:T?
init( action:Action, done:Done? ) {
self.done = done
action(
done: { [weak self] result in
if let sself = self {
synchronized(sself) {
if !sself._canceled {
sself._result = result
sself.done?( result:result )
}
}
}
},
canceled: { [weak self] in
if let sself = self {
return sself._canceled
}
return true
})
}
/*
Create a CancelableAction without a done block
When this action is complete, result will be assigned.
If a done block is assigned later, when the action completes that done block will be invoked.
If when the done block is assigned the action has already completed, the done block will be immediately invoked.
*/
convenience init( action:Action ) {
self.init( action: action, done: nil )
}
/*
Assign done block
If the action has already completed ( result != nil ) the assigned done block will be immediately run
*/
var done:Done? {
didSet {
if let result = self.result {
if let done = self.done {
done( result: result )
}
}
}
}
/*
If the action has completed execution the result is available here
*/
var result:T? {
return _result
}
/*
Cancel this action's execution
This means the done block will never be invoked, and result will never be assigned.
*/
func cancel(){
synchronized(self) {
self._canceled = true
}
}
var canceled:Bool { return _canceled }
}
| b6264a28f050de4e341984d52dda3620 | 20.011628 | 114 | 0.652463 | false | false | false | false |
master-nevi/UPnAtom | refs/heads/master | Source/SSDP/Explorer/SSDPExplorer.swift | mit | 1 | //
// SSDPExplorer.swift
//
// Copyright (c) 2015 David Robles
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import CocoaAsyncSocket
import AFNetworking
protocol SSDPExplorerDelegate: class {
func ssdpExplorer(explorer: SSDPExplorer, didMakeDiscovery discovery: SSDPDiscovery)
// Removed discoveries will have an invalid desciption URL
func ssdpExplorer(explorer: SSDPExplorer, didRemoveDiscovery discovery: SSDPDiscovery)
/// Assume explorer has stopped after a failure.
func ssdpExplorer(explorer: SSDPExplorer, didFailWithError error: NSError)
}
class SSDPExplorer {
enum SSDPMessageType {
case SearchResponse
case AvailableNotification
case UpdateNotification
case UnavailableNotification
}
weak var delegate: SSDPExplorerDelegate?
// private
private static let _multicastGroupAddress = "239.255.255.250"
private static let _multicastUDPPort: UInt16 = 1900
private var _multicastSocket: GCDAsyncUdpSocket? // TODO: Should ideally be a constant, see Github issue #10
private var _unicastSocket: GCDAsyncUdpSocket? // TODO: Should ideally be a constant, see Github issue #10
private var _types = [SSDPType]() // TODO: Should ideally be a Set<SSDPType>, see Github issue #13
func startExploring(forTypes types: [SSDPType], onInterface interface: String = "en0") -> EmptyResult {
assert(_multicastSocket == nil, "Socket is already open, stop it first!")
// create sockets
guard let multicastSocket: GCDAsyncUdpSocket! = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue()),
unicastSocket: GCDAsyncUdpSocket! = GCDAsyncUdpSocket(delegate: self, delegateQueue: dispatch_get_main_queue()) else {
return .Failure(createError("Socket could not be created"))
}
_multicastSocket = multicastSocket
_unicastSocket = unicastSocket
multicastSocket.setIPv6Enabled(false)
unicastSocket.setIPv6Enabled(false)
// Configure unicast socket
// Bind to address on the specified interface to a random port to receive unicast datagrams
do {
try unicastSocket.bindToPort(0, interface: interface)
} catch {
stopExploring()
return .Failure(createError("Could not bind socket to port"))
}
do {
try unicastSocket.beginReceiving()
} catch {
stopExploring()
return .Failure(createError("Could not begin receiving error"))
}
// Configure multicast socket
// Bind to port without defining the interface to bind to the address INADDR_ANY (0.0.0.0). This prevents any address filtering which allows datagrams sent to the multicast group to be receives
do {
try multicastSocket.bindToPort(SSDPExplorer._multicastUDPPort)
} catch {
stopExploring()
return .Failure(createError("Could not bind socket to multicast port"))
}
// Join multicast group to express interest to router of receiving multicast datagrams
do {
try multicastSocket.joinMulticastGroup(SSDPExplorer._multicastGroupAddress)
} catch {
stopExploring()
return .Failure(createError("Could not join multicast group"))
}
do {
try multicastSocket.beginReceiving()
} catch {
stopExploring()
return .Failure(createError("Could not begin receiving error"))
}
_types = types
for type in types {
if let data = searchRequestData(forType: type) {
// println(">>>> SENDING SEARCH REQUEST\n\(NSString(data: data, encoding: NSUTF8StringEncoding))")
unicastSocket.sendData(data, toHost: SSDPExplorer._multicastGroupAddress, port: SSDPExplorer._multicastUDPPort, withTimeout: -1, tag: type.hashValue)
}
}
return .Success
}
func stopExploring() {
_multicastSocket?.close()
_multicastSocket = nil
_unicastSocket?.close()
_unicastSocket = nil
_types = []
}
private func searchRequestData(forType type: SSDPType) -> NSData? {
var requestBody = [
"M-SEARCH * HTTP/1.1",
"HOST: \(SSDPExplorer._multicastGroupAddress):\(SSDPExplorer._multicastUDPPort)",
"MAN: \"ssdp:discover\"",
"ST: \(type.rawValue)",
"MX: 3"]
if let userAgent = AFHTTPRequestSerializer().valueForHTTPHeaderField("User-Agent") {
requestBody += ["USER-AGENT: \(userAgent)\r\n\r\n\r\n"]
}
let requestBodyString = requestBody.joinWithSeparator("\r\n")
return requestBodyString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
private func notifyDelegate(ofFailure error: NSError) {
dispatch_async(dispatch_get_main_queue(), { [unowned self] () -> Void in
self.delegate?.ssdpExplorer(self, didFailWithError: error)
})
}
private func notifyDelegate(discovery: SSDPDiscovery, added: Bool) {
dispatch_async(dispatch_get_main_queue(), { [unowned self] () -> Void in
added ? self.delegate?.ssdpExplorer(self, didMakeDiscovery: discovery) : self.delegate?.ssdpExplorer(self, didRemoveDiscovery: discovery)
})
}
private func handleSSDPMessage(messageType: SSDPMessageType, headers: [String: String]) {
if let usnRawValue = headers["usn"],
usn = UniqueServiceName(rawValue: usnRawValue),
locationString = headers["location"],
locationURL = NSURL(string: locationString),
/// NT = Notification Type - SSDP discovered from device advertisements
/// ST = Search Target - SSDP discovered as a result of using M-SEARCH requests
ssdpTypeRawValue = (headers["st"] != nil ? headers["st"] : headers["nt"]),
ssdpType = SSDPType(rawValue: ssdpTypeRawValue) where _types.indexOf(ssdpType) != nil {
LogVerbose("SSDP response headers: \(headers)")
let discovery = SSDPDiscovery(usn: usn, descriptionURL: locationURL, type: ssdpType)
switch messageType {
case .SearchResponse, .AvailableNotification, .UpdateNotification:
notifyDelegate(discovery, added: true)
case .UnavailableNotification:
notifyDelegate(discovery, added: false)
}
}
}
}
extension SSDPExplorer: GCDAsyncUdpSocketDelegate {
@objc func udpSocket(sock: GCDAsyncUdpSocket!, didNotSendDataWithTag tag: Int, dueToError error: NSError!) {
stopExploring()
// this case should always have an error
notifyDelegate(ofFailure: error ?? createError("Did not send SSDP message."))
}
@objc func udpSocketDidClose(sock: GCDAsyncUdpSocket!, withError error: NSError!) {
if let error = error {
notifyDelegate(ofFailure: error)
}
}
@objc func udpSocket(sock: GCDAsyncUdpSocket!, didReceiveData data: NSData!, fromAddress address: NSData!, withFilterContext filterContext: AnyObject!) {
if let message = NSString(data: data, encoding: NSUTF8StringEncoding) as? String {
// println({ () -> String in
// let socketType = (sock === self._unicastSocket) ? "UNICAST" : "MULTICAST"
// return "<<<< RECEIVED ON \(socketType) SOCKET\n\(message)"
// }())
var httpMethodLine: String?
var headers = [String: String]()
let headersRegularExpression = try? NSRegularExpression(pattern: "^([a-z0-9-]+): *(.+)$", options: [.CaseInsensitive, .AnchorsMatchLines])
message.enumerateLines({ (line, stop) -> () in
if httpMethodLine == nil {
httpMethodLine = line
} else {
headersRegularExpression?.enumerateMatchesInString(line, options: [], range: NSRange(location: 0, length: line.characters.count), usingBlock: { (resultOptional: NSTextCheckingResult?, flags: NSMatchingFlags, stop: UnsafeMutablePointer<ObjCBool>) -> Void in
if let result = resultOptional where result.numberOfRanges == 3 {
let key = (line as NSString).substringWithRange(result.rangeAtIndex(1)).lowercaseString
let value = (line as NSString).substringWithRange(result.rangeAtIndex(2))
headers[key] = value
}
})
}
})
if let httpMethodLine = httpMethodLine {
let nts = headers["nts"]
switch (httpMethodLine, nts) {
case ("HTTP/1.1 200 OK", _):
handleSSDPMessage(.SearchResponse, headers: headers)
case ("NOTIFY * HTTP/1.1", .Some(let notificationType)) where notificationType == "ssdp:alive":
handleSSDPMessage(.AvailableNotification, headers: headers)
case ("NOTIFY * HTTP/1.1", .Some(let notificationType)) where notificationType == "ssdp:update":
handleSSDPMessage(.UpdateNotification, headers: headers)
case ("NOTIFY * HTTP/1.1", .Some(let notificationType)) where notificationType == "ssdp:byebye":
headers["location"] = headers["host"] // byebye messages don't have a location
handleSSDPMessage(.UnavailableNotification, headers: headers)
default:
return
}
}
}
}
}
| d283e1bdec259e6b050b6e3574cccc1a | 46.663755 | 276 | 0.630142 | false | false | false | false |
FoxerLee/iOS_sitp | refs/heads/master | tiankeng/ConfirmTableViewController.swift | mit | 1 | //
// ConfirmTableViewController.swift
// tiankeng
//
// Created by 李源 on 2017/4/3.
// Copyright © 2017年 foxerlee. All rights reserved.
//
import UIKit
//import LeanCloud
import AVOSCloud
import os.log
class ConfirmTableViewController: UITableViewController {
@IBOutlet weak var confirmButton: UIBarButtonItem!
var message: Message!
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
//货物详情的cell
if (indexPath.section == 0) {
let cell = tableView.dequeueReusableCell(withIdentifier: "PackageConfirmTableViewCell", for: indexPath) as! PackageConfirmTableViewCell
cell.packageLabel.text = message?.package
cell.describeLabel.text = message?.describe
cell.timeLabel.text = message?.time
cell.photoImageView.image = message?.photo
return cell
}
//寄货人的cell
else if (indexPath.section == 1) {
let cell = tableView.dequeueReusableCell(withIdentifier: "FounderConfirmTableViewCell", for: indexPath) as! FounderConfirmTableViewCell
let query = AVQuery(className: "_User")
query.whereKey("mobilePhoneNumber", equalTo: message.founderPhone)
var object = query.findObjects()
let founder = object?.popLast() as! AVObject
cell.founderNameLabel.text = founder.object(forKey: "username") as? String
cell.founderPhoneLabel.text = founder.object(forKey: "mobilePhoneNumber") as? String
cell.founderAddressLabel.text = founder.object(forKey: "address") as? String
return cell
}
//收货人的cell
else {
let cell = tableView.dequeueReusableCell(withIdentifier: "ReceiverConfirmTableViewCell", for: indexPath) as! ReceiverConfirmTableViewCell
cell.ReceiverNameLabel.text = message?.name
cell.ReceiverPhoneLabel.text = message?.phone
cell.ReceiverAddressLabel.text = message?.address
return cell
}
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
if (section == 0) {
return "货物信息"
}
else if (section == 1) {
return "寄货人信息"
}
else {
return "收货人信息"
}
}
}
| b592c32ebf5e5f15f8e962aed9d0043b | 30.939394 | 149 | 0.611954 | false | false | false | false |
LGKKTeam/FlagKits | refs/heads/master | Example/FlagKits/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// FlagKits
//
// Created by [email protected] on 05/30/2017.
// Copyright (c) 2017 [email protected]. All rights reserved.
//
import UIKit
import IQKeyboardManagerSwift
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
let keyboardManager = IQKeyboardManager.sharedManager()
keyboardManager.enable = true
keyboardManager.toolbarDoneBarButtonItemText = "Dismiss"
keyboardManager.toolbarTintColor = UIColor.blue
keyboardManager.shouldResignOnTouchOutside = true
keyboardManager.shouldPlayInputClicks = false
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:.
}
}
| 92ba3ce38999bb3363cef443a0ad8d72 | 45.963636 | 285 | 0.749516 | false | false | false | false |
inquisitiveSoft/UIView-ConstraintAdditions | refs/heads/Swift | Constraint Additions Test/ViewController.swift | mit | 1 | //
// ViewController.swift
// Constraint Additions Test
//
// Created by Harry Jordan on 20/07/2014.
// Released under the MIT license: http://opensource.org/licenses/mit-license.php
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
view.backgroundColor = UIColor.whiteColor()
let blueView = UIView(frame: CGRect(x: 40.0, y: 40.0, width: 100.0, height: 100.0))
blueView.setTranslatesAutoresizingMaskIntoConstraints(false)
blueView.backgroundColor = UIColor(red: 0.3, green: 0.3, blue: 0.6, alpha: 1.0)
view.addSubview(blueView)
var constraints = blueView.fillView(view)
if let leftConstraint = constraints[NSLayoutAttribute.Leading] {
println(leftConstraint)
leftConstraint.constant = 40.0
}
let orangeView = UIView(frame: CGRect(x: 20.0, y: 20.0, width: 200.0, height: 200.0))
orangeView.setTranslatesAutoresizingMaskIntoConstraints(false)
orangeView.backgroundColor = UIColor.orangeColor()
blueView.addSubview(orangeView)
constraints = blueView.addConstraints(
views: ["orange" : orangeView],
horizontalFormat: "|-[orange]-|",
verticalFormat:"|-[orange]-|"
)
let greenView = UIView(frame: CGRect(x: 20.0, y: 20.0, width: 200.0, height: 200.0))
greenView.setTranslatesAutoresizingMaskIntoConstraints(false)
greenView.backgroundColor = UIColor.greenColor()
blueView.addSubview(greenView)
greenView.addConstraints(views: ["greenView" : greenView], horizontalFormat:"[greenView(100)]", verticalFormat:"[greenView(100)]")
constraints = view.centerView(greenView, relativeToView: blueView, xAxis: true, yAxis: true)
}
}
| 908fe72e1958c495f696668b23aaaf60 | 31.351852 | 132 | 0.729823 | false | false | false | false |
wikimedia/wikipedia-ios | refs/heads/main | WMF Framework/Remote Notifications/RemoteNotificationsController.swift | mit | 1 | import CocoaLumberjackSwift
import Foundation
public enum RemoteNotificationsControllerError: LocalizedError {
case databaseUnavailable
case attemptingToRefreshBeforeDeadline
case failurePullingAppLanguage
public var errorDescription: String? {
return CommonStrings.genericErrorDescription
}
}
@objc public final class RemoteNotificationsController: NSObject {
private let apiController: RemoteNotificationsAPIController
private let refreshDeadlineController = RemoteNotificationsRefreshDeadlineController()
private let languageLinkController: MWKLanguageLinkController
private let authManager: WMFAuthenticationManager
private var _modelController: RemoteNotificationsModelController?
private var modelController: RemoteNotificationsModelController? {
get {
guard let modelController = _modelController else {
DDLogError("Missing RemoteNotificationsModelController. Confirm Core Data stack was successfully set up.")
return nil
}
return modelController
}
set {
_modelController = newValue
}
}
private var _operationsController: RemoteNotificationsOperationsController?
private var operationsController: RemoteNotificationsOperationsController? {
get {
guard let operationsController = _operationsController else {
DDLogError("Missing RemoteNotificationsOperationsController. Confirm Core Data stack was successfully set up in RemoteNotificationsModelController.")
return nil
}
return operationsController
}
set {
_operationsController = newValue
}
}
public var isLoadingNotifications: Bool {
return operationsController?.isLoadingNotifications ?? false
}
public var areFiltersEnabled: Bool {
return filterState.readStatus != .all || filterState.offProjects.count != 0 || filterState.offTypes.count != 0
}
public static let didUpdateFilterStateNotification = NSNotification.Name(rawValue: "RemoteNotificationsControllerDidUpdateFilterState")
public let configuration: Configuration
@objc public required init(session: Session, configuration: Configuration, languageLinkController: MWKLanguageLinkController, authManager: WMFAuthenticationManager) {
self.apiController = RemoteNotificationsAPIController(session: session, configuration: configuration)
self.configuration = configuration
self.authManager = authManager
self.languageLinkController = languageLinkController
super.init()
do {
modelController = try RemoteNotificationsModelController(containerURL: FileManager.default.wmf_containerURL())
} catch let error {
DDLogError("Failed to initialize RemoteNotificationsModelController: \(error)")
modelController = nil
}
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(authManagerDidLogIn), name:WMFAuthenticationManager.didLogInNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(authManagerDidLogOut), name: WMFAuthenticationManager.didLogOutNotification, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(modelControllerDidLoadPersistentStores(_:)), name: RemoteNotificationsModelController.didLoadPersistentStoresNotification, object: nil)
}
// MARK: NSNotification Listeners
@objc private func modelControllerDidLoadPersistentStores(_ note: Notification) {
guard let modelController = modelController else {
return
}
if let object = note.object, let error = object as? Error {
DDLogError("RemoteNotificationsModelController failed to load persistent stores with error \(error); not instantiating RemoteNotificationsOperationsController")
return
}
operationsController = RemoteNotificationsOperationsController(languageLinkController: languageLinkController, authManager: authManager, apiController: apiController, modelController: modelController)
populateFilterStateFromPersistence()
}
@objc private func applicationDidBecomeActive() {
loadNotifications(force: false)
}
@objc private func authManagerDidLogOut() {
do {
filterState = RemoteNotificationsFilterState(readStatus: .all, offTypes: [], offProjects: [])
allInboxProjects = []
try modelController?.resetDatabaseAndSharedCache()
} catch let error {
DDLogError("Error resetting notifications database on logout: \(error)")
}
}
@objc private func authManagerDidLogIn() {
loadNotifications(force: true)
}
// MARK: Public
/// Fetches notifications from the server and saves them into the local database. Updates local database on a backgroundContext.
/// - Parameters:
/// - force: Flag to force an API call, otherwise this will exit early if it's been less than 30 seconds since the last load attempt.
/// - completion: Completion block called once refresh attempt is complete.
public func loadNotifications(force: Bool, completion: ((Result<Void, Error>) -> Void)? = nil) {
guard let operationsController = operationsController else {
completion?(.failure(RemoteNotificationsControllerError.databaseUnavailable))
return
}
guard authManager.isLoggedIn else {
completion?(.failure(RequestError.unauthenticated))
return
}
if !force && !refreshDeadlineController.shouldRefresh {
completion?(.failure(RemoteNotificationsControllerError.attemptingToRefreshBeforeDeadline))
return
}
operationsController.loadNotifications { [weak self] result in
guard let self = self else {
return
}
switch result {
case .success:
do {
try self.updateAllInboxProjects()
completion?(.success(()))
} catch let error {
completion?(.failure(error))
}
case .failure(let error):
completion?(.failure(error))
}
}
refreshDeadlineController.reset()
}
/// Triggers fetching notifications from the server and saving them into the local database with no completion handler. Used as a bridge for Objective-C use as the `Result` type is unavailable there.
/// - Parameter force: Flag to force an API call, otherwise this will exit early if it's been less than 30 seconds since the last load attempt.
@objc public func triggerLoadNotifications(force: Bool) {
loadNotifications(force: force)
}
/// Marks notifications as read or unread in the local database and on the server. Errors are not returned. Updates local database on a backgroundContext.
/// - Parameters:
/// - identifierGroups: Set of IdentifierGroup objects to identify the correct notification.
/// - shouldMarkRead: Boolean for marking as read or unread.
public func markAsReadOrUnread(identifierGroups: Set<RemoteNotification.IdentifierGroup>, shouldMarkRead: Bool, completion: ((Result<Void, Error>) -> Void)? = nil) {
guard let operationsController = operationsController else {
completion?(.failure(RemoteNotificationsControllerError.databaseUnavailable))
return
}
guard authManager.isLoggedIn else {
completion?(.failure(RequestError.unauthenticated))
return
}
operationsController.markAsReadOrUnread(identifierGroups: identifierGroups, shouldMarkRead: shouldMarkRead, languageLinkController: languageLinkController, completion: completion)
}
/// Asks server to mark all notifications as read for projects that contain local unread notifications. Errors are not returned. Updates local database on a backgroundContext.
public func markAllAsRead(completion: ((Result<Void, Error>) -> Void)? = nil) {
guard let operationsController = operationsController else {
completion?(.failure(RemoteNotificationsControllerError.databaseUnavailable))
return
}
guard authManager.isLoggedIn else {
completion?(.failure(RequestError.unauthenticated))
return
}
operationsController.markAllAsRead(languageLinkController: languageLinkController, completion: completion)
}
/// Asks server to mark all notifications as seen for the primary app language
public func markAllAsSeen(completion: @escaping ((Result<Void, Error>) -> Void)) {
guard authManager.isLoggedIn else {
completion(.failure(RequestError.unauthenticated))
return
}
guard let appLanguage = languageLinkController.appLanguage else {
completion(.failure(RemoteNotificationsControllerError.failurePullingAppLanguage))
return
}
let appLanguageProject = WikimediaProject.wikipedia(appLanguage.languageCode, appLanguage.localizedName, appLanguage.languageVariantCode)
apiController.markAllAsSeen(project: appLanguageProject, completion: completion)
}
/// Passthrough method to listen for NSManagedObjectContextObjectsDidChange notifications on the viewContext, in order to encapsulate viewContext within the WMF Framework.
/// - Parameters:
/// - observer: NSNotification observer
/// - selector: Selector to call on the observer once the NSNotification fires
public func addObserverForViewContextChanges(observer: AnyObject, selector:
Selector) {
guard let viewContext = modelController?.viewContext else {
return
}
NotificationCenter.default.addObserver(observer, selector: selector, name: Notification.Name.NSManagedObjectContextObjectsDidChange, object: viewContext)
}
/// Fetches notifications from the local database. Uses the viewContext and must be called from the main thread
/// - Parameters:
/// - fetchLimit: Number of notifications to fetch. Defaults to 50.
/// - fetchOffset: Offset for fetching notifications. Use when fetching later pages of data
/// - Returns: Array of RemoteNotifications
public func fetchNotifications(fetchLimit: Int = 50, fetchOffset: Int = 0, completion: @escaping (Result<[RemoteNotification], Error>) -> Void) {
guard let modelController = modelController else {
return completion(.failure(RemoteNotificationsControllerError.databaseUnavailable))
}
let fetchFromDatabase: () -> Void = { [weak self] in
guard let self = self else {
return
}
let predicate = self.predicateForFilterSavedState(self.filterState)
do {
let notifications = try modelController.fetchNotifications(fetchLimit: fetchLimit, fetchOffset: fetchOffset, predicate: predicate)
completion(.success(notifications))
} catch let error {
completion(.failure(error))
}
}
guard !isFullyImported else {
fetchFromDatabase()
return
}
loadNotifications(force: true) { result in
switch result {
case .success:
fetchFromDatabase()
case .failure(let error):
completion(.failure(error))
}
}
}
/// Fetches a count of unread notifications from the local database. Uses the viewContext and must be called from the main thread
@objc public func numberOfUnreadNotifications() throws -> NSNumber {
guard let modelController = modelController else {
throw RemoteNotificationsControllerError.databaseUnavailable
}
let count = try modelController.numberOfUnreadNotifications()
return NSNumber.init(value: count)
}
/// Fetches a count of all notifications from the local database. Uses the viewContext and must be called from the main thread
public func numberOfAllNotifications() throws -> Int {
guard let modelController = modelController else {
throw RemoteNotificationsControllerError.databaseUnavailable
}
return try modelController.numberOfAllNotifications()
}
/// List of all possible inbox projects available Notifications Center. Used for populating the Inbox screen and the project count toolbar
public private(set) var allInboxProjects: Set<WikimediaProject> = []
/// A count of showing inbox projects (i.e. allInboxProjects minus those toggled off in the inbox filter screen)
public var countOfShowingInboxProjects: Int {
let filteredProjects = filterState.offProjects
return allInboxProjects.subtracting(filteredProjects).count
}
@objc public func updateCacheWithCurrentUnreadNotificationsCount() throws {
let currentCount = try numberOfUnreadNotifications().intValue
let sharedCache = SharedContainerCache<PushNotificationsCache>(fileName: SharedContainerCacheCommonNames.pushNotificationsCache, defaultCache: { PushNotificationsCache(settings: .default, notifications: []) })
var pushCache = sharedCache.loadCache()
pushCache.currentUnreadCount = currentCount
sharedCache.saveCache(pushCache)
}
public var filterPredicate: NSPredicate? {
predicateForFilterSavedState(filterState)
}
public var filterState: RemoteNotificationsFilterState = RemoteNotificationsFilterState(readStatus: .all, offTypes: [], offProjects: []) {
didSet {
guard let modelController = modelController else {
return
}
// save to library
modelController.setFilterSettingsToLibrary(dictionary: filterState.serialize())
NotificationCenter.default.post(name: RemoteNotificationsController.didUpdateFilterStateNotification, object: nil)
}
}
public var isFullyImported: Bool {
guard let modelController = modelController else {
return false
}
let appLanguageProjects = languageLinkController.preferredLanguages.map { WikimediaProject.wikipedia($0.languageCode, $0.localizedName, $0.languageVariantCode) }
for project in appLanguageProjects {
if !modelController.isProjectAlreadyImported(project: project) {
return false
}
}
return true
}
// MARK: Internal
@objc func deleteLegacyDatabaseFiles() throws {
guard let modelController = modelController else {
throw RemoteNotificationsControllerError.databaseUnavailable
}
try modelController.deleteLegacyDatabaseFiles()
}
// MARK: Private
/// Pulls filter state from local persistence and saves it in memory
private func populateFilterStateFromPersistence() {
guard let modelController = modelController,
let persistentFiltersDict = modelController.getFilterSettingsFromLibrary(),
let persistentFilters = RemoteNotificationsFilterState(nsDictionary: persistentFiltersDict, languageLinkController: languageLinkController) else {
return
}
self.filterState = persistentFilters
}
/// Fetches from the local database all projects that contain a local notification on device. Uses the viewContext and must be called from the main thread.
/// - Returns: Array of WikimediaProject
private func projectsFromLocalNotifications() throws -> Set<WikimediaProject> {
guard let modelController = modelController else {
return []
}
let wikis = try modelController.distinctWikis(predicate: nil)
let projects = wikis.compactMap { WikimediaProject(notificationsApiIdentifier: $0, languageLinkController: languageLinkController) }
return Set(projects)
}
private func predicateForFilterSavedState(_ filterState: RemoteNotificationsFilterState) -> NSPredicate? {
var readStatusPredicate: NSPredicate?
let readStatus = filterState.readStatus
switch readStatus {
case .all:
readStatusPredicate = nil
case .read:
readStatusPredicate = NSPredicate(format: "isRead == %@", NSNumber(value: true))
case .unread:
readStatusPredicate = NSPredicate(format: "isRead == %@", NSNumber(value: false))
}
let offTypes = filterState.offTypes
let onTypes = RemoteNotificationFilterType.orderingForFilters.filter {!offTypes.contains($0)}
var typePredicates: [NSPredicate] = []
let otherIsOff = offTypes.contains(.other)
if onTypes.isEmpty {
return NSPredicate(format: "FALSEPREDICATE")
}
if otherIsOff {
typePredicates = onTypes.compactMap { settingType in
let categoryStrings = RemoteNotificationFilterType.categoryStringsForFilterType(type: settingType)
let typeStrings = RemoteNotificationFilterType.typeStringForFilterType(type: settingType)
guard categoryStrings.count > 0 && typeStrings.count > 0 else {
return nil
}
return NSPredicate(format: "(categoryString IN %@ AND typeString IN %@)", categoryStrings, typeStrings)
}
} else {
typePredicates = offTypes.compactMap { settingType in
let categoryStrings = RemoteNotificationFilterType.categoryStringsForFilterType(type: settingType)
let typeStrings = RemoteNotificationFilterType.typeStringForFilterType(type: settingType)
guard categoryStrings.count > 0 && typeStrings.count > 0 else {
return nil
}
return NSPredicate(format: "NOT (categoryString IN %@ AND typeString IN %@)", categoryStrings, typeStrings)
}
}
let offProjects = filterState.offProjects
let offProjectPredicates: [NSPredicate] = offProjects.compactMap { return NSPredicate(format: "NOT (wiki == %@)", $0.notificationsApiWikiIdentifier) }
guard readStatusPredicate != nil || typePredicates.count > 0 || offProjectPredicates.count > 0 else {
return nil
}
var combinedOffTypePredicate: NSPredicate? = nil
if typePredicates.count > 0 {
if otherIsOff {
combinedOffTypePredicate = NSCompoundPredicate(orPredicateWithSubpredicates: typePredicates)
} else {
combinedOffTypePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: typePredicates)
}
}
var combinedOffProjectPredicate: NSPredicate? = nil
if offProjectPredicates.count > 0 {
combinedOffProjectPredicate = NSCompoundPredicate(andPredicateWithSubpredicates: offProjectPredicates)
}
let finalPredicates = [readStatusPredicate, combinedOffTypePredicate, combinedOffProjectPredicate].compactMap { $0 }
return finalPredicates.count > 0 ? NSCompoundPredicate(andPredicateWithSubpredicates: finalPredicates) : nil
}
/// Updates value of allInboxProjects by gathering list of static projects, app language projects, and local notifications projects. Involves a fetch to the local database. Uses the viewContext and must be called from the main thread
private func updateAllInboxProjects() throws {
let sideProjects: Set<WikimediaProject> = [.commons, .wikidata]
let appLanguageProjects = languageLinkController.preferredLanguages.map { WikimediaProject.wikipedia($0.languageCode, $0.localizedName, $0.languageVariantCode) }
var inboxProjects = sideProjects.union(appLanguageProjects)
let localProjects = try projectsFromLocalNotifications()
for localProject in localProjects {
inboxProjects.insert(localProject)
}
self.allInboxProjects = inboxProjects
}
}
public struct RemoteNotificationsFilterState: Equatable {
public enum ReadStatus: Int, CaseIterable {
case all
case read
case unread
var localizedDescription: String {
switch self {
case .all:
return CommonStrings.notificationsCenterAllNotificationsStatus
case .read:
return CommonStrings.notificationsCenterReadNotificationsStatus
case .unread:
return CommonStrings.notificationsCenterUnreadNotificationsStatus
}
}
}
public let readStatus: ReadStatus
public let offTypes: Set<RemoteNotificationFilterType>
public let offProjects: Set<WikimediaProject>
public init(readStatus: ReadStatus, offTypes: Set<RemoteNotificationFilterType>, offProjects: Set<WikimediaProject>) {
self.readStatus = readStatus
self.offTypes = offTypes
self.offProjects = offProjects
}
private var isReadStatusOrTypeFiltered: Bool {
return (readStatus != .all || !offTypes.isEmpty)
}
public var stateDescription: String {
let filteredBy = WMFLocalizedString("notifications-center-status-filtered-by", value: "Filtered by", comment: "Status header text in Notifications Center displayed when filtering notifications.")
let allNotifications = WMFLocalizedString("notifications-center-status-all-notifications", value: "All notifications", comment: "Status header text in Notifications Center displayed when viewing unfiltered list of notifications.")
let headerText = isReadStatusOrTypeFiltered ? filteredBy : allNotifications
return headerText
}
public static var detailDescriptionHighlightDelineator = "**"
public func detailDescription(totalProjectCount: Int, showingProjectCount: Int) -> String? {
// Generic templates
let doubleConcatenationTemplate = WMFLocalizedString("notifications-center-status-double-concatenation", value: "%1$@ in %2$@", comment: "Notifications Center status description. %1$@ is replaced with the currently applied filters and %2$@ is replaced with the count of projects/inboxes.")
let tripleConcatenationTemplate = WMFLocalizedString("notifications-center-status-triple-concatenation", value: "%1$@ and %2$@ in %3$@", comment: "Notifications Center status description. %1$@ is replaced with the currently applied read status filter, %2$@ is replaced with the count of notification type filters, and %3$@ is replaced with the count of projects/inboxes.")
// Specific plurals
let inProjects = WMFLocalizedString("notifications-center-status-in-projects", value: "{{PLURAL:%1$d|1=In 1 project|In %1$d projects}}", comment: "Notifications Center status description when filtering by projects/inboxes. %1$d is replaced by the count of local projects.")
let projectsPlain = WMFLocalizedString("notifications-center-status-in-projects-plain", value: "{{PLURAL:%1$d|1=1 project|%1$d projects}}", comment: "Notifications Center status description when filtering by projects/inboxes, without preposition. %1$d is replaced by the count of local projects.")
let typesPlain = WMFLocalizedString("notifications-center-status-in-types", value: "{{PLURAL:%1$d|1=1 type|%1$d types}}", comment: "Notifications Center status description when filtering by types. %1$d is replaced by the count of filtered types.")
var descriptionString: String?
switch (readStatus, offTypes.count, offProjects.count) {
case (.all, 0, 0):
// No filtering
descriptionString = String.localizedStringWithFormat(inProjects, totalProjectCount)
case (.all, 1..., 0):
// Only filtering by type
let typesString = String.localizedStringWithFormat(typesPlain, offTypes.count).highlightDelineated
let totalProjectString = String.localizedStringWithFormat(projectsPlain, totalProjectCount)
descriptionString = String.localizedStringWithFormat(doubleConcatenationTemplate, typesString, totalProjectString)
case (.all, 0, 1...):
// Only filtering by project/inbox
descriptionString = String.localizedStringWithFormat(inProjects, showingProjectCount).highlightDelineated
case (.read, 0, 0), (.unread, 0, 0):
// Only filtering by read status
let totalProjectString = String.localizedStringWithFormat(projectsPlain, totalProjectCount)
descriptionString = String.localizedStringWithFormat(doubleConcatenationTemplate, readStatus.localizedDescription.highlightDelineated, totalProjectString)
case (.read, 1..., 0), (.unread, 1..., 0):
// Filtering by read status and type
let typesString = String.localizedStringWithFormat(typesPlain, offTypes.count).highlightDelineated
let totalProjectString = String.localizedStringWithFormat(projectsPlain, totalProjectCount)
descriptionString = String.localizedStringWithFormat(tripleConcatenationTemplate, readStatus.localizedDescription.highlightDelineated, typesString, totalProjectString)
case (.read, 0, 1...), (.unread, 0, 1...):
// Filtering by read status and project/inbox
let projectString = String.localizedStringWithFormat(projectsPlain, showingProjectCount).highlightDelineated
descriptionString = String.localizedStringWithFormat(doubleConcatenationTemplate, readStatus.localizedDescription.highlightDelineated, projectString)
case (let readStatus, 1..., 1...):
// Filtering by type, project/inbox, and potentially read status
switch readStatus {
case .all:
// Filtering by type and project/inbox
let typesString = String.localizedStringWithFormat(typesPlain, offTypes.count).highlightDelineated
let projectString = String.localizedStringWithFormat(projectsPlain, showingProjectCount).highlightDelineated
descriptionString = String.localizedStringWithFormat(doubleConcatenationTemplate, typesString, projectString)
case .read, .unread:
// Filtering by read status, type, and project/inbox
let readString = readStatus.localizedDescription.highlightDelineated
let typesString = String.localizedStringWithFormat(typesPlain, offTypes.count).highlightDelineated
let projectString = String.localizedStringWithFormat(projectsPlain, showingProjectCount).highlightDelineated
descriptionString = String.localizedStringWithFormat(tripleConcatenationTemplate, readString, typesString, projectString)
}
default:
break
}
return descriptionString
}
private let readStatusKey = "readStatus"
private let offTypesKey = "offTypes"
private let offProjectsKey = "offProjects"
func serialize() -> NSDictionary? {
let mutableDictionary = NSMutableDictionary()
let numReadStatus = NSNumber(value: readStatus.rawValue)
mutableDictionary.setValue(numReadStatus, forKey: readStatusKey)
let offTypeIdentifiers = offTypes.compactMap { $0.filterIdentifier as NSString? }
mutableDictionary.setValue(NSArray(array: offTypeIdentifiers), forKey: offTypesKey)
let offProjectIdentifiers = offProjects.compactMap { $0.notificationsApiWikiIdentifier as NSString? }
mutableDictionary.setValue(NSArray(array: offProjectIdentifiers), forKey: offProjectsKey)
return mutableDictionary.copy() as? NSDictionary
}
init?(nsDictionary: NSDictionary, languageLinkController: MWKLanguageLinkController) {
guard let dictionary = nsDictionary as? [String: AnyObject] else {
return nil
}
guard let numReadStatus = dictionary[readStatusKey] as? NSNumber,
let readStatus = ReadStatus(rawValue: numReadStatus.intValue),
let offTypeIdentifiers = dictionary[offTypesKey] as? [NSString],
let offProjectApiIdentifiers = dictionary[offProjectsKey] as? [NSString] else {
return nil
}
let offTypes = offTypeIdentifiers.compactMap { RemoteNotificationFilterType(from: $0 as String) }
let offProjects = offProjectApiIdentifiers.compactMap { WikimediaProject(notificationsApiIdentifier: $0 as String, languageLinkController: languageLinkController) }
self.readStatus = readStatus
self.offTypes = Set(offTypes)
self.offProjects = Set(offProjects)
}
}
fileprivate extension String {
/// Delineated section of string to be highlighted in attributed string
var highlightDelineated: String {
return RemoteNotificationsFilterState.detailDescriptionHighlightDelineator + self + RemoteNotificationsFilterState.detailDescriptionHighlightDelineator
}
}
| 695e98d1c78ac8310f1d31cec0f418eb | 46.516535 | 380 | 0.68031 | false | false | false | false |
OMTS/Lounge | refs/heads/master | Example/Lounge/ViewController.swift | mit | 1 | //
// ViewController.swift
// Lounge
//
// Created by Ysix on 01/19/2016.
// Copyright (c) 2016 Ysix. All rights reserved.
//
import UIKit
import Lounge
class ViewController: LoungeViewController {
override func loadView() {
super.loadView()
self.delegate = self
self.dataSource = self
}
override func viewDidLoad() {
super.viewDidLoad()
//TODO: customizations
setPlaceholder("Type here", color: UIColor.darkGray)
setSeparatorColor(UIColor(red: 66/255.0, green: 122/255.0, blue: 185/255.0, alpha: 1))
// setTopViewHeight(120) // only if you set a top View you can adjust it's height this way
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
// demo only
func fakeServerCallBack()
{
// simulate the call to the server for fetching new messages.
self.newMessagesReceived(self.getMessagesAfter(self.lastMessageIdReceived()))
}
func getMessagesAfter(_ messageId: Int?) -> [LoungeMessageProtocol] // used for demo only
{
var msg = ChatMessage()
if let msgId = messageId
{
msg.id = msgId + 1
msg.text = "Ssshh, it's the quiet room !"
}
else
{
msg.id = 1
msg.text = "Hi I'm Blackagar Boltagon, welcome to the quiet room."
}
if msg.id == 3 {
self.displayAlert()
}
return [msg]
}
func displayAlert()
{
let alert = UIAlertController(title: "I said Ssshh!", message: "(This is for testing that the inputAccessoryView is still present when alert is fired)", preferredStyle: .alert)
let dismissAction = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil)
alert.addAction(dismissAction)
self.present(alert, animated: true, completion: nil)
}
}
extension ViewController : LoungeDataSource {
func getLastMessages(_ limit: Int, completion : (_ messages: [LoungeMessageProtocol]?) -> ())
{
//TODO: fetch last messages from your server or local Datadase
completion([])
}
func getOldMessages(_ limit: Int, beforeMessage: LoungeMessageProtocol, completion : (_ messages: [LoungeMessageProtocol]) -> ())
{
//TODO: fetch messages before "beforeMessage" from your server or local Database
completion([])
}
}
extension ViewController : LoungeDelegate {
func cellForLoadMore(_ indexPath: IndexPath) -> UITableViewCell
{
let cell = self.tableView.dequeueReusableCell(withIdentifier: "LoadMoreCell", for: indexPath)
return cell
}
func cellForMessage(_ message: LoungeMessageProtocol, indexPath: IndexPath, width: CGFloat) -> UITableViewCell
{
let msg = message as! ChatMessage
let cell = self.tableView.dequeueReusableCell(withIdentifier: (msg.fromMe ? "MyMessageCell" : "OthersMessageCell"), for: indexPath) as! ChatMessageCell
cell.textLB.text = msg.text
return cell
}
func cellHeightForMessage(_ message: LoungeMessageProtocol, width: CGFloat) -> CGFloat
{
let msg = message as! ChatMessage
let widthAvailableForText = width - 150 // we remove the size of constraints + space we want on the right or left of the bubble
let textHeight = ceil(msg.text.boundingRect(with: CGSize(width: widthAvailableForText, height: 9999), options: [NSStringDrawingOptions.usesLineFragmentOrigin, NSStringDrawingOptions.usesFontLeading], attributes:[NSFontAttributeName: UIFont(name: MessageCellValues.labelFontName, size: MessageCellValues.labelFontSize)!], context:nil).size.height)
return textHeight + 30 // we add the size of our constraints
}
func messageFromText(_ text: String) -> LoungeMessageProtocol // given a text as String, you should return the appropriate object conform to LoungeMessageProtocol
{
var msg = ChatMessage()
msg.text = text
return msg
}
func sendNewMessage(_ message: LoungeMessageProtocol)
{
//TODO: send the message to your server
// demo only
self.perform("fakeServerCallBack", with: nil, afterDelay: 1)
}
// optionnal
func keyBoardStateChanged(displayed: Bool) {
if displayed
{
print("keyboard is up")
}
else
{
print("keyboard is down")
}
}
}
| cd7ec5e0613880a974259acc4a5f2a6a | 30.574324 | 355 | 0.621656 | false | false | false | false |
HTWDD/HTWDresden-iOS-Temp | refs/heads/master | HTWDresden_old/HTWDresden/AppGlobals.swift | gpl-2.0 | 1 | //
// AppGlobals.swift
// HTWDresden
//
// Created by Benjamin Herzog on 21.08.14.
// Copyright (c) 2014 Benjamin Herzog. All rights reserved.
//
import UIKit
import Foundation
let SUITNAME_NSUSERDEFAULTS = "group.HTW.TodayExtensionSharingDefaults"
let userDefaults = NSUserDefaults(suiteName: SUITNAME_NSUSERDEFAULTS)!
//let DIFF_QUEUE = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)
let DIFF_QUEUE = dispatch_queue_create("de.benchr.HTWDresden.longrunningfunction", nil)
let MAIN_QUEUE = dispatch_get_main_queue()
var user: User!
func setNetworkIndicator(on: Bool) {
UIApplication.sharedApplication().networkActivityIndicatorVisible = on
}
func device() -> UIUserInterfaceIdiom {
return UIDevice.currentDevice().userInterfaceIdiom
}
// MARK: - Alert that works on iOS 7 and 8
class HTWAlert: NSObject, UIAlertViewDelegate {
var actions: [(title: String,action: (() -> Void)?)]!
var numberOfTextFields: Int!
var alert8: UIAlertController!
var alert7: UIAlertView!
override init() {}
func alertInViewController(sender: AnyObject, title: String, message: String, numberOfTextFields: Int, actions: [(title: String,action: (() -> Void)?)]) {
self.actions = actions
self.numberOfTextFields = numberOfTextFields
if (UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8.0 {
// iOS 8
alert8 = UIAlertController(title: title, message: message, preferredStyle: .Alert)
for i in 0..<numberOfTextFields {
alert8.addTextFieldWithConfigurationHandler(nil)
}
for (index,(title, function)) in enumerate(actions) {
alert8.addAction(UIAlertAction(title: title, style: .Default, handler: {
action in
let temp = self.actions[index].action
temp?()
}))
}
sender.presentViewController(alert8, animated: true, completion: nil)
}
else {
// iOS 7
alert7 = UIAlertView()
alert7.title = title
alert7.message = message
alert7.delegate = self
for (title, function) in self.actions {
alert7.addButtonWithTitle(title)
}
switch numberOfTextFields {
case 1:
alert7.alertViewStyle = .PlainTextInput
case 2:
alert7.alertViewStyle = .LoginAndPasswordInput
default:
break
}
alert7.show()
}
}
func stringFromTextFieldAt(index: Int) -> String? {
if index >= numberOfTextFields {
println("Tried to reach textField out of index.. aborting")
return nil
}
if (UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8.0 {
return (alert8.textFields![index] as! UITextField).text
}
else {
return alert7.textFieldAtIndex(index)!.text
}
}
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
self.actions[buttonIndex].action?()
}
}
| 9f739d69372e89f1ad66e797088a61b8 | 31.928571 | 158 | 0.608615 | false | false | false | false |
amezcua/actor-platform | refs/heads/master | actor-apps/app-ios/ActorSwift/Views.swift | mit | 4 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
extension UIView {
func hideView() {
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.alpha = 0
})
}
func showView() {
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.alpha = 1
})
}
var height: CGFloat {
get {
return self.bounds.height
}
}
var width: CGFloat {
get {
return self.bounds.width
}
}
var left: CGFloat {
get {
return self.frame.minX
}
}
var right: CGFloat {
get {
return self.frame.maxX
}
}
var top: CGFloat {
get {
return self.frame.minY
}
}
var bottom: CGFloat {
get {
return self.frame.maxY
}
}
}
class UIViewMeasure {
class func measureText(text: String, width: CGFloat, fontSize: CGFloat) -> CGSize {
return UIViewMeasure.measureText(text, width: width, font: UIFont.systemFontOfSize(fontSize))
}
class func measureText(text: String, width: CGFloat, font: UIFont) -> CGSize {
// Building paragraph styles
let style = NSMutableParagraphStyle()
style.lineBreakMode = NSLineBreakMode.ByWordWrapping
// Measuring text with reduced width
let rect = text.boundingRectWithSize(CGSize(width: width - 2, height: CGFloat.max),
options: NSStringDrawingOptions.UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font, NSParagraphStyleAttributeName: style],
context: nil)
// Returning size with expanded width
return CGSizeMake(ceil(rect.width + 2), CGFloat(ceil(rect.height)))
}
class func measureText(attributedText: NSAttributedString, width: CGFloat) -> CGSize {
// Measuring text with reduced width
let rect = attributedText.boundingRectWithSize(CGSize(width: width - 2, height: CGFloat.max), options: [.UsesLineFragmentOrigin, .UsesFontLeading], context: nil)
// Returning size with expanded width and height
return CGSizeMake(ceil(rect.width + 2), CGFloat(ceil(rect.height)))
}
} | f77629d7b63397ad86ca6531dba1ce75 | 25.761364 | 169 | 0.57859 | false | false | false | false |
SrirangaDigital/shankara-android | refs/heads/master | iOS/Advaita Sharada/Advaita Sharada/TOCTableDataSource.swift | gpl-2.0 | 1 | //
// TOCTableDataSource.swift
// Advaita Sharada
//
// Created by Amiruddin Nagri on 02/08/15.
// Copyright (c) 2015 Sriranga Digital Software Technologies Pvt. Ltd. All rights reserved.
//
import UIKit
import CoreData
class TOCTableDataSource: NSObject, LinkBasedDataSource {
var book: Link?
var tocLinks:[(Link, [Link])]?
var managedObjectContext: NSManagedObjectContext?
var hasSections:Bool?
init(managedObjectContext: NSManagedObjectContext, book: Link) {
super.init()
self.managedObjectContext = managedObjectContext
self.book = book
self.tocLinks = [(Link, [Link])]()
self.initTOCLinks();
}
func initTOCLinks() {
let chaptersCount = Link.getNavigableChildrenCount(self.managedObjectContext!, parent: self.book!)
if chaptersCount != 0 {
for i in 0 ... chaptersCount - 1 {
if let chapter = Link.getNavigableChildAt(self.managedObjectContext!, parent: book!, index: i) {
var sections = [Link]()
let sectionsCount = Link.getNavigableChildrenCount(self.managedObjectContext!, parent: chapter)
if sectionsCount != 0 {
for j in 0 ... sectionsCount - 1 {
if let section = Link.getNavigableChildAt(self.managedObjectContext!, parent: chapter, index: j) {
sections.append(section)
}
}
}
let element = (chapter, sections)
tocLinks!.append(element)
}
}
}
hasSections = tocLinks![0].1.count != 0
}
func linkForIndexPath(indexPath: NSIndexPath) -> Link? {
if hasSections! {
return tocLinks?[indexPath.section].1[indexPath.row]
} else {
return tocLinks?[indexPath.row].0
}
}
@objc func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("book_toc_cell") as! UITableViewCell
cell.textLabel!.text = tocName(indexPath) ?? nil
return cell
}
func tocName(indexPath: NSIndexPath) -> String? {
return linkForIndexPath(indexPath)?.displayName()
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return hasSections! ? tocLinks!.count : 1
}
@objc func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return hasSections! ? tocLinks![section].1.count : tocLinks!.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return hasSections! ? tocLinks![section].0.displayName() : nil
}
}
| 3790e971074eb4262bb6df4c667031b9 | 36.363636 | 126 | 0.602016 | false | false | false | false |
Ivacker/swift | refs/heads/master | stdlib/public/Platform/MachError.swift | apache-2.0 | 14 | #if os(OSX) || os(iOS) || os(tvOS) || os(watchOS)
/// Enumeration describing Mach error codes.
@objc public enum MachError : CInt {
case KERN_SUCCESS = 0
/// Specified address is not currently valid.
case KERN_INVALID_ADDRESS = 1
/// Specified memory is valid, but does not permit the required
/// forms of access.
case KERN_PROTECTION_FAILURE = 2
/// The address range specified is already in use, or no address
/// range of the size specified could be found.
case KERN_NO_SPACE = 3
/// The function requested was not applicable to this type of
/// argument, or an argument is invalid.
case KERN_INVALID_ARGUMENT = 4
/// The function could not be performed. A catch-all.
case KERN_FAILURE = 5
/// A system resource could not be allocated to fulfill this
/// request. This failure may not be permanent.
case KERN_RESOURCE_SHORTAGE = 6
/// The task in question does not hold receive rights for the port
/// argument.
case KERN_NOT_RECEIVER = 7
/// Bogus access restriction.
case KERN_NO_ACCESS = 8
/// During a page fault, the target address refers to a memory
/// object that has been destroyed. This failure is permanent.
case KERN_MEMORY_FAILURE = 9
/// During a page fault, the memory object indicated that the data
/// could not be returned. This failure may be temporary; future
/// attempts to access this same data may succeed, as defined by the
/// memory object.
case KERN_MEMORY_ERROR = 10
/// The receive right is already a member of the portset.
case KERN_ALREADY_IN_SET = 11
/// The receive right is not a member of a port set.
case KERN_NOT_IN_SET = 12
/// The name already denotes a right in the task.
case KERN_NAME_EXISTS = 13
/// The operation was aborted. Ipc code will catch this and reflect
/// it as a message error.
case KERN_ABORTED = 14
/// The name doesn't denote a right in the task.
case KERN_INVALID_NAME = 15
/// Target task isn't an active task.
case KERN_INVALID_TASK = 16
/// The name denotes a right, but not an appropriate right.
case KERN_INVALID_RIGHT = 17
/// A blatant range error.
case KERN_INVALID_VALUE = 18
/// Operation would overflow limit on user-references.
case KERN_UREFS_OVERFLOW = 19
/// The supplied (port) capability is improper.
case KERN_INVALID_CAPABILITY = 20
/// The task already has send or receive rights for the port under
/// another name.
case KERN_RIGHT_EXISTS = 21
/// Target host isn't actually a host.
case KERN_INVALID_HOST = 22
/// An attempt was made to supply "precious" data for memory that is
/// already present in a memory object.
case KERN_MEMORY_PRESENT = 23
/// A page was requested of a memory manager via
/// memory_object_data_request for an object using a
/// MEMORY_OBJECT_COPY_CALL strategy, with the VM_PROT_WANTS_COPY
/// flag being used to specify that the page desired is for a copy
/// of the object, and the memory manager has detected the page was
/// pushed into a copy of the object while the kernel was walking
/// the shadow chain from the copy to the object. This error code is
/// delivered via memory_object_data_error and is handled by the
/// kernel (it forces the kernel to restart the fault). It will not
/// be seen by users.
case KERN_MEMORY_DATA_MOVED = 24
/// A strategic copy was attempted of an object upon which a quicker
/// copy is now possible. The caller should retry the copy using
/// vm_object_copy_quickly. This error code is seen only by the
/// kernel.
case KERN_MEMORY_RESTART_COPY = 25
/// An argument applied to assert processor set privilege was not a
/// processor set control port.
case KERN_INVALID_PROCESSOR_SET = 26
/// The specified scheduling attributes exceed the thread's limits.
case KERN_POLICY_LIMIT = 27
/// The specified scheduling policy is not currently enabled for the
/// processor set.
case KERN_INVALID_POLICY = 28
/// The external memory manager failed to initialize the memory object.
case KERN_INVALID_OBJECT = 29
/// A thread is attempting to wait for an event for which there is
/// already a waiting thread.
case KERN_ALREADY_WAITING = 30
/// An attempt was made to destroy the default processor set.
case KERN_DEFAULT_SET = 31
/// An attempt was made to fetch an exception port that is
/// protected, or to abort a thread while processing a protected
/// exception.
case KERN_EXCEPTION_PROTECTED = 32
/// A ledger was required but not supplied.
case KERN_INVALID_LEDGER = 33
/// The port was not a memory cache control port.
case KERN_INVALID_MEMORY_CONTROL = 34
/// An argument supplied to assert security privilege was not a host
/// security port.
case KERN_INVALID_SECURITY = 35
/// thread_depress_abort was called on a thread which was not
/// currently depressed.
case KERN_NOT_DEPRESSED = 36
/// Object has been terminated and is no longer available
case KERN_TERMINATED = 37
/// Lock set has been destroyed and is no longer available.
case KERN_LOCK_SET_DESTROYED = 38
/// The thread holding the lock terminated before releasing the lock
case KERN_LOCK_UNSTABLE = 39
/// The lock is already owned by another thread
case KERN_LOCK_OWNED = 40
/// The lock is already owned by the calling thread
case KERN_LOCK_OWNED_SELF = 41
/// Semaphore has been destroyed and is no longer available.
case KERN_SEMAPHORE_DESTROYED = 42
/// Return from RPC indicating the target server was terminated
/// before it successfully replied
case KERN_RPC_SERVER_TERMINATED = 43
/// Terminate an orphaned activation.
case KERN_RPC_TERMINATE_ORPHAN = 44
/// Allow an orphaned activation to continue executing.
case KERN_RPC_CONTINUE_ORPHAN = 45
/// Empty thread activation (No thread linked to it)
case KERN_NOT_SUPPORTED = 46
/// Remote node down or inaccessible.
case KERN_NODE_DOWN = 47
/// A signalled thread was not actually waiting.
case KERN_NOT_WAITING = 48
/// Some thread-oriented operation (semaphore_wait) timed out
case KERN_OPERATION_TIMED_OUT = 49
/// During a page fault, indicates that the page was rejected as a
/// result of a signature check.
case KERN_CODESIGN_ERROR = 50
/// The requested property cannot be changed at this time.
case KERN_POLICY_STATIC = 51
}
#endif
| d26761e6298871d1c63a598623efe05e | 35.062176 | 73 | 0.646839 | false | false | false | false |
EvanTrow/TimeUp | refs/heads/master | TimeUp/ViewController.swift | apache-2.0 | 1 | //
// ViewController.swift
// TimeUp
//
// Created by Evan Trowbridge on 1/4/17.
// Copyright © 2017 TrowLink. All rights reserved.
//
import Cocoa
class ViewController: NSViewController, NSApplicationDelegate {
// setup popover
let popover = NSPopover()
var eventMonitor: EventMonitor?
var AppDelegate: AppDelegate?
var RestartViewController: RestartViewController?
// set menu bar text length
let statusItem = NSStatusBar.system().statusItem(withLength: -1)
@IBOutlet weak var popoverMsg: NSTextField!
override func viewDidLoad() {
super.viewDidLoad()
// start TimeUp
uptime()
start()
popoverMsg.stringValue = UserDefaults.standard.string(forKey: "popoverMsg")!
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
// show restart window
func showRestart(){
self.performSegue(withIdentifier: NSStoryboardSegue.Identifier("restartSegue"), sender: self)
}
// start timers in background task
func start(){
DispatchQueue.global(qos: .background).async {
//print("This is run on the background queue")
DispatchQueue.main.async {
//print("This is run on the main queue, after the previous code in outer block")
// setup timers in seperate threads
self.uptime()
_ = Timer.scheduledTimer(timeInterval: TimeInterval(UserDefaults.standard.integer(forKey: "timerInterval")), target: self, selector: #selector(self.uptime), userInfo: nil, repeats: true)
_ = Timer.scheduledTimer(timeInterval: TimeInterval(UserDefaults.standard.integer(forKey: "timerInterval")), target: self, selector: #selector(self.uptimeSevenDays), userInfo: nil, repeats: true)
self.uptimeSevenDays()
_ = Timer.scheduledTimer(timeInterval: TimeInterval(UserDefaults.standard.integer(forKey: "timerInterval")), target: self, selector: #selector(self.uptimeTenDays), userInfo: nil, repeats: true)
self.uptimeTenDays()
_ = Timer.scheduledTimer(timeInterval: TimeInterval(UserDefaults.standard.integer(forKey: "timerInterval")), target: self, selector: #selector(self.uptimeFourteenDays), userInfo: nil, repeats: true)
self.uptimeFourteenDays()
_ = Timer.scheduledTimer(timeInterval: TimeInterval(UserDefaults.standard.integer(forKey: "timerInterval")), target: self, selector: #selector(self.uptimeTwentyOneDays), userInfo: nil, repeats: true)
self.uptimeTwentyOneDays()
//testing
//_ = Timer.scheduledTimer(timeInterval: 20, target: self, selector: #selector(self.test), userInfo: nil, repeats: false)
}
}
}
@objc func test(){
restartProcessCheck(array: UserDefaults.standard.stringArray(forKey: "blacklistApps") ?? [String]())
}
// uptime output text
@IBOutlet weak var timeOut: NSTextField!
@IBOutlet weak var timeUpProgress: NSLevelIndicator!
// show time up in popover
@objc func uptime(){
//debug -------------------------------------------------------------------
//print(Preferences.databaseUploadEnabled)
//restartProcessCheck(array: UserDefaults.standard.stringArray(forKey: "blacklistApps") ?? [String]())
let uptime = getUpTime(no1: 0)
// convert seconds to day, hrs, mins
let days = String((uptime / 86400)) + " days "
let hours = String((uptime % 86400) / 3600) + " hrs "
let minutes = String((uptime % 3600) / 60) + " min"
// show computer uptime and progress bar
timeOut.stringValue = days + hours + minutes
timeUpProgress.doubleValue = ((Double(uptime) / 1814400) * 100)
}
//more than 7 days every 6 hrs
var lastCheckSevenDays = NSDate() //get time when app started for timer
var fistRunSevenDays = false
@objc func uptimeSevenDays() {
let elapsedTime = NSDate().timeIntervalSince(lastCheckSevenDays as Date)
if (elapsedTime>=Double(UserDefaults.standard.integer(forKey: "firstInterval"))){ // if time is more that 6hrs show notification
lastCheckSevenDays = NSDate() // record time again
//convert seconds to days
let daysSeven = getUpTime(no1: 0) / 86400
// if days over limit show restart
if (daysSeven >= UserDefaults.standard.integer(forKey: "firstLow") && UserDefaults.standard.integer(forKey: "firstHigh") < 10){
restartProcessCheck(array: UserDefaults.standard.stringArray(forKey: "blacklistApps") ?? [String]())
}
print("debug: 7 main")
}
if (fistRunSevenDays==false){
lastCheckSevenDays = NSDate() // record time again
let daysSeven = getUpTime(no1: 0) / 86400
// if days over limit show restart
if (daysSeven >= UserDefaults.standard.integer(forKey: "firstLow") && UserDefaults.standard.integer(forKey: "firstHigh") < 10){
restartProcessCheck(array: UserDefaults.standard.stringArray(forKey: "blacklistApps") ?? [String]())
}
fistRunSevenDays = true
print("debug: 7 first")
}
}
//more than 10 days every 3 hrs
var lastCheckTenDays = NSDate() //get time when app started for timer
var fistRunTenDays = false
@objc func uptimeTenDays() {
let elapsedTime = NSDate().timeIntervalSince(lastCheckTenDays as Date)
if (elapsedTime>=Double(UserDefaults.standard.integer(forKey: "secondInterval"))){ // if time is more that 6hrs show notification
lastCheckTenDays = NSDate() // record time again
//convert seconds to days
let daysSeven = getUpTime(no1: 0) / 86400
// if days over limit show restart
if (daysSeven >= UserDefaults.standard.integer(forKey: "secondLow") && daysSeven < UserDefaults.standard.integer(forKey: "secondHigh")){
restartProcessCheck(array: UserDefaults.standard.stringArray(forKey: "blacklistApps") ?? [String]())
}
print("debug: 10 main")
}
if (fistRunTenDays==false){
lastCheckTenDays = NSDate() // record time again
let daysSeven = getUpTime(no1: 0) / 86400
// if days over limit show restart
if (daysSeven >= UserDefaults.standard.integer(forKey: "secondLow") && daysSeven < UserDefaults.standard.integer(forKey: "secondHigh")){
restartProcessCheck(array: UserDefaults.standard.stringArray(forKey: "blacklistApps") ?? [String]())
}
fistRunTenDays = true
print("debug: 10 first")
}
}
//more than 14 days every 1 hr
var lastCheckFourteenDays = NSDate() //get time when app started for timer
var fistRunFourteenDays = false
@objc func uptimeFourteenDays() {
let elapsedTime = NSDate().timeIntervalSince(lastCheckFourteenDays as Date)
if (elapsedTime>=Double(UserDefaults.standard.integer(forKey: "thirdInterval"))){ // if time is more that 6hrs show notification
lastCheckFourteenDays = NSDate() // record time again
//convert seconds to days
let daysSeven = getUpTime(no1: 0) / 86400
// if days over limit show restart
if (daysSeven >= UserDefaults.standard.integer(forKey: "thirdLow") && daysSeven < UserDefaults.standard.integer(forKey: "thirdHigh")){
restartProcessCheck(array: UserDefaults.standard.stringArray(forKey: "blacklistApps") ?? [String]())
}
print("debug: 14 main")
}
if (fistRunFourteenDays==false){
lastCheckFourteenDays = NSDate() // record time again
let daysSeven = getUpTime(no1: 0) / 86400
// if days over limit show restart
if (daysSeven >= UserDefaults.standard.integer(forKey: "thirdLow") && daysSeven < UserDefaults.standard.integer(forKey: "thirdHigh")){
restartProcessCheck(array: UserDefaults.standard.stringArray(forKey: "blacklistApps") ?? [String]())
}
fistRunFourteenDays = true
print("debug: 14 fisrt")
}
}
//more than 21 days every 5 min
var lastCheckTwentyOneDays = NSDate() //get time when app started for timer
var fistRunTwentyOneDays = false
@objc func uptimeTwentyOneDays() {
let elapsedTime = NSDate().timeIntervalSince(lastCheckTwentyOneDays as Date)
if (elapsedTime>=Double(UserDefaults.standard.integer(forKey: "forthInterval"))){ // if time is more that 6hrs show notification
lastCheckTwentyOneDays = NSDate() // record time again
//convert seconds to days
let daysSeven = getUpTime(no1: 0) / 86400
// if days over limit show restart
if (daysSeven >= UserDefaults.standard.integer(forKey: "forthHigh")){
restartProcessCheck(array: UserDefaults.standard.stringArray(forKey: "blacklistApps") ?? [String]())
}
print("debug: 21 main")
}
if (fistRunTwentyOneDays==false){
lastCheckTwentyOneDays = NSDate() // record time again
let daysSeven = getUpTime(no1: 0) / 86400
// if days over limit show restart
if (daysSeven >= UserDefaults.standard.integer(forKey: "forthHigh")){
restartProcessCheck(array: UserDefaults.standard.stringArray(forKey: "blacklistApps") ?? [String]())
}
fistRunTwentyOneDays = true
print("debug: 21 first")
}
}
// if blacklist applications are active don't restart
func restartProcessCheck(array: Array<String>) {
var restartCheck = UserDefaults.standard.bool(forKey: "enableNotifications")
let runningApplications = NSWorkspace.shared().runningApplications
for eachApplication in runningApplications {
if let applicationName = eachApplication.localizedName {
if array.contains(applicationName) {
//print(applicationName+" is open don't restart")
restartCheck = false
print("no restart: blacklist app open")
}
//print("application is \(applicationName) & pid is \(eachApplication.processIdentifier)")
}
}
//print(restartCheck)
// inactivity check
var lastEvent:CFTimeInterval = 0
lastEvent = CGEventSource.secondsSinceLastEventType(CGEventSourceStateID.hidSystemState, eventType: CGEventType(rawValue: ~0)!)
// if inactive for 30 sec
//print(lastEvent)
if(Int(lastEvent) > UserDefaults.standard.integer(forKey: "inactiveTime") && UserDefaults.standard.bool(forKey: "enableInactivityDetection")){
//print("no restart: inactive")
if(UserDefaults.standard.bool(forKey: "enableNotifications")){
checkForActivity()
}
restartCheck = false
}
// show restart dialog
if(restartCheck){
showRestart()
}
}
@objc func checkForActivity(){
//print("activity check")
// inactivity check
var lastEvent:CFTimeInterval = 0
lastEvent = CGEventSource.secondsSinceLastEventType(CGEventSourceStateID.hidSystemState, eventType: CGEventType(rawValue: ~0)!)
if(Int(lastEvent) < UserDefaults.standard.integer(forKey: "inactiveTime")){
showRestart()
} else {
//print("retry: activity")
_ = Timer.scheduledTimer(timeInterval: 5, target: self, selector: #selector(self.checkForActivity), userInfo: nil, repeats: false)
}
}
func getUpTime(no1: Int) -> Int {
// get computer uptime
var boottime = timeval()
var mib: [Int32] = [CTL_KERN, KERN_BOOTTIME]
var size = MemoryLayout<timeval>.stride
var now = time_t()
var uptime: time_t = -1
time(&now)
if (sysctl(&mib, 2, &boottime, &size, nil, 0) != -1 && boottime.tv_sec != 0) {
uptime = now - boottime.tv_sec
}
return uptime
//return 1700000 // TESTING
}
}
| c085f2410e8c5cb61166d5cd7909c4f0 | 43.890459 | 215 | 0.608391 | false | false | false | false |
atrick/swift | refs/heads/main | test/Generics/requirement_inference_funny_order.swift | apache-2.0 | 3 | // RUN: %target-typecheck-verify-swift -requirement-machine-inferred-signatures=on
// RUN: %target-swift-frontend -typecheck %s -debug-generic-signatures -requirement-machine-inferred-signatures=on 2>&1 | %FileCheck %s
protocol P1 {}
protocol P2 {}
protocol IteratorProtocol {
associatedtype Element
func next() -> Element?
}
// CHECK: requirement_inference_funny_order.(file).LocalArray@
// CHECK: Generic signature: <Element where Element : P1>
// CHECK: ExtensionDecl line={{[0-9]+}} base=LocalArray
// CHECK: Generic signature: <Element where Element : P1, Element : P2>
extension LocalArray where Element : P2 {
static func ==(lhs: Self, rhs: Self) -> Bool {}
}
struct LocalArray<Element : P1>: IteratorProtocol {
func next() -> Element? {}
}
| 85364f7da4da292a33396efb3b18a8bf | 29.52 | 135 | 0.718218 | false | false | false | false |
nmdias/FeedKit | refs/heads/master | Sources/FeedKit/Dates/RFC3339DateFormatter.swift | mit | 1 | //
// RFC3339DateFormatter.swift
//
// Copyright (c) 2016 - 2018 Nuno Manuel Dias
//
// 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
/// Converts date and time textual representations within the RFC3339
/// date specification into `Date` objects
class RFC3339DateFormatter: DateFormatter {
let dateFormats = [
"yyyy-MM-dd'T'HH:mm:ssZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss.SSZZZZZ",
"yyyy-MM-dd'T'HH:mm:ss-SS:ZZ",
"yyyy-MM-dd'T'HH:mm:ss"
]
override init() {
super.init()
self.timeZone = TimeZone(secondsFromGMT: 0)
self.locale = Locale(identifier: "en_US_POSIX")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not supported")
}
override func date(from string: String) -> Date? {
let string = string.trimmingCharacters(in: .whitespacesAndNewlines)
for dateFormat in self.dateFormats {
self.dateFormat = dateFormat
if let date = super.date(from: string) {
return date
}
}
return nil
}
}
| 2c500ac5266c86823659f524aecba8ef | 35.711864 | 82 | 0.6759 | false | false | false | false |
kyleweiner/Cool-Beans | refs/heads/master | Cool Beans/Controllers/ConnectedViewController.swift | mit | 1 | //
// ConnectedViewController.swift
// Created by Kyle on 11/14/14.
//
import UIKit
struct Temperature {
enum State {
case Unknown, Cold, Cool, Warm, Hot
}
var degreesCelcius: Float
var degressFahrenheit: Float {
return (degreesCelcius * 1.8) + 32.0
}
func state() -> State {
switch Int(degressFahrenheit) {
case let x where x <= 39: return .Cold
case 40...65: return .Cool
case 66...80: return .Warm
case let x where x >= 81: return .Hot
default: return .Unknown
}
}
}
class ConnectedViewController: UIViewController {
@IBOutlet weak var scrollView: UIScrollView!
@IBOutlet weak var temperatureView: TemperatureView!
var connectedBean: PTDBean?
private var currentTemperature: Temperature = Temperature(degreesCelcius: 0) {
didSet {
updateTemperatureView()
updateBean()
}
}
private let refreshControl = UIRefreshControl()
// MARK: - Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
// Update the name label.
temperatureView.nameLabel.text = connectedBean?.name ?? "Unknown"
// Add pull-to-refresh control.
refreshControl.addTarget(self, action: #selector(didPullToRefresh(_:)), forControlEvents: .ValueChanged)
refreshControl.tintColor = .whiteColor()
scrollView.addSubview(refreshControl)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
connectedBean?.readTemperature()
}
// MARK: - Actions
func didPullToRefresh(sender: AnyObject) {
refreshControl.endRefreshing()
connectedBean?.readTemperature()
}
// MARK: - Helper
func updateTemperatureView() {
// Update the temperature label.
temperatureView.temperatureLabel.text = String(format: "%.f℉", currentTemperature.degressFahrenheit)
// Update the background color.
var backgroundColor: UIColor
switch currentTemperature.state() {
case .Unknown: backgroundColor = .blackColor()
case .Cold: backgroundColor = .CBColdColor()
case .Cool: backgroundColor = .CBCoolColor()
case .Warm: backgroundColor = .CBWarmColor()
case .Hot: backgroundColor = .CBHotColor()
}
UIView.animateWithDuration(0.4, animations: { [unowned self] in
self.scrollView.backgroundColor = backgroundColor
self.temperatureView.containerView.backgroundColor = backgroundColor
})
}
func updateBean() {
connectedBean?.setLedColor(temperatureView.containerView.backgroundColor)
}
}
// MARK: - PTDBeanDelegate
extension ConnectedViewController: PTDBeanDelegate {
func bean(bean: PTDBean!, didUpdateTemperature degrees_celsius: NSNumber!) {
let newTemperature = Temperature(degreesCelcius: degrees_celsius.floatValue)
if newTemperature.degreesCelcius != currentTemperature.degreesCelcius {
currentTemperature = newTemperature
#if DEBUG
print("TEMPERATURE UPDATED \nOld: \(currentTemperature.degressFahrenheit)℉ \nNew: \(newTemperature.degressFahrenheit)℉")
#endif
}
}
} | c4a2e1107f7ac241238017b673ffd13c | 27.745614 | 136 | 0.65232 | false | false | false | false |
0bmxa/CCCB-Lighter | refs/heads/master | CCCB Lighter/DaliConnector.swift | mit | 1 | //
// DaliConnector.swift
// CCCB Lighter
//
// Created by mxa on 03.01.2017.
// Copyright © 2017 mxa. All rights reserved.
//
import Foundation
class DaliConnector {
private static let daliURL = "http://dali.club.berlin.ccc.de/cgi-bin/licht.cgi"
// Getter for a single lamp
class func lampValues(completion: @escaping (Int, Int, Int, Int) -> ()) {
let request = HTTPRequest()
request.GET(urlString: daliURL) { response in
let components = response.replacingOccurrences(of: "\r\n", with: "").components(separatedBy: " ")
guard components.count == 4 else { return }
guard
let lamp0Value = Int(components[0]),
let lamp1Value = Int(components[1]),
let lamp2Value = Int(components[2]),
let lamp3Value = Int(components[3])
else {
print("Invalid response.")
return
}
completion(lamp0Value, lamp1Value, lamp2Value, lamp3Value)
}
}
// Convenience getter for all lamps
class func averageLampValue(completion: @escaping (Int) -> ()) {
self.lampValues { lamp0Value, lamp1Value, lamp2Value, lamp3Value in
let averageLampValue = (lamp0Value + lamp1Value + lamp2Value + lamp3Value) / 4
completion(averageLampValue)
}
}
// Setter for a single lamp
class func setLamp(_ lampID: Int, to lampValue: Int, completion: @escaping () -> ()) {
let request = HTTPRequest()
let lampID = -1
let urlString = daliURL + "?set%20\(lampID)%20to%20\(lampValue)"
request.GET(urlString: urlString) { _ in
completion()
}
}
// Convenience setter for all lamps
class func setAllLamps(to lampValue: Int, completion: @escaping () -> ()) {
let lampID = -1
self.setLamp(lampID, to: lampValue, completion: completion)
}
}
| 3add3eba368330597fed3e6029f76659 | 28.642857 | 109 | 0.551807 | false | false | false | false |
codeliling/DesignResearch | refs/heads/master | DesignBase/DesignBase/Controllers/SubMenuViewController.swift | apache-2.0 | 1 | //
// SubMenuViewController.swift
// DesignBase
//
// Created by lotusprize on 15/4/22.
// Copyright (c) 2015年 geekTeam. All rights reserved.
//
import UIKit
class SubMenuViewController: UIViewController,UICollectionViewDataSource,UICollectionViewDelegate {
var titleView:MenuView?
var collectionView:UICollectionView?
var subMenuData:NSMutableArray!
let blueColor:UIColor = UIColor(red: 102/255.0, green: 59/255.0, blue: 209/255.0, alpha: 1)
let lightGrayColor:UIColor = UIColor(red: 247/255.0, green: 248.0/255.0, blue: 248.0/255.0, alpha: 1)
var lastCellSubMenuView:SubMenuView?
override func viewDidLoad() {
super.viewDidLoad()
subMenuData = NSMutableArray()
var layout:UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.scrollDirection = UICollectionViewScrollDirection.Vertical
layout.itemSize = CGSizeMake(100, 80);
layout.minimumLineSpacing = 2;
layout.minimumInteritemSpacing = 2;
layout.sectionInset = UIEdgeInsetsMake(1, 1, 1, 1);
collectionView = UICollectionView(frame: CGRectMake(0, 180, 210, 650),collectionViewLayout:layout)
collectionView?.dataSource = self
collectionView?.delegate = self
collectionView?.backgroundColor = lightGrayColor
collectionView?.registerClass(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "Cell")
self.view.addSubview(collectionView!)
var lineLayer:CALayer = CALayer()
lineLayer.frame = CGRectMake(23, 165, 170, 3)
lineLayer.backgroundColor = blueColor.CGColor
self.view.layer.addSublayer(lineLayer)
var verticalLineLayer:CALayer = CALayer()
verticalLineLayer.frame = CGRectMake(209, 0, 13, 768)
verticalLineLayer.contents = UIImage(named: "line")?.CGImage
self.view.layer.addSublayer(verticalLineLayer)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOfReceivedNotification:", name: "addSubMenuNotification", object: nil)
}
func methodOfReceivedNotification(notification: NSNotification){
//Action take on Notification
var subMenuModel = notification.object as! SubMenuModel
if titleView == nil{
titleView = MenuView(frame: CGRectMake(10, 110, 130, 50), chineseTitle: subMenuModel.cnName, enTitle: subMenuModel.enName)
titleView?.backgroundColor = lightGrayColor
titleView?.updateTextColor(blueColor)
self.view.addSubview(titleView!)
}
else{
titleView?.chineseTitle = subMenuModel.cnName
titleView?.enTitle = subMenuModel.enName
titleView?.updateTextColor(blueColor)
titleView?.setNeedsDisplay()
}
switch subMenuModel.type.rawValue{
case MenuType.CASE.rawValue:
addCaseSubMenuList(subMenuModel.tableIndex!)
case MenuType.THEORY.rawValue:
println("...theory \(subMenuModel.type.rawValue), \(subMenuModel.tableIndex)")
case MenuType.METHOD.rawValue:
addMethodSubMenuList(subMenuModel.tableIndex!)
default:
println("...fault type")
}
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return subMenuData.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var dict:NSDictionary = subMenuData?.objectAtIndex(indexPath.row) as! NSDictionary
var cell:UICollectionViewCell? = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as? UICollectionViewCell
println(indexPath.row)
if let views = cell?.contentView.subviews{
var isHasSubMenuView:Bool = false
for subMenuView in views{
if (subMenuView.isKindOfClass(SubMenuView.classForCoder()))
{
var subMenuView = subMenuView as! SubMenuView
subMenuView.chineseTitle = dict.objectForKey("cnName") as! String
subMenuView.enTitle = dict.objectForKey("enName") as! String
subMenuView.bgLayer.backgroundColor = UIColor.clearColor().CGColor!
subMenuView.updateTextColor(blueColor)
subMenuView.setNeedsDisplay()
if (indexPath.row % 2 == 0){
subMenuView.frame = CGRectMake(20, 10, 80, 56)
}
else{
subMenuView.frame = CGRectMake(5, 10, 80, 56)
}
isHasSubMenuView = true
}
}
if (!isHasSubMenuView)
{
var subMenuView:SubMenuView = SubMenuView()
subMenuView.chineseTitle = dict.objectForKey("cnName") as! String
subMenuView.enTitle = dict.objectForKey("enName") as! String
if (indexPath.row % 2 == 0){
subMenuView.frame = CGRectMake(20, 10, 80, 56)
}
else{
subMenuView.frame = CGRectMake(5, 10, 80, 56)
}
subMenuView.updateTextColor(UIColor(red: 102/255.0, green: 59/255.0, blue: 209/255.0, alpha: 1))
cell?.contentView.addSubview(subMenuView)
}
}
return cell!
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
println("\(indexPath.row) is click...")
var dict:NSDictionary = subMenuData?.objectAtIndex(indexPath.row) as! NSDictionary
var methodList = [MethodModel]()
var mModel:MethodModel;
for methodModel in dict.objectForKey("list") as! NSArray{
var dict:NSDictionary = methodModel as! NSDictionary
mModel = MethodModel()
mModel.cnName = dict.objectForKey("cnName") as? String
mModel.flag = dict.objectForKey("flag") as? String
mModel.iconName = dict.objectForKey("iconName") as? String
if let object: AnyObject = dict.objectForKey("enName"){
mModel.enName = dict.objectForKey("enName") as? String
}
methodList.append(mModel)
}
if lastCellSubMenuView != nil{
lastCellSubMenuView?.updateTextColor(blueColor)
lastCellSubMenuView?.updateBgColor(UIColor.clearColor())
}
var cell:UICollectionViewCell = collectionView.cellForItemAtIndexPath(indexPath)!
for subMenuView in cell.contentView.subviews{
if (subMenuView.isKindOfClass(SubMenuView.classForCoder()))
{
var subMenu:SubMenuView = subMenuView as! SubMenuView
subMenu.updateTextColor(UIColor.whiteColor())
subMenu.updateBgColor(UIColor(red: 102/255.0, green: 59/255.0, blue: 209/255.0, alpha: 1))
subMenu.layer.insertSublayer(subMenu.bgLayer, atIndex: 0)
lastCellSubMenuView = subMenu
}
}
NSNotificationCenter.defaultCenter().postNotificationName("ListContentNotification", object: methodList)
}
func collectionView(collectionView: UICollectionView, willDisplayCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if (indexPath.row == 0){
for subMenuView in cell.contentView.subviews{
if (subMenuView.isKindOfClass(SubMenuView.classForCoder()))
{
var subMenu:SubMenuView = subMenuView as! SubMenuView
subMenu.updateTextColor(UIColor.whiteColor())
subMenu.updateBgColor(UIColor(red: 102/255.0, green: 59/255.0, blue: 209/255.0, alpha: 1))
subMenu.layer.insertSublayer(subMenu.bgLayer, atIndex: 0)
lastCellSubMenuView = subMenu
}
}
}
}
func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 1
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 1
}
func addMethodSubMenuList(rowIndex:Int){
var pListPath:String?
switch rowIndex{
case MethodTypeList.APPLICATION_PHASE.rawValue:
pListPath = NSBundle.mainBundle().pathForResource("methodStage", ofType: "plist")
case MethodTypeList.DESIGN_REQUIREMENT.rawValue:
pListPath = NSBundle.mainBundle().pathForResource("methodRequirement", ofType: "plist")
case MethodTypeList.RESEARCH_CLASSIFICATION.rawValue:
pListPath = NSBundle.mainBundle().pathForResource("methodCategory", ofType: "plist")
case MethodTypeList.USING_OBJECT.rawValue:
pListPath = NSBundle.mainBundle().pathForResource("methodObject", ofType: "plist")
case MethodTypeList.MAIN_FIELD.rawValue:
pListPath = NSBundle.mainBundle().pathForResource("methodDomain", ofType: "plist")
default:
println("method menu fault")
}
subMenuData = NSMutableArray(contentsOfFile: pListPath!)
println("sub menu data count:\(subMenuData.count)")
collectionView?.reloadData()
}
func addCaseSubMenuList(rowIndex:Int){
var pListPath:String?
switch rowIndex{
case CaseTypeList.TIME_SPECIFIC_YEAR.rawValue:
pListPath = NSBundle.mainBundle().pathForResource("caseStage", ofType: "plist")
case CaseTypeList.DESIGN_REQUIREMENT.rawValue:
pListPath = NSBundle.mainBundle().pathForResource("caseRequirement", ofType: "plist")
case CaseTypeList.RESEARCH_CLASSIFICATION.rawValue:
pListPath = NSBundle.mainBundle().pathForResource("caseCategory", ofType: "plist")
case CaseTypeList.USING_OBJECT.rawValue:
pListPath = NSBundle.mainBundle().pathForResource("caseObject", ofType: "plist")
case CaseTypeList.MAIN_FIELD.rawValue:
pListPath = NSBundle.mainBundle().pathForResource("caseDomain", ofType: "plist")
default:
println("method menu fault")
}
subMenuData = NSMutableArray(contentsOfFile: pListPath!)
println("sub menu data count:\(subMenuData.count)")
lastCellSubMenuView = nil
collectionView?.reloadData()
}
deinit{
NSNotificationCenter.defaultCenter().removeObserver(self, name: "addSubMenuNotification", object: nil)
}
}
| fef15225218f6535bc199cf647013ade | 44.192 | 178 | 0.638609 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/AboutModalController.swift | gpl-2.0 | 1 | //
// AboutModalController.swift
// TelegramMac
//
// Created by keepcoder on 06/12/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
var APP_VERSION_STRING: String {
var vText = "\(Bundle.main.infoDictionary?["CFBundleShortVersionString"] ?? "1").\(Bundle.main.infoDictionary?["CFBundleVersion"] ?? "0")"
#if STABLE
vText += " Stable"
#elseif APP_STORE
vText += " AppStore"
#elseif ALPHA
vText += " Alpha"
#else
vText += " Beta"
#endif
return vText
}
fileprivate class AboutModalView : Control {
fileprivate let copyright:TextView = TextView()
fileprivate let descView:TextView = TextView()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
let formatter = DateFormatter()
formatter.dateFormat = "yyyy"
let copyrightLayout = TextViewLayout(.initialize(string: "Copyright © 2016 - \(formatter.string(from: Date(timeIntervalSinceReferenceDate: Date.timeIntervalSinceReferenceDate))) TELEGRAM MESSENGER", color: theme.colors.grayText, font: .normal(.text)), alignment: .center)
copyrightLayout.measure(width:frameRect.width - 40)
let vText = APP_VERSION_STRING
let attr = NSMutableAttributedString()
_ = attr.append(string: appName, color: theme.colors.text, font: .medium(.header))
_ = attr.append(string: "\n\(vText)", color: theme.colors.link, font: .medium(.text))
attr.addAttribute(.link, value: "copy", range: attr.range)
_ = attr.append(string: "\n\n")
_ = attr.append(string: strings().aboutDescription, color: theme.colors.text, font: .normal(.text))
let descLayout = TextViewLayout(attr, alignment: .center)
descLayout.measure(width:frameRect.width - 40)
descLayout.interactions.copy = {
copyToClipboard(APP_VERSION_STRING)
return true
}
descLayout.interactions.processURL = { _ in
var bp:Int = 0
bp += 1
}
copyright.update(copyrightLayout)
descView.update(descLayout)
copyright.backgroundColor = theme.colors.background
descView.backgroundColor = theme.colors.background
addSubview(copyright)
addSubview(descView)
descView.isSelectable = false
copyright.isSelectable = false
}
fileprivate override func layout() {
super.layout()
descView.centerX(y: 20)
copyright.centerX(y:frame.height - copyright.frame.height - 20)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class AboutModalController: ModalViewController {
override func viewClass() -> AnyClass {
return AboutModalView.self
}
override init() {
super.init(frame: NSMakeRect(0, 0, 300, 190))
bar = .init(height: 0)
}
override func close(animationType: ModalAnimationCloseBehaviour = .common) {
super.close(animationType: animationType)
}
override func viewDidLoad() {
super.viewDidLoad()
genericView.descView.textLayout?.interactions.processURL = { [weak self] url in
if let url = url as? inAppLink {
execute(inapp: url)
} else if let url = url as? String, url == "copy" {
copyToClipboard(APP_VERSION_STRING)
self?.show(toaster: ControllerToaster(text: strings().shareLinkCopied))
return
}
self?.close()
}
readyOnce()
}
private var genericView:AboutModalView {
return self.view as! AboutModalView
}
}
| 74ca332ebc59b5ae83c014cd45cd8b6d | 28.280303 | 279 | 0.603364 | false | false | false | false |
grpc/grpc-swift | refs/heads/main | Tests/GRPCTests/GRPCInteroperabilityTests.swift | apache-2.0 | 1 | /*
* Copyright 2019, gRPC Authors All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import GRPC
import GRPCInteroperabilityTestsImplementation
import NIOCore
import NIOPosix
import XCTest
/// These are the gRPC interoperability tests running on the NIO client and server.
class GRPCInsecureInteroperabilityTests: GRPCTestCase {
var useTLS: Bool { return false }
var serverEventLoopGroup: EventLoopGroup!
var server: Server!
var serverPort: Int!
var clientEventLoopGroup: EventLoopGroup!
var clientConnection: ClientConnection!
override func setUp() {
super.setUp()
self.serverEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
self.server = try! makeInteroperabilityTestServer(
host: "localhost",
port: 0,
eventLoopGroup: self.serverEventLoopGroup!,
serviceProviders: [self.makeProvider()],
useTLS: self.useTLS,
logger: self.serverLogger
).wait()
guard let serverPort = self.server.channel.localAddress?.port else {
XCTFail("Unable to get server port")
return
}
self.serverPort = serverPort
self.clientEventLoopGroup = MultiThreadedEventLoopGroup(numberOfThreads: 1)
}
override func tearDown() {
// This may throw if we shutdown before the channel was ready.
try? self.clientConnection?.close().wait()
XCTAssertNoThrow(try self.clientEventLoopGroup.syncShutdownGracefully())
self.clientConnection = nil
self.clientEventLoopGroup = nil
XCTAssertNoThrow(try self.server.close().wait())
XCTAssertNoThrow(try self.serverEventLoopGroup.syncShutdownGracefully())
self.server = nil
self.serverPort = nil
self.serverEventLoopGroup = nil
super.tearDown()
}
internal func makeProvider() -> CallHandlerProvider {
return TestServiceProvider()
}
private func doRunTest(_ testCase: InteroperabilityTestCase, line: UInt = #line) {
// Does the server support the test?
let implementedFeatures = TestServiceProvider.implementedFeatures
let missingFeatures = testCase.requiredServerFeatures.subtracting(implementedFeatures)
guard missingFeatures.isEmpty else {
print("\(testCase.name) requires features the server does not implement: \(missingFeatures)")
return
}
let test = testCase.makeTest()
let builder = makeInteroperabilityTestClientBuilder(
group: self.clientEventLoopGroup,
useTLS: self.useTLS
).withBackgroundActivityLogger(self.clientLogger)
test.configure(builder: builder)
self.clientConnection = builder.connect(host: "localhost", port: self.serverPort)
XCTAssertNoThrow(try test.run(using: self.clientConnection), line: line)
}
func testEmptyUnary() {
self.doRunTest(.emptyUnary)
}
func testCacheableUnary() {
self.doRunTest(.cacheableUnary)
}
func testLargeUnary() {
self.doRunTest(.largeUnary)
}
func testClientCompressedUnary() {
self.doRunTest(.clientCompressedUnary)
}
func testServerCompressedUnary() {
self.doRunTest(.serverCompressedUnary)
}
func testClientStreaming() {
self.doRunTest(.clientStreaming)
}
func testClientCompressedStreaming() {
self.doRunTest(.clientCompressedStreaming)
}
func testServerStreaming() {
self.doRunTest(.serverStreaming)
}
func testServerCompressedStreaming() {
self.doRunTest(.serverCompressedStreaming)
}
func testPingPong() {
self.doRunTest(.pingPong)
}
func testEmptyStream() {
self.doRunTest(.emptyStream)
}
func testCustomMetadata() {
self.doRunTest(.customMetadata)
}
func testStatusCodeAndMessage() {
self.doRunTest(.statusCodeAndMessage)
}
func testSpecialStatusAndMessage() {
self.doRunTest(.specialStatusMessage)
}
func testUnimplementedMethod() {
self.doRunTest(.unimplementedMethod)
}
func testUnimplementedService() {
self.doRunTest(.unimplementedService)
}
func testCancelAfterBegin() {
self.doRunTest(.cancelAfterBegin)
}
func testCancelAfterFirstResponse() {
self.doRunTest(.cancelAfterFirstResponse)
}
func testTimeoutOnSleepingServer() {
self.doRunTest(.timeoutOnSleepingServer)
}
}
#if canImport(NIOSSL)
class GRPCSecureInteroperabilityTests: GRPCInsecureInteroperabilityTests {
override var useTLS: Bool { return true }
override func testEmptyUnary() {
super.testEmptyUnary()
}
override func testCacheableUnary() {
super.testCacheableUnary()
}
override func testLargeUnary() {
super.testLargeUnary()
}
override func testClientCompressedUnary() {
super.testClientCompressedUnary()
}
override func testServerCompressedUnary() {
super.testServerCompressedUnary()
}
override func testClientStreaming() {
super.testClientStreaming()
}
override func testClientCompressedStreaming() {
super.testClientCompressedStreaming()
}
override func testServerStreaming() {
super.testServerStreaming()
}
override func testServerCompressedStreaming() {
super.testServerCompressedStreaming()
}
override func testPingPong() {
super.testPingPong()
}
override func testEmptyStream() {
super.testEmptyStream()
}
override func testCustomMetadata() {
super.testCustomMetadata()
}
override func testStatusCodeAndMessage() {
super.testStatusCodeAndMessage()
}
override func testSpecialStatusAndMessage() {
super.testSpecialStatusAndMessage()
}
override func testUnimplementedMethod() {
super.testUnimplementedMethod()
}
override func testUnimplementedService() {
super.testUnimplementedService()
}
override func testCancelAfterBegin() {
super.testCancelAfterBegin()
}
override func testCancelAfterFirstResponse() {
super.testCancelAfterFirstResponse()
}
override func testTimeoutOnSleepingServer() {
super.testTimeoutOnSleepingServer()
}
}
#endif // canImport(NIOSSL)
#if compiler(>=5.6)
@available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
class GRPCInsecureInteroperabilityAsyncTests: GRPCInsecureInteroperabilityTests {
override func makeProvider() -> CallHandlerProvider {
return TestServiceAsyncProvider()
}
override func testEmptyStream() {
super.testEmptyStream()
}
override func testPingPong() {
super.testPingPong()
}
override func testEmptyUnary() {
super.testEmptyUnary()
}
override func testTimeoutOnSleepingServer() {
super.testTimeoutOnSleepingServer()
}
override func testCacheableUnary() {
super.testCacheableUnary()
}
override func testLargeUnary() {
super.testLargeUnary()
}
override func testServerCompressedUnary() {
super.testServerCompressedUnary()
}
override func testStatusCodeAndMessage() {
super.testStatusCodeAndMessage()
}
override func testUnimplementedService() {
super.testUnimplementedService()
}
override func testCancelAfterBegin() {
super.testCancelAfterBegin()
}
override func testCustomMetadata() {
super.testCustomMetadata()
}
override func testServerStreaming() {
super.testServerStreaming()
}
override func testClientStreaming() {
super.testClientStreaming()
}
override func testUnimplementedMethod() {
super.testUnimplementedMethod()
}
override func testServerCompressedStreaming() {
super.testServerCompressedStreaming()
}
override func testCancelAfterFirstResponse() {
super.testCancelAfterFirstResponse()
}
override func testSpecialStatusAndMessage() {
super.testSpecialStatusAndMessage()
}
override func testClientCompressedStreaming() {
super.testClientCompressedStreaming()
}
override func testClientCompressedUnary() {
super.testClientCompressedUnary()
}
}
#if canImport(NIOSSL)
@available(macOS 12, iOS 15, tvOS 15, watchOS 8, *)
class GRPCSecureInteroperabilityAsyncTests: GRPCInsecureInteroperabilityAsyncTests {
override var useTLS: Bool { return true }
override func testServerStreaming() {
super.testServerStreaming()
}
override func testLargeUnary() {
super.testLargeUnary()
}
override func testServerCompressedUnary() {
super.testServerCompressedUnary()
}
override func testUnimplementedMethod() {
super.testUnimplementedMethod()
}
override func testServerCompressedStreaming() {
super.testServerCompressedStreaming()
}
override func testCustomMetadata() {
super.testCustomMetadata()
}
override func testCancelAfterBegin() {
super.testCancelAfterBegin()
}
override func testClientStreaming() {
super.testClientStreaming()
}
override func testCacheableUnary() {
super.testCacheableUnary()
}
override func testSpecialStatusAndMessage() {
super.testSpecialStatusAndMessage()
}
override func testTimeoutOnSleepingServer() {
super.testTimeoutOnSleepingServer()
}
override func testClientCompressedUnary() {
super.testClientCompressedUnary()
}
override func testStatusCodeAndMessage() {
super.testStatusCodeAndMessage()
}
override func testCancelAfterFirstResponse() {
super.testCancelAfterFirstResponse()
}
override func testPingPong() {
super.testPingPong()
}
override func testEmptyStream() {
super.testEmptyStream()
}
override func testEmptyUnary() {
super.testEmptyUnary()
}
override func testUnimplementedService() {
super.testUnimplementedService()
}
override func testClientCompressedStreaming() {
super.testClientCompressedStreaming()
}
}
#endif // canImport(NIOSSL)
#endif // compiler(>=5.6)
| 508b8d4733c0896eeb9940a704971ca8 | 22.947743 | 99 | 0.736163 | false | true | false | false |
brentsimmons/Evergreen | refs/heads/ios-candidate | iOS/UIKit Extensions/UIViewController-Extensions.swift | mit | 1 | //
// UIViewController-Extensions.swift
// NetNewsWire-iOS
//
// Created by Maurice Parker on 1/16/20.
// Copyright © 2020 Ranchero Software. All rights reserved.
//
import UIKit
import RSCore
import Account
extension UIViewController {
func presentError(_ error: Error, dismiss: (() -> Void)? = nil) {
if let accountError = error as? AccountError, accountError.isCredentialsError {
presentAccountError(accountError, dismiss: dismiss)
} else if let decodingError = error as? DecodingError {
let errorTitle = NSLocalizedString("Error", comment: "Error")
var informativeText: String = ""
switch decodingError {
case .typeMismatch(let type, _):
let localizedError = NSLocalizedString("This theme cannot be used because the the type—“%@”—is mismatched in the Info.plist", comment: "Type mismatch")
informativeText = NSString.localizedStringWithFormat(localizedError as NSString, type as! CVarArg) as String
presentError(title: errorTitle, message: informativeText, dismiss: dismiss)
case .valueNotFound(let value, _):
let localizedError = NSLocalizedString("This theme cannot be used because the the value—“%@”—is not found in the Info.plist.", comment: "Decoding value missing")
informativeText = NSString.localizedStringWithFormat(localizedError as NSString, value as! CVarArg) as String
presentError(title: errorTitle, message: informativeText, dismiss: dismiss)
case .keyNotFound(let codingKey, _):
let localizedError = NSLocalizedString("This theme cannot be used because the the key—“%@”—is not found in the Info.plist.", comment: "Decoding key missing")
informativeText = NSString.localizedStringWithFormat(localizedError as NSString, codingKey.stringValue) as String
presentError(title: errorTitle, message: informativeText, dismiss: dismiss)
case .dataCorrupted(let context):
guard let error = context.underlyingError as NSError?,
let debugDescription = error.userInfo["NSDebugDescription"] as? String else {
informativeText = error.localizedDescription
presentError(title: errorTitle, message: informativeText, dismiss: dismiss)
return
}
let localizedError = NSLocalizedString("This theme cannot be used because of data corruption in the Info.plist. %@.", comment: "Decoding key missing")
informativeText = NSString.localizedStringWithFormat(localizedError as NSString, debugDescription) as String
presentError(title: errorTitle, message: informativeText, dismiss: dismiss)
default:
informativeText = error.localizedDescription
presentError(title: errorTitle, message: informativeText, dismiss: dismiss)
}
} else {
let errorTitle = NSLocalizedString("Error", comment: "Error")
presentError(title: errorTitle, message: error.localizedDescription, dismiss: dismiss)
}
}
}
private extension UIViewController {
func presentAccountError(_ error: AccountError, dismiss: (() -> Void)? = nil) {
let title = NSLocalizedString("Account Error", comment: "Account Error")
let alertController = UIAlertController(title: title, message: error.localizedDescription, preferredStyle: .alert)
if error.account?.type == .feedbin {
let credentialsTitle = NSLocalizedString("Update Credentials", comment: "Update Credentials")
let credentialsAction = UIAlertAction(title: credentialsTitle, style: .default) { [weak self] _ in
dismiss?()
let navController = UIStoryboard.account.instantiateViewController(withIdentifier: "FeedbinAccountNavigationViewController") as! UINavigationController
navController.modalPresentationStyle = .formSheet
let addViewController = navController.topViewController as! FeedbinAccountViewController
addViewController.account = error.account
self?.present(navController, animated: true)
}
alertController.addAction(credentialsAction)
alertController.preferredAction = credentialsAction
}
let dismissTitle = NSLocalizedString("OK", comment: "OK")
let dismissAction = UIAlertAction(title: dismissTitle, style: .default) { _ in
dismiss?()
}
alertController.addAction(dismissAction)
self.present(alertController, animated: true, completion: nil)
}
}
| a6bbdedec430e312617c99444a8f269e | 45.566667 | 165 | 0.756144 | false | false | false | false |
Olinguito/YoIntervengoiOS | refs/heads/master | Yo Intervengo/Helpers/TabBar/LinkComponent.swift | mit | 1 | //
// LinkComponent.swift
// Yo Intervengo
//
// Created by Jorge Raul Ovalle Zuleta on 2/7/15.
// Copyright (c) 2015 Olinguito. All rights reserved.
//
import UIKit
class LinkComponent: UIView {
var title:UIButton!
var subtitle:UILabel!
var date:UILabel!
var actionPanel:Panel!
var iconLink:UIImageView!
let paddinLeft:CGFloat = 14
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(type:Int, frame:CGRect) {
self.init()
if type == 1{
self.frame = CGRect(x: 0, y: 0, width: frame.width, height: 106)
}
else{
self.frame = CGRect(x: paddinLeft, y: 0, width: 292, height: 72)
self.layer.cornerRadius = 5;
}
self.backgroundColor = UIColor.whiteColor()
iconLink = UIImageView(image: UIImage(named: "Empty"))
iconLink.frame.origin = CGPoint(x: paddinLeft,y: paddinLeft)
self.addSubview(iconLink)
date = UILabel(frame: CGRect(x: paddinLeft + iconLink.frame.maxX, y: 14, width: frame.width, height: 11))
date.text = "Fecha de publicación"
date.font = UIFont(name: "Roboto-Light", size: 10)
date.textColor = UIColor.greyDark()
addSubview(date)
title = UIButton(frame: CGRect(x: paddinLeft + iconLink.frame.maxX, y: date.frame.maxY + 2 , width: frame.width, height: 16))
title.setTitle("Fuente del enlace", forState: UIControlState.Normal)
title.contentHorizontalAlignment = UIControlContentHorizontalAlignment.Left
title.titleLabel?.font = UIFont(name: "Roboto-Regular", size: 16)
title.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
addSubview(title)
subtitle = UILabel(frame: CGRect(x: paddinLeft + iconLink.frame.maxX, y: title.frame.maxY + 2, width: frame.width - ((paddinLeft*2)+iconLink.frame.maxX), height: 13))
subtitle.text = "Descripción del enlace"
subtitle.font = UIFont(name: "Roboto-Italic", size: 12)
subtitle.lineBreakMode = NSLineBreakMode.ByWordWrapping
subtitle.numberOfLines = 1
subtitle.textColor = UIColor.orangeYI()
addSubview(subtitle)
iconLink.center.y = title.center.y
if type == 1 {
actionPanel = Panel(frame: CGRectZero, data: NSMutableArray())
actionPanel.center = CGPoint(x: frame.width/2, y: subtitle.frame.maxY + 20)
addSubview(actionPanel)
var line = UIBezierPath(rect: CGRect(x: 0, y: frame.maxY-1, width: frame.width, height: 0))
var shape = CAShapeLayer(layer: line)
var staticLine = CAShapeLayer()
staticLine.path = line.CGPath
staticLine.strokeColor = UIColor.greyLight().CGColor
self.layer.addSublayer(staticLine)
}
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setAsNew(){
date.textColor = UIColor.greyLight()
title.setTitleColor(UIColor.greyLight(), forState: UIControlState.Normal)
subtitle.textColor = UIColor.greyLight()
setIcon(UIImage(named: "Empty")!)
date.text = "Fecha de publicación"
title.setTitle("Fuente del enlace", forState: UIControlState.Normal)
subtitle.text = "Descripción del enlace"
iconLink.center.y = title.center.y
}
func setDates(dateStr:NSString!){
date.textColor = UIColor.orangeYI()
date.text = dateStr as String!
}
func setIcon(image:UIImage){
if iconLink.isDescendantOfView(self){
iconLink.removeFromSuperview()
}
iconLink = UIImageView(image: image)
iconLink.frame.origin = CGPoint(x: paddinLeft,y: paddinLeft)
addSubview(iconLink)
}
}
| 35b2e7c95ecf65bbe261ada7e0838878 | 34.473214 | 174 | 0.614649 | false | false | false | false |
cc001/learnSwiftBySmallProjects | refs/heads/master | 21-SwipeableCell/SwipeableCell/ViewController.swift | mit | 1 | //
// ViewController.swift
// SwipeableCell
//
// Created by 陈闯 on 2016/12/27.
// Copyright © 2016年 CC. All rights reserved.
//
import UIKit
private let cellIdentifier = "cellID"
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var tableView: UITableView?
var dataArray = [
pattern(image: "1", name: "Pattern Building"),
pattern(image: "2", name: "Joe Beez"),
pattern(image: "3", name: "Car It's car"),
pattern(image: "4", name: "Floral Kaleidoscopic"),
pattern(image: "5", name: "Sprinkle Pattern"),
pattern(image: "6", name: "Palitos de queso"),
pattern(image: "7", name: "Ready to Go? Pattern"),
pattern(image: "8", name: "Sets Seamless"),
]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
tableView = UITableView.init(frame: view.bounds, style: UITableViewStyle.plain)
tableView?.delegate = self
tableView?.dataSource = self
tableView?.rowHeight = 80
tableView?.register(SwipeableCell.self, forCellReuseIdentifier: cellIdentifier)
tableView?.register(UINib.init(nibName: "SwipeableCell", bundle: nil), forCellReuseIdentifier: cellIdentifier)
view.addSubview(tableView!)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as! SwipeableCell
let pattern = dataArray[indexPath.row]
cell.titleImageView?.image = UIImage.init(named: pattern.image)
cell.titleLabel?.text = pattern.name
return cell
}
func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
let delete = UITableViewRowAction(style: .destructive, title: "🗑\nDelete") { (action, index) in
self.dataArray.remove(at: indexPath.row)
tableView.deleteRows(at: [indexPath], with: UITableViewRowAnimation.fade)
}
let share = UITableViewRowAction(style: .normal, title: "🤗\nShare") { (action: UITableViewRowAction!, indexPath: IndexPath) -> Void in
let firstActivitItem = self.dataArray[indexPath.row]
let activityViewController = UIActivityViewController(activityItems: [firstActivitItem.image as NSString], applicationActivities: nil)
self.present(activityViewController, animated: true, completion: nil)
}
let download = UITableViewRowAction(style: .normal, title: "⬇️\nDownload") { (action, index) in
print("Download button tapped")
}
return [share, download, delete]
}
}
| 15c46d430f204e643e11b276e94fbc70 | 25.692982 | 146 | 0.642787 | false | false | false | false |
webim/webim-client-sdk-ios | refs/heads/master | WebimClientLibrary/Backend/FAQClient.swift | mit | 1 | //
// FAQClient.swift
// WebimClientLibrary
//
// Created by Nikita Kaberov on 07.02.19.
// Copyright © 2019 Webim. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
/**
- author:
Nikita Kaberov
- copyright:
2019 Webim
*/
final class FAQClientBuilder {
// MARK: - Properties
private var application: String?
private var baseURL: String?
private var departmentKey: String?
private var language: String?
private var completionHandlerExecutor: ExecIfNotDestroyedFAQHandlerExecutor?
// MARK: - Builder methods
func set(baseURL: String) -> FAQClientBuilder {
self.baseURL = baseURL
return self
}
func set(application: String?) -> FAQClientBuilder {
self.application = application
return self
}
func set(departmentKey: String?) -> FAQClientBuilder {
self.departmentKey = departmentKey
return self
}
func set(language: String?) -> FAQClientBuilder {
self.language = language
return self
}
func set(completionHandlerExecutor: ExecIfNotDestroyedFAQHandlerExecutor?) -> FAQClientBuilder {
self.completionHandlerExecutor = completionHandlerExecutor
return self
}
func build() -> FAQClient {
guard let handler = completionHandlerExecutor else {
WebimInternalLogger.shared.log(entry: "Completion Handler Executor is nil in FAQClient.\(#function)")
fatalError("Completion Handler Executor is nil in FAQClient.\(#function)")
}
let faqRequestLoop = FAQRequestLoop(completionHandlerExecutor: handler)
guard let baseURL = baseURL else {
WebimInternalLogger.shared.log(entry: "Base URL is nil in FAQClient.\(#function)")
fatalError("Base URL is nil in FAQClient.\(#function)")
}
return FAQClient(withFAQRequestLoop: faqRequestLoop,
faqActions: FAQActions(baseURL: baseURL,
faqRequestLoop: faqRequestLoop),
application: application,
departmentKey: departmentKey,
language: language)
}
}
// MARK: -
/**
- author:
Nikita Kaberov
- copyright:
2019 Webim
*/
final class FAQClient {
// MARK: - Properties
private let faqRequestLoop: FAQRequestLoop
private let faqActions: FAQActions
private let application: String?
private let departmentKey: String?
private let language: String?
// MARK: - Initialization
init(withFAQRequestLoop faqRequestLoop: FAQRequestLoop,
faqActions: FAQActions,
application: String?,
departmentKey: String?,
language: String?) {
self.faqRequestLoop = faqRequestLoop
self.faqActions = faqActions
self.application = application
self.departmentKey = departmentKey
self.language = language
}
// MARK: - Methods
func start() {
faqRequestLoop.start()
}
func pause() {
faqRequestLoop.pause()
}
func resume() {
faqRequestLoop.resume()
}
func stop() {
faqRequestLoop.stop()
}
func getActions() -> FAQActions {
return faqActions
}
func getApplication() -> String? {
return application
}
func getDepartmentKey() -> String? {
return departmentKey
}
func getLanguage() -> String? {
return language
}
}
| b00aaf7860d9ee291f20038d05f9e834 | 28.34375 | 113 | 0.637061 | false | false | false | false |
alexhillc/AXPhotoViewer | refs/heads/master | Source/Integrations/SimpleNetworkIntegration.swift | mit | 1 | //
// SimpleNetworkIntegration.swift
// AXPhotoViewer
//
// Created by Alex Hill on 6/11/17.
// Copyright © 2017 Alex Hill. All rights reserved.
//
open class SimpleNetworkIntegration: NSObject, AXNetworkIntegrationProtocol, SimpleNetworkIntegrationURLSessionWrapperDelegate {
fileprivate var urlSessionWrapper = SimpleNetworkIntegrationURLSessionWrapper()
public weak var delegate: AXNetworkIntegrationDelegate?
fileprivate var dataTasks = NSMapTable<AXPhotoProtocol, URLSessionDataTask>(keyOptions: .strongMemory, valueOptions: .strongMemory)
fileprivate var photos = [Int: AXPhotoProtocol]()
public override init() {
super.init()
self.urlSessionWrapper.delegate = self
}
deinit {
self.urlSessionWrapper.invalidate()
}
public func loadPhoto(_ photo: AXPhotoProtocol) {
if photo.imageData != nil || photo.image != nil {
AXDispatchUtils.executeInBackground { [weak self] in
guard let `self` = self else { return }
self.delegate?.networkIntegration(self, loadDidFinishWith: photo)
}
return
}
guard let url = photo.url else { return }
let dataTask = self.urlSessionWrapper.dataTask(with: url)
self.dataTasks.setObject(dataTask, forKey: photo)
self.photos[dataTask.taskIdentifier] = photo
dataTask.resume()
}
public func cancelLoad(for photo: AXPhotoProtocol) {
guard let dataTask = self.dataTasks.object(forKey: photo) else { return }
dataTask.cancel()
}
public func cancelAllLoads() {
let enumerator = self.dataTasks.objectEnumerator()
while let dataTask = enumerator?.nextObject() as? URLSessionDataTask {
dataTask.cancel()
}
self.dataTasks.removeAllObjects()
self.photos.removeAll()
}
// MARK: - SimpleNetworkIntegrationURLSessionWrapperDelegate
fileprivate func urlSessionWrapper(_ urlSessionWrapper: SimpleNetworkIntegrationURLSessionWrapper,
dataTask: URLSessionDataTask,
didUpdateProgress progress: CGFloat) {
guard let photo = self.photos[dataTask.taskIdentifier] else { return }
AXDispatchUtils.executeInBackground { [weak self] in
guard let `self` = self else { return }
self.delegate?.networkIntegration?(self,
didUpdateLoadingProgress: progress,
for: photo)
}
}
fileprivate func urlSessionWrapper(_ urlSessionWrapper: SimpleNetworkIntegrationURLSessionWrapper,
task: URLSessionTask,
didCompleteWithError error: Error?,
object: Any?) {
guard let photo = self.photos[task.taskIdentifier] else { return }
weak var weakSelf = self
func removeDataTask() {
weakSelf?.photos.removeValue(forKey: task.taskIdentifier)
weakSelf?.dataTasks.removeObject(forKey: photo)
}
if let error = error {
removeDataTask()
AXDispatchUtils.executeInBackground { [weak self] in
guard let `self` = self else { return }
self.delegate?.networkIntegration(self, loadDidFailWith: error, for: photo)
}
return
}
guard let data = object as? Data else { return }
if data.containsGIF() {
photo.imageData = data
} else {
photo.image = UIImage(data: data)
}
removeDataTask()
AXDispatchUtils.executeInBackground { [weak self] in
guard let `self` = self else { return }
self.delegate?.networkIntegration(self, loadDidFinishWith: photo)
}
}
}
// This wrapper abstracts the `URLSession` away from `SimpleNetworkIntegration` in order to prevent a retain cycle
// between the `URLSession` and its delegate
fileprivate class SimpleNetworkIntegrationURLSessionWrapper: NSObject, URLSessionDataDelegate, URLSessionTaskDelegate {
weak var delegate: SimpleNetworkIntegrationURLSessionWrapperDelegate?
fileprivate var urlSession: URLSession!
fileprivate var receivedData = [Int: Data]()
fileprivate var receivedContentLength = [Int: Int64]()
override init() {
super.init()
self.urlSession = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
}
func dataTask(with url: URL) -> URLSessionDataTask {
return self.urlSession.dataTask(with: url)
}
func invalidate() {
self.urlSession.invalidateAndCancel()
}
// MARK: - URLSessionDataDelegate
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
self.receivedData[dataTask.taskIdentifier]?.append(data)
guard let receivedData = self.receivedData[dataTask.taskIdentifier],
let expectedContentLength = self.receivedContentLength[dataTask.taskIdentifier] else {
return
}
self.delegate?.urlSessionWrapper(self,
dataTask: dataTask,
didUpdateProgress: CGFloat(receivedData.count) / CGFloat(expectedContentLength))
}
func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Void) {
self.receivedContentLength[dataTask.taskIdentifier] = response.expectedContentLength
self.receivedData[dataTask.taskIdentifier] = Data()
completionHandler(.allow)
}
// MARK: - URLSessionTaskDelegate
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
weak var weakSelf = self
func removeData() {
weakSelf?.receivedData.removeValue(forKey: task.taskIdentifier)
weakSelf?.receivedContentLength.removeValue(forKey: task.taskIdentifier)
}
if let error = error {
self.delegate?.urlSessionWrapper(self, task: task, didCompleteWithError: error, object: nil)
removeData()
return
}
guard let data = self.receivedData[task.taskIdentifier] else {
self.delegate?.urlSessionWrapper(self, task: task, didCompleteWithError: nil, object: nil)
removeData()
return
}
self.delegate?.urlSessionWrapper(self, task: task, didCompleteWithError: nil, object: data)
removeData()
}
}
fileprivate protocol SimpleNetworkIntegrationURLSessionWrapperDelegate: NSObjectProtocol, AnyObject {
func urlSessionWrapper(_ urlSessionWrapper: SimpleNetworkIntegrationURLSessionWrapper,
dataTask: URLSessionDataTask,
didUpdateProgress progress: CGFloat)
func urlSessionWrapper(_ urlSessionWrapper: SimpleNetworkIntegrationURLSessionWrapper,
task: URLSessionTask,
didCompleteWithError error: Error?,
object: Any?)
}
| 7e5067df0a6d06da8e9f9002380c7c96 | 37.891753 | 135 | 0.616832 | false | false | false | false |
wemap/Fusuma | refs/heads/master | Sources/FSAlbumCircleCropView.swift | mit | 1 | //
// FSAlbumCircleCropView.swift
// Fusuma
//
// Created by Ilya Seliverstov on 01/09/2017.
// Copyright © 2017 ytakzk. All rights reserved.
//
import UIKit
final class FSAlbumCircleCropView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.isOpaque = false
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.isOpaque = false
}
override func draw(_ rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
UIColor.black.withAlphaComponent(0.65).setFill()
UIRectFill(rect)
// Draw the circle
let circle = UIBezierPath(ovalIn: CGRect(origin: CGPoint.zero, size: rect.size))
context?.setBlendMode(.clear)
UIColor.clear.setFill()
circle.fill()
}
// Allow touches through the circle crop cutter view
override func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
return subviews
.filter {
$0.isHidden && $0.alpha > 0 && $0.isUserInteractionEnabled && $0.point(inside: convert(point, to: $0), with: event)
}.first != nil
}
}
| 90bd175e0ec4c732ded81a7e1e10c724 | 27.116279 | 131 | 0.606286 | false | false | false | false |
jakarmy/swift-summary | refs/heads/master | The Swift Summary Book.playground/Pages/10 Properties.xcplaygroundpage/Contents.swift | mit | 1 |
// |=------------------------------------------------------=|
// Copyright (c) 2016 Juan Antonio Karmy.
// Licensed under MIT License
//
// See https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/ for Swift Language Reference
//
// See Juan Antonio Karmy - http://karmy.co | http://twitter.com/jkarmy
//
// |=------------------------------------------------------=|
import UIKit
/*
=================================================
Stored Properties of Constant Structure Instances
=================================================
If you create an instance of a structure and assign that instance to a constant, you cannot modify the instance’s properties, even if they were declared as variable properties.
This behavior is due to structures being value types. When an instance of a value type is marked as a constant, so are all of its properties.
The same is not true for classes, which are reference types. If you assign an instance of a reference type to a constant, you can still change that instance’s variable properties.
*/
struct FixedLengthRange {
var firstValue: Int
let length: Int
//These are both stored and computed global variables, or "type" variables. They will apply to all instances of this struct, including their value.
static var storedTypeProperty = "Some value."
static var computedTypeProperty: Int {
// return an Int value here
get {
//This is how type vars are accessed, by calling the class
print(FixedLengthRange.storedTypeProperty)
return self.computedTypeProperty
}
set {
self.computedTypeProperty = newValue
}
}
}
class DataImporter {
/*
DataImporter is a class to import data from an external file.
The class is assumed to take a non-trivial amount of time to initialize.
*/
var fileName = "data.txt"
var cont: ViewController = ViewController()
func doSomething() -> Void {
}
// the DataImporter class would provide data importing functionality here
}
class ViewController: UIViewController {
//This is a "Stored Property". It simply provides a value and the ability to set it back.
var prop = "Hello"
//This is a "Computed Property". Its value is calculated in real-time, and provides getters and setters.
var someCalculation: Int {
get {
return 1 + 1
}
set {
self.someCalculation = newValue
}
}
//This property has observers for when the the value will and did set
var propWithObserver: Int = 0 {
willSet {
print(newValue)
}
didSet {
print(oldValue)
}
//Note that if the didSet sets the value of the property, it doesn't call the setter again
}
//This is a "Computed Property" with just a getter (read-only).
var someFixedCalculatedProperty: Double {
return 3 * 3
}
//This is a type variable for the class ViewController (it'll apply for all instances). It's weirdly declared with the word "class"
class var computedTypeProperty: Int {
// return an Int value here
get {
return 1 + 1
}
set {
self.computedTypeProperty = newValue
}
}
override func viewDidLoad() {
super.viewDidLoad()
var rangeOfFourItems = FixedLengthRange(firstValue: 0, length: 4)
// this range represents integer values 0, 1, 2, and 3
rangeOfFourItems.firstValue = 6
// this will report an error, even though firstValue is a variable property
//Here, importer won't be instantiated until we use it for the first time.
// lazy var importer = DataImporter()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| ff33ae3a59dd1575b78ffe2d94d0fe47 | 31.98374 | 180 | 0.609564 | false | false | false | false |
sanathyml/Swift-Notes | refs/heads/master | Swift-Notes.playground/Pages/19. Protocols.xcplaygroundpage/Contents.swift | mit | 1 | //: # Swift Foundation
//: ----
//: ## Protocols
//: A ***protocol*** defines a blueprint of methods, properties and other functionalities, which can be adopted by a class, structure or enumerations to provide an actual implementation of the requirements.
//: ## Syntax
/*:
protocol SomeProtocol {
//protocol definition
}
//Adopting a protocol.
struct SomeStruct: SomeProtocol {
}
//List superclass name before protocols.
class SomeClass: SuperClass, SomeProtocol, AnotherProtocol {
}
*/
protocol Fuel {
var fuelType: String {get set} //Read-write property
func addFuel() //some method
}
protocol Name {
var name: String {get} //read-only property
var manufacturer: String {get} //read-only property
}
struct Car: Name, Fuel {
let name: String
var manufacturer: String
var fuelType: String
func addFuel() {
//some code.
}
}
//Note that it is mandatory to fulfill all of protocol's requirements
var swiftCar = Car(name: "Swift", manufacturer: "Maruti Suzuki", fuelType: "Diesel")
struct Rocket: Name, Fuel {
let name: String
var manufacturer: String
var fuelType: String
func addFuel() {
//some code.
}
}
var falcon = Rocket(name: "Falcon", manufacturer: "SpaceX", fuelType: "Rocket Fuel")
//: ## 📖
/*:
* Property requirements are always declared as variable properties, prefixed with the var keyword.
* If a protocol requires a property to be gettable and settable, that property requirement cannot be fulfilled by a constant stored property or a read-only computed property.
* If the protocol only requires a property to be gettable, the requirement can be satisfied by any kind of property, and it is valid for the property to be also settable if this is useful for your own code.
*/
falcon.manufacturer = "Telsa"
falcon.manufacturer
//Type property requirements
protocol SomeProtocol {
static var someProperty: Int {get}
}
//: ## 📖
//: Always prefix type property requirements with `static` keyword inside a protocol.
//: ### Mutating method requirements
//: If you define a protocol instance method requirement that is intended to mutate instances of any type that adopts the protocol, mark the method with the mutating keyword as part of the protocol’s definition.
protocol ChangeDirection {
mutating func change()
}
enum Direction: ChangeDirection {
case Forward, Reverse
mutating func change() {
switch self {
case .Forward:
self = .Reverse
case .Reverse :
self = .Forward
}
}
}
var carDirection = Direction.Forward
carDirection.change()
//: ### Initializer requirements
//: You can implement a protocol initializer requirement on a conforming class as either a designated initializer or a convenience initializer. In both cases, you must mark the initializer implementation with the `required` modifier.
protocol AnotherProtocol {
init(name: String)
}
struct SomeStruct: AnotherProtocol {
init(name: String){
}
}
class SomeClass: AnotherProtocol {
required init(name: String) {
}
}
let foo = SomeStruct(name: "Foo")
let bar = SomeClass(name: "Bar")
//: ## 📖
/*:
* `required` ensures that on all subclasses of `SomeClass`, you provide an implementation of the initializer requirement, so the the protocol requirement is fulfilled.
* Therefore, you do not need to mark protocol initializer implementations with the `required` modifier on classes that are marked with the `final` modifier, since `final` classes cannot be subclassed.
*/
//In case the initializer from the superclass matches the initializer from protocol, mark it with both override and required modifiers.
protocol YetAnotherProtocol {
init()
}
class SomeSuperClass {
init() {
// initializer implementation goes here
}
}
class SomeSubClass: SomeSuperClass, YetAnotherProtocol {
// "required" from SomeProtocol conformance; "override" from SomeSuperClass
required override init() {
// initializer implementation goes here
}
}
//: ### Protocols as Types
//: Any protocol is a full-fledged type.
//: ----
//: [Next](@next)
| 06cd8a5e9775103560f963f6b7574255 | 24.572289 | 233 | 0.694935 | false | false | false | false |
VadimPavlov/Swifty | refs/heads/master | Sources/Swifty/ios/Permissions/Notifications.swift | mit | 1 | //
// Notifications.swift
// Swifty
//
// Created by Vadim Pavlov on 8/17/18.
// Copyright © 2018 Vadym Pavlov. All rights reserved.
//
import UserNotifications
public extension Permissions {
@available(iOS 10.0, *)
final class Notifications {
public let status = Observable<UNAuthorizationStatus?>(nil)
private let center = UNUserNotificationCenter.current()
init() {
center.getNotificationSettings { settings in
self.status.value = settings.authorizationStatus
}
}
public func request(options: UNAuthorizationOptions, completion: RequestCompletion? = nil) {
center.requestAuthorization(options: options) { granded, error in
error.map { print($0) }
DispatchQueue.main.async {
self.status.value = granded ? .authorized : .denied
completion?()
}
}
}
}
}
| 0ad1bbeff91f3e56ebd72a8ee6e642b9 | 27.647059 | 100 | 0.589322 | false | false | false | false |
Fidetro/SwiftFFDB | refs/heads/master | Sources/FFDBManager.swift | apache-2.0 | 1 | //
// FFDBManager.swift
// Swift-FFDB
//
// Created by Fidetro on 2017/9/12.
// Copyright © 2017年 Fidetro. All rights reserved.
//
import FMDB
public struct FFDBManager {}
// MARK: - Insert
extension FFDBManager {
/// insert object
///
/// ````
/// let john = Person.init(primaryID: nil, name: "john", age: 10, address: "China")
///
/// FFDBManager.insert(john) // primaryID = 1,name = "john",age = 10,address = "China"
///
/// FFDBManager.insert(john,["name","age"]) // primaryID = 1,name = "john",age = 10
/// ````
/// - Parameters:
/// - object: object
/// - columns: column name
/// - db: set database when use SafeOperation or Transaction,it should be alway nil
/// - Returns: result
/// - Throws: FMDB error
@discardableResult
public static func insert(_ object:FFObject,
_ columns:[String]? = nil,
database db:FMDatabase? = nil) throws -> Bool {
var _result = false
var values = Array<Any>()
for key in columns ?? object.subType.columnsOfSelf() {
values.append(object.valueNotNullFrom(key))
}
try Insert()
.into(object.subType)
.columns(columns ?? object.subType.columnsOfSelf())
.values(values.count)
.executeDBUpdate(db: db,values: values, completion: { (result) in
_result = result
})
return _result
}
/// insert value in table
///
/// - Parameters:
/// - table: FFObject.Type
/// - columns: insert columns
/// - values: the value of column
/// - db: set database when use SafeOperation or Transaction,it should be alway nil
/// - Returns: result
/// - Throws: FMDB error
@discardableResult
public static func insert(_ table:FFObject.Type,
_ columns:[String],
values:[Any],
database db:FMDatabase? = nil) throws -> Bool {
var _result = false
try Insert()
.into(table)
.columns(columns)
.values(columns.count)
.executeDBUpdate(db: db, values: values, completion: { (result) in
_result = result
})
return _result
}
}
// MARK: - Select
extension FFDBManager {
/// select column from table
///
/// - Parameters:
/// - table: table of FFObject.Type
/// - columns: select columns,if columns is nil,return table all columns
/// - condition: for example, "age > ? and address = ? "
/// - values: use params query
/// - type: The type of reception
/// - db: set database when use SafeOperation or Transaction,it should be alway nil
/// - Returns: return select objects
/// - Throws: FMDB error
public static func select<T:FFObject,U:Decodable>(_ table:T.Type,
_ columns:[String]? = nil,
where condition:String? = nil,
values:[Any]? = nil,
order orderConditions:[(column:String,orderByType:OrderByType)]?=nil,
limit :String?=nil,
return type:U.Type,
database db:FMDatabase? = nil) throws -> [Decodable]? {
var _result : [Decodable]?
guard let orderConditions = orderConditions else {
if let format = condition {
if let col = columns {
try Select(col)
.from(table)
.where(format)
.limit(limit)
.executeDBQuery(db: db, return: type, values: values, completion: { (result) in
_result = result
})
}else{
try Select("*")
.from(table)
.where(format)
.limit(limit)
.executeDBQuery(db: db, return: type, values: values, completion: { (result) in
_result = result
})
}
}else{
if let col = columns {
try Select(col)
.from(table)
.limit(limit)
.executeDBQuery(db: db, return: type, values: values, completion: { (result) in
_result = result
})
}else{
try Select("*")
.from(table)
.limit(limit)
.executeDBQuery(db: db, return: type, values: values, completion: { (result) in
_result = result
})
}
}
return _result
}
if let format = condition {
if let col = columns {
try Select(col)
.from(table)
.where(format)
.orderBy(orderConditions)
.limit(limit)
.executeDBQuery(db: db, return: type, values: values, completion: { (result) in
_result = result
})
}else{
try Select("*")
.from(table)
.where(format)
.orderBy(orderConditions)
.limit(limit)
.executeDBQuery(db: db, return: type, values: values, completion: { (result) in
_result = result
})
}
}else{
if let col = columns {
try Select(col)
.from(table)
.orderBy(orderConditions)
.limit(limit)
.executeDBQuery(db: db, return: type, values: values, completion: { (result) in
_result = result
})
}else{
try Select("*")
.from(table)
.orderBy(orderConditions)
.limit(limit)
.executeDBQuery(db: db, return: type, values: values, completion: { (result) in
_result = result
})
}
}
return _result
}
/// select column from table
///
/// - Parameters:
/// - table: table of FFObject.Type
/// - columns: select columns,if columns is nil,return table all columns
/// - condition: for example, "age > ? and address = ? "
/// - values: use params query
/// - db: set database when use SafeOperation or Transaction,it should be alway nil
/// - Returns: return select objects
/// - Throws: FMDB error
public static func select<T:FFObject>(_ table:T.Type,
_ columns:[String]? = nil,
where condition:String? = nil,
values:[Any]? = nil,
order orderConditions:[(column:String,orderByType:OrderByType)]?=nil,
limit: String?=nil,
database db:FMDatabase? = nil) throws -> Array<Decodable>? {
return try select(table, columns,
where: condition,
values: values,
order: orderConditions,
limit: limit,
return: table,
database: db)
}
}
// MARK: - Update
extension FFDBManager {
/// update value of the table
///
/// - Parameters:
/// - table: table of FFObject.Type
/// - setFormat: for example,you want to update Person name and age,you can set "name = ?,age = ?"
/// - condition: for example, "age > ? and address = ? "
/// - values: use params query
/// - db: set database when use SafeOperation or Transaction,it should be alway nil
/// - Returns: result
/// - Throws: FMDB error
@discardableResult
public static func update(_ table:FFObject.Type,
set setFormat:String,
where condition:String?,
values:[Any]? = nil,
database db:FMDatabase? = nil) throws -> Bool {
var _result = false
if let condition = condition {
try Update(table)
.set(setFormat)
.where(condition)
.executeDBUpdate(db: db, values: values, completion: { (result) in
_result = result
})
return _result
}else{
try Update(table)
.set(setFormat)
.executeDBUpdate(db: db, values: values, completion: { (result) in
_result = result
})
return _result
}
}
@discardableResult
public static func update(_ table:FFObject.Type,
set setColumns:[String],
where condition:String?,
values:[Any]? = nil,
database db:FMDatabase? = nil) throws -> Bool {
var _result = false
if let condition = condition {
try Update(table)
.set(setColumns)
.where(condition)
.executeDBUpdate(db: db, values: values, completion: { (result) in
_result = result
})
return _result
}else{
try Update(table)
.set(setColumns)
.executeDBUpdate(db: db, values: values, completion: { (result) in
_result = result
})
return _result
}
}
}
// MARK: - Delete
extension FFDBManager {
/// delete row of the table
///
/// - Parameters:
/// - table: table of FFObject.Type
/// - condition: for example, "age > ? and address = ? "
/// - values: use params query
/// - db: set database when use SafeOperation or Transaction,it should be alway nil
/// - Returns: result
/// - Throws: FMDB error
@discardableResult
public static func delete(_ table:FFObject.Type,
where condition:String? = nil,
values:[Any]? = nil,
database db:FMDatabase? = nil) throws -> Bool {
var _result = false
if let format = condition {
try Delete()
.from(table)
.where(format)
.executeDBUpdate(db: db, values: values, completion: { (result) in
_result = result
})
}else{
try Delete()
.from(table)
.executeDBUpdate(db: db, values: values, completion: { (result) in
_result = result
})
}
return _result
}
}
// MARK: - Create
extension FFDBManager {
static func create(_ table:FFObject.Type) -> Bool {
do {
var _result = false
try Create(table).executeDBUpdate(db: nil, values: nil, completion: { (result) in
_result = result
})
return _result
} catch {
debugPrintLog("failed: \(error.localizedDescription)")
return false
}
}
}
// MARK: - SQL excute
extension FFDBManager {
public static func executeDBQuery<T:Decodable>(db: FMDatabase, return type: T.Type, sql: String, values: [Any]?) throws -> [Decodable]? {
var _result : [Decodable]?
try FFDB.share.connection().executeDBQuery(db: db, return: type, sql: sql, values: values, completion: { (result) in
_result = result
})
return _result
}
@discardableResult
public static func executeDBUpdate(db: FMDatabase,sql: String, values: [Any]?) throws -> Bool {
var _result = false
try FFDB.share.connection().executeDBUpdate(db: db, sql: sql, values: values, completion: { (result) in
_result = result
})
return _result
}
}
// MARK: - Alter
extension FFDBManager {
static func alter(_ table:FFObject.Type) -> Bool {
do {
var _result = false
guard let newColumns = FFDB.share.connection().findNewColumns(table) else {
_result = true
return _result
}
for newColumn in newColumns {
try Alter(table).add(column: newColumn, table: table).executeDBUpdate(db: nil, values: nil, completion: { (result) in
_result = result
})
if _result == false {
return _result
}
}
return _result
} catch {
debugPrintLog("failed: \(error.localizedDescription)")
return false
}
}
}
extension FFDBManager {
public static func newUUID() -> String? {
let theUUID = CFUUIDCreate(kCFAllocatorDefault)
let UUID = CFUUIDCreateString(kCFAllocatorDefault, theUUID)
return UUID as String?
}
}
| f595d2d4d6ee63c258e7a6ca353590a4 | 34.847545 | 142 | 0.460895 | false | false | false | false |
stripe/stripe-ios | refs/heads/master | StripeIdentity/StripeIdentity/Source/NativeComponents/Views/BottomAlignedLabel.swift | mit | 1 | //
// BottomAlignedLabel.swift
// StripeIdentity
//
// Created by Mel Ludowise on 4/26/22.
// Copyright © 2022 Stripe, Inc. All rights reserved.
//
import Foundation
import UIKit
final class BottomAlignedLabel: UIView {
struct ViewModel {
let text: String
let minNumberOfLines: Int
let font: UIFont
let textAlignment: NSTextAlignment
let adjustsFontForContentSizeCategory: Bool
init(
text: String,
minNumberOfLines: Int,
font: UIFont,
textAlignment: NSTextAlignment = .center,
adjustsFontForContentSizeCategory: Bool = true
) {
self.text = text
self.minNumberOfLines = minNumberOfLines
self.font = font
self.textAlignment = textAlignment
self.adjustsFontForContentSizeCategory = adjustsFontForContentSizeCategory
}
}
// MARK: - Properties
private let label: UILabel = {
let label = UILabel()
label.numberOfLines = 0
return label
}()
private var labelMaxTopPaddingConstraint = NSLayoutConstraint()
private var minNumberOfLines: Int = 1
// MARK: - Init
init() {
super.init(frame: .zero)
addSubview(label)
installConstraints()
}
convenience init(
from viewModel: ViewModel
) {
self.init()
configure(from: viewModel)
}
required init?(
coder: NSCoder
) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Configure
func configure(from viewModel: ViewModel) {
self.minNumberOfLines = viewModel.minNumberOfLines
label.text = viewModel.text
label.font = viewModel.font
label.textAlignment = viewModel.textAlignment
label.adjustsFontForContentSizeCategory = viewModel.adjustsFontForContentSizeCategory
adjustLabelTopPadding()
}
// MARK: UIView
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
// NOTE: `traitCollectionDidChange` is called off the main thread when the app backgrounds
DispatchQueue.main.async { [weak self] in
self?.adjustLabelTopPadding()
}
}
}
extension BottomAlignedLabel {
fileprivate func installConstraints() {
label.translatesAutoresizingMaskIntoConstraints = false
label.setContentHuggingPriority(.required, for: .vertical)
// The label should be bottom-aligned to the scanningView, leaving enough
// vertical space above the label to display up to
// `Styling.labelMinHeightNumberOfLines` lines of text.
//
// Constrain the bottom of the label >= the top of this view using a
// constant equivalent to the height of `labelMinHeightNumberOfLines` of
// text, taking the label's font into account.
//
// Constrain the top of the label to the top of this view with a lower
// priority constraint so the label will align to the top if its text
// exceeds `labelMinHeightNumberOfLines`.
let labelMinTopPaddingConstraint = label.topAnchor.constraint(equalTo: topAnchor)
labelMinTopPaddingConstraint.priority = .defaultHigh
// This constant is set in adjustLabelTopPadding()
labelMaxTopPaddingConstraint = label.bottomAnchor.constraint(
greaterThanOrEqualTo: topAnchor,
constant: 0
)
NSLayoutConstraint.activate([
labelMinTopPaddingConstraint,
labelMaxTopPaddingConstraint,
label.bottomAnchor.constraint(equalTo: bottomAnchor),
label.trailingAnchor.constraint(equalTo: trailingAnchor),
label.leadingAnchor.constraint(equalTo: leadingAnchor),
])
}
fileprivate func adjustLabelTopPadding() {
guard let font = label.font else { return }
// In case `minNumberOfLines` is <=0, use a min of 1
let minNumberOfLines = max(self.minNumberOfLines, 1)
// Create some text that is the minimum number of lines of text and
// compute its height based on the label's font
let textWithMinLines = " " + Array(repeating: "\n", count: minNumberOfLines - 1).joined()
labelMaxTopPaddingConstraint.constant =
(textWithMinLines as NSString).size(withAttributes: [
.font: font
]).height
}
}
| bed26ffdd42a0c55e6f2e951a7568ec7 | 30.423611 | 98 | 0.649061 | false | false | false | false |
darrinhenein/firefox-ios | refs/heads/master | ThirdParty/SwiftKeychainWrapper/KeychainWrapper.swift | mpl-2.0 | 2 | //
// KeychainWrapper.swift
// KeychainWrapper
//
// Created by Jason Rendel on 9/23/14.
// Copyright (c) 2014 jasonrendel. All rights reserved.
//
import Foundation
let SecMatchLimit: String! = kSecMatchLimit as String
let SecReturnData: String! = kSecReturnData as String
let SecValueData: String! = kSecValueData as String
let SecAttrAccessible: String! = kSecAttrAccessible as String
let SecClass: String! = kSecClass as String
let SecAttrService: String! = kSecAttrService as String
let SecAttrGeneric: String! = kSecAttrGeneric as String
let SecAttrAccount: String! = kSecAttrAccount as String
public class KeychainWrapper {
private struct internalVars {
static var serviceName: String = ""
}
// MARK: Public Properties
/*!
@var serviceName
@abstract Used for the kSecAttrService property to uniquely identify this keychain accessor.
@discussion Service Name will default to the app's bundle identifier if it can
*/
public class var serviceName: String {
get {
if internalVars.serviceName.isEmpty {
internalVars.serviceName = NSBundle.mainBundle().bundleIdentifier ?? "SwiftKeychainWrapper"
}
return internalVars.serviceName
}
set(newServiceName) {
internalVars.serviceName = newServiceName
}
}
// MARK: Public Methods
public class func hasValueForKey(key: String) -> Bool {
var keychainData: NSData? = self.dataForKey(key)
if let data = keychainData {
return true
} else {
return false
}
}
// MARK: Getting Values
public class func stringForKey(keyName: String) -> String? {
var keychainData: NSData? = self.dataForKey(keyName)
var stringValue: String?
if let data = keychainData {
stringValue = NSString(data: data, encoding: NSUTF8StringEncoding) as String?
}
return stringValue
}
public class func objectForKey(keyName: String) -> NSCoding? {
let dataValue: NSData? = self.dataForKey(keyName)
var objectValue: NSCoding?
if let data = dataValue {
objectValue = NSKeyedUnarchiver.unarchiveObjectWithData(data) as NSCoding?
}
return objectValue;
}
public class func dataForKey(keyName: String) -> NSData? {
var keychainQueryDictionary = self.setupKeychainQueryDictionaryForKey(keyName)
// Limit search results to one
keychainQueryDictionary[SecMatchLimit] = kSecMatchLimitOne
// Specify we want NSData/CFData returned
keychainQueryDictionary[SecReturnData] = kCFBooleanTrue
// Use an unsafe mutable pointer to work around a known issue where data retrieval may fail
// for Swift optimized builds.
// See http://stackoverflow.com/a/27721235
var result: AnyObject?
let status = withUnsafeMutablePointer(&result) { SecItemCopyMatching(keychainQueryDictionary, UnsafeMutablePointer($0)) }
if status == errSecSuccess {
return result as NSData?
} else {
return nil
}
}
// MARK: Setting Values
public class func setString(value: String, forKey keyName: String, accessible: Accessible = .WhenUnlocked) -> Bool {
if let data = value.dataUsingEncoding(NSUTF8StringEncoding) {
return self.setData(data, forKey: keyName, accessible: accessible)
} else {
return false
}
}
public class func setObject(value: NSCoding, forKey keyName: String, accessible: Accessible = .WhenUnlocked) -> Bool {
let data = NSKeyedArchiver.archivedDataWithRootObject(value)
return self.setData(data, forKey: keyName, accessible: accessible)
}
public class func setData(value: NSData, forKey keyName: String, accessible: Accessible = .WhenUnlocked) -> Bool {
var keychainQueryDictionary: NSMutableDictionary = self.setupKeychainQueryDictionaryForKey(keyName)
keychainQueryDictionary[SecValueData] = value
// Protect the keychain entry as requested.
keychainQueryDictionary[SecAttrAccessible] = KeychainWrapper.accessible(accessible)
let status: OSStatus = SecItemAdd(keychainQueryDictionary, nil)
if status == errSecSuccess {
return true
} else if status == errSecDuplicateItem {
return self.updateData(value, forKey: keyName, accessible: accessible)
} else {
return false
}
}
// MARK: Removing Values
public class func removeObjectForKey(keyName: String) -> Bool {
let keychainQueryDictionary: NSMutableDictionary = self.setupKeychainQueryDictionaryForKey(keyName)
// Delete
let status: OSStatus = SecItemDelete(keychainQueryDictionary);
if status == errSecSuccess {
return true
} else {
return false
}
}
// MARK: Private Methods
private class func updateData(value: NSData, forKey keyName: String, accessible: Accessible = .WhenUnlocked) -> Bool {
let keychainQueryDictionary: NSMutableDictionary = self.setupKeychainQueryDictionaryForKey(keyName)
var updateDictionary: NSMutableDictionary = [SecValueData:value]
// Protect the keychain entry as requested.
updateDictionary[SecAttrAccessible] = KeychainWrapper.accessible(accessible)
// Update
let status: OSStatus = SecItemUpdate(keychainQueryDictionary, updateDictionary)
if status == errSecSuccess {
return true
} else {
return false
}
}
private class func setupKeychainQueryDictionaryForKey(keyName: String) -> NSMutableDictionary {
// Setup dictionary to access keychain and specify we are using a generic password (rather than a certificate, internet password, etc)
var keychainQueryDictionary: NSMutableDictionary = [SecClass:kSecClassGenericPassword]
// Uniquely identify this keychain accessor
keychainQueryDictionary[SecAttrService] = KeychainWrapper.serviceName
// Uniquely identify the account who will be accessing the keychain
var encodedIdentifier: NSData? = keyName.dataUsingEncoding(NSUTF8StringEncoding)
keychainQueryDictionary[SecAttrGeneric] = encodedIdentifier
keychainQueryDictionary[SecAttrAccount] = encodedIdentifier
return keychainQueryDictionary
}
public enum Accessible: Int {
case WhenUnlocked, AfterFirstUnlock, Always, WhenPasscodeSetThisDeviceOnly,
WhenUnlockedThisDeviceOnly, AfterFirstUnlockThisDeviceOnly, AlwaysThisDeviceOnly
}
private class func accessible(accessible: Accessible) -> CFStringRef {
switch accessible {
case .WhenUnlocked:
return kSecAttrAccessibleWhenUnlocked
case .AfterFirstUnlock:
return kSecAttrAccessibleAfterFirstUnlock
case .Always:
return kSecAttrAccessibleAlways
case .WhenPasscodeSetThisDeviceOnly:
return kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly
case .WhenUnlockedThisDeviceOnly:
return kSecAttrAccessibleWhenUnlockedThisDeviceOnly
case .AfterFirstUnlockThisDeviceOnly:
return kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
case .AlwaysThisDeviceOnly:
return kSecAttrAccessibleAlwaysThisDeviceOnly
}
}
}
| ab90b310e80fd7493a6121b0d02d0bc9 | 35.642157 | 142 | 0.686421 | false | false | false | false |
faimin/ZDOpenSourceDemo | refs/heads/master | ZDOpenSourceSwiftDemo/Pods/ResponseDetective/ResponseDetective/Sources/ConsoleOutputFacility.swift | mit | 1 | //
// ConsoleOutputFacility.swift
//
// Copyright © 2016-2017 Netguru Sp. z o.o. All rights reserved.
// Licensed under the MIT License.
//
import Foundation
/// An output facility which outputs requests, responses and errors to console.
@objc(RDTConsoleOutputFacility) public final class ConsoleOutputFacility: NSObject, OutputFacility {
// MARK: Initializers
/// Initializes the receiver with default print closure.
public convenience override init() {
self.init(printClosure: { print($0) })
}
/// Initializes the receiver.
///
/// - Parameters:
/// - printClosure: The print closure used to output strings into the
/// console.
@objc(initWithPrintBlock:) public init(printClosure: @escaping @convention(block) (String) -> Void) {
self.printClosure = printClosure
}
// MARK: Properties
/// Print closure used to output strings into the console.
private let printClosure: @convention(block) (String) -> Void
// MARK: OutputFacility
/// Prints the request in the following format:
///
/// <0xbadf00d> [REQUEST] POST https://httpbin.org/post
/// ├─ Headers
/// │ Content-Type: application/json
/// │ Content-Length: 14
/// ├─ Body
/// │ {
/// │ "foo": "bar"
/// │ }
///
/// - SeeAlso: OutputFacility.output(requestRepresentation:)
public func output(requestRepresentation request: RequestRepresentation) {
let headers = request.headers.reduce([]) {
$0 + ["\($1.0): \($1.1)"]
}
let body = request.deserializedBody.map {
#if swift(>=3.2)
return $0.split { $0 == "\n" }.map(String.init)
#else
return $0.characters.split { $0 == "\n" }.map(String.init)
#endif
} ?? ["<none>"]
printBoxString(title: "<\(request.identifier)> [REQUEST] \(request.method) \(request.urlString)", sections: [
("Headers", headers),
("Body", body),
])
}
/// Prints the response in the following format:
///
/// <0xbadf00d> [RESPONSE] 200 (NO ERROR) https://httpbin.org/post
/// ├─ Headers
/// │ Content-Type: application/json
/// │ Content-Length: 24
/// ├─ Body
/// │ {
/// │ "args": {},
/// │ "headers": {}
/// │ }
///
/// - SeeAlso: OutputFacility.output(responseRepresentation:)
public func output(responseRepresentation response: ResponseRepresentation) {
let headers = response.headers.reduce([]) {
$0 + ["\($1.0): \($1.1)"]
}
let body = response.deserializedBody.map {
#if swift(>=3.2)
return $0.split { $0 == "\n" }.map(String.init)
#else
return $0.characters.split { $0 == "\n" }.map(String.init)
#endif
} ?? ["<none>"]
printBoxString(title: "<\(response.requestIdentifier)> [RESPONSE] \(response.statusCode) (\(response.statusString.uppercased())) \(response.urlString)", sections: [
("Headers", headers),
("Body", body),
])
}
/// Prints the error in the following format:
///
/// <0xbadf00d> [ERROR] NSURLErrorDomain -1009
/// ├─ User Info
/// │ NSLocalizedDescriptionKey: The device is not connected to the internet.
/// │ NSURLErrorKey: https://httpbin.org/post
///
/// - SeeAlso: OutputFacility.output(errorRepresentation:)
public func output(errorRepresentation error: ErrorRepresentation) {
let userInfo = error.userInfo.reduce([]) {
$0 + ["\($1.0): \($1.1)"]
}
printBoxString(title: "<\(error.requestIdentifier)> [ERROR] \(error.domain) \(error.code)", sections: [
("User Info", userInfo),
])
}
// MARK: Printing boxes
/// Composes a box string in the following format:
///
/// box title
/// ├─ section title
/// │ section
/// │ contents
///
/// - Parameters:
/// - title: The title of the box
/// - sections: A dictionary with section titles as keys and content
/// lines as values.
///
/// - Returns: A composed box string.
private func composeBoxString(title: String, sections: [(String, [String])]) -> String {
return "\(title)\n" + sections.reduce("") {
"\($0) ├─ \($1.0)\n" + $1.1.reduce("") {
"\($0) │ \($1)\n"
}
}
}
/// Composes and prints the box sting in the console.
///
/// - Parameters:
/// - title: The title of the box
/// - sections: A dictionary with section titles as keys and content
/// lines as values.
private func printBoxString(title: String, sections: [(String, [String])]) {
printClosure(composeBoxString(title: title, sections: sections))
}
}
| 7bd71b92aac11dd81f81d72b39149438 | 29.558621 | 166 | 0.616114 | false | false | false | false |
buildasaurs/Buildasaur | refs/heads/master | BuildaGitServer/BitBucket/BitBucketServer.swift | mit | 2 | //
// BitBucketServer.swift
// Buildasaur
//
// Created by Honza Dvorsky on 1/27/16.
// Copyright © 2016 Honza Dvorsky. All rights reserved.
//
import Foundation
import BuildaUtils
import ReactiveCocoa
import Result
class BitBucketServer : GitServer {
let endpoints: BitBucketEndpoints
let cache = InMemoryURLCache()
init(endpoints: BitBucketEndpoints, http: HTTP? = nil) {
self.endpoints = endpoints
super.init(service: .GitHub, http: http)
}
override func authChangedSignal() -> Signal<ProjectAuthenticator?, NoError> {
var res: Signal<ProjectAuthenticator?, NoError>?
self.endpoints.auth.producer.startWithSignal { res = $0.0 }
return res!.observeOn(UIScheduler())
}
}
extension BitBucketServer: SourceServerType {
func createStatusFromState(state: BuildState, description: String?, targetUrl: String?) -> StatusType {
let bbState = BitBucketStatus.BitBucketState.fromBuildState(state)
let key = "Buildasaur"
let url = targetUrl ?? "https://github.com/czechboy0/Buildasaur"
return BitBucketStatus(state: bbState, key: key, name: key, description: description, url: url)
}
func getBranchesOfRepo(repo: String, completion: (branches: [BranchType]?, error: ErrorType?) -> ()) {
//TODO: start returning branches
completion(branches: [], error: nil)
}
func getOpenPullRequests(repo: String, completion: (prs: [PullRequestType]?, error: ErrorType?) -> ()) {
let params = [
"repo": repo
]
self._sendRequestWithMethod(.GET, endpoint: .PullRequests, params: params, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(prs: nil, error: error)
return
}
if let body = body as? [NSDictionary] {
let (result, error): ([BitBucketPullRequest]?, NSError?) = unthrow {
return try BitBucketArray(body)
}
completion(prs: result?.map { $0 as PullRequestType }, error: error)
} else {
completion(prs: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
func getPullRequest(pullRequestNumber: Int, repo: String, completion: (pr: PullRequestType?, error: ErrorType?) -> ()) {
let params = [
"repo": repo,
"pr": pullRequestNumber.description
]
self._sendRequestWithMethod(.GET, endpoint: .PullRequests, params: params, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(pr: nil, error: error)
return
}
if let body = body as? NSDictionary {
let (result, error): (BitBucketPullRequest?, NSError?) = unthrow {
return try BitBucketPullRequest(json: body)
}
completion(pr: result, error: error)
} else {
completion(pr: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
func getRepo(repo: String, completion: (repo: RepoType?, error: ErrorType?) -> ()) {
let params = [
"repo": repo
]
self._sendRequestWithMethod(.GET, endpoint: .Repos, params: params, query: nil, body: nil) {
(response, body, error) -> () in
if error != nil {
completion(repo: nil, error: error)
return
}
if let body = body as? NSDictionary {
let (result, error): (BitBucketRepo?, NSError?) = unthrow {
return try BitBucketRepo(json: body)
}
completion(repo: result, error: error)
} else {
completion(repo: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
func getStatusOfCommit(commit: String, repo: String, completion: (status: StatusType?, error: ErrorType?) -> ()) {
let params = [
"repo": repo,
"sha": commit,
"status_key": "Buildasaur"
]
self._sendRequestWithMethod(.GET, endpoint: .CommitStatuses, params: params, query: nil, body: nil) { (response, body, error) -> () in
if response?.statusCode == 404 {
//no status yet, just pass nil but OK
completion(status: nil, error: nil)
return
}
if error != nil {
completion(status: nil, error: error)
return
}
if let body = body as? NSDictionary {
let (result, error): (BitBucketStatus?, NSError?) = unthrow {
return try BitBucketStatus(json: body)
}
completion(status: result, error: error)
} else {
completion(status: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
func postStatusOfCommit(commit: String, status: StatusType, repo: String, completion: (status: StatusType?, error: ErrorType?) -> ()) {
let params = [
"repo": repo,
"sha": commit
]
let body = (status as! BitBucketStatus).dictionarify()
self._sendRequestWithMethod(.POST, endpoint: .CommitStatuses, params: params, query: nil, body: body) { (response, body, error) -> () in
if error != nil {
completion(status: nil, error: error)
return
}
if let body = body as? NSDictionary {
let (result, error): (BitBucketStatus?, NSError?) = unthrow {
return try BitBucketStatus(json: body)
}
completion(status: result, error: error)
} else {
completion(status: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
func postCommentOnIssue(comment: String, issueNumber: Int, repo: String, completion: (comment: CommentType?, error: ErrorType?) -> ()) {
let params = [
"repo": repo,
"pr": issueNumber.description
]
let body = [
"content": comment
]
self._sendRequestWithMethod(.POST, endpoint: .PullRequestComments, params: params, query: nil, body: body) { (response, body, error) -> () in
if error != nil {
completion(comment: nil, error: error)
return
}
if let body = body as? NSDictionary {
let (result, error): (BitBucketComment?, NSError?) = unthrow {
return try BitBucketComment(json: body)
}
completion(comment: result, error: error)
} else {
completion(comment: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
func getCommentsOfIssue(issueNumber: Int, repo: String, completion: (comments: [CommentType]?, error: ErrorType?) -> ()) {
let params = [
"repo": repo,
"pr": issueNumber.description
]
self._sendRequestWithMethod(.GET, endpoint: .PullRequestComments, params: params, query: nil, body: nil) { (response, body, error) -> () in
if error != nil {
completion(comments: nil, error: error)
return
}
if let body = body as? [NSDictionary] {
let (result, error): ([BitBucketComment]?, NSError?) = unthrow {
return try BitBucketArray(body)
}
completion(comments: result?.map { $0 as CommentType }, error: error)
} else {
completion(comments: nil, error: Error.withInfo("Wrong body \(body)"))
}
}
}
}
extension BitBucketServer {
private func _sendRequest(request: NSMutableURLRequest, isRetry: Bool = false, completion: HTTP.Completion) {
self.http.sendRequest(request) { (response, body, error) -> () in
if let error = error {
completion(response: response, body: body, error: error)
return
}
//error out on special HTTP status codes
let statusCode = response!.statusCode
switch statusCode {
case 401: //unauthorized, use refresh token to get a new access token
//only try to refresh token once
if !isRetry {
self._handle401(request, completion: completion)
}
return
case 400, 402 ... 500:
let message = ((body as? NSDictionary)?["error"] as? NSDictionary)?["message"] as? String ?? (body as? String ?? "Unknown error")
let resultString = "\(statusCode): \(message)"
completion(response: response, body: body, error: Error.withInfo(resultString, internalError: error))
return
default:
break
}
completion(response: response, body: body, error: error)
}
}
private func _handle401(request: NSMutableURLRequest, completion: HTTP.Completion) {
//we need to use the refresh token to request a new access token
//then we need to notify that we updated the secret, so that it can
//be saved by buildasaur
//then we need to set the new access token to this waiting request and
//run it again. if that fails too, we fail for real.
Log.verbose("Got 401, starting a BitBucket refresh token flow...")
//get a new access token
self._refreshAccessToken(request) { error in
if let error = error {
Log.verbose("Failed to get a new access token")
completion(response: nil, body: nil, error: error)
return
}
//we have a new access token, force set the new cred on the original
//request
self.endpoints.setAuthOnRequest(request)
Log.verbose("Successfully refreshed a BitBucket access token")
//retrying the original request
self._sendRequest(request, isRetry: true, completion: completion)
}
}
private func _refreshAccessToken(request: NSMutableURLRequest, completion: (NSError?) -> ()) {
let refreshRequest = self.endpoints.createRefreshTokenRequest()
self.http.sendRequest(refreshRequest) { (response, body, error) -> () in
if let error = error {
completion(error)
return
}
guard response?.statusCode == 200 else {
completion(Error.withInfo("Wrong status code returned, refreshing access token failed"))
return
}
do {
let payload = body as! NSDictionary
let accessToken = try payload.stringForKey("access_token")
let refreshToken = try payload.stringForKey("refresh_token")
let secret = [refreshToken, accessToken].joinWithSeparator(":")
let newAuth = ProjectAuthenticator(service: .BitBucket, username: "GIT", type: .OAuthToken, secret: secret)
self.endpoints.auth.value = newAuth
completion(nil)
} catch {
completion(error as NSError)
}
}
}
private func _sendRequestWithMethod(method: HTTP.Method, endpoint: BitBucketEndpoints.Endpoint, params: [String: String]?, query: [String: String]?, body: NSDictionary?, completion: HTTP.Completion) {
var allParams = [
"method": method.rawValue
]
//merge the two params
if let params = params {
for (key, value) in params {
allParams[key] = value
}
}
do {
let request = try self.endpoints.createRequest(method, endpoint: endpoint, params: allParams, query: query, body: body)
self._sendRequestWithPossiblePagination(request, accumulatedResponseBody: NSArray(), completion: completion)
} catch {
completion(response: nil, body: nil, error: Error.withInfo("Couldn't create Request, error \(error)"))
}
}
private func _sendRequestWithPossiblePagination(request: NSMutableURLRequest, accumulatedResponseBody: NSArray, completion: HTTP.Completion) {
self._sendRequest(request) {
(response, body, error) -> () in
if error != nil {
completion(response: response, body: body, error: error)
return
}
guard let dictBody = body as? NSDictionary else {
completion(response: response, body: body, error: error)
return
}
//pull out the values
guard let arrayBody = dictBody["values"] as? [AnyObject] else {
completion(response: response, body: dictBody, error: error)
return
}
//we do have more, let's fetch it
let newBody = accumulatedResponseBody.arrayByAddingObjectsFromArray(arrayBody)
guard let nextLink = dictBody.optionalStringForKey("next") else {
//is array, but we don't have any more data
completion(response: response, body: newBody, error: error)
return
}
let newRequest = request.mutableCopy() as! NSMutableURLRequest
newRequest.URL = NSURL(string: nextLink)!
self._sendRequestWithPossiblePagination(newRequest, accumulatedResponseBody: newBody, completion: completion)
return
}
}
}
| df741b59bafa96373e88f6111f92e696 | 36.563307 | 204 | 0.530164 | false | false | false | false |
yeziahehe/Gank | refs/heads/master | Pods/Kingfisher/Sources/Image/ImageProcessor.swift | gpl-3.0 | 1 | //
// ImageProcessor.swift
// Kingfisher
//
// Created by Wei Wang on 2016/08/26.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import CoreGraphics
#if canImport(AppKit)
import AppKit
#endif
/// Represents an item which could be processed by an `ImageProcessor`.
///
/// - image: Input image. The processor should provide a way to apply
/// processing on this `image` and return the result image.
/// - data: Input data. The processor should provide a way to apply
/// processing on this `image` and return the result image.
public enum ImageProcessItem {
/// Input image. The processor should provide a way to apply
/// processing on this `image` and return the result image.
case image(Image)
/// Input data. The processor should provide a way to apply
/// processing on this `image` and return the result image.
case data(Data)
}
/// An `ImageProcessor` would be used to convert some downloaded data to an image.
public protocol ImageProcessor {
/// Identifier of the processor. It will be used to identify the processor when
/// caching and retrieving an image. You might want to make sure that processors with
/// same properties/functionality have the same identifiers, so correct processed images
/// could be retrieved with proper key.
///
/// - Note: Do not supply an empty string for a customized processor, which is already reserved by
/// the `DefaultImageProcessor`. It is recommended to use a reverse domain name notation string of
/// your own for the identifier.
var identifier: String { get }
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: The return value should be `nil` if processing failed while converting an input item to image.
/// If `nil` received by the processing caller, an error will be reported and the process flow stops.
/// If the processing flow is not critical for your flow, then when the input item is already an image
/// (`.image` case) and there is any errors in the processing, you could return the input image itself
/// to keep the processing pipeline continuing.
/// - Note: Most processor only supports CG-based images. watchOS is not supported for processors containing
/// a filter, the input image will be returned directly on watchOS.
/// - Note:
/// This method is deprecated. Please implement the version with
/// `KingfisherParsedOptionsInfo` as parameter instead.
@available(*, deprecated,
message: "Deprecated. Implement the method with same name but with `KingfisherParsedOptionsInfo` instead.")
func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image?
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: The parsed options when processing the item.
/// - Returns: The processed image.
///
/// - Note: The return value should be `nil` if processing failed while converting an input item to image.
/// If `nil` received by the processing caller, an error will be reported and the process flow stops.
/// If the processing flow is not critical for your flow, then when the input item is already an image
/// (`.image` case) and there is any errors in the processing, you could return the input image itself
/// to keep the processing pipeline continuing.
/// - Note: Most processor only supports CG-based images. watchOS is not supported for processors containing
/// a filter, the input image will be returned directly on watchOS.
func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image?
}
extension ImageProcessor {
public func process(item: ImageProcessItem, options: KingfisherOptionsInfo) -> Image? {
return process(item: item, options: KingfisherParsedOptionsInfo(options))
}
}
extension ImageProcessor {
/// Appends an `ImageProcessor` to another. The identifier of the new `ImageProcessor`
/// will be "\(self.identifier)|>\(another.identifier)".
///
/// - Parameter another: An `ImageProcessor` you want to append to `self`.
/// - Returns: The new `ImageProcessor` will process the image in the order
/// of the two processors concatenated.
public func append(another: ImageProcessor) -> ImageProcessor {
let newIdentifier = identifier.appending("|>\(another.identifier)")
return GeneralProcessor(identifier: newIdentifier) {
item, options in
if let image = self.process(item: item, options: options) {
return another.process(item: .image(image), options: options)
} else {
return nil
}
}
}
}
func ==(left: ImageProcessor, right: ImageProcessor) -> Bool {
return left.identifier == right.identifier
}
func !=(left: ImageProcessor, right: ImageProcessor) -> Bool {
return !(left == right)
}
typealias ProcessorImp = ((ImageProcessItem, KingfisherParsedOptionsInfo) -> Image?)
struct GeneralProcessor: ImageProcessor {
let identifier: String
let p: ProcessorImp
func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
return p(item, options)
}
}
/// The default processor. It converts the input data to a valid image.
/// Images of .PNG, .JPEG and .GIF format are supported.
/// If an image item is given as `.image` case, `DefaultImageProcessor` will
/// do nothing on it and return the associated image.
public struct DefaultImageProcessor: ImageProcessor {
/// A default `DefaultImageProcessor` could be used across.
public static let `default` = DefaultImageProcessor()
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier = ""
/// Creates a `DefaultImageProcessor`. Use `DefaultImageProcessor.default` to get an instance,
/// if you do not have a good reason to create your own `DefaultImageProcessor`.
public init() {}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
case .data(let data):
return KingfisherWrapper.image(data: data, options: options.imageCreatingOptions)
}
}
}
/// Represents the rect corner setting when processing a round corner image.
public struct RectCorner: OptionSet {
/// Raw value of the rect corner.
public let rawValue: Int
/// Represents the top left corner.
public static let topLeft = RectCorner(rawValue: 1 << 0)
/// Represents the top right corner.
public static let topRight = RectCorner(rawValue: 1 << 1)
/// Represents the bottom left corner.
public static let bottomLeft = RectCorner(rawValue: 1 << 2)
/// Represents the bottom right corner.
public static let bottomRight = RectCorner(rawValue: 1 << 3)
/// Represents all corners.
public static let all: RectCorner = [.topLeft, .topRight, .bottomLeft, .bottomRight]
/// Creates a `RectCorner` option set with a given value.
///
/// - Parameter rawValue: The value represents a certain corner option.
public init(rawValue: Int) {
self.rawValue = rawValue
}
var cornerIdentifier: String {
if self == .all {
return ""
}
return "_corner(\(rawValue))"
}
}
#if !os(macOS)
/// Processor for adding an blend mode to images. Only CG-based images are supported.
public struct BlendImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Blend Mode will be used to blend the input image.
public let blendMode: CGBlendMode
/// Alpha will be used when blend image.
public let alpha: CGFloat
/// Background color of the output image. If `nil`, it will stay transparent.
public let backgroundColor: Color?
/// Creates a `BlendImageProcessor`.
///
/// - Parameters:
/// - blendMode: Blend Mode will be used to blend the input image.
/// - alpha: Alpha will be used when blend image. From 0.0 to 1.0. 1.0 means solid image,
/// 0.0 means transparent image (not visible at all). Default is 1.0.
/// - backgroundColor: Background color to apply for the output image. Default is `nil`.
public init(blendMode: CGBlendMode, alpha: CGFloat = 1.0, backgroundColor: Color? = nil) {
self.blendMode = blendMode
self.alpha = alpha
self.backgroundColor = backgroundColor
var identifier = "com.onevcat.Kingfisher.BlendImageProcessor(\(blendMode.rawValue),\(alpha))"
if let color = backgroundColor {
identifier.append("_\(color.hex)")
}
self.identifier = identifier
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.image(withBlendMode: blendMode, alpha: alpha, backgroundColor: backgroundColor)
case .data:
return (DefaultImageProcessor.default >> self).process(item: item, options: options)
}
}
}
#endif
#if os(macOS)
/// Processor for adding an compositing operation to images. Only CG-based images are supported in macOS.
public struct CompositingImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Compositing operation will be used to the input image.
public let compositingOperation: NSCompositingOperation
/// Alpha will be used when compositing image.
public let alpha: CGFloat
/// Background color of the output image. If `nil`, it will stay transparent.
public let backgroundColor: Color?
/// Creates a `CompositingImageProcessor`
///
/// - Parameters:
/// - compositingOperation: Compositing operation will be used to the input image.
/// - alpha: Alpha will be used when compositing image.
/// From 0.0 to 1.0. 1.0 means solid image, 0.0 means transparent image.
/// Default is 1.0.
/// - backgroundColor: Background color to apply for the output image. Default is `nil`.
public init(compositingOperation: NSCompositingOperation,
alpha: CGFloat = 1.0,
backgroundColor: Color? = nil)
{
self.compositingOperation = compositingOperation
self.alpha = alpha
self.backgroundColor = backgroundColor
var identifier = "com.onevcat.Kingfisher.CompositingImageProcessor(\(compositingOperation.rawValue),\(alpha))"
if let color = backgroundColor {
identifier.append("_\(color.hex)")
}
self.identifier = identifier
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.image(
withCompositingOperation: compositingOperation,
alpha: alpha,
backgroundColor: backgroundColor)
case .data:
return (DefaultImageProcessor.default >> self).process(item: item, options: options)
}
}
}
#endif
/// Processor for making round corner images. Only CG-based images are supported in macOS,
/// if a non-CG image passed in, the processor will do nothing.
///
/// Note: The input image will be rendered with round corner pixels removed. If the image itself does not contain
/// alpha channel (for example, a JPEG image), the processed image will contain an alpha channel in memory in order
/// to show correctly. However, when cached into disk, the image format will be respected and the alpha channel will
/// be removed. That means when you load the processed image from cache again, you will lose transparent corner.
/// You could use `FormatIndicatedCacheSerializer.png` to force Kingfisher to serialize the image to PNG format in this
/// case.
public struct RoundCornerImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Corner radius will be applied in processing.
public let cornerRadius: CGFloat
/// The target corners which will be applied rounding.
public let roundingCorners: RectCorner
/// Target size of output image should be. If `nil`, the image will keep its original size after processing.
public let targetSize: CGSize?
/// Background color of the output image. If `nil`, it will use a transparent background.
public let backgroundColor: Color?
/// Creates a `RoundCornerImageProcessor`.
///
/// - Parameters:
/// - cornerRadius: Corner radius will be applied in processing.
/// - targetSize: Target size of output image should be. If `nil`,
/// the image will keep its original size after processing.
/// Default is `nil`.
/// - corners: The target corners which will be applied rounding. Default is `.all`.
/// - backgroundColor: Background color to apply for the output image. Default is `nil`.
public init(
cornerRadius: CGFloat,
targetSize: CGSize? = nil,
roundingCorners corners: RectCorner = .all,
backgroundColor: Color? = nil)
{
self.cornerRadius = cornerRadius
self.targetSize = targetSize
self.roundingCorners = corners
self.backgroundColor = backgroundColor
self.identifier = {
var identifier = ""
if let size = targetSize {
identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" +
"(\(cornerRadius)_\(size)\(corners.cornerIdentifier))"
} else {
identifier = "com.onevcat.Kingfisher.RoundCornerImageProcessor" +
"(\(cornerRadius)\(corners.cornerIdentifier))"
}
if let backgroundColor = backgroundColor {
identifier += "_\(backgroundColor)"
}
return identifier
}()
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
switch item {
case .image(let image):
let size = targetSize ?? image.kf.size
return image.kf.scaled(to: options.scaleFactor)
.kf.image(
withRoundRadius: cornerRadius,
fit: size,
roundingCorners: roundingCorners,
backgroundColor: backgroundColor)
case .data:
return (DefaultImageProcessor.default >> self).process(item: item, options: options)
}
}
}
/// Represents how a size adjusts itself to fit a target size.
///
/// - none: Not scale the content.
/// - aspectFit: Scales the content to fit the size of the view by maintaining the aspect ratio.
/// - aspectFill: Scales the content to fill the size of the view.
public enum ContentMode {
/// Not scale the content.
case none
/// Scales the content to fit the size of the view by maintaining the aspect ratio.
case aspectFit
/// Scales the content to fill the size of the view.
case aspectFill
}
/// Processor for resizing images.
/// If you need to resize a data represented image to a smaller size, use `DownsamplingImageProcessor`
/// instead, which is more efficient and takes less memory.
public struct ResizingImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// The reference size for resizing operation in point.
public let referenceSize: CGSize
/// Target content mode of output image should be.
/// Default is `.none`.
public let targetContentMode: ContentMode
/// Creates a `ResizingImageProcessor`.
///
/// - Parameters:
/// - referenceSize: The reference size for resizing operation in point.
/// - mode: Target content mode of output image should be.
///
/// - Note:
/// The instance of `ResizingImageProcessor` will follow its `mode` property
/// and try to resizing the input images to fit or fill the `referenceSize`.
/// That means if you are using a `mode` besides of `.none`, you may get an
/// image with its size not be the same as the `referenceSize`.
///
/// **Example**: With input image size: {100, 200},
/// `referenceSize`: {100, 100}, `mode`: `.aspectFit`,
/// you will get an output image with size of {50, 100}, which "fit"s
/// the `referenceSize`.
///
/// If you need an output image exactly to be a specified size, append or use
/// a `CroppingImageProcessor`.
public init(referenceSize: CGSize, mode: ContentMode = .none) {
self.referenceSize = referenceSize
self.targetContentMode = mode
if mode == .none {
self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize))"
} else {
self.identifier = "com.onevcat.Kingfisher.ResizingImageProcessor(\(referenceSize), \(mode))"
}
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.resize(to: referenceSize, for: targetContentMode)
case .data:
return (DefaultImageProcessor.default >> self).process(item: item, options: options)
}
}
}
/// Processor for adding blur effect to images. `Accelerate.framework` is used underhood for
/// a better performance. A simulated Gaussian blur with specified blur radius will be applied.
public struct BlurImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Blur radius for the simulated Gaussian blur.
public let blurRadius: CGFloat
/// Creates a `BlurImageProcessor`
///
/// - parameter blurRadius: Blur radius for the simulated Gaussian blur.
public init(blurRadius: CGFloat) {
self.blurRadius = blurRadius
self.identifier = "com.onevcat.Kingfisher.BlurImageProcessor(\(blurRadius))"
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
switch item {
case .image(let image):
let radius = blurRadius * options.scaleFactor
return image.kf.scaled(to: options.scaleFactor)
.kf.blurred(withRadius: radius)
case .data:
return (DefaultImageProcessor.default >> self).process(item: item, options: options)
}
}
}
/// Processor for adding an overlay to images. Only CG-based images are supported in macOS.
public struct OverlayImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Overlay color will be used to overlay the input image.
public let overlay: Color
/// Fraction will be used when overlay the color to image.
public let fraction: CGFloat
/// Creates an `OverlayImageProcessor`
///
/// - parameter overlay: Overlay color will be used to overlay the input image.
/// - parameter fraction: Fraction will be used when overlay the color to image.
/// From 0.0 to 1.0. 0.0 means solid color, 1.0 means transparent overlay.
public init(overlay: Color, fraction: CGFloat = 0.5) {
self.overlay = overlay
self.fraction = fraction
self.identifier = "com.onevcat.Kingfisher.OverlayImageProcessor(\(overlay.hex)_\(fraction))"
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.overlaying(with: overlay, fraction: fraction)
case .data:
return (DefaultImageProcessor.default >> self).process(item: item, options: options)
}
}
}
/// Processor for tint images with color. Only CG-based images are supported.
public struct TintImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Tint color will be used to tint the input image.
public let tint: Color
/// Creates a `TintImageProcessor`
///
/// - parameter tint: Tint color will be used to tint the input image.
public init(tint: Color) {
self.tint = tint
self.identifier = "com.onevcat.Kingfisher.TintImageProcessor(\(tint.hex))"
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.tinted(with: tint)
case .data:
return (DefaultImageProcessor.default >> self).process(item: item, options: options)
}
}
}
/// Processor for applying some color control to images. Only CG-based images are supported.
/// watchOS is not supported.
public struct ColorControlsProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Brightness changing to image.
public let brightness: CGFloat
/// Contrast changing to image.
public let contrast: CGFloat
/// Saturation changing to image.
public let saturation: CGFloat
/// InputEV changing to image.
public let inputEV: CGFloat
/// Creates a `ColorControlsProcessor`
///
/// - Parameters:
/// - brightness: Brightness changing to image.
/// - contrast: Contrast changing to image.
/// - saturation: Saturation changing to image.
/// - inputEV: InputEV changing to image.
public init(brightness: CGFloat, contrast: CGFloat, saturation: CGFloat, inputEV: CGFloat) {
self.brightness = brightness
self.contrast = contrast
self.saturation = saturation
self.inputEV = inputEV
self.identifier = "com.onevcat.Kingfisher.ColorControlsProcessor(\(brightness)_\(contrast)_\(saturation)_\(inputEV))"
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.adjusted(brightness: brightness, contrast: contrast, saturation: saturation, inputEV: inputEV)
case .data:
return (DefaultImageProcessor.default >> self).process(item: item, options: options)
}
}
}
/// Processor for applying black and white effect to images. Only CG-based images are supported.
/// watchOS is not supported.
public struct BlackWhiteProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier = "com.onevcat.Kingfisher.BlackWhiteProcessor"
/// Creates a `BlackWhiteProcessor`
public init() {}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
return ColorControlsProcessor(brightness: 0.0, contrast: 1.0, saturation: 0.0, inputEV: 0.7)
.process(item: item, options: options)
}
}
/// Processor for cropping an image. Only CG-based images are supported.
/// watchOS is not supported.
public struct CroppingImageProcessor: ImageProcessor {
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Target size of output image should be.
public let size: CGSize
/// Anchor point from which the output size should be calculate.
/// The anchor point is consisted by two values between 0.0 and 1.0.
/// It indicates a related point in current image.
/// See `CroppingImageProcessor.init(size:anchor:)` for more.
public let anchor: CGPoint
/// Creates a `CroppingImageProcessor`.
///
/// - Parameters:
/// - size: Target size of output image should be.
/// - anchor: The anchor point from which the size should be calculated.
/// Default is `CGPoint(x: 0.5, y: 0.5)`, which means the center of input image.
/// - Note:
/// The anchor point is consisted by two values between 0.0 and 1.0.
/// It indicates a related point in current image, eg: (0.0, 0.0) for top-left
/// corner, (0.5, 0.5) for center and (1.0, 1.0) for bottom-right corner.
/// The `size` property of `CroppingImageProcessor` will be used along with
/// `anchor` to calculate a target rectangle in the size of image.
///
/// The target size will be automatically calculated with a reasonable behavior.
/// For example, when you have an image size of `CGSize(width: 100, height: 100)`,
/// and a target size of `CGSize(width: 20, height: 20)`:
/// - with a (0.0, 0.0) anchor (top-left), the crop rect will be `{0, 0, 20, 20}`;
/// - with a (0.5, 0.5) anchor (center), it will be `{40, 40, 20, 20}`
/// - while with a (1.0, 1.0) anchor (bottom-right), it will be `{80, 80, 20, 20}`
public init(size: CGSize, anchor: CGPoint = CGPoint(x: 0.5, y: 0.5)) {
self.size = size
self.anchor = anchor
self.identifier = "com.onevcat.Kingfisher.CroppingImageProcessor(\(size)_\(anchor))"
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.crop(to: size, anchorOn: anchor)
case .data: return (DefaultImageProcessor.default >> self).process(item: item, options: options)
}
}
}
/// Processor for downsampling an image. Compared to `ResizingImageProcessor`, this processor
/// does not render the images to resize. Instead, it downsample the input data directly to an
/// image. It is a more efficient than `ResizingImageProcessor`.
///
/// - Note:
/// Downsampling only happens when this processor used as the first processor in a processing
/// pipeline, when the input `ImageProcessItem` is an `.data` value. If appending to any other
/// processors, it falls back to use the normal rendering resizing behavior.
///
/// Only CG-based images are supported. Animated images (like GIF) is not supported.
public struct DownsamplingImageProcessor: ImageProcessor {
/// Target size of output image should be. It should be smaller than the size of
/// input image. If it is larger, the result image will be the same size of input
/// data without downsampling.
public let size: CGSize
/// Identifier of the processor.
/// - Note: See documentation of `ImageProcessor` protocol for more.
public let identifier: String
/// Creates a `DownsamplingImageProcessor`.
///
/// - Parameter size: The target size of the downsample operation.
public init(size: CGSize) {
self.size = size
self.identifier = "com.onevcat.Kingfisher.DownsamplingImageProcessor(\(size))"
}
/// Processes the input `ImageProcessItem` with this processor.
///
/// - Parameters:
/// - item: Input item which will be processed by `self`.
/// - options: Options when processing the item.
/// - Returns: The processed image.
///
/// - Note: See documentation of `ImageProcessor` protocol for more.
public func process(item: ImageProcessItem, options: KingfisherParsedOptionsInfo) -> Image? {
switch item {
case .image(let image):
return image.kf.scaled(to: options.scaleFactor)
.kf.resize(to: size, for: .none)
case .data(let data):
return KingfisherWrapper.downsampledImage(data: data, to: size, scale: options.scaleFactor)
}
}
}
/// Concatenates two `ImageProcessor`s. `ImageProcessor.append(another:)` is used internally.
///
/// - Parameters:
/// - left: The first processor.
/// - right: The second processor.
/// - Returns: The concatenated processor.
public func >>(left: ImageProcessor, right: ImageProcessor) -> ImageProcessor {
return left.append(another: right)
}
extension Color {
var hex: String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
#if os(macOS)
(usingColorSpace(.sRGB) ?? self).getRed(&r, green: &g, blue: &b, alpha: &a)
#else
getRed(&r, green: &g, blue: &b, alpha: &a)
#endif
let rInt = Int(r * 255) << 24
let gInt = Int(g * 255) << 16
let bInt = Int(b * 255) << 8
let aInt = Int(a * 255)
let rgba = rInt | gInt | bInt | aInt
return String(format:"#%08x", rgba)
}
}
| daaa7ac15e131ca95288315b96d59223 | 40.977381 | 125 | 0.650889 | false | false | false | false |
exyte/Macaw | refs/heads/master | Source/animation/AnimationProducer.swift | mit | 1 | import Foundation
#if os(iOS)
import UIKit
#elseif os(OSX)
import AppKit
#endif
let animationProducer = AnimationProducer()
class AnimationProducer {
var storedAnimations = [Node: BasicAnimation]() // is used to make sure node is in view hierarchy before actually creating the animation
var delayedAnimations = [BasicAnimation: Timer]()
var displayLink: MDisplayLinkProtocol?
struct ContentAnimationDesc {
let animation: ContentsAnimation
let startDate: Date
let finishDate: Date
let completion: (() -> Void)?
}
var contentsAnimations = [ContentAnimationDesc]()
func play(_ animation: BasicAnimation, _ context: AnimationContext, withoutDelay: Bool = false) {
// Delay - launching timer
if animation.delay > 0.0 && !withoutDelay {
let timer = Timer.schedule(delay: animation.delay) { [weak self] _ in
self?.play(animation, context, withoutDelay: true)
_ = self?.delayedAnimations.removeValue(forKey: animation)
animation.delayed = false
}
animation.delayed = true
delayedAnimations[animation] = timer
return
}
// Empty - executing completion
if animation.type == .empty {
executeCompletion(animation)
return
}
// Cycle - attaching "re-add animation" logic
if animation.cycled {
if animation.manualStop {
return
}
let reAdd = EmptyAnimation {
self.play(animation, context)
}
if let nextAnimation = animation.next {
nextAnimation.next = reAdd
} else {
animation.next = reAdd
}
}
// General case
guard let node = animation.node else {
return
}
for observer in node.animationObservers {
observer.processAnimation(animation)
}
switch animation.type {
case .unknown:
return
case .empty:
executeCompletion(animation)
case .sequence:
addAnimationSequence(animation, context)
case .combine:
addCombineAnimation(animation, context)
default:
break
}
guard let macawView = animation.nodeRenderer?.view else {
storedAnimations[node] = animation
return
}
guard let layer = macawView.mLayer else {
return
}
// swiftlint:disable superfluous_disable_command switch_case_alignment
switch animation.type {
case .affineTransformation:
addTransformAnimation(animation, context, sceneLayer: layer, completion: {
if let next = animation.next {
self.play(next, context)
}
})
case .opacity:
addOpacityAnimation(animation, context, sceneLayer: layer, completion: {
if let next = animation.next {
self.play(next, context)
}
})
case .contents:
addContentsAnimation(animation, context) {
if let next = animation.next {
self.play(next, context)
}
}
case .morphing:
addMorphingAnimation(animation, context, sceneLayer: layer) {
if let next = animation.next {
self.play(next, context)
}
}
case .shape:
addShapeAnimation(animation, context, sceneLayer: layer) {
if let next = animation.next {
self.play(next, context)
}
}
case .path:
addPathAnimation(animation, context, sceneLayer: layer) {
if let next = animation.next {
self.play(next, context)
}
}
default:
break
}
// swiftlint:enable superfluous_disable_command switch_case_alignment
}
func removeDelayed(animation: BasicAnimation) {
guard let timer = delayedAnimations[animation] else {
return
}
timer.invalidate()
animation.delayed = false
delayedAnimations.removeValue(forKey: animation)
}
// MARK: - Sequence animation
func addAnimationSequence(_ animationSequence: Animation,
_ context: AnimationContext) {
guard let sequence = animationSequence as? AnimationSequence else {
return
}
// Generating sequence
var sequenceAnimations = [BasicAnimation]()
var cycleAnimations = sequence.animations
if sequence.autoreverses {
cycleAnimations.append(contentsOf: sequence.animations.reversed())
}
if sequence.repeatCount > 0.0001 {
for _ in 0..<Int(sequence.repeatCount) {
sequenceAnimations.append(contentsOf: cycleAnimations)
}
} else {
sequenceAnimations.append(contentsOf: cycleAnimations)
}
// Connecting animations
for i in 0..<(sequenceAnimations.count - 1) {
let animation = sequenceAnimations[i]
animation.next = sequenceAnimations[i + 1]
}
// Completion
if let completion = sequence.completion {
let completionAnimation = EmptyAnimation(completion: completion)
if let next = sequence.next {
completionAnimation.next = next
}
sequenceAnimations.last?.next = completionAnimation
} else {
if let next = sequence.next {
sequenceAnimations.last?.next = next
}
}
// Launching
if let firstAnimation = sequence.animations.first {
self.play(firstAnimation, context)
}
}
// MARK: - Empty Animation
fileprivate func executeCompletion(_ emptyAnimation: BasicAnimation) {
emptyAnimation.completion?()
}
// MARK: - Stored animation
func addStoredAnimations(_ node: Node, _ view: DrawingView) {
addStoredAnimations(node, AnimationContext())
}
func addStoredAnimations(_ node: Node, _ context: AnimationContext) {
if let animation = storedAnimations[node] {
play(animation, context)
storedAnimations.removeValue(forKey: node)
}
guard let group = node as? Group else {
return
}
group.contents.forEach { child in
addStoredAnimations(child, context)
}
}
// MARK: - Contents animation
func addContentsAnimation(_ animation: BasicAnimation, _ context: AnimationContext, completion: @escaping (() -> Void)) {
guard let contentsAnimation = animation as? ContentsAnimation else {
return
}
if animation.autoreverses {
animation.autoreverses = false
play([animation, animation.reverse()].sequence() as! BasicAnimation, context)
return
}
if animation.repeatCount > 0.0001 {
animation.repeatCount = 0.0
var animSequence = [Animation]()
for _ in 0...Int(animation.repeatCount) {
animSequence.append(animation)
}
play(animSequence.sequence() as! BasicAnimation, context)
return
}
let startDate = Date(timeInterval: contentsAnimation.delay, since: Date())
let animationDesc = ContentAnimationDesc(
animation: contentsAnimation,
startDate: Date(),
finishDate: Date(timeInterval: contentsAnimation.duration, since: startDate),
completion: completion
)
contentsAnimations.append(animationDesc)
if displayLink == nil {
displayLink = MDisplayLink()
displayLink?.startUpdates { [weak self] in
DispatchQueue.main.async {
self?.updateContentAnimations(context)
}
}
}
}
func updateContentAnimations(_ context: AnimationContext) {
if contentsAnimations.isEmpty {
displayLink?.invalidate()
displayLink = .none
}
let currentDate = Date()
let count = contentsAnimations.count
for (index, animationDesc) in contentsAnimations.reversed().enumerated() {
let animation = animationDesc.animation
guard let group = animation.node as? Group, let renderer = animation.nodeRenderer else {
continue
}
defer {
renderer.sceneLayer?.setNeedsDisplay()
}
let progress = currentDate.timeIntervalSince(animationDesc.startDate) / animation.duration + animation.pausedProgress
// Completion
if progress >= 1.0 {
// Final update
group.contents = animation.getVFunc()(1.0)
animation.onProgressUpdate?(1.0)
animation.pausedProgress = 0.0
// Finishing animation
if !animation.cycled {
animation.completion?()
}
contentsAnimations.remove(at: count - 1 - index)
renderer.freeLayer()
animationDesc.completion?()
continue
}
let t = animation.easing.progressFor(time: progress)
group.contents = animation.getVFunc()(t)
animation.onProgressUpdate?(progress)
// Manual stop
if animation.manualStop || animation.paused {
defer {
contentsAnimations.remove(at: count - 1 - index)
renderer.freeLayer()
}
if animation.manualStop {
animation.pausedProgress = 0.0
group.contents = animation.getVFunc()(0)
} else if animation.paused {
animation.pausedProgress = progress
}
}
}
}
}
class AnimationContext {
var rootTransform: Transform?
func getLayoutTransform(_ renderer: NodeRenderer?) -> Transform {
if rootTransform == nil {
if let view = renderer?.view {
rootTransform = view.place
}
}
return rootTransform ?? Transform.identity
}
}
| 0dacacaa280c86ba204da79d9442441e | 29.67052 | 140 | 0.555786 | false | false | false | false |
Flinesoft/BartyCrouch | refs/heads/main | Sources/BartyCrouchConfiguration/Options/UpdateOptions/NormalizeOptions.swift | mit | 1 | import BartyCrouchUtility
import Foundation
import Toml
public struct NormalizeOptions {
public let paths: [String]
public let subpathsToIgnore: [String]
public let sourceLocale: String
public let harmonizeWithSource: Bool
public let sortByKeys: Bool
}
extension NormalizeOptions: TomlCodable {
static func make(toml: Toml) throws -> NormalizeOptions {
let update: String = "update"
let normalize: String = "normalize"
return NormalizeOptions(
paths: toml.filePaths(update, normalize, singularKey: "path", pluralKey: "paths"),
subpathsToIgnore: toml.array(update, normalize, "subpathsToIgnore") ?? Constants.defaultSubpathsToIgnore,
sourceLocale: toml.string(update, normalize, "sourceLocale") ?? "en",
harmonizeWithSource: toml.bool(update, normalize, "harmonizeWithSource") ?? true,
sortByKeys: toml.bool(update, normalize, "sortByKeys") ?? true
)
}
func tomlContents() -> String {
var lines: [String] = ["[update.normalize]"]
lines.append("paths = \(paths)")
lines.append("subpathsToIgnore = \(subpathsToIgnore)")
lines.append("sourceLocale = \"\(sourceLocale)\"")
lines.append("harmonizeWithSource = \(harmonizeWithSource)")
lines.append("sortByKeys = \(sortByKeys)")
return lines.joined(separator: "\n")
}
}
| ab20385bdfb90e97c29d80d261496833 | 33.5 | 111 | 0.710145 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.