repo_name
stringlengths 7
91
| path
stringlengths 8
658
| copies
stringclasses 125
values | size
stringlengths 3
6
| content
stringlengths 118
674k
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6.09
99.2
| line_max
int64 17
995
| alpha_frac
float64 0.3
0.9
| ratio
float64 2
9.18
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
mvader/advent-of-code | 2020/03/02.swift | 1 | 745 | import Foundation
func isTree(_ map: [[Character]], x: Int, y: Int) -> Bool {
let row = map[y]
return row[x % row.count] == Character("#")
}
func treesInSlope(_ map: [[Character]], slopeX: Int, slopeY: Int) -> Int {
var (x, y) = (0, 0)
var trees = 0
while y < map.count {
if isTree(map, x: x, y: y) {
trees += 1
}
x += slopeX
y += slopeY
}
return trees
}
let slopes = [
(1, 1),
(3, 1),
(5, 1),
(7, 1),
(1, 2),
]
let map = (try String(contentsOfFile: "./input.txt", encoding: .utf8))
.components(separatedBy: "\n")
.map { s in Array(s) }
let result =
slopes
.map { slope in treesInSlope(map, slopeX: slope.0, slopeY: slope.1) }
.reduce(1) { acc, trees in acc * trees }
print(result)
| mit | 7b7dac0e531aa407783e562fac528909 | 18.102564 | 74 | 0.555705 | 2.709091 | false | false | false | false |
sman591/csh-drink-ios | CSH Drink/HistoryTableViewController.swift | 1 | 3064 | //
// HistoryTableViewController.swift
// CSH Drink
//
// Created by Stuart Olivera on 1/20/15.
// Copyright (c) 2015 Stuart Olivera. All rights reserved.
//
import UIKit
import Alamofire
import SwiftyJSON
class HistoryTableViewController: UITableViewController {
var drops = [Drop]()
var updatedAt = Date()
override func viewDidLoad() {
super.viewDidLoad()
updateHistory()
self.tableView.rowHeight = UITableViewAutomaticDimension
self.tableView.estimatedRowHeight = 55.0
self.refreshControl = UIRefreshControl()
self.refreshControl?.addTarget(self, action: #selector(HistoryTableViewController.refresh(_:)), for: UIControlEvents.valueChanged)
}
override func viewDidAppear(_ animated: Bool) {
let comparison = CurrentUser.sharedInstance.updatedAt.compare(updatedAt)
if comparison == ComparisonResult.orderedDescending
|| comparison == ComparisonResult.orderedSame
|| updatedAt.compare(1.minute.ago!) == ComparisonResult.orderedAscending {
updateHistory()
}
}
func refresh(_ sender: AnyObject) {
updateHistory()
}
func updateHistory() {
var drops = [Drop]()
DrinkAPI.getDrops(completion: { data in
for (_, drop): (String, JSON) in data {
drops.append(Drop(
item_name: drop["item_name"].stringValue,
item_price: drop["current_item_price"].intValue,
machine_name: drop["display_name"].stringValue,
time: drop["time"].stringValue))
}
self.refreshControl?.endRefreshing()
if drops.count > self.drops.count {
self.drops = drops
self.tableView.reloadSections(NSIndexSet(index: 0) as IndexSet, with: .automatic)
}
self.updatedAt = NSDate() as Date
}, failure: { (error, message) in
self.refreshControl?.endRefreshing()
DrinkAPI.genericApiError(self.view.window!.rootViewController!, message: message)
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.drops.count
}
override func tableView(_ tableView: UITableView?, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! DropTableViewCell
let drop = self.drops[(indexPath as NSIndexPath).row]
cell.itemNameLabel.text = drop.item_name
cell.machineNameLabel.text = drop.machine_name
cell.timeLabel.text = drop.relativeTime()
cell.creditsLabel.text = drop.humanPrice()
return cell
}
}
| mit | 81b80b75fb49c92e5a8703b98cc20de6 | 32.304348 | 138 | 0.619125 | 5.14094 | false | false | false | false |
naoty/Timepiece | Sources/DateComponents+Timepiece.swift | 1 | 3615 | //
// DateComponents+Timepiece.swift
// Timepiece
//
// Created by Naoto Kaneko on 10/16/16.
// Copyright © 2016 Naoto Kaneko. All rights reserved.
//
import Foundation
public extension DateComponents {
var ago: Date? {
return Calendar.current.date(byAdding: -self, to: Date())
}
var later: Date? {
return Calendar.current.date(byAdding: self, to: Date())
}
/// Creates inverse `DateComponents`
///
/// - parameter rhs: A `DateComponents`
///
/// - returns: A created inverse `DateComponents`
static prefix func -(rhs: DateComponents) -> DateComponents {
var dateComponents = DateComponents()
if let year = rhs.year {
dateComponents.year = -year
}
if let month = rhs.month {
dateComponents.month = -month
}
if let day = rhs.day {
dateComponents.day = -day
}
if let hour = rhs.hour {
dateComponents.hour = -hour
}
if let minute = rhs.minute {
dateComponents.minute = -minute
}
if let second = rhs.second {
dateComponents.second = -second
}
if let nanosecond = rhs.nanosecond {
dateComponents.nanosecond = -nanosecond
}
return dateComponents
}
/// Creates a instance calculated by the addition of `right` and `left`
///
/// - parameter left: The date components at left side.
/// - parameter right: The date components at right side.
///
/// - returns: Created `DateComponents` instance.
static func + (left: DateComponents, right: DateComponents) -> DateComponents {
var dateComponents = left
if let year = right.year {
dateComponents.year = (dateComponents.year ?? 0) + year
}
if let month = right.month {
dateComponents.month = (dateComponents.month ?? 0) + month
}
if let day = right.day {
dateComponents.day = (dateComponents.day ?? 0) + day
}
if let hour = right.hour {
dateComponents.hour = (dateComponents.hour ?? 0) + hour
}
if let minute = right.minute {
dateComponents.minute = (dateComponents.minute ?? 0) + minute
}
if let second = right.second {
dateComponents.second = (dateComponents.second ?? 0) + second
}
if let nanosecond = right.nanosecond {
dateComponents.nanosecond = (dateComponents.nanosecond ?? 0) + nanosecond
}
return dateComponents
}
/// Creates a instance calculated by the subtraction from `right` to `left`
///
/// - parameter left: The date components at left side.
/// - parameter right: The date components at right side.
///
/// - returns: Created `DateComponents` instance.
static func - (left: DateComponents, right: DateComponents) -> DateComponents {
return left + (-right)
}
/// Creates a `String` instance representing the receiver formatted in given units style.
///
/// - parameter unitsStyle: The units style.
///
/// - returns: The created a `String` instance.
@available(OSX 10.10, *)
func string(in unitsStyle: DateComponentsFormatter.UnitsStyle) -> String? {
let dateComponentsFormatter = DateComponentsFormatter()
dateComponentsFormatter.unitsStyle = unitsStyle
dateComponentsFormatter.allowedUnits = [.year, .month, .weekOfMonth, .day, .hour, .minute, .second]
return dateComponentsFormatter.string(from: self)
}
}
| mit | d80e85073d28451f9aa480ace4ae085a | 28.622951 | 107 | 0.598229 | 4.799469 | false | false | false | false |
icapps/ios_objective_c_workshop | Teacher/General Objective-C example/Pods/Faro/Sources/MockSession.swift | 1 | 3134 | import Foundation
open class MockURLSession: URLSession {
open override func invalidateAndCancel() {
// Do nothing
}
open override func finishTasksAndInvalidate() {
// Do nothing
}
}
open class MockSession: FaroQueueSessionable {
public let session: URLSession
public var data: Data?
public var urlResponse: URLResponse?
public var error: Error?
var completionHandlers = [Int : ((Data?, URLResponse?, Error?) -> ())]()
public init(data: Data? = nil, urlResponse: URLResponse? = nil, error: Error? = nil) {
self.data = data
self.urlResponse = urlResponse
self.error = error
self.session = MockURLSession()
}
open func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> ()) -> URLSessionDataTask {
let task = MockURLSessionTask()
completionHandlers[task.taskIdentifier] = completionHandler
return task
}
open func resume(_ task: URLSessionDataTask) {
let completionHandler = completionHandlers[task.taskIdentifier]
completionHandler?(data, urlResponse, error)
}
}
open class MockAsyncSession: MockSession {
private let delay: DispatchTimeInterval
var tasksToFail: Set<MockURLSessionTask>?
var mockFailedResponse = HTTPURLResponse(url: URL(string: "http://www.google.com")!, statusCode: 401, httpVersion:nil, headerFields: nil)
public init(data: Data? = nil, urlResponse: URLResponse? = nil, error: Error? = nil, delay: DispatchTimeInterval = .nanoseconds(1)) {
self.delay = delay
super.init(data: data, urlResponse: urlResponse, error: error)
}
open override func resume(_ task: URLSessionDataTask) {
let delayTime = DispatchTime.now() + delay
let completionHandler = completionHandlers[task.taskIdentifier]
DispatchQueue.main.asyncAfter(deadline: delayTime) {
(task as! MockURLSessionTask).mockedState = .completed
if let tasksToFail = self.tasksToFail {
if tasksToFail.contains(task as! MockURLSessionTask) {
completionHandler?(self.data, self.mockFailedResponse, self.error)
} else {
completionHandler?(self.data, self.urlResponse, self.error)
}
} else {
completionHandler?(self.data, self.urlResponse, self.error)
}
}
}
}
open class MockURLSessionTask : URLSessionDataTask{
private let uuid: UUID
public override init() {
uuid = UUID()
super.init()
}
override open var taskIdentifier: Int {
get {
return uuid.hashValue
}
}
var mockedState: URLSessionTask.State = .suspended
override open var state: URLSessionTask.State {
get {
return mockedState
}
}
override open func cancel() {
mockedState = .canceling
}
override open func suspend() {
mockedState = .suspended
}
override open func resume() {
mockedState = .running
}
}
| mit | f1582f509de3b9ff34752cc67098b795 | 27.490909 | 141 | 0.631461 | 4.958861 | false | false | false | false |
kostiakoval/Swift-TuplesPower | Tuple-Other.playground/contents.swift | 1 | 865 | // Playground - noun: a place where people can play
import Cocoa
//Default value
func sum4(x: Int, y: Int, maybe: Int = 1) -> Int {
return x + y + maybe
}
sum4(1, 5, maybe: 1)
sum4(1, 5)
let params4 = (1, 5, 1)
let params4_1 = (1, 5, maybe: 1)
sum4(params4) //Fails
sum4(params4_1) //Fails
// Optional
func sum5(x: Int, y: Int, maybe: Int?) -> Int {
return x + y + (maybe ?? 0)
}
let params5 = (1, 5, 3)
let params5_1 = (1, 5, Optional<Int>.None)
sum5(params5) //Fails, 3 is not optional
sum5(params5_1)
struct A {
let c: Int
func sum(x: Int, y: Int) { }
static func sum1(x: Int, y: Int) { }
}
let aParams = (1, y:4)
let a = A(c: 0)
a.sum(aParams)
A.sum1(aParams)
// inline Tuples
a.sum((1, y:1)) // Fails
let aInit = (1)
let aInit1 = (c: 11)
let aInit2 = (It_Works: 10);
let aInit3 = (1, 10);
A(c: aInit)
A(c: aInit2)
A(c: aInit3) //Fails
| mit | dadd5301a49d646660f40ea7fa333d78 | 15.320755 | 51 | 0.59422 | 2.229381 | false | false | false | false |
sopinetchat/SopinetChat-iOS | Pod/Factories/SChatBubbleImageFactory.swift | 1 | 2795 | //
// SChatBubbleImageFactory.swift
// Pods
//
// Created by David Moreno Lora on 20/5/16.
//
//
import Foundation
public class SChatBubbleImageFactory: NSObject
{
// MARK: Properties
var bubbleImage: UIImage?
var capInsets: UIEdgeInsets?
// MARK: Initialization
override convenience public init()
{
self.init(bubbleImage: UIImage.sChatBubbleCompactImage(), capInsets: UIEdgeInsetsZero)
}
public init(bubbleImage: UIImage, capInsets: UIEdgeInsets)
{
super.init()
self.bubbleImage = bubbleImage
if UIEdgeInsetsEqualToEdgeInsets(capInsets, UIEdgeInsetsZero)
{
self.capInsets = sChatCenterPointEdgeInsetsForImageSize(bubbleImage.size)
}
else
{
self.capInsets = capInsets
}
}
// MARK: Public
public func outgoingMessageBubbleImageWithColor(color: UIColor) -> SChatBubbleImage
{
return self.sChatMessagesBubbleImageWithColor(color, flippedForIncoming: false)
}
public func incomingMessageBubbleImageWithColor(color: UIColor) -> SChatBubbleImage
{
return self.sChatMessagesBubbleImageWithColor(color, flippedForIncoming: true)
}
// MARK: Private
func sChatCenterPointEdgeInsetsForImageSize(bubbleImageSize: CGSize) -> UIEdgeInsets
{
let center = CGPointMake(bubbleImageSize.width / 2.0, bubbleImageSize.height / 2.0)
return UIEdgeInsetsMake(center.y, center.x, center.y, center.x)
}
func sChatMessagesBubbleImageWithColor(color: UIColor, flippedForIncoming: Bool) -> SChatBubbleImage
{
var normalBubble = self.bubbleImage!.sChatImageMaskedWithColor(color)
var highlightedImage = self.bubbleImage!.sChatImageMaskedWithColor(color) // TODO: Colorbydarkeringcolorwithvalue()
if flippedForIncoming
{
normalBubble = self.self.sChatHorizontallyFlippedImageFromImage(normalBubble)
highlightedImage = self.sChatHorizontallyFlippedImageFromImage(highlightedImage)
}
normalBubble = self.sChatStretchableImageFromImage(normalBubble, withCapInsets: self.capInsets!)
return SChatBubbleImage(bubbleImage: normalBubble, highlightedImage: highlightedImage)
}
func sChatHorizontallyFlippedImageFromImage(image: UIImage) -> UIImage
{
return UIImage(CGImage: image.CGImage!, scale: image.scale, orientation: UIImageOrientation.UpMirrored)
}
func sChatStretchableImageFromImage(image: UIImage, withCapInsets capInsets: UIEdgeInsets) -> UIImage
{
return image.resizableImageWithCapInsets(capInsets, resizingMode: UIImageResizingMode.Stretch)
}
} | gpl-3.0 | 3a6d902fb8aefe2ae94e85dacabb4938 | 30.41573 | 123 | 0.686941 | 5.137868 | false | false | false | false |
glessard/swift-atomics | Tests/CAtomicsTests/CAtomicsTests.swift | 1 | 39105 | //
// CAtomicsTests.swift
// AtomicsTests
//
// Copyright © 2016-2017 Guillaume Lessard. All rights reserved.
// This file is distributed under the BSD 3-clause license. See LICENSE for details.
//
import XCTest
import CAtomics
public class CAtomicsBasicTests: XCTestCase
{
public func testInt()
{
var i = AtomicInt()
CAtomicsInitialize(&i, 0)
XCTAssertEqual(CAtomicsLoad(&i, .relaxed), 0)
XCTAssertEqual(CAtomicsIsLockFree(&i), true)
#if swift(>=4.0)
let r1 = Int.randomPositive()
let r2 = Int.randomPositive()
let r3 = Int.randomPositive()
#else
let r1 = Int(UInt.randomPositive())
let r2 = Int(UInt.randomPositive())
let r3 = Int(UInt.randomPositive())
#endif
CAtomicsStore(&i, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
var j = CAtomicsExchange(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsAdd(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsSubtract(&i, r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseOr(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r2, .relaxed)
j = CAtomicsBitwiseXor(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseAnd(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, CAtomicsLoad(&i, .relaxed))
j = r1
CAtomicsStore(&i, r1, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&i, &j, r2, .relaxed, .relaxed))
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = r2
CAtomicsStore(&i, r1, .relaxed)
while(!CAtomicsCompareAndExchangeWeak(&i, &j, r3, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&i, .relaxed))
}
public func testUInt()
{
var i = AtomicUInt()
CAtomicsInitialize(&i, 0)
XCTAssertEqual(CAtomicsLoad(&i, .relaxed), 0)
XCTAssertEqual(CAtomicsIsLockFree(&i), true)
#if swift(>=4.0)
let r1 = UInt.randomPositive()
let r2 = UInt.randomPositive()
let r3 = UInt.randomPositive()
#else
let r1 = UInt(UInt.randomPositive())
let r2 = UInt(UInt.randomPositive())
let r3 = UInt(UInt.randomPositive())
#endif
CAtomicsStore(&i, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
var j = CAtomicsExchange(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsAdd(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsSubtract(&i, r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseOr(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r2, .relaxed)
j = CAtomicsBitwiseXor(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseAnd(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, CAtomicsLoad(&i, .relaxed))
j = r1
CAtomicsStore(&i, r1, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&i, &j, r2, .relaxed, .relaxed))
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = r2
CAtomicsStore(&i, r1, .relaxed)
while(!CAtomicsCompareAndExchangeWeak(&i, &j, r3, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&i, .relaxed))
}
public func testInt8()
{
var i = AtomicInt8()
CAtomicsInitialize(&i, 0)
XCTAssertEqual(CAtomicsLoad(&i, .relaxed), 0)
XCTAssertEqual(CAtomicsIsLockFree(&i), true)
#if swift(>=4.0)
let r1 = Int8.randomPositive()
let r2 = Int8.randomPositive()
let r3 = Int8.randomPositive()
#else
let r1 = Int8(truncatingBitPattern: UInt.randomPositive())
let r2 = Int8(truncatingBitPattern: UInt.randomPositive())
let r3 = Int8(truncatingBitPattern: UInt.randomPositive())
#endif
CAtomicsStore(&i, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
var j = CAtomicsExchange(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsAdd(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsSubtract(&i, r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseOr(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r2, .relaxed)
j = CAtomicsBitwiseXor(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseAnd(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, CAtomicsLoad(&i, .relaxed))
j = r1
CAtomicsStore(&i, r1, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&i, &j, r2, .relaxed, .relaxed))
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = r2
CAtomicsStore(&i, r1, .relaxed)
while(!CAtomicsCompareAndExchangeWeak(&i, &j, r3, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&i, .relaxed))
}
public func testUInt8()
{
var i = AtomicUInt8()
CAtomicsInitialize(&i, 0)
XCTAssertEqual(CAtomicsLoad(&i, .relaxed), 0)
XCTAssertEqual(CAtomicsIsLockFree(&i), true)
#if swift(>=4.0)
let r1 = UInt8.randomPositive()
let r2 = UInt8.randomPositive()
let r3 = UInt8.randomPositive()
#else
let r1 = UInt8(truncatingBitPattern: UInt.randomPositive())
let r2 = UInt8(truncatingBitPattern: UInt.randomPositive())
let r3 = UInt8(truncatingBitPattern: UInt.randomPositive())
#endif
CAtomicsStore(&i, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
var j = CAtomicsExchange(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsAdd(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsSubtract(&i, r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseOr(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r2, .relaxed)
j = CAtomicsBitwiseXor(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseAnd(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, CAtomicsLoad(&i, .relaxed))
j = r1
CAtomicsStore(&i, r1, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&i, &j, r2, .relaxed, .relaxed))
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = r2
CAtomicsStore(&i, r1, .relaxed)
while(!CAtomicsCompareAndExchangeWeak(&i, &j, r3, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&i, .relaxed))
}
public func testInt16()
{
var i = AtomicInt16()
CAtomicsInitialize(&i, 0)
XCTAssertEqual(CAtomicsLoad(&i, .relaxed), 0)
XCTAssertEqual(CAtomicsIsLockFree(&i), true)
#if swift(>=4.0)
let r1 = Int16.randomPositive()
let r2 = Int16.randomPositive()
let r3 = Int16.randomPositive()
#else
let r1 = Int16(truncatingBitPattern: UInt.randomPositive())
let r2 = Int16(truncatingBitPattern: UInt.randomPositive())
let r3 = Int16(truncatingBitPattern: UInt.randomPositive())
#endif
CAtomicsStore(&i, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
var j = CAtomicsExchange(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsAdd(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsSubtract(&i, r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseOr(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r2, .relaxed)
j = CAtomicsBitwiseXor(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseAnd(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, CAtomicsLoad(&i, .relaxed))
j = r1
CAtomicsStore(&i, r1, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&i, &j, r2, .relaxed, .relaxed))
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = r2
CAtomicsStore(&i, r1, .relaxed)
while(!CAtomicsCompareAndExchangeWeak(&i, &j, r3, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&i, .relaxed))
}
public func testUInt16()
{
var i = AtomicUInt16()
CAtomicsInitialize(&i, 0)
XCTAssertEqual(CAtomicsLoad(&i, .relaxed), 0)
XCTAssertEqual(CAtomicsIsLockFree(&i), true)
#if swift(>=4.0)
let r1 = UInt16.randomPositive()
let r2 = UInt16.randomPositive()
let r3 = UInt16.randomPositive()
#else
let r1 = UInt16(truncatingBitPattern: UInt.randomPositive())
let r2 = UInt16(truncatingBitPattern: UInt.randomPositive())
let r3 = UInt16(truncatingBitPattern: UInt.randomPositive())
#endif
CAtomicsStore(&i, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
var j = CAtomicsExchange(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsAdd(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsSubtract(&i, r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseOr(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r2, .relaxed)
j = CAtomicsBitwiseXor(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseAnd(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, CAtomicsLoad(&i, .relaxed))
j = r1
CAtomicsStore(&i, r1, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&i, &j, r2, .relaxed, .relaxed))
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = r2
CAtomicsStore(&i, r1, .relaxed)
while(!CAtomicsCompareAndExchangeWeak(&i, &j, r3, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&i, .relaxed))
}
public func testInt32()
{
var i = AtomicInt32()
CAtomicsInitialize(&i, 0)
XCTAssertEqual(CAtomicsLoad(&i, .relaxed), 0)
XCTAssertEqual(CAtomicsIsLockFree(&i), true)
#if swift(>=4.0)
let r1 = Int32.randomPositive()
let r2 = Int32.randomPositive()
let r3 = Int32.randomPositive()
#else
let r1 = Int32(truncatingBitPattern: UInt.randomPositive())
let r2 = Int32(truncatingBitPattern: UInt.randomPositive())
let r3 = Int32(truncatingBitPattern: UInt.randomPositive())
#endif
CAtomicsStore(&i, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
var j = CAtomicsExchange(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsAdd(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsSubtract(&i, r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseOr(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r2, .relaxed)
j = CAtomicsBitwiseXor(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseAnd(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, CAtomicsLoad(&i, .relaxed))
j = r1
CAtomicsStore(&i, r1, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&i, &j, r2, .relaxed, .relaxed))
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = r2
CAtomicsStore(&i, r1, .relaxed)
while(!CAtomicsCompareAndExchangeWeak(&i, &j, r3, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&i, .relaxed))
}
public func testUInt32()
{
var i = AtomicUInt32()
CAtomicsInitialize(&i, 0)
XCTAssertEqual(CAtomicsLoad(&i, .relaxed), 0)
XCTAssertEqual(CAtomicsIsLockFree(&i), true)
#if swift(>=4.0)
let r1 = UInt32.randomPositive()
let r2 = UInt32.randomPositive()
let r3 = UInt32.randomPositive()
#else
let r1 = UInt32(truncatingBitPattern: UInt.randomPositive())
let r2 = UInt32(truncatingBitPattern: UInt.randomPositive())
let r3 = UInt32(truncatingBitPattern: UInt.randomPositive())
#endif
CAtomicsStore(&i, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
var j = CAtomicsExchange(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsAdd(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsSubtract(&i, r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseOr(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r2, .relaxed)
j = CAtomicsBitwiseXor(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseAnd(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, CAtomicsLoad(&i, .relaxed))
j = r1
CAtomicsStore(&i, r1, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&i, &j, r2, .relaxed, .relaxed))
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = r2
CAtomicsStore(&i, r1, .relaxed)
while(!CAtomicsCompareAndExchangeWeak(&i, &j, r3, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&i, .relaxed))
}
public func testInt64()
{
var i = AtomicInt64()
CAtomicsInitialize(&i, 0)
XCTAssertEqual(CAtomicsLoad(&i, .relaxed), 0)
XCTAssertEqual(CAtomicsIsLockFree(&i), true)
#if swift(>=4.0)
let r1 = Int64.randomPositive()
let r2 = Int64.randomPositive()
let r3 = Int64.randomPositive()
#else
let r1 = Int64(UInt.randomPositive())
let r2 = Int64(UInt.randomPositive())
let r3 = Int64(UInt.randomPositive())
#endif
CAtomicsStore(&i, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
var j = CAtomicsExchange(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsAdd(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsSubtract(&i, r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseOr(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r2, .relaxed)
j = CAtomicsBitwiseXor(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseAnd(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, CAtomicsLoad(&i, .relaxed))
j = r1
CAtomicsStore(&i, r1, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&i, &j, r2, .relaxed, .relaxed))
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = r2
CAtomicsStore(&i, r1, .relaxed)
while(!CAtomicsCompareAndExchangeWeak(&i, &j, r3, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&i, .relaxed))
}
public func testUInt64()
{
var i = AtomicUInt64()
CAtomicsInitialize(&i, 0)
XCTAssertEqual(CAtomicsLoad(&i, .relaxed), 0)
XCTAssertEqual(CAtomicsIsLockFree(&i), true)
#if swift(>=4.0)
let r1 = UInt64.randomPositive()
let r2 = UInt64.randomPositive()
let r3 = UInt64.randomPositive()
#else
let r1 = UInt64(UInt.randomPositive())
let r2 = UInt64(UInt.randomPositive())
let r3 = UInt64(UInt.randomPositive())
#endif
CAtomicsStore(&i, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
var j = CAtomicsExchange(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsAdd(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 &+ r2, CAtomicsLoad(&i, .relaxed))
j = CAtomicsSubtract(&i, r2, .relaxed)
XCTAssertEqual(r1 &+ r2, j)
XCTAssertEqual(r1, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseOr(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 | r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r2, .relaxed)
j = CAtomicsBitwiseXor(&i, r1, .relaxed)
XCTAssertEqual(r2, j)
XCTAssertEqual(r1 ^ r2, CAtomicsLoad(&i, .relaxed))
CAtomicsStore(&i, r1, .relaxed)
j = CAtomicsBitwiseAnd(&i, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r1 & r2, CAtomicsLoad(&i, .relaxed))
j = r1
CAtomicsStore(&i, r1, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&i, &j, r2, .relaxed, .relaxed))
XCTAssertEqual(r2, CAtomicsLoad(&i, .relaxed))
j = r2
CAtomicsStore(&i, r1, .relaxed)
while(!CAtomicsCompareAndExchangeWeak(&i, &j, r3, .relaxed, .relaxed)) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&i, .relaxed))
}
public func testBool()
{
var b = AtomicBool()
CAtomicsInitialize(&b, false)
XCTAssertEqual(CAtomicsLoad(&b, .relaxed), false)
XCTAssertEqual(CAtomicsIsLockFree(&b), true)
CAtomicsStore(&b, false, .relaxed)
XCTAssertEqual(CAtomicsLoad(&b, .relaxed), false)
CAtomicsStore(&b, true, .relaxed)
XCTAssertEqual(CAtomicsLoad(&b, .relaxed), true)
CAtomicsStore(&b, false, .relaxed)
CAtomicsOr(&b, true, .relaxed)
XCTAssertEqual(CAtomicsLoad(&b, .relaxed), true)
CAtomicsOr(&b, false, .relaxed)
XCTAssertEqual(CAtomicsLoad(&b, .relaxed), true)
CAtomicsStore(&b, false, .relaxed)
CAtomicsOr(&b, false, .relaxed)
XCTAssertEqual(CAtomicsLoad(&b, .relaxed), false)
CAtomicsOr(&b, true, .relaxed)
XCTAssertEqual(CAtomicsLoad(&b, .relaxed), true)
CAtomicsAnd(&b, false, .relaxed)
XCTAssertEqual(CAtomicsLoad(&b, .relaxed), false)
CAtomicsAnd(&b, true, .relaxed)
XCTAssertEqual(CAtomicsLoad(&b, .relaxed), false)
CAtomicsXor(&b, false, .relaxed)
XCTAssertEqual(CAtomicsLoad(&b, .relaxed), false)
CAtomicsXor(&b, true, .relaxed)
XCTAssertEqual(CAtomicsLoad(&b, .relaxed), true)
let old = CAtomicsExchange(&b, false, .relaxed)
XCTAssertEqual(old, true)
XCTAssertEqual(CAtomicsExchange(&b, true, .relaxed), false)
var current = true
XCTAssertEqual(CAtomicsLoad(&b, .relaxed), current)
CAtomicsCompareAndExchangeStrong(&b, ¤t, false, .relaxed, .relaxed)
XCTAssertEqual(CAtomicsLoad(&b, .relaxed), false)
current = false
XCTAssertEqual(CAtomicsCompareAndExchangeStrong(&b, ¤t, true, .relaxed, .relaxed), true)
while !CAtomicsCompareAndExchangeWeak(&b, ¤t, false, .relaxed, .relaxed) {}
while !CAtomicsCompareAndExchangeWeak(&b, ¤t, true, .relaxed, .relaxed) {}
}
}
extension CAtomicsBasicTests
{
public func testAtomicOptionalRawPointer()
{
let r0 = UnsafeRawPointer(bitPattern: UInt.randomPositive())
let r1 = UnsafeRawPointer(bitPattern: UInt.randomPositive())
let r2 = UnsafeRawPointer(bitPattern: UInt.randomPositive())
let r3 = UnsafeRawPointer(bitPattern: UInt.randomPositive())
var p = AtomicOptionalRawPointer(r3)
XCTAssertEqual(CAtomicsLoad(&p, .relaxed), r3)
XCTAssertEqual(CAtomicsIsLockFree(&p), true)
CAtomicsInitialize(&p, r0)
XCTAssertEqual(r0, CAtomicsLoad(&p, .relaxed))
CAtomicsStore(&p, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&p, .relaxed))
var j = CAtomicsExchange(&p, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&p, .relaxed))
j = r2
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r3, .relaxed, .relaxed))
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
XCTAssertFalse(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = r3
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = CAtomicsLoad(&p, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r1, .relaxed, .relaxed))
while !CAtomicsCompareAndExchangeWeak(&p, &j, r3, .relaxed, .relaxed) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
}
public func testAtomicRawPointer()
{
let r0 = UnsafeRawPointer(bitPattern: UInt.randomPositive())!
let r1 = UnsafeRawPointer(bitPattern: UInt.randomPositive())!
let r2 = UnsafeRawPointer(bitPattern: UInt.randomPositive())!
let r3 = UnsafeRawPointer(bitPattern: UInt.randomPositive())!
var p = AtomicRawPointer(r3)
XCTAssertEqual(CAtomicsLoad(&p, .relaxed), r3)
XCTAssertEqual(CAtomicsIsLockFree(&p), true)
CAtomicsInitialize(&p, r0)
XCTAssertEqual(r0, CAtomicsLoad(&p, .relaxed))
CAtomicsStore(&p, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&p, .relaxed))
var j = CAtomicsExchange(&p, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&p, .relaxed))
j = r2
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r3, .relaxed, .relaxed))
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
XCTAssertFalse(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = r3
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = CAtomicsLoad(&p, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r1, .relaxed, .relaxed))
while !CAtomicsCompareAndExchangeWeak(&p, &j, r3, .relaxed, .relaxed) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
}
public func testAtomicMutableRawPointer()
{
let r0 = UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())!
let r1 = UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())!
let r2 = UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())!
let r3 = UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())!
var p = AtomicMutableRawPointer(r3)
XCTAssertEqual(CAtomicsLoad(&p, .relaxed), r3)
XCTAssertEqual(CAtomicsIsLockFree(&p), true)
CAtomicsInitialize(&p, r0)
XCTAssertEqual(r0, CAtomicsLoad(&p, .relaxed))
CAtomicsStore(&p, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&p, .relaxed))
var j = CAtomicsExchange(&p, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&p, .relaxed))
j = r2
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r3, .relaxed, .relaxed))
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
XCTAssertFalse(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = r3
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = CAtomicsLoad(&p, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r1, .relaxed, .relaxed))
while !CAtomicsCompareAndExchangeWeak(&p, &j, r3, .relaxed, .relaxed) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
}
public func testAtomicOptionalMutableRawPointer()
{
let r0 = UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())
let r1 = UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())
let r2 = UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())
let r3 = UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())
var p = AtomicOptionalMutableRawPointer(r3)
XCTAssertEqual(CAtomicsLoad(&p, .relaxed), r3)
XCTAssertEqual(CAtomicsIsLockFree(&p), true)
CAtomicsInitialize(&p, r0)
XCTAssertEqual(r0, CAtomicsLoad(&p, .relaxed))
CAtomicsStore(&p, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&p, .relaxed))
var j = CAtomicsExchange(&p, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&p, .relaxed))
j = r2
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r3, .relaxed, .relaxed))
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
XCTAssertFalse(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = r3
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = CAtomicsLoad(&p, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r1, .relaxed, .relaxed))
while !CAtomicsCompareAndExchangeWeak(&p, &j, r3, .relaxed, .relaxed) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
}
public func testAtomicOpaquePointer()
{
let r0 = OpaquePointer(bitPattern: UInt.randomPositive())!
let r1 = OpaquePointer(bitPattern: UInt.randomPositive())!
let r2 = OpaquePointer(bitPattern: UInt.randomPositive())!
let r3 = OpaquePointer(bitPattern: UInt.randomPositive())!
var p = AtomicOpaquePointer(r3)
XCTAssertEqual(CAtomicsLoad(&p, .relaxed), r3)
XCTAssertEqual(CAtomicsIsLockFree(&p), true)
CAtomicsInitialize(&p, r0)
XCTAssertEqual(r0, CAtomicsLoad(&p, .relaxed))
CAtomicsStore(&p, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&p, .relaxed))
var j = CAtomicsExchange(&p, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&p, .relaxed))
j = r2
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r3, .relaxed, .relaxed))
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
XCTAssertFalse(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = r3
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = CAtomicsLoad(&p, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r1, .relaxed, .relaxed))
while !CAtomicsCompareAndExchangeWeak(&p, &j, r3, .relaxed, .relaxed) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
}
public func testAtomicOptionalOpaquePointer()
{
let r0 = OpaquePointer(bitPattern: UInt.randomPositive())
let r1 = OpaquePointer(bitPattern: UInt.randomPositive())
let r2 = OpaquePointer(bitPattern: UInt.randomPositive())
let r3 = OpaquePointer(bitPattern: UInt.randomPositive())
var p = AtomicOptionalOpaquePointer(r3)
XCTAssertEqual(CAtomicsLoad(&p, .relaxed), r3)
XCTAssertEqual(CAtomicsIsLockFree(&p), true)
CAtomicsInitialize(&p, r0)
XCTAssertEqual(r0, CAtomicsLoad(&p, .relaxed))
CAtomicsStore(&p, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&p, .relaxed))
var j = CAtomicsExchange(&p, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&p, .relaxed))
j = r2
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r3, .relaxed, .relaxed))
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
XCTAssertFalse(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = r3
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = CAtomicsLoad(&p, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r1, .relaxed, .relaxed))
while !CAtomicsCompareAndExchangeWeak(&p, &j, r3, .relaxed, .relaxed) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
}
public func testFence()
{
CAtomicsThreadFence(.release)
CAtomicsThreadFence(.acquire)
}
}
protocol TaggedPointer: Equatable
{
associatedtype Pointer: Equatable
var ptr: Pointer { get }
var tag: Int { get }
}
extension TaggedPointer
{
static public func ==(lhs: Self, rhs: Self) -> Bool
{
return (lhs.ptr == rhs.ptr) && (lhs.tag == rhs.tag)
}
}
protocol TaggedOptionalPointer: Equatable
{
associatedtype Pointer: Equatable
var ptr: Optional<Pointer> { get }
var tag: Int { get }
}
extension TaggedOptionalPointer
{
static public func ==(lhs: Self, rhs: Self) -> Bool
{
return (lhs.ptr == rhs.ptr) && (lhs.tag == rhs.tag)
}
}
extension TaggedRawPointer: TaggedPointer {}
extension TaggedMutableRawPointer: TaggedPointer {}
extension TaggedOptionalRawPointer: TaggedOptionalPointer {}
extension TaggedOptionalMutableRawPointer: TaggedOptionalPointer {}
extension CAtomicsBasicTests
{
public func testTaggedRawPointer()
{
let r0 = TaggedRawPointer(UnsafeRawPointer(bitPattern: UInt.randomPositive())!, tag: 2)
var r1 = r0
let r2 = TaggedRawPointer(UnsafeRawPointer(bitPattern: UInt.randomPositive())!, tag: 4)
XCTAssertEqual(MemoryLayout<TaggedRawPointer>.size, MemoryLayout<UnsafeRawPointer>.size*2)
XCTAssertEqual(r0, r1)
r1 = r0.incremented()
XCTAssertNotEqual(r0, r1)
XCTAssertEqual(r0.ptr, r1.ptr)
XCTAssertEqual(r0.tag &+ 1, r1.tag)
XCTAssertEqual(r1.tag, 3)
r1 = r0.incremented(with: r2.ptr)
XCTAssertEqual(r0.tag &+ 1, r1.tag)
XCTAssertEqual(r1.ptr, r2.ptr)
XCTAssertNotEqual(r1, r2)
r1.increment()
XCTAssertEqual(r1, r2)
let r3 = r2.incremented()
XCTAssertNotEqual(r2, r3)
XCTAssertEqual(r2.ptr, r3.ptr)
XCTAssertEqual(r2.tag, r3.tag &- 1)
var r4 = r2
r4.tag += 1
XCTAssertEqual(r3, r4)
}
public func testAtomicTaggedRawPointer()
{
let r0 = TaggedRawPointer(UnsafeRawPointer(bitPattern: UInt.randomPositive())!, tag: 0)
let r1 = TaggedRawPointer(UnsafeRawPointer(bitPattern: UInt.randomPositive())!, tag: 1)
let r2 = TaggedRawPointer(UnsafeRawPointer(bitPattern: UInt.randomPositive())!, tag: 2)
let r3 = r2.incremented()
var p = AtomicTaggedRawPointer(r3)
XCTAssertEqual(CAtomicsLoad(&p, .relaxed), r3)
XCTAssertEqual(CAtomicsIsLockFree(&p), true)
CAtomicsInitialize(&p, r0)
XCTAssertEqual(r0, CAtomicsLoad(&p, .relaxed))
CAtomicsStore(&p, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&p, .relaxed))
var j = CAtomicsExchange(&p, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&p, .relaxed))
j = r2
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r3, .relaxed, .relaxed))
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
XCTAssertFalse(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = CAtomicsLoad(&p, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r1, .relaxed, .relaxed))
while !CAtomicsCompareAndExchangeWeak(&p, &j, r3, .relaxed, .relaxed) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
}
public func testTaggedMutableRawPointer()
{
let r0 = TaggedMutableRawPointer(UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())!, tag: 2)
var r1 = r0
let r2 = TaggedMutableRawPointer(UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())!, tag: 4)
XCTAssertEqual(MemoryLayout<TaggedMutableRawPointer>.size, MemoryLayout<UnsafeMutableRawPointer>.size*2)
XCTAssertEqual(r0, r1)
r1 = r0.incremented()
XCTAssertNotEqual(r0, r1)
XCTAssertEqual(r0.ptr, r1.ptr)
XCTAssertEqual(r0.tag &+ 1, r1.tag)
XCTAssertEqual(r1.tag, 3)
r1 = r0.incremented(with: r2.ptr)
XCTAssertEqual(r0.tag &+ 1, r1.tag)
XCTAssertEqual(r1.ptr, r2.ptr)
XCTAssertNotEqual(r1, r2)
r1.increment()
XCTAssertEqual(r1, r2)
let r3 = r2.incremented()
XCTAssertNotEqual(r2, r3)
XCTAssertEqual(r2.ptr, r3.ptr)
XCTAssertEqual(r2.tag, r3.tag &- 1)
var r4 = r2
r4.tag += 1
XCTAssertEqual(r3, r4)
}
public func testAtomicTaggedMutableRawPointer()
{
let r0 = TaggedMutableRawPointer(UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())!, tag: 0)
let r1 = TaggedMutableRawPointer(UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())!, tag: 1)
let r2 = TaggedMutableRawPointer(UnsafeMutableRawPointer(bitPattern: UInt.randomPositive())!, tag: 2)
let r3 = r2.incremented()
var p = AtomicTaggedMutableRawPointer(r3)
XCTAssertEqual(CAtomicsLoad(&p, .relaxed), r3)
XCTAssertEqual(CAtomicsIsLockFree(&p), true)
CAtomicsInitialize(&p, r0)
XCTAssertEqual(r0, CAtomicsLoad(&p, .relaxed))
CAtomicsStore(&p, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&p, .relaxed))
var j = CAtomicsExchange(&p, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&p, .relaxed))
j = r2
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r3, .relaxed, .relaxed))
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
XCTAssertFalse(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = CAtomicsLoad(&p, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r1, .relaxed, .relaxed))
while !CAtomicsCompareAndExchangeWeak(&p, &j, r3, .relaxed, .relaxed) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
}
public func testTaggedOptionalRawPointer()
{
let r0 = TaggedOptionalRawPointer(UnsafeRawPointer(bitPattern: UInt.randomPositive()), tag: 2)
var r1 = r0
let r2 = TaggedOptionalRawPointer(UnsafeRawPointer(bitPattern: UInt.randomPositive()), tag: 4)
XCTAssertEqual(MemoryLayout<TaggedOptionalRawPointer>.size, MemoryLayout<UnsafeRawPointer>.size*2)
XCTAssertEqual(r0, r1)
r1 = r0.incremented()
XCTAssertNotEqual(r0, r1)
XCTAssertEqual(r0.ptr, r1.ptr)
XCTAssertEqual(r0.tag &+ 1, r1.tag)
XCTAssertEqual(r1.tag, 3)
r1 = r0.incremented(with: r2.ptr)
XCTAssertEqual(r0.tag &+ 1, r1.tag)
XCTAssertEqual(r1.ptr, r2.ptr)
XCTAssertNotEqual(r1, r2)
r1.increment()
XCTAssertEqual(r1, r2)
let r3 = r2.incremented()
XCTAssertNotEqual(r2, r3)
XCTAssertEqual(r2.ptr, r3.ptr)
XCTAssertEqual(r2.tag, r3.tag &- 1)
var r4 = r2
r4.tag += 1
XCTAssertEqual(r3, r4)
}
public func testAtomicTaggedOptionalRawPointer()
{
let r0 = TaggedOptionalRawPointer(UnsafeRawPointer(bitPattern: UInt.randomPositive()), tag: 0)
let r1 = TaggedOptionalRawPointer(UnsafeRawPointer(bitPattern: UInt.randomPositive()), tag: 1)
let r2 = TaggedOptionalRawPointer(UnsafeRawPointer(bitPattern: UInt.randomPositive()), tag: 2)
let r3 = r2.incremented()
var p = AtomicTaggedOptionalRawPointer(r3)
XCTAssertEqual(CAtomicsLoad(&p, .relaxed), r3)
XCTAssertEqual(CAtomicsIsLockFree(&p), true)
CAtomicsInitialize(&p, r0)
XCTAssertEqual(r0, CAtomicsLoad(&p, .relaxed))
CAtomicsStore(&p, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&p, .relaxed))
var j = CAtomicsExchange(&p, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&p, .relaxed))
j = r2
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r3, .relaxed, .relaxed))
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
XCTAssertFalse(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = CAtomicsLoad(&p, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r1, .relaxed, .relaxed))
while !CAtomicsCompareAndExchangeWeak(&p, &j, r3, .relaxed, .relaxed) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
}
public func testTaggedOptionalMutableRawPointer()
{
let r0 = TaggedOptionalMutableRawPointer(UnsafeMutableRawPointer(bitPattern: UInt.randomPositive()), tag: 2)
var r1 = r0
let r2 = TaggedOptionalMutableRawPointer(UnsafeMutableRawPointer(bitPattern: UInt.randomPositive()), tag: 4)
XCTAssertEqual(MemoryLayout<TaggedOptionalMutableRawPointer>.size, MemoryLayout<UnsafeMutableRawPointer>.size*2)
XCTAssertEqual(r0, r1)
r1 = r0.incremented()
XCTAssertNotEqual(r0, r1)
XCTAssertEqual(r0.ptr, r1.ptr)
XCTAssertEqual(r0.tag &+ 1, r1.tag)
XCTAssertEqual(r1.tag, 3)
r1 = r0.incremented(with: r2.ptr)
XCTAssertEqual(r0.tag &+ 1, r1.tag)
XCTAssertEqual(r1.ptr, r2.ptr)
XCTAssertNotEqual(r1, r2)
r1.increment()
XCTAssertEqual(r1, r2)
let r3 = r2.incremented()
XCTAssertNotEqual(r2, r3)
XCTAssertEqual(r2.ptr, r3.ptr)
XCTAssertEqual(r2.tag, r3.tag &- 1)
var r4 = r2
r4.tag += 1
XCTAssertEqual(r3, r4)
}
public func testAtomicTaggedOptionalMutableRawPointer()
{
let r0 = TaggedOptionalMutableRawPointer(UnsafeMutableRawPointer(bitPattern: UInt.randomPositive()), tag: 0)
let r1 = TaggedOptionalMutableRawPointer(UnsafeMutableRawPointer(bitPattern: UInt.randomPositive()), tag: 1)
let r2 = TaggedOptionalMutableRawPointer(UnsafeMutableRawPointer(bitPattern: UInt.randomPositive()), tag: 2)
let r3 = r2.incremented()
var p = AtomicTaggedOptionalMutableRawPointer(r3)
XCTAssertEqual(CAtomicsLoad(&p, .relaxed), r3)
XCTAssertEqual(CAtomicsIsLockFree(&p), true)
CAtomicsInitialize(&p, r0)
XCTAssertEqual(r0, CAtomicsLoad(&p, .relaxed))
CAtomicsStore(&p, r1, .relaxed)
XCTAssertEqual(r1, CAtomicsLoad(&p, .relaxed))
var j = CAtomicsExchange(&p, r2, .relaxed)
XCTAssertEqual(r1, j)
XCTAssertEqual(r2, CAtomicsLoad(&p, .relaxed))
j = r2
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r3, .relaxed, .relaxed))
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
XCTAssertFalse(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r2, .relaxed, .relaxed))
j = CAtomicsLoad(&p, .relaxed)
XCTAssertTrue(CAtomicsCompareAndExchangeStrong(&p, &j, r1, .relaxed, .relaxed))
while !CAtomicsCompareAndExchangeWeak(&p, &j, r3, .relaxed, .relaxed) {}
XCTAssertEqual(r1, j)
XCTAssertEqual(r3, CAtomicsLoad(&p, .relaxed))
}
}
| bsd-3-clause | bdfaf451752590fe278c76769a08db17 | 32.393681 | 116 | 0.686145 | 3.514335 | false | false | false | false |
marklin2012/iOS_Animation | Section4/Chapter21/O2Cook_completed/O2Cook/PopAnimator.swift | 1 | 2292 | //
// PopAnimator.swift
// O2Cook
//
// Created by O2.LinYi on 16/3/21.
// Copyright © 2016年 jd.com. All rights reserved.
//
import UIKit
class PopAnimator: NSObject, UIViewControllerAnimatedTransitioning {
let duration = 1.0
var presenting = true
var originFrame = CGRect.zero
var dismissCompletion: (() -> ())?
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return duration
}
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
let containerView = transitionContext.containerView()!
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
let herbView = presenting ? toView : transitionContext.viewForKey(UITransitionContextFromViewKey)!
let initialFrame = presenting ? originFrame : herbView.frame
let finalFrame = presenting ? herbView.frame : originFrame
let xScaleFactor = presenting ? initialFrame.width/finalFrame.width : finalFrame.width/initialFrame.width
let yScaleFactor = presenting ? initialFrame.height/finalFrame.height : finalFrame.height/initialFrame.height
let scaleTransform = CGAffineTransformMakeScale(xScaleFactor, yScaleFactor)
if presenting {
herbView.transform = scaleTransform
herbView.center = CGPoint(x: CGRectGetMidX(initialFrame), y: CGRectGetMidY(initialFrame))
herbView.clipsToBounds = true
}
containerView.addSubview(toView)
containerView.bringSubviewToFront(herbView)
UIView.animateWithDuration(duration, delay: 0, usingSpringWithDamping: 0.4, initialSpringVelocity: 0, options: [], animations: { () -> Void in
herbView.transform = self.presenting ? CGAffineTransformIdentity : scaleTransform
herbView.center = CGPoint(x: CGRectGetMidX(finalFrame), y: CGRectGetMidY(finalFrame))
}, completion: { _ in
if !self.presenting {
self.dismissCompletion?()
}
transitionContext.completeTransition(true)
})
}
}
| mit | 03a53a893481029452048b3fcef70d43 | 33.681818 | 150 | 0.650066 | 6.104 | false | false | false | false |
kinetic-fit/sensors-swift | Sources/SwiftySensors/FitnessMachineSerializer.swift | 1 | 27071 | //
// FitnessMachineSerializer.swift
// SwiftySensors
//
// https://github.com/kinetic-fit/sensors-swift
//
// Copyright © 2017 Kinetic. All rights reserved.
//
import Foundation
/// :nodoc:
open class FitnessMachineSerializer {
public struct MachineFeatures: OptionSet {
public let rawValue: UInt32
public static let averageSpeedSupported = MachineFeatures(rawValue: 1 << 0)
public static let cadenceSupported = MachineFeatures(rawValue: 1 << 1)
public static let totalDistanceSupported = MachineFeatures(rawValue: 1 << 2)
public static let inclinationSupported = MachineFeatures(rawValue: 1 << 3)
public static let elevationGainSupported = MachineFeatures(rawValue: 1 << 4)
public static let paceSupported = MachineFeatures(rawValue: 1 << 5)
public static let stepCountSupported = MachineFeatures(rawValue: 1 << 6)
public static let resistanceLevelSupported = MachineFeatures(rawValue: 1 << 7)
public static let strideCountSupported = MachineFeatures(rawValue: 1 << 8)
public static let expendedEnergySupported = MachineFeatures(rawValue: 1 << 9)
public static let heartRateMeasurementSupported = MachineFeatures(rawValue: 1 << 10)
public static let metabolicEquivalentSupported = MachineFeatures(rawValue: 1 << 11)
public static let elapsedTimeSupported = MachineFeatures(rawValue: 1 << 12)
public static let remainingTimeSupported = MachineFeatures(rawValue: 1 << 13)
public static let powerMeasurementSupported = MachineFeatures(rawValue: 1 << 14)
public static let forceOnBeltAndPowerOutputSupported = MachineFeatures(rawValue: 1 << 15)
public static let userDataRetentionSupported = MachineFeatures(rawValue: 1 << 16)
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
}
public struct TargetSettingFeatures: OptionSet {
public let rawValue: UInt32
public static let speedTargetSettingSupported = TargetSettingFeatures(rawValue: 1 << 0)
public static let inclinationTargetSettingSupported = TargetSettingFeatures(rawValue: 1 << 1)
public static let resistanceTargetSettingSupported = TargetSettingFeatures(rawValue: 1 << 2)
public static let powerTargetSettingSupported = TargetSettingFeatures(rawValue: 1 << 3)
public static let heartRateTargetSettingSupported = TargetSettingFeatures(rawValue: 1 << 4)
public static let targetedExpendedEnergyConfigurationSupported = TargetSettingFeatures(rawValue: 1 << 5)
public static let targetedStepNumberConfigurationSupported = TargetSettingFeatures(rawValue: 1 << 6)
public static let targetedStrideNumberConfigurationSupported = TargetSettingFeatures(rawValue: 1 << 7)
public static let targetedDistanceConfigurationSupported = TargetSettingFeatures(rawValue: 1 << 8)
public static let targetedTrainingTimeConfigurationSupported = TargetSettingFeatures(rawValue: 1 << 9)
public static let targetedTimeInTwoHeartRateZonesConfigurationSupported = TargetSettingFeatures(rawValue: 1 << 10)
public static let targetedTimeInThreeHeartRateZonesConfigurationSupported = TargetSettingFeatures(rawValue: 1 << 11)
public static let targetedTimeInFiveHeartRateZonesConfigurationSupported = TargetSettingFeatures(rawValue: 1 << 12)
public static let indoorBikeSimulationParametersSupported = TargetSettingFeatures(rawValue: 1 << 13)
public static let wheelCircumferenceConfigurationSupported = TargetSettingFeatures(rawValue: 1 << 14)
public static let spinDownControlSupported = TargetSettingFeatures(rawValue: 1 << 15)
public static let targetedCadenceConfigurationSupported = TargetSettingFeatures(rawValue: 1 << 16)
public init(rawValue: UInt32) {
self.rawValue = rawValue
}
}
public static func readFeatures(_ data: Data) -> (machine: MachineFeatures, targetSettings: TargetSettingFeatures) {
let bytes = data.map { $0 }
var rawMachine: UInt32 = UInt32(bytes[0])
rawMachine |= UInt32(bytes[1]) << 8
rawMachine |= UInt32(bytes[2]) << 16
rawMachine |= UInt32(bytes[3]) << 24
var rawTargetSettings: UInt32 = UInt32(bytes[4])
rawTargetSettings |= UInt32(bytes[5]) << 8
rawTargetSettings |= UInt32(bytes[6]) << 16
rawTargetSettings |= UInt32(bytes[7]) << 24
return (MachineFeatures(rawValue: rawMachine), TargetSettingFeatures(rawValue: rawTargetSettings))
}
public struct TrainerStatusFlags: OptionSet {
public let rawValue: UInt8
static let TrainingStatusStringPresent = TrainerStatusFlags(rawValue: 1 << 0)
static let ExtendedStringPresent = TrainerStatusFlags(rawValue: 1 << 2)
public init(rawValue: UInt8) {
self.rawValue = rawValue
}
}
public enum TrainingStatusField: UInt8 {
case other = 0x00
case idle = 0x01
case warmingUp = 0x02
case lowIntensityInterval = 0x03
case highIntensityInterval = 0x04
case recoveryInterval = 0x05
case isometric = 0x06
case heartRateControl = 0x07
case fitnessTest = 0x08
case speedOutsideControlRegionLow = 0x09
case speedOutsideControlRegionHigh = 0x0A
case coolDown = 0x0B
case wattControl = 0x0C
case manualMode = 0x0D
case preWorkout = 0x0E
case postWorkout = 0x0F
}
public struct TrainingStatus {
public var flags: TrainerStatusFlags = TrainerStatusFlags()
public var status: TrainingStatusField = .other
public var statusString: String?
}
public static func readTrainingStatus(_ data: Data) -> TrainingStatus {
var status = TrainingStatus()
let bytes = data.map { $0 }
status.flags = TrainerStatusFlags(rawValue: bytes[0])
status.status = TrainingStatusField(rawValue: bytes[1]) ?? .other
if status.flags.contains(.TrainingStatusStringPresent), bytes.count > 2 {
let statusBytes = bytes.suffix(from: 2)
status.statusString = String(bytes: statusBytes, encoding: .utf8)
}
return status
}
public enum ControlOpCode: UInt8 {
case requestControl = 0x00
case reset = 0x01
case setTargetSpeed = 0x02
case setTargetInclincation = 0x03
case setTargetResistanceLevel = 0x04
case setTargetPower = 0x05
case setTargetHeartRate = 0x06
case startOrResume = 0x07
case stopOrPause = 0x08
case setTargetedExpendedEnergy = 0x09
case setTargetedNumberOfSteps = 0x0A
case setTargetedNumberOfStrides = 0x0B
case setTargetedDistance = 0x0C
case setTargetedTrainingTime = 0x0D
case setTargetedTimeInTwoHeartRateZones = 0x0E
case setTargetedTimeInThreeHeartRateZones = 0x0F
case setTargetedTimeInFiveHeartRateZones = 0x10
case setIndoorBikeSimulationParameters = 0x11
case setWheelCircumference = 0x12
case spinDownControl = 0x13
case setTargetedCadence = 0x14
case responseCode = 0x80
case unknown = 0xFF
}
public enum ResultCode: UInt8 {
case reserved = 0x00
case success = 0x01
case opCodeNotSupported = 0x02
case invalidParameter = 0x03
case operationFailed = 0x04
case controlNotPermitted = 0x05
}
public struct ControlPointResponse {
public var requestOpCode: ControlOpCode = .unknown
public var resultCode: ResultCode = .opCodeNotSupported
// Target Speed Params when the request is SpinDownControler
public var targetSpeedLow: Float?
public var targetSpeedHigh: Float?
}
public static func readControlPointResponse(_ data: Data) -> ControlPointResponse {
let bytes = data.map { $0 }
var response = ControlPointResponse()
if bytes.count > 2, bytes[0] == ControlOpCode.responseCode.rawValue {
response.requestOpCode = ControlOpCode(rawValue: bytes[1]) ?? .unknown
response.resultCode = ResultCode(rawValue: bytes[2]) ?? .opCodeNotSupported
if response.resultCode == .success && response.requestOpCode == .spinDownControl {
// If success and spindown control response, the target high / low speeds are tacked onto the end
if bytes.count > 6 {
response.targetSpeedLow = Float(UInt16(bytes[3]) | UInt16(bytes[4]) << 8) / 100
response.targetSpeedHigh = Float(UInt16(bytes[5]) | UInt16(bytes[6]) << 8) / 100
}
}
}
return response
}
public struct IndoorBikeSimulationParameters: Equatable {
let windSpeed: Double
let grade: Double
let crr: Double
let crw: Double
public static func ==(lhs: FitnessMachineSerializer.IndoorBikeSimulationParameters, rhs: FitnessMachineSerializer.IndoorBikeSimulationParameters) -> Bool {
return abs(lhs.windSpeed - rhs.windSpeed) <= .ulpOfOne &&
abs(lhs.grade - rhs.grade) <= .ulpOfOne &&
abs(lhs.crr - rhs.crr) <= .ulpOfOne &&
abs(lhs.crw - rhs.crw) <= .ulpOfOne
}
}
public static func setIndoorBikeSimulationParameters(_ parameters: IndoorBikeSimulationParameters) -> [UInt8] {
// windSpeed = meters / second res 0.001
// grade = percentage res 0.01
// crr = unitless res 0.0001
// cw = kg / meter res 0.01
let mpsN = Int16(parameters.windSpeed * 1000)
let gradeN = Int16(parameters.grade * 100)
let crrN = UInt8(Int(parameters.crr * 10000) & 0xFF)
let crwN = UInt8(Int(parameters.crw * 100) & 0xFF)
return [
ControlOpCode.setIndoorBikeSimulationParameters.rawValue,
UInt8(mpsN & 0xFF), UInt8(mpsN >> 8 & 0xFF),
UInt8(gradeN & 0xFF), UInt8(gradeN >> 8 & 0xFF),
crrN,
crwN
]
}
public static func requestControl() -> [UInt8] {
return [
ControlOpCode.requestControl.rawValue
]
}
public static func reset() -> [UInt8] {
return [
ControlOpCode.reset.rawValue
]
}
public static func startOrResume() -> [UInt8] {
return [
ControlOpCode.startOrResume.rawValue
]
}
public static func stop() -> [UInt8] {
return [
ControlOpCode.stopOrPause.rawValue,
0x01
]
}
public static func pause() -> [UInt8] {
return [
ControlOpCode.stopOrPause.rawValue,
0x02
]
}
public static func setTargetResistanceLevel(level: Double) -> [UInt8] {
// level = unitless res 0.1
let levelN = Int16(level * 10)
return [
ControlOpCode.setTargetResistanceLevel.rawValue,
UInt8(levelN & 0xFF), UInt8(levelN >> 8 & 0xFF)
]
}
public static func setTargetPower(watts: Int16) -> [UInt8] {
return [
ControlOpCode.setTargetPower.rawValue,
UInt8(watts & 0xFF), UInt8(watts >> 8 & 0xFF)
]
}
public static func startSpinDownControl() -> [UInt8] {
return [
ControlOpCode.spinDownControl.rawValue,
0x01
]
}
public static func ignoreSpinDownControlRequest() -> [UInt8] {
return [
ControlOpCode.spinDownControl.rawValue,
0x02
]
}
public struct IndoorBikeDataFlags: OptionSet {
public let rawValue: UInt16
public static let MoreData = IndoorBikeDataFlags(rawValue: 1 << 0)
public static let AverageSpeedPresent = IndoorBikeDataFlags(rawValue: 1 << 1)
public static let InstantaneousCadencePresent = IndoorBikeDataFlags(rawValue: 1 << 2)
public static let AverageCadencePresent = IndoorBikeDataFlags(rawValue: 1 << 3)
public static let TotalDistancePresent = IndoorBikeDataFlags(rawValue: 1 << 4)
public static let ResistanceLevelPresent = IndoorBikeDataFlags(rawValue: 1 << 5)
public static let InstantaneousPowerPresent = IndoorBikeDataFlags(rawValue: 1 << 6)
public static let AveragePowerPresent = IndoorBikeDataFlags(rawValue: 1 << 7)
public static let ExpendedEnergyPresent = IndoorBikeDataFlags(rawValue: 1 << 8)
public static let HeartRatePresent = IndoorBikeDataFlags(rawValue: 1 << 9)
public static let MetabolicEquivalentPresent = IndoorBikeDataFlags(rawValue: 1 << 10)
public static let ElapsedTimePresent = IndoorBikeDataFlags(rawValue: 1 << 11)
public static let RemainingTimePresent = IndoorBikeDataFlags(rawValue: 1 << 12)
public init(rawValue: UInt16) {
self.rawValue = rawValue
}
}
public struct IndoorBikeData {
public var flags: IndoorBikeDataFlags = IndoorBikeDataFlags(rawValue: 0)
public var instantaneousSpeed: Double?
public var averageSpeed: Double?
public var instantaneousCadence: Double?
public var averageCadence: Double?
public var totalDistance: UInt32?
public var resistanceLevel: Int16?
public var instantaneousPower: Int16?
public var averagePower: Int16?
public var totalEnergy: UInt16?
public var energyPerHour: UInt16?
public var energyPerMinute: UInt8?
public var heartRate: UInt8?
public var metabolicEquivalent: Double?
public var elapsedTime: UInt16?
public var remainingTime: UInt16?
}
public static func readIndoorBikeData(_ data: Data) -> IndoorBikeData {
var bikeData = IndoorBikeData()
let bytes = data.map { $0 }
var index: Int = 0
let rawFlags: UInt16 = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
bikeData.flags = IndoorBikeDataFlags(rawValue: rawFlags)
if !bikeData.flags.contains(.MoreData) {
let value: UInt16 = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
bikeData.instantaneousSpeed = Double(value) / 100.0
}
if bikeData.flags.contains(.AverageSpeedPresent) {
let value: UInt16 = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
bikeData.averageSpeed = Double(value) / 100.0
}
if bikeData.flags.contains(.InstantaneousCadencePresent) {
let value: UInt16 = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
bikeData.instantaneousCadence = Double(value) / 2.0
}
if bikeData.flags.contains(.AverageCadencePresent) {
let value: UInt16 = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
bikeData.averageCadence = Double(value) / 2.0
}
if bikeData.flags.contains(.TotalDistancePresent) {
var value: UInt32 = UInt32(bytes[index++=])
value |= UInt32(bytes[index++=]) << 8
value |= UInt32(bytes[index++=]) << 16
bikeData.totalDistance = value
}
if bikeData.flags.contains(.ResistanceLevelPresent) {
let value: Int16 = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
bikeData.resistanceLevel = value
}
if bikeData.flags.contains(.InstantaneousPowerPresent) {
let value: Int16 = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
bikeData.instantaneousPower = value
}
if bikeData.flags.contains(.AveragePowerPresent) {
let value: Int16 = Int16(bytes[index++=]) | Int16(bytes[index++=]) << 8
bikeData.averagePower = value
}
if bikeData.flags.contains(.ExpendedEnergyPresent) {
bikeData.totalEnergy = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
bikeData.energyPerHour = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
bikeData.energyPerMinute = bytes[index++=]
}
if bikeData.flags.contains(.HeartRatePresent) {
bikeData.heartRate = bytes[index++=]
}
if bikeData.flags.contains(.MetabolicEquivalentPresent) {
let value: UInt8 = bytes[index++=]
bikeData.metabolicEquivalent = Double(value) / 10.0
}
if bikeData.flags.contains(.ElapsedTimePresent) {
bikeData.elapsedTime = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
if bikeData.flags.contains(.RemainingTimePresent) {
bikeData.remainingTime = UInt16(bytes[index++=]) | UInt16(bytes[index++=]) << 8
}
return bikeData
}
public struct SupportedResistanceLevelRange {
public var minimumResistanceLevel: Double = 0
public var maximumResistanceLevel: Double = 0
public var minimumIncrement: Double = 0
}
public static func readSupportedResistanceLevelRange(_ data: Data) -> SupportedResistanceLevelRange {
let bytes = data.map { $0 }
var response = SupportedResistanceLevelRange()
let value1: Int16 = Int16(bytes[0]) | Int16(bytes[1]) << 8
let value2: Int16 = Int16(bytes[2]) | Int16(bytes[3]) << 8
let value3: UInt16 = UInt16(bytes[4]) | UInt16(bytes[5]) << 8
response.minimumResistanceLevel = Double(value1) / 10.0
response.maximumResistanceLevel = Double(value2) / 10.0
response.minimumIncrement = Double(value3) / 10.0
return response
}
public struct SupportedPowerRange {
public var minimumPower: Int16 = 0
public var maximumPower: Int16 = 0
public var minimumIncrement: UInt16 = 0
}
public static func readSupportedPowerRange(_ data: Data) -> SupportedPowerRange {
let bytes = data.map { $0 }
var response = SupportedPowerRange()
response.minimumPower = Int16(bytes[0]) | Int16(bytes[1]) << 8
response.maximumPower = Int16(bytes[2]) | Int16(bytes[3]) << 8
response.minimumIncrement = UInt16(bytes[4]) | UInt16(bytes[5]) << 8
return response
}
public enum MachineStatusOpCode: UInt8 {
case reservedForFutureUse = 0x00
case reset = 0x01
case stoppedOrPausedByUser = 0x02
case stoppedBySafetyKey = 0x03
case startedOrResumedByUser = 0x04
case targetSpeedChanged = 0x05
case targetInclineChanged = 0x06
case targetResistancLevelChanged = 0x07
case targetPowerChanged = 0x08
case targetHeartRateChanged = 0x09
case targetedExpendedEnergyChanged = 0x0A
case targetedNumberOfStepsChanged = 0x0B
case targetedNumberOfStridesChanged = 0x0C
case targetedDistanceChanged = 0x0D
case targetedTrainingTimeChanged = 0x0E
case targetedTimeInTwoHeartRateZonesChanged = 0x0F
case targetedTimeInThreeHeartRateZonesChanged = 0x10
case targetedTimeInFiveHeartRateZonesChanged = 0x11
case indoorBikeSimulationParametersChanged = 0x12
case wheelCircumferenceChanged = 0x13
case spinDownStatus = 0x14
case targetedCadenceChanged = 0x15
case controlPermissionLost = 0xFF
}
public struct MachineStatusMessage {
public var opCode: MachineStatusOpCode = .reservedForFutureUse
public enum SpinDownStatus: UInt8 {
case reservedForFutureUse = 0x00
case spinDownRequested = 0x01
case success = 0x02
case error = 0x03
case stopPedaling = 0x04
}
public var spinDownStatus: SpinDownStatus?
public var spinDownTime: TimeInterval?
public var targetPower: Int16?
public var targetResistanceLevel: Double?
public var targetSimParameters: IndoorBikeSimulationParameters?
}
public static func readMachineStatus(_ data: Data) -> MachineStatusMessage {
var message = MachineStatusMessage()
let bytes = data.map { $0 }
if bytes.count > 0 {
message.opCode = MachineStatusOpCode(rawValue: bytes[0]) ?? .reservedForFutureUse
}
switch message.opCode {
case .reservedForFutureUse:
break
case .reset:
break
case .stoppedOrPausedByUser:
if bytes.count > 1 {
// 0x01 = stop
// 0x02 = pause
}
break
case .stoppedBySafetyKey:
break
case .startedOrResumedByUser:
break
case .targetSpeedChanged:
if bytes.count > 2 {
// UInt16 km / hour w/ res 0.01
// message.targetSpeed = UInt16(bytes[1]) | UInt16(bytes[2]) << 8
}
break
case .targetInclineChanged:
if bytes.count > 2 {
// Int16 percent w/ res 0.1
// message.targetIncline = Int16(bytes[1]) | Int16(bytes[2]) << 8
}
break
case .targetResistancLevelChanged:
if bytes.count > 2 {
// ??? the spec cannot be correct here
// If we go by the Supported Resistance Level Range characteristic,
// this value *should* be a SInt16 w/ res 0.1
message.targetResistanceLevel = Double(Int16(bytes[1]) | Int16(bytes[2]) << 8) / 10
}
break
case .targetPowerChanged:
if bytes.count > 2 {
// Int16 watts w/ res 1
message.targetPower = Int16(bytes[1]) | Int16(bytes[2]) << 8
}
break
case .targetHeartRateChanged:
if bytes.count > 1 {
// UInt8 bpm w/ res 1
// message.targetHeartRate = bytes[1]
}
break
case .targetedExpendedEnergyChanged:
if bytes.count > 2 {
// UInt16 cals w/ res 1
// message.targetedExpendedEnergy = UInt16(bytes[1]) | UInt16(bytes[2]) << 8
}
break
case .targetedNumberOfStepsChanged:
if bytes.count > 2 {
// UInt16 steps w/ res 1
// message.targetedNumberOfSteps = UInt16(bytes[1]) | UInt16(bytes[2]) << 8
}
break
case .targetedNumberOfStridesChanged:
if bytes.count > 2 {
// UInt16 strides w/ res 1
// message.targetedNumberOfStrides = UInt16(bytes[1]) | UInt16(bytes[2]) << 8
}
break
case .targetedDistanceChanged:
if bytes.count > 3 {
// UInt24 meters w/ res 1
}
break
case .targetedTrainingTimeChanged:
if bytes.count > 2 {
// UInt16 seconds w/ res 1
// message.targetedTrainingTime = UInt16(bytes[1]) | UInt16(bytes[2]) << 8
}
break
case .targetedTimeInTwoHeartRateZonesChanged:
break
case .targetedTimeInThreeHeartRateZonesChanged:
break
case .targetedTimeInFiveHeartRateZonesChanged:
break
case .indoorBikeSimulationParametersChanged:
if bytes.count > 6 {
let windSpeed = Double(Int16(bytes[1]) | Int16(bytes[2]) << 8) / 1000
let grade = Double(Int16(bytes[3]) | Int16(bytes[4]) << 8) / 100
let crr = Double(bytes[5]) / 10000
let cwr = Double(bytes[6]) / 100
message.targetSimParameters = IndoorBikeSimulationParameters(windSpeed: windSpeed, grade: grade, crr: crr, crw: cwr)
}
break
case .wheelCircumferenceChanged:
if bytes.count > 2 {
// UInt16 mm w/ res 0.1
// message.wheelCircumferenceChanged = UInt16(bytes[1]) | UInt16(bytes[2]) << 8
}
break
case .spinDownStatus:
if bytes.count > 1 {
message.spinDownStatus = MachineStatusMessage.SpinDownStatus(rawValue: bytes[1])
if message.spinDownStatus == .success || message.spinDownStatus == .error, bytes.count > 3 {
// Milliseconds attached: convert to seconds
message.spinDownTime = TimeInterval(UInt16(bytes[2]) | UInt16(bytes[3]) << 8) / 1000
}
}
break
case .targetedCadenceChanged:
if bytes.count > 2 {
// UInt16 rpm w/ res 0.5
// message.targetedCadence = UInt16(bytes[1]) | UInt16(bytes[2]) << 8
}
break
case .controlPermissionLost:
break
}
return message
}
}
| mit | f07669b0e9a448842ff2104719647cc9 | 43.669967 | 163 | 0.571629 | 4.644818 | false | false | false | false |
wireapp/wire-ios-data-model | Source/Model/User/ZMUser+Availability.swift | 1 | 6199 | //
// Wire
// Copyright (C) 2017 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
@objc
public enum AvailabilityKind: Int, CaseIterable {
case none, available, busy, away
public init(proto: WireProtos.Availability) {
/// TODO: change ZMAvailabilityType to NS_CLOSED_ENUM
switch proto.type {
case .none:
self = .none
case .available:
self = .available
case .away:
self = .away
case .busy:
self = .busy
}
}
}
/// Describes how the user should be notified about a change.
public struct NotificationMethod: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
/// Alert user by local notification
public static let notification = NotificationMethod(rawValue: 1 << 0)
/// Alert user by alert dialogue
public static let alert = NotificationMethod(rawValue: 1 << 1)
public static let all: NotificationMethod = [.notification, .alert]
}
extension ZMUser {
/// The set of all users to receive an availability status broadcast message.
///
/// Broadcast messages are expensive for large teams. Therefore it is necessary broadcast to
/// a limited subset of all users. Known team members are priortized first, followed by
/// connected non team members. The self user is guaranteed to be a recipient.
///
/// - Parameters:
/// - context: The context to search in.
/// - maxCount: The maximum number of recipients to return.
public static func recipientsForAvailabilityStatusBroadcast(in context: NSManagedObjectContext, maxCount: Int) -> Set<ZMUser> {
var recipients: Set = [selfUser(in: context)]
var remainingSlots = maxCount - recipients.count
let sortByIdentifer: (ZMUser, ZMUser) -> Bool = {
$0.remoteIdentifier.transportString() < $1.remoteIdentifier.transportString()
}
let teamMembers = knownTeamMembers(in: context)
.sorted(by: sortByIdentifer)
.prefix(remainingSlots)
recipients.formUnion(teamMembers)
remainingSlots = maxCount - recipients.count
guard remainingSlots > 0 else { return recipients }
let teamUsers = knownTeamUsers(in: context)
.sorted(by: sortByIdentifer)
.prefix(remainingSlots)
recipients.formUnion(teamUsers)
recipients = recipients.filter { !$0.isFederated }
return recipients
}
/// The set of all users who both share the team and a conversation with the self user.
///
/// Note: the self user is not included.
static func knownTeamMembers(in context: NSManagedObjectContext) -> Set<ZMUser> {
let selfUser = ZMUser.selfUser(in: context)
guard selfUser.hasTeam else { return Set() }
let teamMembersInConversationWithSelfUser = selfUser.conversations.lazy
.flatMap { $0.participantRoles }
.compactMap { $0.user }
.filter { $0.isOnSameTeam(otherUser: selfUser) && !$0.isSelfUser }
return Set(teamMembersInConversationWithSelfUser)
}
/// The set of all users from another team who are connected with the self user.
static func knownTeamUsers(in context: NSManagedObjectContext) -> Set<ZMUser> {
let connectedPredicate = ZMUser.predicateForUsers(withConnectionStatuses: [ZMConnectionStatus.accepted.rawValue])
let request = NSFetchRequest<ZMUser>(entityName: ZMUser.entityName())
request.predicate = connectedPredicate
let connections = Set(context.fetchOrAssert(request: request))
let selfUser = ZMUser.selfUser(in: context)
let result = connections.filter { $0.hasTeam && !$0.isOnSameTeam(otherUser: selfUser) }
return Set(result)
}
@objc public var availability: AvailabilityKind {
get {
self.willAccessValue(forKey: AvailabilityKey)
let value = (self.primitiveValue(forKey: AvailabilityKey) as? NSNumber) ?? NSNumber(value: 0)
self.didAccessValue(forKey: AvailabilityKey)
return AvailabilityKind(rawValue: value.intValue) ?? .none
}
set {
guard isSelfUser else { return } // TODO move this setter to ZMEditableUser
updateAvailability(newValue)
}
}
internal func updateAvailability(_ newValue: AvailabilityKind) {
self.willChangeValue(forKey: AvailabilityKey)
self.setPrimitiveValue(NSNumber(value: newValue.rawValue), forKey: AvailabilityKey)
self.didChangeValue(forKey: AvailabilityKey)
}
public func updateAvailability(from genericMessage: GenericMessage) {
updateAvailability(AvailabilityKind(proto: genericMessage.availability))
}
private static let needsToNotifyAvailabilityBehaviourChangeKey = "needsToNotifyAvailabilityBehaviourChange"
/// Returns an option set describing how we should notify the user about the change in behaviour for the availability feature
public var needsToNotifyAvailabilityBehaviourChange: NotificationMethod {
get {
guard let rawValue = managedObjectContext?.persistentStoreMetadata(forKey: type(of: self).needsToNotifyAvailabilityBehaviourChangeKey) as? Int else { return [] }
return NotificationMethod(rawValue: rawValue)
}
set {
managedObjectContext?.setPersistentStoreMetadata(newValue.rawValue, key: type(of: self).needsToNotifyAvailabilityBehaviourChangeKey)
}
}
}
| gpl-3.0 | 96a9f21531377a692860f76914590232 | 35.680473 | 173 | 0.68382 | 4.809154 | false | false | false | false |
wjk930726/CCColorPinker | CCColorPinker/CCColorPinker/Controller/ViewController.swift | 1 | 2711 | //
// ViewController.swift
// CCColorPinker
//
// Created by 王靖凯 on 2017/8/4.
// Copyright © 2017年 王靖凯. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet var colorVIew: UIView!
// 蒙板效果
// fileprivate lazy var blurView: UIToolbar = {
// let blurView = UIToolbar.init(frame: self.view.bounds)
// blurView.barStyle = .blackTranslucent
// return blurView
// }()
fileprivate lazy var blurView: UIView = {
let blurView = UIView(frame: self.view.bounds)
blurView.backgroundColor = UIColor.black
return blurView
}()
// 颜色选择器视图
fileprivate lazy var colorPinker: CCColorPinker = {
let colorPinker = CCColorPinker()
return colorPinker
}()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func modalColorPinker(_: UIButton) {
// 蒙板效果
view.addSubview(blurView)
// CCColorPinker
colorPinker.delegete = self
colorPinker.backgroundColor = UIColor.colorWithHex(hex: 0x303D52)
// 布局
let widthFix = 0.85
let heightFix = 0.75
view.addSubview(colorPinker)
colorPinker.translatesAutoresizingMaskIntoConstraints = false
view.addConstraint(NSLayoutConstraint(item: colorPinker, attribute: .centerX, relatedBy: .equal, toItem: view, attribute: .centerX, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: colorPinker, attribute: .centerY, relatedBy: .equal, toItem: view, attribute: .centerY, multiplier: 1, constant: 0))
view.addConstraint(NSLayoutConstraint(item: colorPinker, attribute: .width, relatedBy: .equal, toItem: view, attribute: .width, multiplier: CGFloat(widthFix), constant: 0))
view.addConstraint(NSLayoutConstraint(item: colorPinker, attribute: .height, relatedBy: .equal, toItem: view, attribute: .height, multiplier: CGFloat(heightFix), constant: 0))
}
}
// MARK: - CCColorPinkerDelegete
extension ViewController: CCColorPinkerDelegete {
func colorPinker(_ colorPinker: CCColorPinker, didSelectedCancelButton _: UIButton) {
colorPinker.removeFromSuperview()
blurView.removeFromSuperview()
}
func colorPinker(_ colorPinker: CCColorPinker, didSelectedConfirmButton _: UIButton) {
colorPinker.removeFromSuperview()
blurView.removeFromSuperview()
}
}
| mit | 2b84bdd664af4518e8fff97c42a61d69 | 34.972973 | 183 | 0.680316 | 4.444073 | false | false | false | false |
bsmith11/ScoreReporter | ScoreReporterCore/ScoreReporterCore/Extensions/UIView+KeyboardLayoutGuide.swift | 1 | 3241 | //
// UIView+KeyboardLayoutGuide.swift
// ScoreReporter
//
// Created by Bradley Smith on 9/13/16.
// Copyright © 2016 Brad Smith. All rights reserved.
//
//https://github.com/Raizlabs/Swiftilities/blob/develop/Pod/Classes/Keyboard/UIView%2BKeyboardLayoutGuide.swift
import UIKit
public extension UIView {
var keyboardLayoutGuide: UILayoutGuide {
if let index = layoutGuides.index(where: { $0 is KeyboardLayoutGuide }) {
return layoutGuides[index]
}
return addKeyboardLayoutGuide()
}
}
private extension UIView {
func addKeyboardLayoutGuide() -> UILayoutGuide {
let guide = KeyboardLayoutGuide()
addLayoutGuide(guide)
guide.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
guide.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
guide.topAnchor.constraint(equalTo: bottomAnchor).isActive = true
let heightConstraint = guide.heightAnchor.constraint(equalToConstant: 0.0)
heightConstraint.isActive = true
guide.keyboardFrameBlock = { [weak self] keyboardFrame in
if let sself = self, sself.window != nil {
var frameInWindow = sself.frame
if let superview = sself.superview {
frameInWindow = superview.convert(sself.frame, to: nil)
}
heightConstraint.constant = max(0.0, frameInWindow.maxY - keyboardFrame.minY)
sself.superview?.layoutIfNeeded()
}
}
return guide
}
}
// MARK: - KeyboardLayoutGuide
private typealias KeyboardFrameBlock = (CGRect) -> Void
private class KeyboardLayoutGuide: UILayoutGuide {
fileprivate var currentKeyboardFrame = CGRect.zero
var keyboardFrameBlock: KeyboardFrameBlock?
override init() {
super.init()
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillUpdate(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillUpdate(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc func keyboardWillUpdate(_ notification: Notification) {
guard let block = keyboardFrameBlock else {
return
}
let keyboardFrame = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue ?? CGRect.zero
guard !currentKeyboardFrame.equalTo(keyboardFrame) else {
return
}
currentKeyboardFrame = keyboardFrame
let animationDuration = (notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue ?? 0.0
let animationCurve = (notification.userInfo?[UIKeyboardAnimationCurveUserInfoKey] as? NSNumber)?.uintValue ?? 0
let options = UIViewAnimationOptions(rawValue: animationCurve << 16)
let animations = {
block(keyboardFrame)
}
UIView.animate(withDuration: animationDuration, delay: 0.0, options: options, animations: animations, completion: nil)
}
}
| mit | 8024d7cc471e3509d21461c4395d0863 | 33.468085 | 156 | 0.68179 | 5.25974 | false | false | false | false |
squarefrog/TraktTopTen | TraktTopTen/Views/SynopsisBackgroundView.swift | 1 | 1029 | //
// SynopsisBackgroundView.swift
// TraktTopTen
//
// Created by Paul Williamson on 21/04/2015.
// Copyright (c) 2015 Paul Williamson. All rights reserved.
//
import UIKit
class SynopsisBackgroundView: UIView {
override func drawRect(rect: CGRect) {
UIColor(white: 0.0, alpha: 0.1).setFill()
UIRectFill(rect)
let borderColour = UIColor(white: 1.0, alpha: 0.1)
// Add a top border
let topRect = CGRect(
x: 0,
y: 0,
width: CGRectGetWidth(self.bounds),
height: 1)
let topPath = UIBezierPath(rect: topRect)
borderColour.setFill()
topPath.fill()
// Add a bottom border
let bottomRect = CGRect(
x: 0,
y: CGRectGetHeight(self.bounds) - 1,
width: CGRectGetWidth(self.bounds),
height: 1)
let bottomPath = UIBezierPath(rect: bottomRect)
bottomPath.fill()
}
} | mit | 543912d5d4af2098186426240d901fc6 | 22.953488 | 60 | 0.537415 | 4.323529 | false | false | false | false |
apple/swift-async-algorithms | Tests/AsyncAlgorithmsTests/Support/Validator.swift | 1 | 3074 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
import AsyncAlgorithms
public struct Validator<Element: Sendable>: Sendable {
private enum Ready {
case idle
case ready
case pending(UnsafeContinuation<Void, Never>)
}
private struct State: Sendable {
var collected = [Element]()
var failure: Error?
var ready: Ready = .idle
}
private struct Envelope<Contents>: @unchecked Sendable {
var contents: Contents
}
private let state = ManagedCriticalState(State())
private func ready(_ apply: (inout State) -> Void) {
state.withCriticalRegion { state -> UnsafeContinuation<Void, Never>? in
apply(&state)
switch state.ready {
case .idle:
state.ready = .ready
return nil
case .pending(let continuation):
state.ready = .idle
return continuation
case .ready:
return nil
}
}?.resume()
}
internal func step() async {
await withUnsafeContinuation { (continuation: UnsafeContinuation<Void, Never>) in
state.withCriticalRegion { state -> UnsafeContinuation<Void, Never>? in
switch state.ready {
case .ready:
state.ready = .idle
return continuation
case .idle:
state.ready = .pending(continuation)
return nil
case .pending:
fatalError()
}
}?.resume()
}
}
let onEvent: (@Sendable (Result<Element?, Error>) async -> Void)?
init(onEvent: @Sendable @escaping (Result<Element?, Error>) async -> Void) {
self.onEvent = onEvent
}
public init() {
self.onEvent = nil
}
public func test<S: AsyncSequence>(_ sequence: S, onFinish: @Sendable @escaping (inout S.AsyncIterator) async -> Void) where S.Element == Element {
let envelope = Envelope(contents: sequence)
Task {
var iterator = envelope.contents.makeAsyncIterator()
ready { _ in }
do {
while let item = try await iterator.next() {
await onEvent?(.success(item))
ready { state in
state.collected.append(item)
}
}
await onEvent?(.success(nil))
} catch {
await onEvent?(.failure(error))
ready { state in
state.failure = error
}
}
ready { _ in }
await onFinish(&iterator)
}
}
public func validate() async -> [Element] {
await step()
return current
}
public var current: [Element] {
return state.withCriticalRegion { state in
return state.collected
}
}
public var failure: Error? {
return state.withCriticalRegion { state in
return state.failure
}
}
}
| apache-2.0 | 2fbdbaf6601ddc8edb5fbd02a541f935 | 25.273504 | 149 | 0.580677 | 4.818182 | false | false | false | false |
SmitaMMI/MMIDirection | MMIDirection/Model/mmi API/mmiAdvices.swift | 1 | 3174 | //
// mmiAdvices.swift
//
// Created by CEINFO on 9/12/17
// Copyright (c) . All rights reserved.
//
import Foundation
import SwiftyJSON
public final class mmiAdvices: NSCoding {
// MARK: Declaration for string constants to be used to decode and also serialize.
private struct SerializationKeys {
static let pt = "pt"
static let seconds = "seconds"
static let meters = "meters"
static let text = "text"
static let iconId = "icon_id"
static let exitNr = "exit_nr"
}
// MARK: Properties
public var pt: mmiPt?
public var seconds: Int?
public var meters: Int?
public var text: String?
public var iconId: Int?
public var exitNr: Int?
// MARK: SwiftyJSON Initializers
/// Initiates the instance based on the object.
///
/// - parameter object: The object of either Dictionary or Array kind that was passed.
/// - returns: An initialized instance of the class.
public convenience init(object: Any) {
self.init(json: JSON(object))
}
/// Initiates the instance based on the JSON that was passed.
///
/// - parameter json: JSON object from SwiftyJSON.
public required init(json: JSON) {
pt = mmiPt(json: json[SerializationKeys.pt])
seconds = json[SerializationKeys.seconds].int
meters = json[SerializationKeys.meters].int
text = json[SerializationKeys.text].string
iconId = json[SerializationKeys.iconId].int
exitNr = json[SerializationKeys.exitNr].int
}
/// Generates description of the object in the form of a NSDictionary.
///
/// - returns: A Key value pair containing all valid values in the object.
public func dictionaryRepresentation() -> [String: Any] {
var dictionary: [String: Any] = [:]
if let value = pt { dictionary[SerializationKeys.pt] = value.dictionaryRepresentation() }
if let value = seconds { dictionary[SerializationKeys.seconds] = value }
if let value = meters { dictionary[SerializationKeys.meters] = value }
if let value = text { dictionary[SerializationKeys.text] = value }
if let value = iconId { dictionary[SerializationKeys.iconId] = value }
if let value = exitNr { dictionary[SerializationKeys.exitNr] = value }
return dictionary
}
// MARK: NSCoding Protocol
required public init(coder aDecoder: NSCoder) {
self.pt = aDecoder.decodeObject(forKey: SerializationKeys.pt) as? mmiPt
self.seconds = aDecoder.decodeObject(forKey: SerializationKeys.seconds) as? Int
self.meters = aDecoder.decodeObject(forKey: SerializationKeys.meters) as? Int
self.text = aDecoder.decodeObject(forKey: SerializationKeys.text) as? String
self.iconId = aDecoder.decodeObject(forKey: SerializationKeys.iconId) as? Int
self.exitNr = aDecoder.decodeObject(forKey: SerializationKeys.exitNr) as? Int
}
public func encode(with aCoder: NSCoder) {
aCoder.encode(pt, forKey: SerializationKeys.pt)
aCoder.encode(seconds, forKey: SerializationKeys.seconds)
aCoder.encode(meters, forKey: SerializationKeys.meters)
aCoder.encode(text, forKey: SerializationKeys.text)
aCoder.encode(iconId, forKey: SerializationKeys.iconId)
aCoder.encode(exitNr, forKey: SerializationKeys.exitNr)
}
}
| isc | c7d9dcd26fc7239978627eca3f43f32e | 36.341176 | 93 | 0.717391 | 4.100775 | false | false | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Home/Views/HomeSongCell.swift | 1 | 1622 | //
// HomeSongCell.swift
// MusicApp
//
// Created by Hưng Đỗ on 7/1/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
import Action
class HomeSongCell: UITableViewCell {
@IBOutlet weak var tableView: UITableView!
override func awakeFromNib() {
super.awakeFromNib()
tableView.dataSource = self
tableView.delegate = self
}
var songs: [Song] = [] {
didSet {
tableView.reloadData()
}
}
var onSongDidSelect: Action<Song, Void>!
var onContextButtonTap: Action<Song, Void>!
}
extension HomeSongCell: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return songs.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: SongCell.self), for: indexPath)
if let cell = cell as? SongCell {
let song = songs[indexPath.row]
let contextAction = CocoaAction { [weak self] _ in
self?.onContextButtonTap.execute(song).map { _ in } ?? .empty()
}
cell.configure(name: song.name, singer: song.singer, contextAction: contextAction)
}
return cell
}
}
extension HomeSongCell: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let song = songs[indexPath.row]
onSongDidSelect.execute(song)
}
}
| mit | 4137088447324f72012cc0d6b8f4a44e | 25.080645 | 115 | 0.62585 | 4.62 | false | false | false | false |
TheNounProject/CollectionView | CollectionView/Layouts/CollectionViewFlowLayout.swift | 1 | 34577 | //
// CollectionViewMasonryLayout.swift
// CollectionView
//
// Created by Wesley Byrne on 9/12/16.
// Copyright © 2016 Noun Project. All rights reserved.
//
import Foundation
/// CollectionViewDelegateFlowLayout
public protocol CollectionViewDelegateFlowLayout {
// MARK: - Element Size
/*-------------------------------------------------------------------------------*/
/// Asks the delegate for the layout style for the item at the specified index path
///
/// - Parameter collectionView: The collection view requesting the information
/// - Parameter gridLayout: The layout
/// - Parameter indexPath: The index path of the item to style
///
/// - Returns: A style to apply to the item
func collectionView(_ collectionView: CollectionView,
flowLayout: CollectionViewFlowLayout,
styleForItemAt indexPath: IndexPath) -> CollectionViewFlowLayout.ItemStyle
/// Asks the delegate for the height of the header view in a specified section
///
/// Return 0 for no header view
///
/// - Parameter collectionView: The collection view requesting the information
/// - Parameter collectionViewLayout: The layout
/// - Parameter section: The section affected by this height
///
/// - Returns: The height to apply to the header view in the specified section
func collectionView (_ collectionView: CollectionView,
flowLayout collectionViewLayout: CollectionViewFlowLayout,
heightForHeaderInSection section: Int) -> CGFloat
/// Asks the delegate for the height of the footer view in a specified section
///
/// Return 0 for no footer view
///
/// - Parameter collectionView: The collection view requesting the information
/// - Parameter collectionViewLayout: The layout
/// - Parameter section: The section affected by this height
///
/// - Returns: The height to apply to the header view in the specified section
func collectionView (_ collectionView: CollectionView,
flowLayout collectionViewLayout: CollectionViewFlowLayout,
heightForFooterInSection section: Int) -> CGFloat
// MARK: - Insets & Transforms
/*-------------------------------------------------------------------------------*/
/// Asks the delegate for the insets for the content of the specified index path
///
/// - Parameter collectionView: The collection view requesting the information
/// - Parameter collectionViewLayout: The layout
/// - Parameter section: Thhe section that the return value will be applied to
///
/// - Returns: Edge insets for the specified section
func collectionView (_ collectionView: CollectionView,
flowLayout collectionViewLayout: CollectionViewFlowLayout,
insetsForSectionAt section: Int) -> NSEdgeInsets
/// Asks the delegate for a transform to apply to the content in each row the specified section, defaults to .none
///
/// - Parameter collectionView: The collection requesting the information
/// - Parameter collectionViewLayout: The layout
/// - Parameter section: The section to transform
///
/// - Returns: The type of row transform to apply
func collectionView (_ collectionView: CollectionView,
flowLayout collectionViewLayout: CollectionViewFlowLayout,
rowTransformForSectionAt section: Int) -> CollectionViewFlowLayout.RowTransform
/// <#Description#>
/// - Parameters:
/// - collectionView: <#collectionView description#>
/// - collectionViewLayout: <#collectionViewLayout description#>
/// - section: <#section description#>
func collectionView (_ collectionView: CollectionView,
flowLayout collectionViewLayout: CollectionViewFlowLayout,
interspanSpacingForSectionAt section: Int) -> CGFloat?
func collectionView (_ collectionView: CollectionView,
flowLayout collectionViewLayout: CollectionViewFlowLayout,
interitemSpacingForSectionAt section: Int) -> CGFloat
}
extension CollectionViewDelegateFlowLayout {
public func collectionView(_ collectionView: CollectionView,
flowLayout: CollectionViewFlowLayout,
styleForItemAt indexPath: IndexPath) -> CollectionViewFlowLayout.ItemStyle {
return flowLayout.defaultItemStyle
}
public func collectionView (_ collectionView: CollectionView,
flowLayout collectionViewLayout: CollectionViewFlowLayout,
heightForHeaderInSection section: Int) -> CGFloat {
return collectionViewLayout.defaultHeaderHeight
}
public func collectionView (_ collectionView: CollectionView,
flowLayout collectionViewLayout: CollectionViewFlowLayout,
heightForFooterInSection section: Int) -> CGFloat {
return collectionViewLayout.defaultFooterHeight
}
public func collectionView (_ collectionView: CollectionView,
flowLayout collectionViewLayout: CollectionViewFlowLayout,
insetsForSectionAt section: Int) -> NSEdgeInsets {
return collectionViewLayout.defaultSectionInsets
}
public func collectionView (_ collectionView: CollectionView,
flowLayout collectionViewLayout: CollectionViewFlowLayout,
rowTransformForSectionAt section: Int) -> CollectionViewFlowLayout.RowTransform {
return collectionViewLayout.defaultRowTransform
}
public func collectionView (_ collectionView: CollectionView,
flowLayout collectionViewLayout: CollectionViewFlowLayout,
interitemSpacingForSectionAt section: Int) -> CGFloat {
return collectionViewLayout.interitemSpacing
}
public func collectionView (_ collectionView: CollectionView,
flowLayout collectionViewLayout: CollectionViewFlowLayout,
interspanSpacingForSectionAt section: Int) -> CGFloat? {
return collectionViewLayout.interspanSpacing
}
}
/**
A variation of UICollectionViewFlowLayout
This layout is primarily row based, but uses ItemStyles to group similar items together.
The layout's delegate, CollectionViewDelegateFlowLayout, is responsible for providing a style for each item in the collection view.
Flow items are grouped together, always placing as many same height items in each row as possible. If the row becomes full or an flow item of a different height is provided, the layout will just to the next row and continue.
Span items are always placed an their own row and fill the width of the Collection View.
### Example
```
+---------------------------------+
| +-----+ +------------+ +--+ |
| | 1 | | 2 | | 3| |
| | | | | | | |
| +-----+ +------------+ +--+ |
| +--------+ +---------+ |
| | 4 | | 5 | |
| | | | | |
| | | | | |
| | | | | |
| +--------+ +---------+ |
| +-------------------------+ |
| | 6. Span | |
| +-------------------------+ |
+---------------------------------+
```
### Transformations
Transformations allow you to adjust the content of each row before moving on to the next row.
The "center" transformation will shift the of the row to be center aligned rather than left aligned.
The fill tranformation will enlarge the items in a row proportionally to fill the row if their is empty space on the right. Note that this will affect the height of the entire row.
### Spacing
Spacing options such as interspanSpacing and spanGroupSpacingBefore allow you to customize the space around different types of style groups.
The spanGroupSpacingBefore/After options will apply a set amount of space before or after a group of span items (one or more spans).
*/
open class CollectionViewFlowLayout: CollectionViewLayout {
// MARK: - Options
/*-------------------------------------------------------------------------------*/
/// Spacing between flow elements
public var interitemSpacing: CGFloat = 8
@available(*, renamed: "interspanSpacing")
public var interpanSpacing: CGFloat?
/// Vertical spacing between multiple span elements (defaults to interitemSpacing)
public var interspanSpacing: CGFloat?
/// Top spacing between the span elements that are preceded by flow elements
public var spanGroupSpacingBefore: CGFloat?
/// Bottom spacing between span elements that are followed by flow elements
public var spanGroupSpacingAfter: CGFloat?
public var defaultItemStyle = ItemStyle.flow(CGSize(width: 60, height: 60))
public var defaultFooterHeight: CGFloat = 0
public var defaultHeaderHeight: CGFloat = 0
public var defaultRowTransform: RowTransform = .none
public var defaultSectionInsets: NSEdgeInsets = NSEdgeInsetsZero
/// If supplementary views should be inset to section insets
public var insetSupplementaryViews = false
// MARK: - Layout Information
/*-------------------------------------------------------------------------------*/
/// Only used during layout preparation to reference the width of the previously inserted row
private(set) public var widthOfLastRow: CGFloat?
/// Row transforms can be applied to flow elements that fall within the same row
///
/// - none: No transform
/// - center: Center the elements at their current size and spacing
/// - fill: Enlarge the elements to fill the row specifying the max scale (< 1 for no max)
public enum RowTransform {
case none
case center
case fill(CGFloat)
case custom(RowTransformer)
}
public typealias RowTransformer = ([(IndexPath, CGRect)], CGFloat) -> [CGRect]
/// Styles for CollectionViewFlowLayout
public enum ItemStyle {
/// Flow items with like other surrounding like-sized items
case flow(CGSize)
/// Break from the flow positioning the item in it's own row
case span(CGSize)
var isSpan: Bool {
switch self {
case .span: return true
default: return false
}
}
}
private struct RowAttributes: CustomStringConvertible {
var frame = CGRect.null
var itemHeight: CGFloat {
return items.last?.frame.size.height ?? 0
}
var items: [CollectionViewLayoutAttributes]
init(attributes: CollectionViewLayoutAttributes) {
self.items = [attributes]
self.frame = attributes.frame
}
mutating func add(attributes: CollectionViewLayoutAttributes) {
items.append(attributes)
frame = frame.union(attributes.frame)
}
func contains(_ indexPath: IndexPath) -> Bool {
guard let f = items.first?.indexPath._item, f <= indexPath._item else { return false }
guard let l = items.last?.indexPath._item, l >= indexPath._item else { return false }
return true
}
mutating func applyTransform(_ transform: RowTransform, leftInset: CGFloat, width: CGFloat, spacing: CGFloat) -> CGFloat {
func apply(_ transformer: RowTransformer) -> CGRect {
let _items = self.items.map { attrs in (attrs.indexPath, attrs.frame)}
let transformed = transformer(_items, width)
var union = CGRect()
for (idx, item) in items.enumerated() {
let f = transformed[idx].integral
item.frame = f
union = union.union(f)
}
return union
}
var union: CGRect
switch transform {
case .center:
let adjust = ((width - frame.size.width)/2)
union = apply { (attrs, _) in
attrs.map { $0.1.offsetBy(dx: adjust, dy: 0) }
}
case let .fill(maxScale):
var scale = width/frame.size.width
if maxScale > 1 && scale > maxScale { scale = maxScale }
var left = leftInset
union = apply { (attrs, _) in
attrs.map { attr -> CGRect in
var frame = attr.1
frame.origin.x = left
frame.size.width *= scale
frame.size.height *= scale
frame = frame.integral
left = frame.maxX + spacing
return frame
}
}
case let .custom(transformer):
union = apply(transformer)
case .none: union = self.frame
}
self.frame = self.frame.union(union)
return self.frame.maxY
}
func index(of indexPath: IndexPath) -> Int? {
guard let f = self.items.first,
let l = self.items.last else { return nil }
if f.indexPath > indexPath { return nil }
if l.indexPath < indexPath { return nil }
return self.items.firstIndex {
return $0.indexPath == indexPath
}
}
func item(verticallyAlignedTo attrs: CollectionViewLayoutAttributes) -> IndexPath? {
guard self.items.count > 1, !self.items.isEmpty,
let l = self.items.last else { return items.last?.indexPath }
let center = attrs.frame.midX
if l.frame.origin.x < center { return l.indexPath }
return self.items.first {
return $0.frame.maxX > center
}?.indexPath
}
var description: String {
return "Row Attributes : \(frame) -- \(items.count)"
}
}
private struct SectionAttributes: CustomStringConvertible {
var frame = CGRect.zero
let insets: NSEdgeInsets
let transform: RowTransform
var contentFrame = CGRect.zero
var header: CollectionViewLayoutAttributes?
var footer: CollectionViewLayoutAttributes?
var rows: [RowAttributes] = []
var items: [CollectionViewLayoutAttributes] = []
var description: String {
return "Section Attributes : \(frame) content: \(contentFrame) Rows: \(rows.count) Items: \(items.count)"
}
init(insets: NSEdgeInsets, transform: RowTransform) {
self.insets = insets
self.transform = transform
}
}
private var delegate: CollectionViewDelegateFlowLayout? {
return self.collectionView?.delegate as? CollectionViewDelegateFlowLayout
}
private var sectionAttributes = [SectionAttributes]()
// MARK: - Layout Overrides
/*-------------------------------------------------------------------------------*/
private var _lastSize = CGSize.zero
open override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return _lastSize != newBounds.size
}
override open func prepare() {
self.allIndexPaths.removeAll()
self.sectionAttributes.removeAll()
guard let cv = self.collectionView else { return }
self._lastSize = cv.frame.size
let numSections = cv.numberOfSections
guard numSections > 0 else { return }
var top: CGFloat = self.collectionView?.leadingView?.bounds.size.height ?? 0
let contentInsets = cv.contentInsets
for sec in 0..<numSections {
let _interitemSpacing = self.delegate?.collectionView(cv, flowLayout: self, interitemSpacingForSectionAt: sec) ?? self.interitemSpacing
let _interspanSpacing = self.delegate?.collectionView(cv, flowLayout: self, interspanSpacingForSectionAt: sec) ?? self.interpanSpacing
let insets = self.delegate?.collectionView(cv, flowLayout: self, insetsForSectionAt: sec) ?? self.defaultSectionInsets
let transform = self.delegate?.collectionView(cv, flowLayout: self, rowTransformForSectionAt: sec) ?? self.defaultRowTransform
var sectionAttrs = SectionAttributes(insets: insets, transform: transform)
let numItems = cv.numberOfItems(in: sec)
sectionAttrs.frame.origin.y = top
sectionAttrs.contentFrame.origin.y = top
let contentWidth = cv.contentVisibleRect.size.width - insets.width
let heightHeader: CGFloat = self.delegate?.collectionView(cv, flowLayout: self, heightForHeaderInSection: sec) ?? self.defaultHeaderHeight
if heightHeader > 0 {
let attrs = CollectionViewLayoutAttributes(forSupplementaryViewOfKind: CollectionViewLayoutElementKind.SectionHeader,
with: IndexPath.for(section: sec))
attrs.frame = insetSupplementaryViews
? CGRect(x: insets.left, y: top, width: contentWidth, height: heightHeader)
: CGRect(x: contentInsets.left, y: top, width: cv.frame.size.width - contentInsets.width, height: heightHeader)
sectionAttrs.header = attrs
sectionAttrs.frame = attrs.frame
top = attrs.frame.maxY
}
top += insets.top
sectionAttrs.contentFrame.origin.y = top
var previousStyle: ItemStyle?
if numItems > 0 {
func adjustOversizedIfNeeded(_ attributes: CollectionViewLayoutAttributes) {
if attributes.frame.size.width > contentWidth {
let scale = contentWidth/attributes.frame.size.width
attributes.frame.size = CGSize(width: attributes.frame.size.width * scale, height: attributes.frame.size.height * scale)
}
}
var forceBreak: Bool = false
for item in 0..<numItems {
let ip = IndexPath.for(item: item, section: sec)
allIndexPaths.append(ip)
let style = self.delegate?.collectionView(cv, flowLayout: self, styleForItemAt: ip) ?? defaultItemStyle
let attrs = CollectionViewLayoutAttributes(forCellWith: ip)
switch style {
case let .flow(size):
func newRow() {
var spacing: CGFloat = 0
if !sectionAttrs.rows.isEmpty {
top = sectionAttrs.rows[sectionAttrs.rows.count - 1].applyTransform(transform,
leftInset: insets.left,
width: contentWidth,
spacing: _interitemSpacing)
if let s = self.spanGroupSpacingAfter, previousStyle?.isSpan == true {
spacing = s
} else {
spacing = _interitemSpacing
}
}
attrs.frame = CGRect(x: insets.left, y: top + spacing, width: size.width, height: size.height)
adjustOversizedIfNeeded(attrs)
sectionAttrs.rows.append(RowAttributes(attributes: attrs))
}
// Check if the last row (if any) matches this items height
if !forceBreak, let prev = sectionAttrs.rows.last?.items.last, prev.frame.size.height == size.height {
// If there is enough space remaining, add it to the current row
let rem = contentWidth - (prev.frame.maxX - contentInsets.left - insets.left) - _interitemSpacing
if rem >= size.width {
attrs.frame = CGRect(x: prev.frame.maxX + _interitemSpacing, y: prev.frame.origin.y,
width: size.width, height: size.height)
sectionAttrs.rows[sectionAttrs.rows.count - 1].add(attributes: attrs)
} else { newRow() }
} else { newRow() }
forceBreak = false
case let .span(size):
if !sectionAttrs.rows.isEmpty && previousStyle?.isSpan != true {
top = sectionAttrs.rows[sectionAttrs.rows.count - 1].applyTransform(transform,
leftInset: insets.left,
width: contentWidth,
spacing: _interitemSpacing)
}
var spacing: CGFloat = 0
if !sectionAttrs.rows.isEmpty {
if let s = self.spanGroupSpacingBefore, previousStyle?.isSpan == false {
spacing = s
} else if let s = _interspanSpacing, previousStyle?.isSpan == true {
spacing = s
} else {
spacing = _interitemSpacing
}
}
attrs.frame = CGRect(x: insets.left, y: top + spacing, width: size.width, height: size.height)
sectionAttrs.rows.append(RowAttributes(attributes: attrs))
forceBreak = true
}
sectionAttrs.items.append(attrs)
sectionAttrs.contentFrame = sectionAttrs.contentFrame.union(attrs.frame)
top = sectionAttrs.contentFrame.maxY
widthOfLastRow = sectionAttrs.rows.last?.frame.size.width
previousStyle = style
}
// Cleanup section
widthOfLastRow = nil
previousStyle = nil
if !sectionAttrs.rows.isEmpty {
top = sectionAttrs.rows[sectionAttrs.rows.count - 1].applyTransform(transform,
leftInset: insets.left,
width: contentWidth,
spacing: _interitemSpacing)
}
}
top += insets.bottom
sectionAttrs.frame = sectionAttrs.frame.union(sectionAttrs.contentFrame)
sectionAttrs.frame.size.height += insets.bottom
let footerHeader: CGFloat = self.delegate?.collectionView(cv, flowLayout: self, heightForFooterInSection: sec) ?? 0
if footerHeader > 0 {
let attrs = CollectionViewLayoutAttributes(forSupplementaryViewOfKind: CollectionViewLayoutElementKind.SectionFooter,
with: IndexPath.for(section: sec))
attrs.frame = insetSupplementaryViews
? CGRect(x: insets.left + contentInsets.left, y: top, width: contentWidth, height: heightHeader)
: CGRect(x: contentInsets.left, y: top,
width: cv.contentVisibleRect.size.width - contentInsets.left - contentInsets.right, height: heightHeader)
sectionAttrs.footer = attrs
sectionAttrs.frame = sectionAttrs.frame.union(attrs.frame)
top = attrs.frame.maxY
}
sectionAttributes.append(sectionAttrs)
}
}
// MARK: - Query Content
/*-------------------------------------------------------------------------------*/
override open func indexPathsForItems(in rect: CGRect) -> [IndexPath] {
return itemAttributes(in: rect) { return $0.indexPath }
}
override open func layoutAttributesForItems(in rect: CGRect) -> [CollectionViewLayoutAttributes] {
return itemAttributes(in: rect) { return $0.copy() }
}
private func itemAttributes<T>(in rect: CGRect, reducer: ((CollectionViewLayoutAttributes) -> T)) -> [T] {
guard !rect.isEmpty && !self.sectionAttributes.isEmpty else { return [] }
var results = [T]()
for sAttrs in self.sectionAttributes {
// If we have passed the target, finish
guard sAttrs.frame.intersects(rect) else {
guard sAttrs.frame.origin.y < rect.maxY else { break }
continue
}
// If the section is completely shown, add all the attrs
if rect.contains(sAttrs.frame) {
results.append(contentsOf: sAttrs.items.map { return reducer($0) })
}
// Scan the rows of the section
else if !sAttrs.rows.isEmpty {
for row in sAttrs.rows {
guard row.frame.intersects(rect) else {
guard row.frame.origin.y < rect.maxY else { break }
continue
}
for item in row.items where item.frame.intersects(rect) {
results.append(reducer(item))
}
}
}
}
return results
}
override open func layoutAttributesForItem(at indexPath: IndexPath) -> CollectionViewLayoutAttributes? {
return self.sectionAttributes.object(at: indexPath._section)?.items.object(at: indexPath._item)?.copy()
}
override open func layoutAttributesForSupplementaryView(ofKind elementKind: String, at indexPath: IndexPath) -> CollectionViewLayoutAttributes? {
if elementKind == CollectionViewLayoutElementKind.SectionHeader {
let attrs = self.sectionAttributes[indexPath._section].header?.copy()
if pinHeadersToTop, let currentAttrs = attrs, let cv = self.collectionView {
let contentOffset = cv.contentOffset
let frame = currentAttrs.frame
// let lead = cv.leadingView?.bounds.size.height ?? 0
// if indexPath._section == 0 && contentOffset.y < cv.contentInsets.top {
// currentAttrs.frame.origin.y = lead
// currentAttrs.floating = false
// }
// else {
var nextHeaderOrigin = CGPoint(x: CGFloat.greatestFiniteMagnitude, y: CGFloat.greatestFiniteMagnitude)
if let nextHeader = self.sectionAttributes.object(at: indexPath._section + 1)?.header {
nextHeaderOrigin = nextHeader.frame.origin
}
let topInset = cv.contentInsets.top
currentAttrs.frame.origin.y = min(max(contentOffset.y + topInset, frame.origin.y), nextHeaderOrigin.y - frame.height)
currentAttrs.floating = indexPath._section == 0 || currentAttrs.frame.origin.y > frame.origin.y
// }
}
return attrs
} else if elementKind == CollectionViewLayoutElementKind.SectionFooter {
return self.sectionAttributes[indexPath._section].footer?.copy()
}
return nil
}
open override func rectForSection(_ section: Int) -> CGRect {
return sectionAttributes[section].frame
}
open override func contentRectForSection(_ section: Int) -> CGRect {
return sectionAttributes[section].contentFrame
}
override open var collectionViewContentSize: CGSize {
guard let cv = collectionView else { return CGSize.zero }
let numberOfSections = cv.numberOfSections
if numberOfSections == 0 { return CGSize.zero }
var contentSize = cv.contentVisibleRect.size as CGSize
let height = self.sectionAttributes.last?.frame.maxY ?? 0
if height == 0 { return CGSize.zero }
contentSize.height = max(height, cv.contentVisibleRect.height - cv.contentInsets.height)
return contentSize
}
open override func scrollRectForItem(at indexPath: IndexPath, atPosition: CollectionViewScrollPosition) -> CGRect? {
guard var frame = self.layoutAttributesForItem(at: indexPath)?.frame else { return nil }
let section = self.sectionAttributes[indexPath._section]
let inset = (self.collectionView?.contentInsets.top ?? 0) - section.insets.top
if let headerHeight = section.header?.frame.size.height {
var y = frame.origin.y
if pinHeadersToTop || section.rows.first?.contains(indexPath) == true {
y = (frame.origin.y - headerHeight)
}
let height = frame.size.height + headerHeight
frame.size.height = height
frame.origin.y = y
}
frame.origin.y += inset
return frame
}
open override func indexPathForNextItem(moving direction: CollectionViewDirection, from currentIndexPath: IndexPath) -> IndexPath? {
guard let collectionView = self.collectionView else { fatalError() }
// var index = currentIndexPath._item
let section = currentIndexPath._section
// let numberOfSections = collectionView.numberOfSections
// let numberOfItemsInSection = collectionView.numberOfItems(in: currentIndexPath._section)
guard collectionView.rectForItem(at: currentIndexPath) != nil else { return nil }
var startingIP = currentIndexPath
func shouldSelectItem(at indexPath: IndexPath) -> IndexPath? {
let set = Set([indexPath])
let valid = self.collectionView?.delegate?.collectionView?(collectionView, shouldSelectItemsAt: set) ?? set
return valid.first
}
switch direction {
case .up:
guard let cAttrs = collectionView.layoutAttributesForItem(at: currentIndexPath) else { return nil }
var proposed: IndexPath?
var prev: RowAttributes?
for row in sectionAttributes[section].rows {
if row.index(of: currentIndexPath) != nil {
guard let pRow = prev else {
guard let pSectionRow = sectionAttributes.object(at: section - 1)?.rows.last else { return nil }
proposed = pSectionRow.item(verticallyAlignedTo: cAttrs)
break
}
proposed = pRow.item(verticallyAlignedTo: cAttrs)
break
}
prev = row
}
guard let ip = proposed else { return nil }
if let p = shouldSelectItem(at: ip) {
return p
}
startingIP = ip
fallthrough
case .left:
var ip = startingIP
while true {
guard let prop = self.allIndexPaths.object(before: ip) else { return nil }
if let p = shouldSelectItem(at: prop) {
return p
}
ip = prop
}
case .down:
guard let cAttrs = collectionView.layoutAttributesForItem(at: currentIndexPath) else { return nil }
var proposed: IndexPath?
var prev: RowAttributes?
for row in sectionAttributes[section].rows.reversed() {
if row.index(of: currentIndexPath) != nil {
guard let pRow = prev else {
guard let pSectionRow = sectionAttributes.object(at: section + 1)?.rows.first else { return nil }
proposed = pSectionRow.item(verticallyAlignedTo: cAttrs)
break
}
proposed = pRow.item(verticallyAlignedTo: cAttrs)
break
}
prev = row
}
guard let ip = proposed else { return nil }
if let p = shouldSelectItem(at: ip) {
return p
}
startingIP = ip
fallthrough
case .right :
var ip = startingIP
while true {
guard let prop = self.allIndexPaths.object(after: ip) else { return nil }
if let p = shouldSelectItem(at: prop) {
return p
}
ip = prop
}
}
}
}
| mit | 0aaede09708a725f32c8cb79a77fad6c | 44.978723 | 225 | 0.541214 | 5.90538 | false | false | false | false |
steve-holmes/music-app-2 | MusicApp/Modules/Rank/RankType.swift | 1 | 630 | //
// RankType.swift
// MusicApp
//
// Created by Hưng Đỗ on 6/30/17.
// Copyright © 2017 HungDo. All rights reserved.
//
import UIKit
let kRankTypeSong = "song"
let kRankTypePlaylist = "playlist"
let kRankTypeVideo = "video"
let kRankCountryVietnam = "nhac-viet"
let kRankCountryEurope = "au-my"
let kRankCountryKorea = "nhac-han"
let kRankColorFirst = UIColor(withIntRed: 255, green: 0, blue: 0)
let kRankColorSecond = UIColor(withIntRed: 255, green: 102, blue: 102)
let kRankColorThird = UIColor(withIntRed: 255, green: 128, blue: 0)
let kRankColorNormal = UIColor(withIntWhite: 153)
| mit | f67bc1cf2e7ef01c6d94f4164b8375b2 | 27.409091 | 73 | 0.6992 | 2.893519 | false | false | false | false |
HabitRPG/habitrpg-ios | HabitRPG/UI/Purchases/GiftSubscriptionViewController.swift | 1 | 9849 | //
// GiftSubscriptionViewController.swift
// Habitica
//
// Created by Phillip Thelen on 10.12.18.
// Copyright © 2018 HabitRPG Inc. All rights reserved.
//
import UIKit
import SwiftyStoreKit
import StoreKit
import Keys
import ReactiveSwift
import Habitica_Models
class GiftSubscriptionViewController: BaseTableViewController {
@IBOutlet weak var avatarView: AvatarView!
@IBOutlet weak var displayNameLabel: UsernameLabel!
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var explanationTitle: UILabel!
@IBOutlet weak var giftOneGetOneTitleLabel: UILabel!
@IBOutlet weak var giftOneGetOneDescriptionLabel: UILabel!
private let socialRepository = SocialRepository()
private let configRepository = ConfigRepository()
private let disposable = ScopedDisposable(CompositeDisposable())
var products: [SKProduct]?
var selectedSubscriptionPlan: SKProduct?
public var giftRecipientUsername: String?
var giftedUser: MemberProtocol? {
didSet {
if let user = giftedUser {
avatarView.avatar = AvatarViewModel(avatar: user)
displayNameLabel.text = giftedUser?.profile?.name
displayNameLabel.contributorLevel = user.contributor?.level ?? 0
usernameLabel.text = "@\(user.username ?? "")"
}
}
}
let appleValidator: AppleReceiptValidator
let itunesSharedSecret = HabiticaKeys().itunesSharedSecret
var expandedList = [Bool](repeating: false, count: 4)
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
#if DEBUG
appleValidator = AppleReceiptValidator(service: .production, sharedSecret: itunesSharedSecret)
#else
appleValidator = AppleReceiptValidator(service: .production, sharedSecret: itunesSharedSecret)
#endif
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
required init?(coder aDecoder: NSCoder) {
#if DEBUG
appleValidator = AppleReceiptValidator(service: .production, sharedSecret: itunesSharedSecret)
#else
appleValidator = AppleReceiptValidator(service: .production, sharedSecret: itunesSharedSecret)
#endif
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
let optionNib = UINib.init(nibName: "SubscriptionOptionView", bundle: nil)
self.tableView.register(optionNib, forCellReuseIdentifier: "OptionCell")
retrieveProductList()
avatarView.showPet = false
avatarView.showMount = false
avatarView.showBackground = false
avatarView.ignoreSleeping = true
if let username = giftRecipientUsername {
disposable.inner.add(socialRepository.retrieveMemberWithUsername(username).observeValues({ member in
self.giftedUser = member
}))
}
if !configRepository.bool(variable: .enableGiftOneGetOne) {
tableView.tableFooterView = nil
}
explanationTitle.text = L10n.giftSubscriptionPrompt
}
override func populateText() {
navigationItem.title = L10n.Titles.giftSubscription
}
override func applyTheme(theme: Theme) {
super.applyTheme(theme: theme)
navigationController?.navigationBar.shadowImage = UIImage()
}
func retrieveProductList() {
SwiftyStoreKit.retrieveProductsInfo(Set(PurchaseHandler.noRenewSubscriptionIdentifiers)) { (result) in
self.products = Array(result.retrievedProducts)
self.products?.sort(by: { (product1, product2) -> Bool in
guard let firstIndex = PurchaseHandler.noRenewSubscriptionIdentifiers.firstIndex(of: product1.productIdentifier) else {
return false
}
guard let secondIndex = PurchaseHandler.noRenewSubscriptionIdentifiers.firstIndex(of: product2.productIdentifier) else {
return true
}
return firstIndex < secondIndex
})
self.selectedSubscriptionPlan = self.products?.first
self.tableView.reloadData()
self.tableView.selectRow(at: IndexPath(item: 0, section: 0), animated: true, scrollPosition: .none)
}
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 3
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
guard let products = self.products else {
return 0
}
if section == 0 {
return products.count
} else {
return 1
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if indexPath.section == 0 {
return 106
}
return 70
}
override func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if indexPath.section != 0 {
return nil
}
return indexPath
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.selectedSubscriptionPlan = (self.products?[indexPath.item])
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
var returnedCell: UITableViewCell?
if indexPath.section == 0 {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "OptionCell", for: indexPath) as? SubscriptionOptionView else {
fatalError()
}
let product = self.products?[indexPath.item]
cell.priceLabel.text = product?.localizedPrice
cell.titleLabel.text = product?.localizedTitle
cell.flagView.isHidden = true
switch product?.productIdentifier {
case PurchaseHandler.noRenewSubscriptionIdentifiers[0]:
cell.setMonthCount(1)
case PurchaseHandler.noRenewSubscriptionIdentifiers[1]:
cell.setMonthCount(3)
case PurchaseHandler.noRenewSubscriptionIdentifiers[2]:
cell.setMonthCount(6)
case PurchaseHandler.noRenewSubscriptionIdentifiers[3]:
cell.setMonthCount(12)
cell.flagView.text = "Save 20%"
cell.flagView.textColor = .white
cell.flagView.isHidden = false
default:
break
}
DispatchQueue.main.async {
cell.setSelected(product?.productIdentifier == self.selectedSubscriptionPlan?.productIdentifier, animated: true)
}
returnedCell = cell
} else if indexPath.section == tableView.numberOfSections-1 {
returnedCell = tableView.dequeueReusableCell(withIdentifier: "SubscribeButtonCell", for: indexPath)
(returnedCell?.viewWithTag(1) as? UIButton)?.setTitle(L10n.sendGift, for: .normal)
}
returnedCell?.selectionStyle = .none
return returnedCell ?? UITableViewCell()
}
func isInformationSection(_ section: Int) -> Bool {
return section == 0
}
@IBAction func subscribeButtonPressed(_ sender: Any) {
self.subscribeToPlan()
}
func subscribeToPlan() {
guard let identifier = self.selectedSubscriptionPlan?.productIdentifier else {
return
}
PurchaseHandler.shared.pendingGifts[identifier] = self.giftedUser?.id
SwiftyStoreKit.purchaseProduct(identifier, atomically: false) { result in
switch result {
case .success(let product):
self.displayConfirmationDialog()
print("Purchase Success: \(product.productId)")
case .error(let error):
print("Purchase Failed: \(error)")
}
}
}
func isSubscription(_ identifier: String) -> Bool {
return PurchaseHandler.subscriptionIdentifiers.contains(identifier)
}
func isValidSubscription(_ identifier: String, receipt: ReceiptInfo) -> Bool {
if !isSubscription(identifier) {
return false
}
let purchaseResult = SwiftyStoreKit.verifySubscription(
ofType: .autoRenewable,
productId: identifier,
inReceipt: receipt,
validUntil: Date()
)
switch purchaseResult {
case .purchased:
return true
case .expired:
return false
case .notPurchased:
return false
}
}
private func selectedDurationString() -> String {
switch selectedSubscriptionPlan?.productIdentifier {
case PurchaseHandler.noRenewSubscriptionIdentifiers[0]:
return "1"
case PurchaseHandler.noRenewSubscriptionIdentifiers[1]:
return "3"
case PurchaseHandler.noRenewSubscriptionIdentifiers[2]:
return "6"
case PurchaseHandler.noRenewSubscriptionIdentifiers[3]:
return "12"
default:
return ""
}
}
func displayConfirmationDialog() {
let body = L10n.giftConfirmationBody(usernameLabel.text ?? "", selectedDurationString())
let alertController = HabiticaAlertController(title: L10n.giftConfirmationTitle, message: body)
alertController.addCloseAction { _ in
self.dismiss(animated: true, completion: nil)
}
alertController.show()
}
@IBAction func cancelButtonTapped(_ sender: Any) {
dismiss(animated: true, completion: nil)
}
}
| gpl-3.0 | 06485d183a6829991c77b824e8b29969 | 36.30303 | 138 | 0.6316 | 5.452935 | false | false | false | false |
neonichu/Doppler | Code/Radar.swift | 1 | 954 | import Foundation
public struct Radar {
public let radarNumber: Int
public let title: String
public let body: String
public let product: String
public let version: String
public let classification: String
public let reproducible: String
public let status: String? = nil
public let dateOriginated: NSDate? = nil
public let configurationString: String? = nil
public let attachmentURL: NSURL? = nil
}
/* TODO: unhandled OpenRadar data: originated, resolved, status, user */
extension Radar : Decodable {
public static func decode(json: AnyObject) throws -> Radar {
let result = try json => "result"
let number = (try result => "number") as String
return try Radar(
radarNumber: Int(number) ?? 0,
title: result => "title",
body: result => "description",
product: result => "product",
version: result => "product_version",
classification: result => "classification",
reproducible: result => "reproducible")
}
}
| mit | 6b306ad1548e1410fd2d941ed28a3091 | 24.783784 | 72 | 0.710692 | 3.785714 | false | false | false | false |
meismyles/SwiftWebVC | Example/SwiftWebVCExample/ViewController.swift | 1 | 1671 | //
// ViewController.swift
// SwiftWebVCExample
//
// Created by Myles Ringle on 20/12/2016.
// Copyright © 2016 Myles Ringle. 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.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: Push
@IBAction func push() {
let webVC = SwiftWebVC(urlString: "https://www.google.com")
webVC.delegate = self
self.navigationController?.pushViewController(webVC, animated: true)
}
// MARK: Modal
@IBAction func presentModalWithDefaultTheme() {
let webVC = SwiftModalWebVC(urlString: "www.google.com")
self.present(webVC, animated: true, completion: nil)
}
@IBAction func presentModalWithLightBlackTheme() {
let webVC = SwiftModalWebVC(urlString: "https://www.google.com", theme: .lightBlack, dismissButtonStyle: .cross)
self.present(webVC, animated: true, completion: nil)
}
@IBAction func presentModalWithDarkTheme() {
let webVC = SwiftModalWebVC(urlString: "https://www.google.com", theme: .dark, dismissButtonStyle: .arrow)
self.present(webVC, animated: true, completion: nil)
}
}
extension ViewController: SwiftWebVCDelegate {
func didStartLoading() {
print("Started loading.")
}
func didFinishLoading(success: Bool) {
print("Finished loading. Success: \(success).")
}
}
| mit | 40647a929b781b836bd156365b858ba1 | 28.298246 | 120 | 0.65988 | 4.513514 | false | false | false | false |
fritzgerald/CustomLoader | Source/ProgressRingView.swift | 1 | 7366 | //
// LoadingIndicatorView.swift
// CustomLoader
//
// Created by fritzgerald muiseroux on 23/01/2017.
// Copyright © 2017 fritzgerald muiseroux. All rights reserved.
//
import UIKit
/**
A ring that view that can represent some background activity
*/
@IBDesignable
public class ProgressRingView: UIView {
private var addedLayer = [CALayer]()
/** Color of the inner ring */
@IBInspectable
public var innerColor: UIColor = UIColor.clear {
didSet {
setNeedsLayout()
}
}
/** Color of the outter ring */
@IBInspectable
public var outterColor: UIColor = UIColor.clear {
didSet {
setNeedsLayout()
}
}
/** the line width of each circle */
@IBInspectable
public var lineWidth: CGFloat = 3.0 {
didSet {
setNeedsLayout()
}
}
/**
A boolean that indicate if the view represent a determinate activity.
If false then the view will stop the animation and the outter ring will progress following the value ratio
*/
@IBInspectable
public var isIndeterminate: Bool = true {
didSet {
setNeedsLayout()
}
}
/** default 0.0. the current value may change if outside new min value */
@IBInspectable
public var minimumValue: CGFloat = 0 {
didSet {
if minimumValue >= maximumValue {
maximumValue = minimumValue + 1
}
if isIndeterminate == false {
setNeedsLayout()
}
}
}
/** default 1.0. the current value may change if outside new max value */
@IBInspectable
public var maximumValue: CGFloat = 1 {
didSet {
if isIndeterminate == false {
setNeedsLayout()
}
}
}
private var _value: CGFloat = 0
/** default 0.0. this value will be pinned to min/max */
@IBInspectable
public var value: CGFloat {
get { return _value }
set {
_value = min(max(newValue, minimumValue), maximumValue)
if isIndeterminate == false {
setNeedsLayout()
}
}
}
/** the actual progression between 0 and 1 */
public var valueRatio: Double {
return ProgressRingView.valueRatio(minumum: minimumValue, maximum: maximumValue, value: value)
}
public override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func circleLayer(color: UIColor, radius: CGFloat, angle: Double, lineWith width: CGFloat) -> CALayer {
let shapeLayer = CAShapeLayer(circleInFrame: bounds, radius:radius, maxAngle: angle)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = color.cgColor
shapeLayer.lineWidth = width
layer.addSublayer(shapeLayer)
return shapeLayer
}
private func initialize() {
if isIndeterminate {
initializeIndeterminate()
} else {
initializeDeterminate()
}
}
private func initializeDeterminate() {
let bigRadius = (bounds.width / 2.0) - lineWidth
let centerRadius = bigRadius - lineWidth
let valueRatio = ProgressRingView.valueRatio(minumum: minimumValue, maximum: maximumValue, value: value)
let theLayer = circleLayer(color: outterColor, radius: bigRadius, angle: .pi * 2 * valueRatio, lineWith: lineWidth)
layer.addSublayer(theLayer)
let theLayer2 = circleLayer(color: innerColor, radius: centerRadius, angle: .pi * 2, lineWith: lineWidth)
layer.addSublayer(theLayer2)
addedLayer.append(theLayer)
addedLayer.append(theLayer2)
}
private func initializeIndeterminate() {
let bigRadius = (bounds.width / 2.0) - lineWidth
let theLayer = circleLayer(color: outterColor, radius: bigRadius, angle: .pi, lineWith: lineWidth)
layer.addSublayer(theLayer)
theLayer.addRotationAnimation(clockwise: true)
let theLayer2 = circleLayer(color: innerColor, radius: bigRadius - lineWidth, angle: .pi, lineWith: lineWidth)
layer.addSublayer(theLayer2)
theLayer2.addRotationAnimation(clockwise: false)
addedLayer.append(theLayer)
addedLayer.append(theLayer2)
}
public override func layoutSubviews() {
super.layoutSubviews()
addedLayer.forEach { subLayer in
subLayer.removeFromSuperlayer()
}
addedLayer.removeAll()
initialize()
}
public override var intrinsicContentSize: CGSize {
return CGSize(width: 40, height: 40)
}
}
extension ProgressRingView {
// MARK: Helper
static func valueRatio(minumum: CGFloat, maximum: CGFloat, value: CGFloat) -> Double{
let amplitude = maximum - minumum
let translatedValue = fabs(Double(value - minumum))
let valueRatio = Double(translatedValue) / Double(amplitude)
return fmin(fmax(0, valueRatio), 1.0)
}
}
public extension ProgressRingView {
/** A progress Ring with a white outter color an dark gray inner color*/
public static var light: ProgressRingView {
let view = ProgressRingView()
view.outterColor = .white
view.innerColor = .darkGray
return view
}
/** A progress Ring with a black outter color an dark darkGray inner color*/
public static var dark: ProgressRingView {
let view = ProgressRingView()
view.outterColor = .black
view.innerColor = .darkGray
return view
}
}
extension CAShapeLayer {
convenience init(circleInFrame drawingFrame: CGRect,
radius: CGFloat,
maxAngle: Double = .pi * 2,
clockwise: Bool = true) {
self.init()
//let diameter = fmin(drawingFrame.width, drawingFrame.height)
let center = CGPoint(x: drawingFrame.width / 2.0, y: drawingFrame.height / 2.0)
let circlePath = UIBezierPath(arcCenter: center,
radius: radius,
startAngle: CGFloat(-.pi / 2.0),
endAngle:CGFloat(maxAngle - (.pi / 2.0)),
clockwise: clockwise)
path = circlePath.cgPath
frame = drawingFrame
}
}
extension CALayer {
/// Rotate forever around the Z axis
func addRotationAnimation(clockwise: Bool) {
let rotation = CABasicAnimation(keyPath: "transform.rotation.z")
rotation.fromValue = 0
rotation.toValue = Double.pi
if clockwise {
rotation.toValue = -Double.pi
}
rotation.isCumulative = true
rotation.timingFunction = CAMediaTimingFunction(name: .linear)
rotation.duration = 0.75
rotation.isAdditive = true
rotation.fillMode = .forwards
rotation.repeatCount = Float.greatestFiniteMagnitude;
self.add(rotation, forKey: "rotation")
}
}
| mit | b2a489bffb17475b44be7f2911e9b693 | 29.560166 | 123 | 0.594976 | 4.91 | false | false | false | false |
practicalswift/swift | stdlib/public/core/Builtin.swift | 2 | 34917 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SwiftShims
// Definitions that make elements of Builtin usable in real code
// without gobs of boilerplate.
// This function is the implementation of the `_roundUp` overload set. It is
// marked `@inline(__always)` to make primary `_roundUp` entry points seem
// cheap enough for the inliner.
@inlinable
@inline(__always)
internal func _roundUpImpl(_ offset: UInt, toAlignment alignment: Int) -> UInt {
_internalInvariant(alignment > 0)
_internalInvariant(_isPowerOf2(alignment))
// Note, given that offset is >= 0, and alignment > 0, we don't
// need to underflow check the -1, as it can never underflow.
let x = offset + UInt(bitPattern: alignment) &- 1
// Note, as alignment is a power of 2, we'll use masking to efficiently
// get the aligned value
return x & ~(UInt(bitPattern: alignment) &- 1)
}
@inlinable
internal func _roundUp(_ offset: UInt, toAlignment alignment: Int) -> UInt {
return _roundUpImpl(offset, toAlignment: alignment)
}
@inlinable
internal func _roundUp(_ offset: Int, toAlignment alignment: Int) -> Int {
_internalInvariant(offset >= 0)
return Int(_roundUpImpl(UInt(bitPattern: offset), toAlignment: alignment))
}
/// Returns a tri-state of 0 = no, 1 = yes, 2 = maybe.
@_transparent
public // @testable
func _canBeClass<T>(_: T.Type) -> Int8 {
return Int8(Builtin.canBeClass(T.self))
}
/// Returns the bits of the given instance, interpreted as having the specified
/// type.
///
/// Use this function only to convert the instance passed as `x` to a
/// layout-compatible type when conversion through other means is not
/// possible. Common conversions supported by the Swift standard library
/// include the following:
///
/// - Value conversion from one integer type to another. Use the destination
/// type's initializer or the `numericCast(_:)` function.
/// - Bitwise conversion from one integer type to another. Use the destination
/// type's `init(truncatingIfNeeded:)` or `init(bitPattern:)` initializer.
/// - Conversion from a pointer to an integer value with the bit pattern of the
/// pointer's address in memory, or vice versa. Use the `init(bitPattern:)`
/// initializer for the destination type.
/// - Casting an instance of a reference type. Use the casting operators (`as`,
/// `as!`, or `as?`) or the `unsafeDowncast(_:to:)` function. Do not use
/// `unsafeBitCast(_:to:)` with class or pointer types; doing so may
/// introduce undefined behavior.
///
/// - Warning: Calling this function breaks the guarantees of the Swift type
/// system; use with extreme care.
///
/// - Parameters:
/// - x: The instance to cast to `type`.
/// - type: The type to cast `x` to. `type` and the type of `x` must have the
/// same size of memory representation and compatible memory layout.
/// - Returns: A new instance of type `U`, cast from `x`.
@inlinable // unsafe-performance
@_transparent
public func unsafeBitCast<T, U>(_ x: T, to type: U.Type) -> U {
_precondition(MemoryLayout<T>.size == MemoryLayout<U>.size,
"Can't unsafeBitCast between types of different sizes")
return Builtin.reinterpretCast(x)
}
/// Returns `x` as its concrete type `U`.
///
/// This cast can be useful for dispatching to specializations of generic
/// functions.
///
/// - Requires: `x` has type `U`.
@_transparent
public func _identityCast<T, U>(_ x: T, to expectedType: U.Type) -> U {
_precondition(T.self == expectedType, "_identityCast to wrong type")
return Builtin.reinterpretCast(x)
}
/// `unsafeBitCast` something to `AnyObject`.
@usableFromInline @_transparent
internal func _reinterpretCastToAnyObject<T>(_ x: T) -> AnyObject {
return unsafeBitCast(x, to: AnyObject.self)
}
@usableFromInline @_transparent
internal func == (
lhs: Builtin.NativeObject, rhs: Builtin.NativeObject
) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@usableFromInline @_transparent
internal func != (
lhs: Builtin.NativeObject, rhs: Builtin.NativeObject
) -> Bool {
return !(lhs == rhs)
}
@usableFromInline @_transparent
internal func == (
lhs: Builtin.RawPointer, rhs: Builtin.RawPointer
) -> Bool {
return unsafeBitCast(lhs, to: Int.self) == unsafeBitCast(rhs, to: Int.self)
}
@usableFromInline @_transparent
internal func != (lhs: Builtin.RawPointer, rhs: Builtin.RawPointer) -> Bool {
return !(lhs == rhs)
}
/// Returns a Boolean value indicating whether two types are identical.
///
/// - Parameters:
/// - t0: A type to compare.
/// - t1: Another type to compare.
/// - Returns: `true` if both `t0` and `t1` are `nil` or if they represent the
/// same type; otherwise, `false`.
@inlinable
public func == (t0: Any.Type?, t1: Any.Type?) -> Bool {
switch (t0, t1) {
case (.none, .none): return true
case let (.some(ty0), .some(ty1)):
return Bool(Builtin.is_same_metatype(ty0, ty1))
default: return false
}
}
/// Returns a Boolean value indicating whether two types are not identical.
///
/// - Parameters:
/// - t0: A type to compare.
/// - t1: Another type to compare.
/// - Returns: `true` if one, but not both, of `t0` and `t1` are `nil`, or if
/// they represent different types; otherwise, `false`.
@inlinable
public func != (t0: Any.Type?, t1: Any.Type?) -> Bool {
return !(t0 == t1)
}
/// Tell the optimizer that this code is unreachable if condition is
/// known at compile-time to be true. If condition is false, or true
/// but not a compile-time constant, this call has no effect.
@usableFromInline @_transparent
internal func _unreachable(_ condition: Bool = true) {
if condition {
// FIXME: use a parameterized version of Builtin.unreachable when
// <rdar://problem/16806232> is closed.
Builtin.unreachable()
}
}
/// Tell the optimizer that this code is unreachable if this builtin is
/// reachable after constant folding build configuration builtins.
@usableFromInline @_transparent
internal func _conditionallyUnreachable() -> Never {
Builtin.conditionallyUnreachable()
}
@usableFromInline
@_silgen_name("_swift_isClassOrObjCExistentialType")
internal func _swift_isClassOrObjCExistentialType<T>(_ x: T.Type) -> Bool
/// Returns `true` iff `T` is a class type or an `@objc` existential such as
/// `AnyObject`.
@inlinable
@inline(__always)
internal func _isClassOrObjCExistential<T>(_ x: T.Type) -> Bool {
switch _canBeClass(x) {
// Is not a class.
case 0:
return false
// Is a class.
case 1:
return true
// Maybe a class.
default:
return _swift_isClassOrObjCExistentialType(x)
}
}
/// Converts a reference of type `T` to a reference of type `U` after
/// unwrapping one level of Optional.
///
/// Unwrapped `T` and `U` must be convertible to AnyObject. They may
/// be either a class or a class protocol. Either T, U, or both may be
/// optional references.
@_transparent
public func _unsafeReferenceCast<T, U>(_ x: T, to: U.Type) -> U {
return Builtin.castReference(x)
}
/// Returns the given instance cast unconditionally to the specified type.
///
/// The instance passed as `x` must be an instance of type `T`.
///
/// Use this function instead of `unsafeBitcast(_:to:)` because this function
/// is more restrictive and still performs a check in debug builds. In -O
/// builds, no test is performed to ensure that `x` actually has the dynamic
/// type `T`.
///
/// - Warning: This function trades safety for performance. Use
/// `unsafeDowncast(_:to:)` only when you are confident that `x is T` always
/// evaluates to `true`, and only after `x as! T` has proven to be a
/// performance problem.
///
/// - Parameters:
/// - x: An instance to cast to type `T`.
/// - type: The type `T` to which `x` is cast.
/// - Returns: The instance `x`, cast to type `T`.
@_transparent
public func unsafeDowncast<T : AnyObject>(_ x: AnyObject, to type: T.Type) -> T {
_debugPrecondition(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
@_transparent
public func _unsafeUncheckedDowncast<T : AnyObject>(_ x: AnyObject, to type: T.Type) -> T {
_internalInvariant(x is T, "invalid unsafeDowncast")
return Builtin.castReference(x)
}
@inlinable
@inline(__always)
public func _getUnsafePointerToStoredProperties(_ x: AnyObject)
-> UnsafeMutableRawPointer {
let storedPropertyOffset = _roundUp(
MemoryLayout<SwiftShims.HeapObject>.size,
toAlignment: MemoryLayout<Optional<AnyObject>>.alignment)
return UnsafeMutableRawPointer(Builtin.bridgeToRawPointer(x)) +
storedPropertyOffset
}
/// Get the minimum alignment for manually allocated memory.
///
/// Memory allocated via UnsafeMutable[Raw][Buffer]Pointer must never pass
/// an alignment less than this value to Builtin.allocRaw. This
/// ensures that the memory can be deallocated without specifying the
/// alignment.
@inlinable
@inline(__always)
internal func _minAllocationAlignment() -> Int {
return _swift_MinAllocationAlignment
}
//===----------------------------------------------------------------------===//
// Branch hints
//===----------------------------------------------------------------------===//
// Use @_semantics to indicate that the optimizer recognizes the
// semantics of these function calls. This won't be necessary with
// mandatory generic inlining.
@usableFromInline @_transparent
@_semantics("branchhint")
internal func _branchHint(_ actual: Bool, expected: Bool) -> Bool {
return Bool(Builtin.int_expect_Int1(actual._value, expected._value))
}
/// Optimizer hint that `x` is expected to be `true`.
@_transparent
@_semantics("fastpath")
public func _fastPath(_ x: Bool) -> Bool {
return _branchHint(x, expected: true)
}
/// Optimizer hint that `x` is expected to be `false`.
@_transparent
@_semantics("slowpath")
public func _slowPath(_ x: Bool) -> Bool {
return _branchHint(x, expected: false)
}
/// Optimizer hint that the code where this function is called is on the fast
/// path.
@_transparent
public func _onFastPath() {
Builtin.onFastPath()
}
// Optimizer hint that the condition is true. The condition is unchecked.
// The builtin acts as an opaque instruction with side-effects.
@usableFromInline @_transparent
func _uncheckedUnsafeAssume(_ condition: Bool) {
_ = Builtin.assume_Int1(condition._value)
}
//===--- Runtime shim wrappers --------------------------------------------===//
/// Returns `true` iff the class indicated by `theClass` uses native
/// Swift reference-counting.
#if _runtime(_ObjC)
// Declare it here instead of RuntimeShims.h, because we need to specify
// the type of argument to be AnyClass. This is currently not possible
// when using RuntimeShims.h
@usableFromInline
@_silgen_name("_swift_objcClassUsesNativeSwiftReferenceCounting")
internal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool
#else
@inlinable
@inline(__always)
internal func _usesNativeSwiftReferenceCounting(_ theClass: AnyClass) -> Bool {
return true
}
#endif
@usableFromInline
@_silgen_name("_swift_getSwiftClassInstanceExtents")
internal func getSwiftClassInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@usableFromInline
@_silgen_name("_swift_getObjCClassInstanceExtents")
internal func getObjCClassInstanceExtents(_ theClass: AnyClass)
-> (negative: UInt, positive: UInt)
@inlinable
@inline(__always)
internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int {
#if _runtime(_ObjC)
return Int(getObjCClassInstanceExtents(theClass).positive)
#else
return Int(getSwiftClassInstanceExtents(theClass).positive)
#endif
}
@inlinable
internal func _isValidAddress(_ address: UInt) -> Bool {
// TODO: define (and use) ABI max valid pointer value
return address >= _swift_abi_LeastValidPointerValue
}
//===--- Builtin.BridgeObject ---------------------------------------------===//
// TODO(<rdar://problem/34837023>): Get rid of superfluous UInt constructor
// calls
@inlinable
internal var _bridgeObjectTaggedPointerBits: UInt {
@inline(__always) get { return UInt(_swift_BridgeObject_TaggedPointerBits) }
}
@inlinable
internal var _objCTaggedPointerBits: UInt {
@inline(__always) get { return UInt(_swift_abi_ObjCReservedBitsMask) }
}
@inlinable
internal var _objectPointerSpareBits: UInt {
@inline(__always) get {
return UInt(_swift_abi_SwiftSpareBitsMask) & ~_bridgeObjectTaggedPointerBits
}
}
@inlinable
internal var _objectPointerLowSpareBitShift: UInt {
@inline(__always) get {
_internalInvariant(_swift_abi_ObjCReservedLowBits < 2,
"num bits now differs from num-shift-amount, new platform?")
return UInt(_swift_abi_ObjCReservedLowBits)
}
}
#if arch(i386) || arch(arm) || arch(powerpc64) || arch(powerpc64le) || arch(
s390x)
@inlinable
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x0000_0002 }
}
#else
@inlinable
internal var _objectPointerIsObjCBit: UInt {
@inline(__always) get { return 0x4000_0000_0000_0000 }
}
#endif
/// Extract the raw bits of `x`.
@inlinable
@inline(__always)
internal func _bitPattern(_ x: Builtin.BridgeObject) -> UInt {
return UInt(Builtin.castBitPatternFromBridgeObject(x))
}
/// Extract the raw spare bits of `x`.
@inlinable
@inline(__always)
internal func _nonPointerBits(_ x: Builtin.BridgeObject) -> UInt {
return _bitPattern(x) & _objectPointerSpareBits
}
@inlinable
@inline(__always)
internal func _isObjCTaggedPointer(_ x: AnyObject) -> Bool {
return (Builtin.reinterpretCast(x) & _objCTaggedPointerBits) != 0
}
@inlinable
@inline(__always)
internal func _isObjCTaggedPointer(_ x: UInt) -> Bool {
return (x & _objCTaggedPointerBits) != 0
}
/// TODO: describe extras
@inlinable @inline(__always) public // FIXME
func _isTaggedObject(_ x: Builtin.BridgeObject) -> Bool {
return _bitPattern(x) & _bridgeObjectTaggedPointerBits != 0
}
@inlinable @inline(__always) public // FIXME
func _isNativePointer(_ x: Builtin.BridgeObject) -> Bool {
return (
_bitPattern(x) & (_bridgeObjectTaggedPointerBits | _objectPointerIsObjCBit)
) == 0
}
@inlinable @inline(__always) public // FIXME
func _isNonTaggedObjCPointer(_ x: Builtin.BridgeObject) -> Bool {
return !_isTaggedObject(x) && !_isNativePointer(x)
}
@inlinable
@inline(__always)
func _getNonTagBits(_ x: Builtin.BridgeObject) -> UInt {
// Zero out the tag bits, and leave them all at the top.
_internalInvariant(_isTaggedObject(x), "not tagged!")
return (_bitPattern(x) & ~_bridgeObjectTaggedPointerBits)
>> _objectPointerLowSpareBitShift
}
// Values -> BridgeObject
@inline(__always)
@inlinable
public func _bridgeObject(fromNative x: AnyObject) -> Builtin.BridgeObject {
_internalInvariant(!_isObjCTaggedPointer(x))
let object = Builtin.castToBridgeObject(x, 0._builtinWordValue)
_internalInvariant(_isNativePointer(object))
return object
}
@inline(__always)
@inlinable
public func _bridgeObject(
fromNonTaggedObjC x: AnyObject
) -> Builtin.BridgeObject {
_internalInvariant(!_isObjCTaggedPointer(x))
let object = _makeObjCBridgeObject(x)
_internalInvariant(_isNonTaggedObjCPointer(object))
return object
}
@inline(__always)
@inlinable
public func _bridgeObject(fromTagged x: UInt) -> Builtin.BridgeObject {
_internalInvariant(x & _bridgeObjectTaggedPointerBits != 0)
let object: Builtin.BridgeObject = Builtin.valueToBridgeObject(x._value)
_internalInvariant(_isTaggedObject(object))
return object
}
@inline(__always)
@inlinable
public func _bridgeObject(taggingPayload x: UInt) -> Builtin.BridgeObject {
let shifted = x &<< _objectPointerLowSpareBitShift
_internalInvariant(x == (shifted &>> _objectPointerLowSpareBitShift),
"out-of-range: limited bit range requires some zero top bits")
_internalInvariant(shifted & _bridgeObjectTaggedPointerBits == 0,
"out-of-range: post-shift use of tag bits")
return _bridgeObject(fromTagged: shifted | _bridgeObjectTaggedPointerBits)
}
// BridgeObject -> Values
@inline(__always)
@inlinable
public func _bridgeObject(toNative x: Builtin.BridgeObject) -> AnyObject {
_internalInvariant(_isNativePointer(x))
return Builtin.castReferenceFromBridgeObject(x)
}
@inline(__always)
@inlinable
public func _bridgeObject(
toNonTaggedObjC x: Builtin.BridgeObject
) -> AnyObject {
_internalInvariant(_isNonTaggedObjCPointer(x))
return Builtin.castReferenceFromBridgeObject(x)
}
@inline(__always)
@inlinable
public func _bridgeObject(toTagged x: Builtin.BridgeObject) -> UInt {
_internalInvariant(_isTaggedObject(x))
let bits = _bitPattern(x)
_internalInvariant(bits & _bridgeObjectTaggedPointerBits != 0)
return bits
}
@inline(__always)
@inlinable
public func _bridgeObject(toTagPayload x: Builtin.BridgeObject) -> UInt {
return _getNonTagBits(x)
}
@inline(__always)
@inlinable
public func _bridgeObject(
fromNativeObject x: Builtin.NativeObject
) -> Builtin.BridgeObject {
return _bridgeObject(fromNative: _nativeObject(toNative: x))
}
//
// NativeObject
//
@inlinable
@inline(__always)
public func _nativeObject(fromNative x: AnyObject) -> Builtin.NativeObject {
_internalInvariant(!_isObjCTaggedPointer(x))
let native = Builtin.unsafeCastToNativeObject(x)
// _internalInvariant(native == Builtin.castToNativeObject(x))
return native
}
@inlinable
@inline(__always)
public func _nativeObject(
fromBridge x: Builtin.BridgeObject
) -> Builtin.NativeObject {
return _nativeObject(fromNative: _bridgeObject(toNative: x))
}
@inlinable
@inline(__always)
public func _nativeObject(toNative x: Builtin.NativeObject) -> AnyObject {
return Builtin.castFromNativeObject(x)
}
// FIXME
extension ManagedBufferPointer {
// FIXME: String Guts
@inline(__always)
@inlinable
public init(_nativeObject buffer: Builtin.NativeObject) {
self._nativeBuffer = buffer
}
}
/// Create a `BridgeObject` around the given `nativeObject` with the
/// given spare bits.
///
/// Reference-counting and other operations on this
/// object will have access to the knowledge that it is native.
///
/// - Precondition: `bits & _objectPointerIsObjCBit == 0`,
/// `bits & _objectPointerSpareBits == bits`.
@inlinable
@inline(__always)
internal func _makeNativeBridgeObject(
_ nativeObject: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_internalInvariant(
(bits & _objectPointerIsObjCBit) == 0,
"BridgeObject is treated as non-native when ObjC bit is set"
)
return _makeBridgeObject(nativeObject, bits)
}
/// Create a `BridgeObject` around the given `objCObject`.
@inlinable
@inline(__always)
public // @testable
func _makeObjCBridgeObject(
_ objCObject: AnyObject
) -> Builtin.BridgeObject {
return _makeBridgeObject(
objCObject,
_isObjCTaggedPointer(objCObject) ? 0 : _objectPointerIsObjCBit)
}
/// Create a `BridgeObject` around the given `object` with the
/// given spare bits.
///
/// - Precondition:
///
/// 1. `bits & _objectPointerSpareBits == bits`
/// 2. if `object` is a tagged pointer, `bits == 0`. Otherwise,
/// `object` is either a native object, or `bits ==
/// _objectPointerIsObjCBit`.
@inlinable
@inline(__always)
internal func _makeBridgeObject(
_ object: AnyObject, _ bits: UInt
) -> Builtin.BridgeObject {
_internalInvariant(!_isObjCTaggedPointer(object) || bits == 0,
"Tagged pointers cannot be combined with bits")
_internalInvariant(
_isObjCTaggedPointer(object)
|| _usesNativeSwiftReferenceCounting(type(of: object))
|| bits == _objectPointerIsObjCBit,
"All spare bits must be set in non-native, non-tagged bridge objects"
)
_internalInvariant(
bits & _objectPointerSpareBits == bits,
"Can't store non-spare bits into Builtin.BridgeObject")
return Builtin.castToBridgeObject(
object, bits._builtinWordValue
)
}
@_silgen_name("_swift_class_getSuperclass")
internal func _swift_class_getSuperclass(_ t: AnyClass) -> AnyClass?
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// a root class or class protocol.
public func _getSuperclass(_ t: AnyClass) -> AnyClass? {
return _swift_class_getSuperclass(t)
}
/// Returns the superclass of `t`, if any. The result is `nil` if `t` is
/// not a class, is a root class, or is a class protocol.
@inlinable
@inline(__always)
public // @testable
func _getSuperclass(_ t: Any.Type) -> AnyClass? {
return (t as? AnyClass).flatMap { _getSuperclass($0) }
}
//===--- Builtin.IsUnique -------------------------------------------------===//
// _isUnique functions must take an inout object because they rely on
// Builtin.isUnique which requires an inout reference to preserve
// source-level copies in the presence of ARC optimization.
//
// Taking an inout object makes sense for two additional reasons:
//
// 1. You should only call it when about to mutate the object.
// Doing so otherwise implies a race condition if the buffer is
// shared across threads.
//
// 2. When it is not an inout function, self is passed by
// value... thus bumping the reference count and disturbing the
// result we are trying to observe, Dr. Heisenberg!
//
// _isUnique cannot be made public or the compiler
// will attempt to generate generic code for the transparent function
// and type checking will fail.
/// Returns `true` if `object` is uniquely referenced.
@usableFromInline @_transparent
internal func _isUnique<T>(_ object: inout T) -> Bool {
return Bool(Builtin.isUnique(&object))
}
/// Returns `true` if `object` is uniquely referenced.
/// This provides sanity checks on top of the Builtin.
@_transparent
public // @testable
func _isUnique_native<T>(_ object: inout T) -> Bool {
// This could be a bridge object, single payload enum, or plain old
// reference. Any case it's non pointer bits must be zero, so
// force cast it to BridgeObject and check the spare bits.
_internalInvariant(
(_bitPattern(Builtin.reinterpretCast(object)) & _objectPointerSpareBits)
== 0)
_internalInvariant(_usesNativeSwiftReferenceCounting(
type(of: Builtin.reinterpretCast(object) as AnyObject)))
return Bool(Builtin.isUnique_native(&object))
}
/// Returns `true` if type is a POD type. A POD type is a type that does not
/// require any special handling on copying or destruction.
@_transparent
public // @testable
func _isPOD<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.ispod(type))
}
/// Returns `true` if type is a bitwise takable. A bitwise takable type can
/// just be moved to a different address in memory.
@_transparent
public // @testable
func _isBitwiseTakable<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.isbitwisetakable(type))
}
/// Returns `true` if type is nominally an Optional type.
@_transparent
public // @testable
func _isOptional<T>(_ type: T.Type) -> Bool {
return Bool(Builtin.isOptional(type))
}
/// Extract an object reference from an Any known to contain an object.
@inlinable
internal func _unsafeDowncastToAnyObject(fromAny any: Any) -> AnyObject {
_internalInvariant(type(of: any) is AnyObject.Type
|| type(of: any) is AnyObject.Protocol,
"Any expected to contain object reference")
// Ideally we would do something like this:
//
// func open<T>(object: T) -> AnyObject {
// return unsafeBitCast(object, to: AnyObject.self)
// }
// return _openExistential(any, do: open)
//
// Unfortunately, class constrained protocol existentials conform to AnyObject
// but are not word-sized. As a result, we cannot currently perform the
// `unsafeBitCast` on them just yet. When they are word-sized, it would be
// possible to efficiently grab the object reference out of the inline
// storage.
return any as AnyObject
}
// Game the SIL diagnostic pipeline by inlining this into the transparent
// definitions below after the stdlib's diagnostic passes run, so that the
// `staticReport`s don't fire while building the standard library, but do
// fire if they ever show up in code that uses the standard library.
@inlinable
@inline(__always)
public // internal with availability
func _trueAfterDiagnostics() -> Builtin.Int1 {
return true._value
}
/// Returns the dynamic type of a value.
///
/// You can use the `type(of:)` function to find the dynamic type of a value,
/// particularly when the dynamic type is different from the static type. The
/// *static type* of a value is the known, compile-time type of the value. The
/// *dynamic type* of a value is the value's actual type at run-time, which
/// can be a subtype of its concrete type.
///
/// In the following code, the `count` variable has the same static and dynamic
/// type: `Int`. When `count` is passed to the `printInfo(_:)` function,
/// however, the `value` parameter has a static type of `Any` (the type
/// declared for the parameter) and a dynamic type of `Int`.
///
/// func printInfo(_ value: Any) {
/// let t = type(of: value)
/// print("'\(value)' of type '\(t)'")
/// }
///
/// let count: Int = 5
/// printInfo(count)
/// // '5' of type 'Int'
///
/// The dynamic type returned from `type(of:)` is a *concrete metatype*
/// (`T.Type`) for a class, structure, enumeration, or other nonprotocol type
/// `T`, or an *existential metatype* (`P.Type`) for a protocol or protocol
/// composition `P`. When the static type of the value passed to `type(of:)`
/// is constrained to a class or protocol, you can use that metatype to access
/// initializers or other static members of the class or protocol.
///
/// For example, the parameter passed as `value` to the `printSmileyInfo(_:)`
/// function in the example below is an instance of the `Smiley` class or one
/// of its subclasses. The function uses `type(of:)` to find the dynamic type
/// of `value`, which itself is an instance of the `Smiley.Type` metatype.
///
/// class Smiley {
/// class var text: String {
/// return ":)"
/// }
/// }
///
/// class EmojiSmiley : Smiley {
/// override class var text: String {
/// return "😀"
/// }
/// }
///
/// func printSmileyInfo(_ value: Smiley) {
/// let smileyType = type(of: value)
/// print("Smile!", smileyType.text)
/// }
///
/// let emojiSmiley = EmojiSmiley()
/// printSmileyInfo(emojiSmiley)
/// // Smile! 😀
///
/// In this example, accessing the `text` property of the `smileyType` metatype
/// retrieves the overridden value from the `EmojiSmiley` subclass, instead of
/// the `Smiley` class's original definition.
///
/// Finding the Dynamic Type in a Generic Context
/// =============================================
///
/// Normally, you don't need to be aware of the difference between concrete and
/// existential metatypes, but calling `type(of:)` can yield unexpected
/// results in a generic context with a type parameter bound to a protocol. In
/// a case like this, where a generic parameter `T` is bound to a protocol
/// `P`, the type parameter is not statically known to be a protocol type in
/// the body of the generic function. As a result, `type(of:)` can only
/// produce the concrete metatype `P.Protocol`.
///
/// The following example defines a `printGenericInfo(_:)` function that takes
/// a generic parameter and declares the `String` type's conformance to a new
/// protocol `P`. When `printGenericInfo(_:)` is called with a string that has
/// `P` as its static type, the call to `type(of:)` returns `P.self` instead
/// of `String.self` (the dynamic type inside the parameter).
///
/// func printGenericInfo<T>(_ value: T) {
/// let t = type(of: value)
/// print("'\(value)' of type '\(t)'")
/// }
///
/// protocol P {}
/// extension String: P {}
///
/// let stringAsP: P = "Hello!"
/// printGenericInfo(stringAsP)
/// // 'Hello!' of type 'P'
///
/// This unexpected result occurs because the call to `type(of: value)` inside
/// `printGenericInfo(_:)` must return a metatype that is an instance of
/// `T.Type`, but `String.self` (the expected dynamic type) is not an instance
/// of `P.Type` (the concrete metatype of `value`). To get the dynamic type
/// inside `value` in this generic context, cast the parameter to `Any` when
/// calling `type(of:)`.
///
/// func betterPrintGenericInfo<T>(_ value: T) {
/// let t = type(of: value as Any)
/// print("'\(value)' of type '\(t)'")
/// }
///
/// betterPrintGenericInfo(stringAsP)
/// // 'Hello!' of type 'String'
///
/// - Parameter value: The value for which to find the dynamic type.
/// - Returns: The dynamic type, which is a metatype instance.
@_transparent
@_semantics("typechecker.type(of:)")
public func type<T, Metatype>(of value: T) -> Metatype {
// This implementation is never used, since calls to `Swift.type(of:)` are
// resolved as a special case by the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: 'type(of:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
/// Allows a nonescaping closure to temporarily be used as if it were allowed
/// to escape.
///
/// You can use this function to call an API that takes an escaping closure in
/// a way that doesn't allow the closure to escape in practice. The examples
/// below demonstrate how to use `withoutActuallyEscaping(_:do:)` in
/// conjunction with two common APIs that use escaping closures: lazy
/// collection views and asynchronous operations.
///
/// The following code declares an `allValues(in:match:)` function that checks
/// whether all the elements in an array match a predicate. The function won't
/// compile as written, because a lazy collection's `filter(_:)` method
/// requires an escaping closure. The lazy collection isn't persisted, so the
/// `predicate` closure won't actually escape the body of the function;
/// nevertheless, it can't be used in this way.
///
/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {
/// return array.lazy.filter { !predicate($0) }.isEmpty
/// }
/// // error: closure use of non-escaping parameter 'predicate'...
///
/// `withoutActuallyEscaping(_:do:)` provides a temporarily escapable copy of
/// `predicate` that _can_ be used in a call to the lazy view's `filter(_:)`
/// method. The second version of `allValues(in:match:)` compiles without
/// error, with the compiler guaranteeing that the `escapablePredicate`
/// closure doesn't last beyond the call to `withoutActuallyEscaping(_:do:)`.
///
/// func allValues(in array: [Int], match predicate: (Int) -> Bool) -> Bool {
/// return withoutActuallyEscaping(predicate) { escapablePredicate in
/// array.lazy.filter { !escapablePredicate($0) }.isEmpty
/// }
/// }
///
/// Asynchronous calls are another type of API that typically escape their
/// closure arguments. The following code declares a
/// `perform(_:simultaneouslyWith:)` function that uses a dispatch queue to
/// execute two closures concurrently.
///
/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {
/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)
/// queue.async(execute: f)
/// queue.async(execute: g)
/// queue.sync(flags: .barrier) {}
/// }
/// // error: passing non-escaping parameter 'f'...
/// // error: passing non-escaping parameter 'g'...
///
/// The `perform(_:simultaneouslyWith:)` function ends with a call to the
/// `sync(flags:execute:)` method using the `.barrier` flag, which forces the
/// function to wait until both closures have completed running before
/// returning. Even though the barrier guarantees that neither closure will
/// escape the function, the `async(execute:)` method still requires that the
/// closures passed be marked as `@escaping`, so the first version of the
/// function does not compile. To resolve these errors, you can use
/// `withoutActuallyEscaping(_:do:)` to get copies of `f` and `g` that can be
/// passed to `async(execute:)`.
///
/// func perform(_ f: () -> Void, simultaneouslyWith g: () -> Void) {
/// withoutActuallyEscaping(f) { escapableF in
/// withoutActuallyEscaping(g) { escapableG in
/// let queue = DispatchQueue(label: "perform", attributes: .concurrent)
/// queue.async(execute: escapableF)
/// queue.async(execute: escapableG)
/// queue.sync(flags: .barrier) {}
/// }
/// }
/// }
///
/// - Important: The escapable copy of `closure` passed to `body` is only valid
/// during the call to `withoutActuallyEscaping(_:do:)`. It is undefined
/// behavior for the escapable closure to be stored, referenced, or executed
/// after the function returns.
///
/// - Parameters:
/// - closure: A nonescaping closure value that is made escapable for the
/// duration of the execution of the `body` closure. If `body` has a
/// return value, that value is also used as the return value for the
/// `withoutActuallyEscaping(_:do:)` function.
/// - body: A closure that is executed immediately with an escapable copy of
/// `closure` as its argument.
/// - Returns: The return value, if any, of the `body` closure.
@_transparent
@_semantics("typechecker.withoutActuallyEscaping(_:do:)")
public func withoutActuallyEscaping<ClosureType, ResultType>(
_ closure: ClosureType,
do body: (_ escapingClosure: ClosureType) throws -> ResultType
) rethrows -> ResultType {
// This implementation is never used, since calls to
// `Swift.withoutActuallyEscaping(_:do:)` are resolved as a special case by
// the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: 'withoutActuallyEscaping(_:do:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
@_transparent
@_semantics("typechecker._openExistential(_:do:)")
public func _openExistential<ExistentialType, ContainedType, ResultType>(
_ existential: ExistentialType,
do body: (_ escapingClosure: ContainedType) throws -> ResultType
) rethrows -> ResultType {
// This implementation is never used, since calls to
// `Swift._openExistential(_:do:)` are resolved as a special case by
// the type checker.
Builtin.staticReport(_trueAfterDiagnostics(), true._value,
("internal consistency error: '_openExistential(_:do:)' operation failed to resolve"
as StaticString).utf8Start._rawValue)
Builtin.unreachable()
}
| apache-2.0 | c15c3cde72e2882cf679ecc477c043ff | 35.065083 | 95 | 0.692189 | 4.086982 | false | false | false | false |
timvermeulen/DraughtsCloud | Sources/App/Models/Move/MoveKeys.swift | 1 | 340 | enum MoveKeys {
enum JSON {
static let id = "id"
static let start = "start"
static let end = "end"
static let bitboards = "bitboards"
static let notation = "notation"
}
enum Row {
static let id = "id"
static let start = "start"
static let end = "end"
}
}
| mit | b1f1b62a2aae21e9fc62a438f4ee2222 | 21.666667 | 42 | 0.508824 | 3.908046 | false | false | false | false |
Daij-Djan/DDUtils | swift/ddutils-common/model/EWSProfileImage [ios+osx + demo]/EWSProfileImages.swift | 1 | 6005 | //
// EWSProfileImages.swift
//
// Created by Dominik Pich on 7/8/16.
// Copyright © 2016 Dominik Pich. All rights reserved.
//
import UIKit
open class EWSProfileImages: NSObject, URLSessionDelegate {
//our manager class
open static var shared = EWSProfileImages()
open var credentials:EWSProfileImagesCredentials!
open var placeholder:UIImage?
public init(credentials:EWSProfileImagesCredentials? = nil,
placeholder:UIImage? = UIImage(named: "person")) {
self.credentials = credentials
self.placeholder = placeholder
}
//cache
fileprivate var queuedCompletions = [String:[EWSProfileImageCompletionBlock]]()
fileprivate var cache = [String:EWSProfileImage]()
fileprivate lazy var session:Foundation.URLSession = {
return Foundation.URLSession(configuration: URLSessionConfiguration.ephemeral, delegate: self, delegateQueue: OperationQueue.main)
}()
//MARK: image loading
open func get(_ email : String, imageSize:EWSProfileImageSize = .big, completion:EWSProfileImageCompletionBlock? = nil) throws -> EWSProfileImage {
guard Thread.isMainThread else {
throw NSError(domain: "EWS", code: -1, userInfo: [NSLocalizedDescriptionKey: "EWSProfileImages class is only to be used on main thread. cant get image"])
}
guard credentials != nil else {
throw NSError(domain: "EWS", code: 0, userInfo: [NSLocalizedDescriptionKey: "credentials for EWS not set. cant get image"])
}
//get cache object
let key = "\(email)_\(imageSize.rawValue)"
if cache[key] == nil {
cache[key] = EWSProfileImage(email: email, size: imageSize, state: .new, image: placeholder)
}
let image = cache[key]!
//enque pending completion
if let completion = completion {
if queuedCompletions[key] == nil {
queuedCompletions[key] = [EWSProfileImageCompletionBlock]()
}
queuedCompletions[key]!.append(completion)
}
//load and handle completion
try load(image, completion: { [unowned self](loadedImage) in
guard let blocks = self.queuedCompletions[key] else {
print("no queuedCompletions[key]? weird but we can ignore this")
return
}
for block in blocks {
block(loadedImage)
}
self.queuedCompletions[key] = nil
})
return image
}
fileprivate func load(_ image:EWSProfileImage, completion:EWSProfileImageCompletionBlock?) throws {
if image.state == .loaded || image.state == .loading {
DispatchQueue.main.async(execute: {
completion?(image)
})
return
}
let urlString = "https://\(credentials.host)/ews/Exchange.asmx/s/GetUserPhoto?email=\(image.email)&size=\(image.size.rawValue)"
guard let imgURL = URL(string: urlString) else {
throw NSError(domain: "EWS", code: 1, userInfo: [NSLocalizedDescriptionKey: "cant assemble imgURL from urlString '\(urlString)'. cant get image"])
}
image.state = .loading
let request = URLRequest(url: imgURL)
session.dataTask(with: request, completionHandler: { (data, response, error) in
if (response as! HTTPURLResponse).statusCode == 200,
let data = data,
let img = UIImage(data: data) {
image.state = .loaded
image.image = img
}
else {
image.state = .failed
}
completion?(image)
}).resume()
}
// MARK: URLSessionDelegate
open func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let authenticationMethod = challenge.protectionSpace.authenticationMethod
if authenticationMethod == NSURLAuthenticationMethodServerTrust {
if challenge.protectionSpace.host == "webmail.sapient.com" {
completionHandler(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
}
} else {
if challenge.previousFailureCount > 0 {
print("Alert Please check the credential")
completionHandler(Foundation.URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
} else {
let credentials = self.credentials
let credential = URLCredential(user:(credentials?.username)!, password:(credentials?.password)!, persistence: .forSession)
completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential,credential)
}
}
}
//MARK: - objects & types
public typealias EWSProfileImagesCredentials = (host:String, username:String, password:String)
public enum EWSProfileImageSize: String {
case small = "HR48x48"
case regular = "HR360x360"
case big = "HR648x648"
}
public enum EWSProfileImageState {
case new
case loading
case failed
case loaded
}
open class EWSProfileImage {
open internal(set) var email : String
open internal(set) var size : EWSProfileImageSize
open internal(set) var state : EWSProfileImageState
open internal(set) var image : UIImage?
internal init( email : String, size : EWSProfileImageSize, state : EWSProfileImageState, image : UIImage?) {
self.email = email
self.size = size
self.state = state
self.image = image
}
}
public typealias EWSProfileImageCompletionBlock = ((EWSProfileImage)->Void)
}
| mit | 67037039a659bdb70bd2746ff6cc159e | 37.735484 | 191 | 0.616755 | 5.136014 | false | false | false | false |
GTMYang/GTMRefresh | GTMRefreshExample/Default/DefaultScrollViewController.swift | 1 | 1704 | //
// DefaultScrollViewController.swift
// PullToRefreshKit
//
// Created by luoyang on 2016/12/8.
// Copyright © 2016年 luoyang. All rights reserved.
//
import Foundation
import UIKit
import GTMRefresh
class DefaultScrollViewController:UIViewController{
var scrollView:UIScrollView?
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.white
self.automaticallyAdjustsScrollViewInsets = false
setUpScrollView()
self.scrollView?.gtm_addRefreshHeaderView {
[weak self] in
print("excute refreshBlock")
self?.refresh()
}
self.scrollView?.gtm_addLoadMoreFooterView {
[weak self] in
print("excute loadMoreBlock")
self?.loadMore()
}
}
// MARK: Test
func refresh() {
perform(#selector(endRefresing), with: nil, afterDelay: 3)
}
@objc func endRefresing() {
self.scrollView?.endRefreshing(isSuccess: true)
}
func loadMore() {
perform(#selector(endLoadMore), with: nil, afterDelay: 3)
}
@objc func endLoadMore() {
self.scrollView?.endLoadMore(isNoMoreData: true)
}
func setUpScrollView(){
self.scrollView = UIScrollView(frame: CGRect(x: 0,y: 0,width: 300,height: 300))
self.scrollView?.backgroundColor = UIColor.lightGray
self.scrollView?.center = self.view.center
self.scrollView?.contentSize = CGSize(width: 300,height: 600)
self.view.addSubview(self.scrollView!)
}
deinit{
print("Deinit of \(NSStringFromClass(type(of: self)))")
}
}
| mit | 4a68a56931c6532329882f10e6ae0fac | 25.578125 | 87 | 0.616108 | 4.572581 | false | false | false | false |
tlax/GaussSquad | GaussSquad/Model/Calculator/FunctionsItems/MCalculatorFunctionsItemSquare.swift | 1 | 920 | import UIKit
class MCalculatorFunctionsItemSquare:MCalculatorFunctionsItem
{
private let kExponent:Double = 2
init()
{
let icon:UIImage = #imageLiteral(resourceName: "assetFunctionSquare")
let title:String = NSLocalizedString("MCalculatorFunctionsItemSquare_title", comment:"")
super.init(
icon:icon,
title:title)
}
override func processFunction(
currentValue:Double,
currentString:String,
modelKeyboard:MKeyboard,
view:UITextView)
{
let sqValue:Double = pow(currentValue, kExponent)
let sqString:String = modelKeyboard.numberAsString(scalar:sqValue)
let descr:String = "square (\(currentString)) = \(sqString)"
applyUpdate(
modelKeyboard:modelKeyboard,
view:view,
newEditing:sqString,
descr:descr)
}
}
| mit | b51f164aafc6902d1475ca18fa0cce72 | 26.878788 | 96 | 0.617391 | 4.742268 | false | false | false | false |
yusuga/RemoteNotificationHandling | RemoteNotificationHandling/Classes/Util/RemoteNotificationUtility.swift | 1 | 1294 | //
// RemoteNotificationUtility.swift
// Pods
//
// Created by Yu Sugawara on 7/19/17.
//
//
import UserNotifications
public struct RemoteNotificationUtility {
@available(iOS 10.0, *)
public static func requestAuthorization(
options: UNAuthorizationOptions = [.badge, .sound, .alert],
application: UIApplication = UIApplication.shared) {
UNUserNotificationCenter.current().requestAuthorization(
options: options) { (granted, error) in
DispatchQueue.main.async {
if granted {
application.registerForRemoteNotifications()
}
}
}
}
@available(iOS, deprecated: 10.0)
public static func registerUserNotificationSettings(
_ settings: UIUserNotificationSettings = UIUserNotificationSettings(types: [.badge, .sound, .alert],
categories: nil),
application: UIApplication = UIApplication.shared) {
application.registerUserNotificationSettings(settings)
}
public static func clearApplicationIconBadge(withApplication application: UIApplication = UIApplication.shared) {
application.applicationIconBadgeNumber = 0
}
}
| mit | c399898a17f3e702d29627f7dd80cd52 | 32.179487 | 117 | 0.622875 | 5.908676 | false | false | false | false |
meninsilicium/apple-swifty | Dictionary.swift | 1 | 2020 | //
// author: fabrice truillot de chambrier
// created: 14.02.2015
//
// license: see license.txt
//
// © 2015-2015, men in silicium sàrl
//
import class Foundation.NSDictionary
extension Dictionary {
/// updateValue(_, value:)
mutating func updateValue( key: Key, value: Value ) -> Value? {
return self.updateValue( value, forKey: key )
}
mutating func updateValues( values: Dictionary ) -> Dictionary {
var dictionary = [Key: Value]()
for (key, value) in values {
let oldValue = self.updateValue( key, value: value )
if oldValue != nil {
dictionary[ key ] = oldValue
}
}
return dictionary
}
// naive first implementation
func union( rhs: Dictionary ) -> Dictionary {
var values = self
for (let key, let value) in rhs {
if values[ key ] == nil {
values[ key ] = value
}
}
return values
}
// naive first implementation
func subtract( rhs: Dictionary ) -> Dictionary {
var values = [Key: Value]()
for (key, value) in self {
if rhs[ key ] == nil {
values[ key ] = value
}
}
return values
}
// naive first implementation
func intersect( rhs: Dictionary ) -> Dictionary {
var values = [Key: Value]()
for (key, value) in self {
if rhs[ key ] != nil {
values[ key ] = value
}
}
return values
}
}
// Iterable
extension Dictionary : Iterable_ {
/// apply the function to each (key, value) pairs
func foreach( @noescape function: (Key, Value) -> Void ) {
for (key, value) in self {
function( key, value )
}
}
/// apply the function to each (key, value) pairs
func foreach( @noescape function: (Int, (Key, Value)) -> Void ) {
for (index, (key, value)) in Swift.enumerate( self ) {
function( index, (key, value) )
}
}
}
// Enumerable
extension Dictionary : Enumerable_ {
func enumerate( @noescape function: (Int, (Key, Value)) -> Bool ) {
for (index, (key, value)) in Swift.enumerate( self ) {
let next = function( index, (key, value) )
if !next { break }
}
}
}
| mpl-2.0 | fbbb8e8b22fca4f450759cee84c5378b | 18.784314 | 68 | 0.616452 | 3.198098 | false | false | false | false |
yl-github/YLDYZB | YLDouYuZB/YLDouYuZB/Classes/Main/Model/YLCollectionBaseCell.swift | 1 | 1350 | //
// YLCollectionBaseCell.swift
// YLDouYuZB
//
// Created by yl on 2016/10/12.
// Copyright © 2016年 yl. All rights reserved.
//
import UIKit
class YLCollectionBaseCell: UICollectionViewCell {
//MARK:- 定义控件属性
@IBOutlet weak var iconImg: UIImageView!
@IBOutlet weak var anchorNameLabel: UILabel!
@IBOutlet weak var onlineNum: UIButton!
var anchor : YLAnchorModel? {
didSet{
// 这里使用可选链不合适,所以直接校验一下anchor是否有值,下面就不需要在anchor后面加?号了
guard let anchor = anchor else { return }
// 1.设置房间封面图片 (这里使用到了一个加载网络图片的第三方Kingfirs)
guard let iconUrl = URL(string: anchor.vertical_src) else { return };
iconImg.kf.setImage(with: iconUrl);
// 2.设置主播昵称
anchorNameLabel.text = anchor.nickname;
// 3.设置在线人数
var onlineStr : String = "";
if anchor.online >= 10000 {
onlineStr = "\(Int(anchor.online / 10000))万在线";
}else {
onlineStr = "\(anchor.online)在线";
}
onlineNum.setTitle(onlineStr, for: UIControlState());
}
}
}
| mit | 56f3467fdf7706755605a3170b1b4aca | 27.560976 | 81 | 0.563621 | 4.108772 | false | false | false | false |
jduquennoy/Log4swift | Log4swiftTests/LogLevelTests.swift | 1 | 1877 | //
// LogLevelTests.swift
// Log4swift
//
// Created by jduquennoy on 26/06/2015.
// Copyright © 2015 Jérôme Duquennoy. 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 XCTest
import Log4swift
class LogLevelTests: XCTestCase {
func testLogLevelFromStringConvertsInvalidValuesToNil() {
let parsedLevel = LogLevel("value that does not exist")
XCTAssertTrue(parsedLevel == nil)
}
func testLogLevelFromStringIsCaseInsensitive() {
let parsedLevel1 = LogLevel("debug")
let parsedLevel2 = LogLevel("DEBUg")
XCTAssertEqual(parsedLevel1!, LogLevel.Debug)
XCTAssertEqual(parsedLevel2!, LogLevel.Debug)
}
func testLogLevelFromStringCanConvertAllLogLevels() {
let parsedTrace = LogLevel("trace")
let parsedDebug = LogLevel("debug")
let parsedInfo = LogLevel("info")
let parsedWarning = LogLevel("warning")
let parsedError = LogLevel("error")
let parsedFatal = LogLevel("fatal")
let parsedOff = LogLevel("oFf")
XCTAssertEqual(parsedTrace!, LogLevel.Trace)
XCTAssertEqual(parsedDebug!, LogLevel.Debug)
XCTAssertEqual(parsedInfo!, LogLevel.Info)
XCTAssertEqual(parsedWarning!, LogLevel.Warning)
XCTAssertEqual(parsedError!, LogLevel.Error)
XCTAssertEqual(parsedFatal!, LogLevel.Fatal)
XCTAssertEqual(parsedOff!, LogLevel.Off)
}
}
| apache-2.0 | 34f8d89be0393971c48adb677c09e3b8 | 31.310345 | 75 | 0.731057 | 4.259091 | false | true | false | false |
mofneko/swift-layout | swift-layout/sampleViewControllers/RoundedRectViewController.swift | 1 | 2879 | //
// RoundedRectViewController.swift
// swift-layout
//
// Created by grachro on 2014/09/28.
// Copyright (c) 2014年 grachro. All rights reserved.
//
import UIKit
class RoundedRectViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
let lTop = Layout.addUILabel(superview: self.view)
.top(30).fromSuperviewTop()
.left(50).fromSuperviewLeft()
.width(100)
.height(100)
.backgroundColor(UIColor.redColor())
.text("Top")
.roundRectTop(20)
let lRight = Layout.addUILabel(superview: self.view)
.top(10).fromBottom(lTop.view)
.left(50).fromSuperviewLeft()
.width(100)
.height(100)
.backgroundColor(UIColor.cyanColor())
.text("Right")
.roundRectRight(20)
let lLeft = Layout.addUILabel(superview: self.view)
.top(30).fromSuperviewTop()
.left(10).fromRight(lTop.view)
.width(100)
.height(100)
.backgroundColor(UIColor.yellowColor())
.text("Left")
.roundRectLeft(20)
_ = Layout.addUILabel(superview: self.view)
.top(10).fromBottom(lLeft.view)
.left(10).fromRight(lRight.view)
.width(100)
.height(100)
.backgroundColor(UIColor.greenColor())
.text("Bottom")
.roundRectBottom(20)
_ = Layout.addSubView(Layout.createCharWrappingLabel("TopLeft\nBottomRight"), superview: self.view)
.top(10).fromBottom(lRight.view)
.left(50).fromSuperviewLeft()
.width(100)
.height(100)
.backgroundColor(UIColor.grayColor())
.roundRect(byRoundingCorners: ([UIRectCorner.TopLeft, UIRectCorner.BottomRight]), cornerRadii: 20)
_ = Layout.addSubView(Layout.createCharWrappingLabel("all"), superview: self.view)
.top(10).fromBottom(lRight.view)
.left(10).fromRight(lTop.view)
.width(100)
.height(100)
.backgroundColor(UIColor.blueColor())
.roundRect(20)
//戻るボタン
addReturnBtn()
}
private func addReturnBtn() {
let btn = Layout.createSystemTypeBtn("return")
Layout.addSubView(btn, superview: self.view)
.bottomIsSameSuperview()
.rightIsSameSuperview()
TouchBlocks.append(btn){
self.dismissViewControllerAnimated(true, completion:nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 16fd6225ffda5d5af7d9ec724fa516e2 | 30.163043 | 110 | 0.567492 | 4.363775 | false | false | false | false |
daggmano/photo-management-studio | src/Client/OSX/Photo Management Studio/Photo Management Studio/HTTP.swift | 1 | 5213 | import Foundation
/**
* HTTP
*/
public class HTTP {
public typealias Response = (Result) -> Void
public typealias Headers = [String: String]
public enum Method: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case HEAD = "HEAD"
case DELETE = "DELETE"
}
public enum Result {
case Success(AnyObject, NSHTTPURLResponse)
case Error(NSError)
}
private var request: NSMutableURLRequest
/**
* Init
*/
public init(method: Method, url: String) {
self.request = NSMutableURLRequest(URL: NSURL(string: url)!)
self.request.HTTPMethod = method.rawValue
}
public init(method: Method, url: String, headers: Headers?) {
self.request = NSMutableURLRequest(URL: NSURL(string: url)!)
self.request.HTTPMethod = method.rawValue
if let headers = headers {
self.request.allHTTPHeaderFields = headers
}
}
/**
* Class funcs
*/
// GET
public class func get(url: String) -> HTTP {
return HTTP(method: .GET, url: url)
}
public class func get(url: String, headers: Headers?) -> HTTP {
return HTTP(method: .GET, url: url, headers: headers)
}
public class func get(url: String, done: Response) -> HTTP {
return HTTP.get(url).end(done)
}
public class func get(url: String, headers: Headers?, done: Response) -> HTTP {
return HTTP(method: .GET, url: url, headers: headers).end(done)
}
// POST
public class func post(url: String) -> HTTP {
return HTTP(method: .POST, url: url)
}
public class func post(url: String, headers: Headers?) -> HTTP {
print("Posting to \(url)")
return HTTP(method: .POST, url: url, headers: headers)
}
public class func post(url: String, done: Response) -> HTTP {
return HTTP.post(url).end(done)
}
public class func post(url: String, data: AnyObject, done: Response) -> HTTP {
return HTTP.post(url).send(data).end(done)
}
public class func post(url: String, headers: Headers?, data: AnyObject, done: Response) -> HTTP {
return HTTP.post(url, headers: headers).send(data).end(done)
}
// PUT
public class func put(url: String) -> HTTP {
return HTTP(method: .PUT, url: url)
}
public class func put(url: String, done: Response) -> HTTP {
return HTTP.put(url).end(done)
}
public class func put(url: String, data: AnyObject, done: Response) -> HTTP {
return HTTP.put(url).send(data).end(done)
}
// DELETE
public class func delete(url: String) -> HTTP {
return HTTP(method: .DELETE, url: url)
}
public class func delete(url: String, done: Response) -> HTTP {
return HTTP.delete(url).end(done)
}
/**
* Methods
*/
public func send(data: AnyObject) -> HTTP {
do {
var d = try NSJSONSerialization.dataWithJSONObject(data, options: [])
//NSJSONSerialization converts a URL string from http://... to http:\/\/... remove the extra escapes
var dataStr = NSString.init(data: d, encoding: NSUTF8StringEncoding)
dataStr = dataStr?.stringByReplacingOccurrencesOfString("\\/", withString: "/")
d = (dataStr?.dataUsingEncoding(NSUTF8StringEncoding))!
self.request.HTTPBody = d//try NSJSONSerialization.dataWithJSONObject(data, options: [])
let dataString = NSString(data: self.request.HTTPBody!, encoding: NSUTF8StringEncoding)!
print("Sending data: \(dataString)")
} catch {
self.request.HTTPBody = nil
}
self.request.addValue("application/json", forHTTPHeaderField: "Accept")
self.request.addValue("application/json", forHTTPHeaderField: "Content-Type")
if let length = self.request.HTTPBody?.length {
self.request.addValue(String(length), forHTTPHeaderField: "Content-Length")
} else {
self.request.addValue("0", forHTTPHeaderField: "Content-Length")
}
return self
}
public func end(done: Response) -> HTTP {
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(self.request) { data, response, error in
// we have an error -> maybe connection lost
if let error = error {
done(Result.Error(error))
return
}
// request was success
var json: AnyObject!
if let data = data {
do {
json = try NSJSONSerialization.JSONObjectWithData(data, options: [])
} catch let error as NSError {
done(Result.Error(error))
return
}
}
// looking good
let res = response as! NSHTTPURLResponse
done(Result.Success(json, res))
}
task.resume()
return self
}
}
| mit | cb13324433620f595dc05d0a58476c25 | 30.786585 | 112 | 0.565509 | 4.584872 | false | false | false | false |
PrashantMangukiya/SwiftUIDemo | Demo8-UIActivityIndicatorView/Demo8-UIActivityIndicatorView/ViewController.swift | 1 | 2910 | //
// ViewController.swift
// Demo8-UIActivityIndicatorView
//
// Created by Prashant on 27/09/15.
// Copyright © 2015 PrashantKumar Mangukiya. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// outlet - all spinner
@IBOutlet var spinner1: UIActivityIndicatorView!
@IBOutlet var spinner2: UIActivityIndicatorView!
@IBOutlet var spinner3: UIActivityIndicatorView!
@IBOutlet var spinner4: UIActivityIndicatorView!
// action & outlet - spin button
@IBOutlet var spinButton: UIButton!
@IBAction func spinButtonAction(_ sender: UIButton) {
self.spinner1.startAnimating()
self.spinner2.startAnimating()
self.spinner3.startAnimating()
self.spinner4.startAnimating()
self.spinButton.isEnabled = false
self.stopButton.isEnabled = true
self.showHideButton.isEnabled = false
}
// action & outlet - stop button
@IBOutlet var stopButton: UIButton!
@IBAction func stopButtonAction(_ sender: UIButton) {
self.spinner1.stopAnimating()
self.spinner2.stopAnimating()
self.spinner3.stopAnimating()
self.spinner4.stopAnimating()
self.spinButton.isEnabled = true
self.stopButton.isEnabled = false
self.showHideButton.isEnabled = true
}
// action & outlet - show/hide spinner button
@IBOutlet var showHideButton: UIButton!
@IBAction func showHideButtonAction(_ sender: UIButton) {
if self.showHideButton.isSelected {
self.showHideButton.isSelected = false
self.spinner1.isHidden = false
self.spinner2.isHidden = false
self.spinner3.isHidden = false
self.spinner4.isHidden = false
self.spinButton.isEnabled = true
self.stopButton.isEnabled = false
}else{
self.showHideButton.isSelected = true
self.spinner1.isHidden = true
self.spinner2.isHidden = true
self.spinner3.isHidden = true
self.spinner4.isHidden = true
self.spinButton.isEnabled = false
self.stopButton.isEnabled = false
}
}
// MARK: - View function
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// enable spin button
self.spinButton.isEnabled = true
// disable stop button
self.stopButton.isEnabled = false
// enable show/hide spinner button
self.showHideButton.isEnabled = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | 71dcc4b0bff12c727958b1f5f30c8ab8 | 26.971154 | 80 | 0.616707 | 5.222621 | false | false | false | false |
nodes-ios/ModelBoiler | Model Boiler/Classes/Helpers/KeyCommandManager.swift | 1 | 3901 | //
// KeyCommandManager.swift
// Model Boiler
//
// Created by Dominik Hádl on 27/01/16.
// Copyright © 2016 Nodes. All rights reserved.
//
import Cocoa
struct KeyCommandManager {
static let settingsKey = "KeyCommandManager"
static func setDefaultKeyCommand() {
let key = "§"
let mask = NSEvent.ModifierFlags.command
do {
try KeyCommandManager.updateKeyCommand(key, modifierMask: mask)
} catch {
}
}
// MARK: - Key Command -
static func currentKeyCommand() -> (command: String, modifierMask: NSEvent.ModifierFlags)? {
if let keyCommandString = UserDefaults.standard.string(forKey: settingsKey) {
return keyCommandForString(keyCommandString)
}
return nil
}
static func updateKeyCommand(_ command: String, modifierMask: NSEvent.ModifierFlags) throws {
let bundle = Bundle.main
guard let appServices = (bundle.infoDictionary?["NSServices"] as AnyObject).firstObject as? [String: AnyObject],
let bundleIdentifier = bundle.bundleIdentifier,
let serviceName = appServices["NSMenuItem"]?["default"] as? String,
let methodName = appServices["NSMessage"] as? String else {
throw NSError(domain: "com.nodes.Model-Boiler", code: 1000, userInfo: [NSLocalizedDescriptionKey: "Can't get information about app services."])
}
let serviceHelperName = "pbs"
let serviceStatusName = "\(bundleIdentifier) - \(serviceName) - \(methodName)"
let serviceStatusRoot = "NSServicesStatus"
var services: [String: AnyObject] = (CFPreferencesCopyAppValue(serviceStatusRoot as CFString, serviceHelperName as CFString) as? [String: AnyObject] ?? [:])
let keyCommand = stringForKeyCommand(command, modifierMask: modifierMask)
NSUpdateDynamicServices()
let serviceStatus: [String: AnyObject] = [
"enabled_context_menu": true as AnyObject,
"enabled_services_menu": true as AnyObject,
"key_equivalent": keyCommand as AnyObject]
services[serviceStatusName] = serviceStatus as AnyObject?
CFPreferencesSetAppValue(serviceStatusRoot as CFString, services as CFPropertyList?, serviceHelperName as CFString)
let success = CFPreferencesAppSynchronize(serviceHelperName as CFString)
if success {
NSUpdateDynamicServices()
let task = Process()
task.launchPath = "/System/Library/CoreServices/pbs"
task.arguments = ["-flush"]
task.launch()
UserDefaults.standard.set(keyCommand, forKey: settingsKey)
} else {
throw NSError(domain: bundleIdentifier, code: 1000, userInfo: [NSLocalizedDescriptionKey: "Can't save key command for service."])
}
}
// MARK: - Helpers -
static func stringForKeyCommand(_ command: String, modifierMask: NSEvent.ModifierFlags) -> String {
var key = ""
if modifierMask.contains(.command) { key += "@" }
if modifierMask.contains(.option) { key += "~" }
if modifierMask.contains(.shift) { key += "$" }
return key + (command == "$" ? "\\$" : command)
}
static func keyCommandForString(_ string: String) -> (command: String, modifierMask: NSEvent.ModifierFlags) {
var returnValue = (command: "", modifierMask: NSEvent.ModifierFlags(rawValue: 0))
if string.isEmpty { return returnValue }
switch string.first! {
case "@": returnValue.modifierMask = .command
case "~": returnValue.modifierMask = .option
case "$": returnValue.modifierMask = .shift
default: break
}
let command = string[string.index(string.startIndex, offsetBy: 1)...]
returnValue.command = (command == "\\$" ? "$" : String(command))
return returnValue
}
}
| mit | aab501e7ded83e76925346bb9c1e8569 | 34.117117 | 164 | 0.642124 | 4.702051 | false | false | false | false |
hakan4/LineGraphKit | LineGraphKit/LineGraphKit/Classes/ViewElements/LineGraph.swift | 1 | 12173 | //
// LineGraph.swift
// GraphKit
//
// Created by Håkan Andersson on 19/06/15.
// Copyright (c) 2015 Fineline. All rights reserved.
//
import UIKit
public protocol LineGraphDatasource: class {
func numberOfLines(lineGraph: LineGraph) -> Int
func lineGraph(_ lineGraph: LineGraph, numberOfPointsForLineWithIndex index: Int) -> Int
func lineGraph(_ lineGraph: LineGraph, colorForLineWithIndex index: Int) -> UIColor
func lineGraph(_ lineGraph: LineGraph, pointForLineWithIndex index: Int, position: Int) -> GraphPoint
func lineGraph(_ lineGraph: LineGraph, animationDurationForLineWithIndex index: Int) -> Double
func lineGraph(_ lineGraph: LineGraph, titleForYValue value: Double, index: Int) -> String?
func lineGraph(_ lineGraph: LineGraph, titleForXValue value: Double, position: Int) -> String?
func notEnoughPointsToShowMessageForLineGraph(lineGraph: LineGraph) -> String?
func fractionForSpacingInLineGraph(lineGraph: LineGraph) -> Double?
func lineGraph(lineGraph: LineGraph, minimumPointsToShowForIndex index: Int) -> Int
}
@IBDesignable public final class LineGraph: UIView {
fileprivate let defaultLabelWidth: CGFloat = 50.0
fileprivate let defaultLabelHeight: CGFloat = 25.0
fileprivate let defaultAxisMargin: CGFloat = 50.0
fileprivate let defaultMargin: CGFloat = 20.0
fileprivate let defaultMarginTop: CGFloat = 20.0
fileprivate let defaultMarginBottom: CGFloat = 20.0
fileprivate let defaultLabelPadding: CGFloat = 5.0
public final weak var datasource: LineGraphDatasource?
@IBInspectable final var font: UIFont! = UIFont(name: "HelveticaNeue-Light", size: 14)
@IBInspectable final var textColor: UIColor! = UIColor.lightGray
fileprivate final var plotLayer: PlotLayer!
fileprivate final var messageLabel: UILabel!
fileprivate final var valueLabels: [UILabel]!
fileprivate final var titleLabels: [UILabel]!
fileprivate final lazy var lineLayers: [LineLayer] = []
fileprivate final var minValue: GraphPoint!
fileprivate final var maxValue: GraphPoint!
fileprivate final var plotHeight: CGFloat {
return plotLayer.frame.size.height
}
fileprivate final var plotWidth: CGFloat {
return plotLayer.frame.size.width
}
fileprivate final var hasValidValues: Bool {
return numberOfLines > 0
}
fileprivate final var numberOfLines: Int {
guard let count = self.datasource?.numberOfLines(lineGraph: self) else {
return 0
}
return count
}
fileprivate final var margin: CGFloat {
return defaultMargin
}
public init() {
super.init(frame: CGRect.zero)
initializeGraph()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeGraph()
}
public override init(frame: CGRect) {
super.init(frame: frame)
initializeGraph()
}
fileprivate func initializeGraph() {
let plotLayer = PlotLayer()
plotLayer.isHidden = true
layer.addSublayer(plotLayer)
self.plotLayer = plotLayer
setupMessageLabel()
}
public override func layoutSubviews() {
super.layoutSubviews()
let leadingMargin = margin + defaultAxisMargin
let plotWidth = (frame.width - leadingMargin - (2 * margin))
let bottomMargin = (defaultLabelHeight + defaultMarginBottom)
let plotHeight = (frame.height - bottomMargin - defaultMarginTop)
plotLayer.frame = CGRect(x: leadingMargin, y: defaultMarginTop, width: plotWidth, height: plotHeight)
messageLabel.frame = CGRect(x: plotLayer.frame.origin.x + defaultLabelPadding, y: plotLayer.frame.origin.y + defaultLabelPadding, width: plotLayer.frame.size.width - 2 * defaultLabelPadding, height: plotLayer.frame.size.height - 2 * defaultLabelPadding)
}
public func drawGraph() {
clearLines()
clearLabels()
updateMinMaxValues()
createTitleLabels()
createValueLabels()
var successfullyDrawnGraph: Bool = false
let count = numberOfLines
CATransaction.begin()
plotLayer.isHidden = false
for i in 0 ..< count {
successfullyDrawnGraph = drawLineForIndex(i) || successfullyDrawnGraph
}
CATransaction.commit()
showMessageLabel(!successfullyDrawnGraph)
}
fileprivate func showMessageLabel(_ show: Bool) {
let title = self.datasource?.notEnoughPointsToShowMessageForLineGraph(lineGraph: self)
messageLabel.text = title
UIView.animate(withDuration: 0.25, animations: {
self.messageLabel.alpha = (show ? 1.0 : 0.0)
})
}
fileprivate func setupMessageLabel() {
let label = UILabel(frame: plotLayer.frame)
label.backgroundColor = UIColor.clear
label.textAlignment = NSTextAlignment.center
label.font = font
label.textColor = textColor
label.alpha = 0
label.lineBreakMode = NSLineBreakMode.byWordWrapping
label.numberOfLines = 0
addSubview(label)
self.messageLabel = label
}
fileprivate func clearLabels() {
if let labels = titleLabels {
for label in labels {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
label.alpha = 0
}, completion: { (_) -> Void in
label.removeFromSuperview()
})
}
titleLabels = nil
}
if let labels = valueLabels {
for label in labels {
UIView.animate(withDuration: 0.25, animations: { () -> Void in
label.alpha = 0
}, completion: { (_) -> Void in
label.removeFromSuperview()
})
}
valueLabels = nil
}
}
fileprivate func clearLines() {
plotLayer.clearLineLayers()
lineLayers.removeAll(keepingCapacity: false)
}
fileprivate final func updateMinMaxValues() {
let (minValue, maxValue) = minMaxValues()
guard let fraction = self.datasource?.fractionForSpacingInLineGraph(lineGraph: self), fraction >= 0 && fraction <= 1 else {
self.minValue = minValue
self.maxValue = maxValue
return
}
let addon = (((maxValue.y - minValue.y) / Double(numberOfYLabels())) * fraction)
self.minValue = GraphPoint(x: minValue.x, y: max(0, minValue.y - addon))
self.maxValue = GraphPoint(x: maxValue.x, y: maxValue.y + addon)
}
//to be tested
final func minMaxValues() -> (GraphPoint, GraphPoint) {
let maxValue: GraphPoint = GraphPoint(x: DBL_MIN, y: DBL_MIN)
let minValue: GraphPoint = GraphPoint(x: DBL_MAX, y: DBL_MAX)
guard let datasource = self.datasource else {
return (minValue, maxValue)
}
let count = numberOfLines
for index in 0 ..< count {
let numberOfPoints = datasource.lineGraph(self, numberOfPointsForLineWithIndex: index)
for position in 0 ..< numberOfPoints {
let point = datasource.lineGraph(self, pointForLineWithIndex: index, position: position)
maxValue.x = max(maxValue.x, point.x)
maxValue.y = max(maxValue.y, point.y)
minValue.x = min(minValue.x, point.x)
minValue.y = min(minValue.y, point.y)
}
}
return (minValue, maxValue)
}
fileprivate final func drawLineForIndex(_ index: Int) -> Bool{
let points: [Point] = normalizedPointsForIndex(index)
guard let minCount = self.datasource?.lineGraph(lineGraph: self, minimumPointsToShowForIndex: index), points.count > minCount else {
return false
}
let color = self.datasource?.lineGraph(self, colorForLineWithIndex: index)
let lineLayer = LineLayer(points: points)
lineLayer.strokeColor = color.or(UIColor.randomColor()).cgColor
plotLayer.addLineLayer(lineLayer)
lineLayers.append(lineLayer)
lineLayer.drawLine()
return true
}
fileprivate final func normalizedPointsForIndex(_ index: Int) -> [Point] {
guard let count = self.datasource?.lineGraph(self, numberOfPointsForLineWithIndex: index) else {
return []
}
var points: [Point] = []
for position in 0 ..< count {
let graphPoint = self.datasource?.lineGraph(self, pointForLineWithIndex: index, position: position)
let x: CGFloat = xPositionForValue(graphPoint!.x)
let y: CGFloat = yPositionForValue(graphPoint!.y)
let point = Point(x: x, y: y)
points.append(point)
}
return points
}
fileprivate final func yPositionForValue(_ value: Double) -> CGFloat {
let scale = (value - minValue.y) / (maxValue.y - minValue.y)
return plotHeight * (1.0 - CGFloat(scale))
}
fileprivate final func xPositionForValue(_ value: Double) -> CGFloat {
let delta = maxValue.x - minValue.x
let scale = delta <= 0 ? 0.5 : (value - minValue.x) / delta
return plotWidth * CGFloat(scale)
}
fileprivate final func createTitleLabels() {
if !hasValidValues {
return
}
let count = Int((plotWidth + defaultLabelWidth) / defaultLabelWidth)
let additionalLeftSpacing: CGFloat = -3.0
var labels: [UILabel] = []
let step = max(Int(maxValue.x - minValue.x) / (count - 1), 1)
for i in stride(from: Int(minValue.x), to: Int(maxValue.x), by: step) {
//for var i = Int(minValue.x); i <= ; i += step {
let x = defaultAxisMargin + xPositionForValue(Double(i)) + additionalLeftSpacing
let y = self.frame.height - (1.5 * defaultLabelHeight)
let frame = CGRect(x: x, y: y, width: defaultLabelWidth, height: defaultLabelHeight)
let label = UILabel(frame: frame)
label.backgroundColor = UIColor.clear
label.textAlignment = NSTextAlignment.center
label.font = font
label.textColor = textColor
let title = self.datasource?.lineGraph(self, titleForXValue: Double(i), position: labels.count)
label.text = title ?? "\(i)"
labels.append(label)
label.alpha = 0
addSubview(label)
UIView.animate(withDuration: 0.35, animations: {
label.alpha = 1
})
}
titleLabels = labels
}
fileprivate final func numberOfYLabels() -> Int {
return Int((plotHeight + defaultLabelHeight) / defaultLabelHeight)
}
fileprivate final func createValueLabels() {
if !hasValidValues {
return
}
let count = numberOfYLabels()
let labelHeight = (plotHeight + defaultLabelHeight) / CGFloat(count)
var labels: [UILabel] = []
for i in 0 ..< count {
let x = margin
let y = (defaultMarginTop - (defaultLabelHeight / 2.0)) + labelHeight * CGFloat(i)
let frame = CGRect(x: x, y: y, width: defaultLabelWidth, height: labelHeight)
let label = UILabel(frame: frame)
label.backgroundColor = UIColor.clear
label.textAlignment = NSTextAlignment.center
label.font = font
label.textColor = textColor
let step = GraphPoint.yStepCalculation(maxValue, minValue: minValue, count: count, i: i)
let title = self.datasource?.lineGraph(self, titleForYValue: step, index: i)
label.text = title ?? "\(step)"
labels.append(label)
label.alpha = 0
addSubview(label)
UIView.animate(withDuration: 0.35, animations: {
label.alpha = 1
})
}
self.valueLabels = labels
}
}
| mit | 660ca05c0b16f6e18f7e60ddb6dd7e98 | 37.518987 | 261 | 0.617318 | 4.730665 | false | false | false | false |
apple/swift | test/IDE/complete_protocol_static_member.swift | 4 | 2937 | // RUN: %empty-directory(%t)
// RUN: %target-swift-ide-test -batch-code-completion -source-filename %s -filecheck %raw-FileCheck -completion-output-dir %t
protocol FontStyle {}
struct FontStyleOne: FontStyle {}
struct FontStyleTwo: FontStyle {}
extension FontStyle where Self == FontStyleOne {
static var variableDeclaredInConstraintExtension: FontStyleOne { FontStyleOne() }
}
func foo<T: FontStyle>(x: T) {}
func test() {
foo(x: .#^COMPLETE_STATIC_MEMBER?check=EXTENSION_APPLIED^#)
}
// EXTENSION_APPLIED: Begin completions, 1 item
// EXTENSION_APPLIED-DAG: Decl[StaticVar]/CurrNominal/TypeRelation[Convertible]: variableDeclaredInConstraintExtension[#FontStyleOne#];
// EXTENSION_APPLIED: End completions
func test<T: FontStyle>(x: T) {
x.#^COMPLETE_MEMBER_IN_GENERIC_CONTEXT?check=EXTENSION_NOT_APPLIED^#
}
// EXTENSION_NOT_APPLIED: Begin completions, 1 item
// EXTENSION_NOT_APPLIED-DAG: Keyword[self]/CurrNominal: self[#T#];
// EXTENSION_NOT_APPLIED-NOT: variableDeclaredInConstraintExtension
// EXTENSION_NOT_APPLIED: End completions
struct WrapperStruct<T: FontStyle> {
let y: T
func test(x: T) {
x.#^COMPLETE_MEMBER_IN_NESTED_GENERIC_CONTEXT?check=EXTENSION_NOT_APPLIED^#
y.#^COMPLETE_MEMBER_FROM_OUTER_GENERIC_CONTEXT_IN_INNER?check=EXTENSION_NOT_APPLIED^#
test(x: .#^COMPLETE_GENERIC_FUNC_WITH_TYPE_SPECIALIZED^#)
// COMPLETE_GENERIC_FUNC_WITH_TYPE_SPECIALIZED-NOT: variableDeclaredInConstraintExtension
}
}
func bar<T: FontStyle>(x: T) -> T { return x }
func test2<T: FontStyle>(x: T) {
bar(x).#^COMPLETE_ON_GENERIC_FUNC_WITH_GENERIC_ARG?check=EXTENSION_NOT_APPLIED^#
bar(FontStyleTwo()).#^COMPLETE_ON_GENERIC_FUNC^#
// COMPLETE_ON_GENERIC_FUNC: Begin completions, 1 item
// COMPLETE_ON_GENERIC_FUNC-DAG: Keyword[self]/CurrNominal: self[#FontStyleTwo#];
// COMPLETE_ON_GENERIC_FUNC: End completions
}
// https://github.com/apple/swift/issues/55419
struct Struct {}
struct Indicator<T> {}
extension Indicator where T == Struct {
static var activity: Indicator<Struct> { fatalError() }
}
func receiver<T>(_ inidicator: Indicator<T>) {}
func test() {
receiver(.#^COMPLETE_GENERIC_TYPE^#)
}
// COMPLETE_GENERIC_TYPE: Begin completions, 2 items
// COMPLETE_GENERIC_TYPE: Decl[Constructor]/CurrNominal/TypeRelation[Convertible]: init()[#Indicator<T>#];
// COMPLETE_GENERIC_TYPE: Decl[StaticVar]/CurrNominal/TypeRelation[Convertible]: activity[#Indicator<Struct>#];
// COMPLETE_GENERIC_TYPE: End completions
func testRecursive<T>(_ inidicator: Indicator<T>) {
testRecursive(.#^COMPLETE_RECURSIVE_GENERIC^#)
// FIXME: We should be suggesting `.activity` here because the call to `testRecursive` happens with new generic parameters
// COMPLETE_RECURSIVE_GENERIC: Begin completions, 1 item
// COMPLETE_RECURSIVE_GENERIC-DAG: Decl[Constructor]/CurrNominal/TypeRelation[Convertible]: init()[#Indicator<T>#];
// COMPLETE_RECURSIVE_GENERIC: End completions
}
| apache-2.0 | 9c11b0561bb3a4f89bcd65d5a9846c9e | 38.689189 | 135 | 0.741573 | 3.577345 | false | true | false | false |
yangchenghu/actor-platform | actor-apps/app-ios/ActorApp/View/TableViewHeader.swift | 11 | 814 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
class TableViewHeader: UIView {
override func layoutSubviews() {
super.layoutSubviews()
for view in self.subviews {
view.frame = CGRectMake(view.frame.minX, view.frame.minY, self.frame.width, view.frame.height)
// Fix for UISearchBar disappear
// http://stackoverflow.com/questions/19044156/searchbar-disappears-from-headerview-in-ios-7
if let search = view as? UISearchBar {
if let buggyView = search.subviews.first {
buggyView.bounds = search.bounds
buggyView.center = CGPointMake(buggyView.bounds.width/2,buggyView.bounds.height/2)
}
}
}
}
} | mit | e1c4de99074b2e7ab887ca25c2101a9a | 32.958333 | 106 | 0.588452 | 4.284211 | false | false | false | false |
GirAppe/BTracker | Sources/Classes/Beacon.swift | 1 | 3841 | //
// Copyright © 2017 GirAppe Studio. All rights reserved.
//
import Foundation
import CoreLocation
public typealias Identifier = String
public struct Beacon {
public let identifier: Identifier
public let proximityUUID: UUID
public let motionUUID: UUID?
public let major: Value<Int>
public let minor: Value<Int>
}
extension Beacon {
public var isMotion: Bool { return motionUUID != nil }
var proximityIdentifier: Identifier { return "\(proximityUUID.uuidString).\(identifier)" }
var motionIdentifier: Identifier { return "\(motionUUID?.uuidString ?? "motion").\(identifier)" }
internal var proximity: CLBeaconRegion? { return region(uuid: proximityUUID, identifier: proximityIdentifier) }
internal var motion: CLBeaconRegion? { return region(uuid: motionUUID, identifier: motionIdentifier) }
public init?(identifier: Identifier, proximityUUID: String, motionUUID: String? = nil) {
guard let beacon = Beacon(identifier: identifier, proximityUUID: proximityUUID, motionUUID: motionUUID, major: .any, minor: .any) else {
return nil
}
self = beacon
}
public init?(identifier: Identifier, proximityUUID: String, major: Int, motionUUID: String? = nil) {
guard let beacon = Beacon(identifier: identifier, proximityUUID: proximityUUID, motionUUID: motionUUID, major: .some(major), minor: .any) else {
return nil
}
self = beacon
}
public init?(identifier: Identifier, proximityUUID: String, major: Int, minor: Int, motionUUID: String? = nil) {
guard let beacon = Beacon(identifier: identifier, proximityUUID: proximityUUID, motionUUID: motionUUID, major: .some(major), minor: .some(minor)) else {
return nil
}
self = beacon
}
}
extension Beacon: Equatable {
public static func == (lhs: Beacon, rhs: Beacon) -> Bool {
return lhs.identifier == rhs.identifier
}
public static func == (lhs: Beacon, rhs: CLBeacon) -> Bool {
let proximity = lhs.proximityUUID == rhs.proximityUUID
let motion = lhs.motionUUID == rhs.proximityUUID
let majorMatches = lhs.major == rhs.major.intValue
let minorMatches = lhs.minor == rhs.minor.intValue
return (proximity || motion) && majorMatches && minorMatches
}
public func matches(proximity identifier: Identifier) -> Bool {
return self.proximityIdentifier == identifier
}
public func matches(motion identifier: Identifier) -> Bool {
return self.motionIdentifier == identifier
}
}
fileprivate extension Beacon {
init?(identifier: Identifier, proximityUUID: String, motionUUID: String? = nil, major: Value<Int> = .any, minor: Value<Int> = .any) {
guard let proximityUUID = UUID(uuidString: proximityUUID) else {
return nil
}
let motionUUID = UUID(uuidString: motionUUID)
self = Beacon(identifier: identifier, proximityUUID: proximityUUID, motionUUID: motionUUID, major: major, minor: minor)
}
func region(uuid: UUID?, identifier: Identifier) -> CLBeaconRegion? {
guard let uuid = uuid else { return nil }
switch (major, minor) {
case let (.some(major), .any): return CLBeaconRegion(proximityUUID: uuid, major: UInt16(major), identifier: identifier)
case let (.some(major), .some(minor)): return CLBeaconRegion(proximityUUID: uuid, major: UInt16(major), minor: UInt16(minor), identifier: identifier)
default: return CLBeaconRegion(proximityUUID: uuid, identifier: identifier)
}
}
}
fileprivate extension UUID {
init?(uuidString: String?) {
guard let uuidString = uuidString else { return nil }
guard let uuid = UUID(uuidString: uuidString) else { return nil }
self = uuid
}
}
| mit | e1cd8a4f6607acf6f97dadfa7ce52dbd | 38.587629 | 161 | 0.670573 | 4.604317 | false | false | false | false |
aroyarexs/PASTA | PASTA/Classes/PASTAManager.swift | 1 | 6746 | //
// PASTAManager.swift
// PAD
//
// Created by Aaron Krämer on 09.08.17.
// Copyright © 2017 Aaron Krämer. All rights reserved.
//
import CoreGraphics
/// Collects markers and provides functions to compose/complete Tangibles.
class PASTAManager: TangibleManager {
// MARK: - Marker Manager Properties
/// A set of markers which are not assigned to any Tangible.
var unassigned = Set<PASTAMarker>()
// MARK: - Tangible Manager Properties
/// Holds all tangibles with active markers only.
private (set) var complete = Set<PASTATangible>()
/// Contains all tangibles which have at least one active and one inactive marker.
private (set) var incomplete = Set<PASTATangible>()
/// A set of tangibles which are either not allowed or similar to existing ones (`similarPatternsAllowed == true`).
private (set) var blocked = Set<PASTATangible>()
/// Compares all currently active Tangible patterns on the screen against `pattern`.
/// - parameter pattern: A Tangible pattern.
/// - returns: `true` if `pattern` is similar to any currently active pattern, otherwise `false`.
func isSimilar(pattern: PASTAPattern) -> Bool {
return complete.union(incomplete).contains { $0.pattern.isSimilar(to: pattern) }
}
/// `true` if `patternWhitelistDisabled == true` or `pattern` is contained in `patternWhitelist`.
/// - parameter pattern: A Tangible pattern.
/// - returns: `true` if `patternWhitelistDisabled == true` or `pattern` is contained in `patternWhitelist`.
func isPatternAllowed(pattern: PASTAPattern) -> Bool {
return patternWhitelistDisabled || patternWhitelist.contains { $0.value.isSimilar(to: pattern) }
}
/// Concatenated `isSimilar(pattern:)` and `isPatternAllowed(pattern:)` with boolean AND.
/// - parameter pattern: A tangible pattern.
/// - returns: `true` if both functions return `true`, otherwise `false`.
func willAcceptPattern(pattern: PASTAPattern) -> Bool {
return isPatternAllowed(pattern: pattern) && isSimilar(pattern: pattern)
}
/// Tries to composes a new Tangible.
/// `self` is assigned to `tangibleManager` property and `tangibleDelegate` is assigned to `eventDelegate`.
/// - parameter markers: An array of marker.
/// - returns: `nil` of Tangible could not be composed, otherwise a new Tangible.
private func createTangible(markers: [PASTAMarker]) -> PASTATangible? {
let tangible = PASTATangible(markers: markers)
tangible?.tangibleManager = self
tangible?.eventDelegate = tangibleDelegate
return tangible
}
/// Tries to creates a new Tangible and insert it into `blocked` set.
/// - parameter markers: An array of markers.
/// - returns: `true` if Tangible could be formed, otherwise `false`.
private func insertBlockedTangible(markers: [PASTAMarker]) -> Bool {
guard let tangible = PASTATangible(markers: markers) else { return false }
tangible.tangibleManager = self
blocked.insert(tangible)
return true
}
// MARK: - TangibleManager
weak var tangibleDelegate: TangibleEvent?
private (set) var patternWhitelist: [String: PASTAPattern] = [:]
var patternWhitelistDisabled: Bool = false
var similarPatternsAllowed: Bool = false
func whitelist(pattern: PASTAPattern, identifier: String) -> Bool {
let patternOrIdentifierAlreadyUsed = patternWhitelist.contains {
pattern.isSimilar(to: $0.value) || $0.key == identifier
}
guard patternOrIdentifierAlreadyUsed == false else { return false }
patternWhitelist[identifier] = pattern
return true
}
func compose(markers: [PASTAMarker]) -> Bool {
guard markers.count == 3 else { return false }
let pattern = PASTAPattern(marker1: markers[0], marker2: markers[1], marker3: markers[2])
guard willAcceptPattern(pattern: pattern) else { return insertBlockedTangible(markers: markers) }
guard let tangible = createTangible(markers: markers) else { return false }
if tangible.inactiveMarkers.isEmpty { complete.insert(tangible) } else { incomplete.insert(tangible) }
tangibleDelegate?.tangibleDidBecomeActive(tangible)
return true
}
func complete(with marker: PASTAMarker) -> PASTATangible? {
return incomplete.first { $0.replaceInactiveMarker(with: marker) }
}
// MARK: - TangibleStatus
func tangibleDidBecomeInactive(_ tangible: PASTATangible) {
complete.remove(tangible)
incomplete.remove(tangible)
blocked.remove(tangible)
}
func tangibleDidBecomeActive(_ tangible: PASTATangible) {
if tangible.inactiveMarkers.isEmpty { complete.insert(tangible) } else { incomplete.insert(tangible) }
}
func tangible(_ tangible: PASTATangible, lost marker: PASTAMarker) {
guard blocked.contains(tangible) == false else { return }
incomplete.insert(tangible)
complete.remove(tangible)
}
func tangible(_ tangible: PASTATangible, recovered marker: PASTAMarker) {
guard blocked.contains(tangible) == false else { return }
if tangible.inactiveMarkers.isEmpty {
complete.insert(tangible)
incomplete.remove(tangible)
}
}
}
extension PASTAManager: MarkerStatus {
func markerDidBecomeActive(_ marker: PASTAMarker) {
// incomplete available?
if (complete(with: marker)) != nil {
marker.markerManager = nil
return
}
/// block marker which are not used by `incomplete` or `blocked` tangibles but are inside tangible
let pointInsideIncomplete = incomplete.union(blocked).contains { tangible in
let convertedCenter = marker.superview?.convert(marker.center, to: tangible) ??
CGPoint(x: CGFloat.infinity, y:CGFloat.infinity)
return tangible.point(inside: convertedCenter, with: nil)
}
guard pointInsideIncomplete == false else { return }
// can a new tangible be composed?
if unassigned.count >= 2 {
let configs = PASTAHeap(marker: marker, unassigned: Array(unassigned))
for config in configs {
if compose(markers: config) {
config.forEach {
unassigned.remove($0)
$0.markerManager = nil
}
return
}
}
}
// could not complete or compose
unassigned.insert(marker)
}
func markerDidBecomeInactive(_ marker: PASTAMarker) {
unassigned.remove(marker)
marker.removeFromSuperview()
}
}
| mit | 51e700e25e4dd668349f23abcaca9176 | 38.899408 | 119 | 0.659795 | 4.785664 | false | false | false | false |
xu6148152/binea_project_for_ios | Trax/Trax/GPX.swift | 1 | 1643 | //
// GPX.swift
// Trax
//
// Created by Binea Xu on 7/19/15.
// Copyright (c) 2015 Binea Xu. All rights reserved.
//
import Foundation
class GPX: NSObject, Printable, NSXMLParserDelegate{
// var wayPoints = []()
// var tracks = [Track]()
// var routes = [Track]()
//
// override var description: String{
// var descriptions = [String]()
// if wayPoints.count > 0 {descriptions.append("waypoints = \(wayPoints)")
// if tracks.count > 0{descriptions.append("tracks = \(tracks)")}
// if routes.count > 0{descriptions.append("routes = \(routes)")}
// return "\n".join(descriptions)
// }
//
// typealias GPXCompletionHandler = (GPX?) -> Void
//
// class func parse(url: NSURL, completionHandler: GPXCompletionHandler){
// GPX(url: url, completionHandler: completionHandler).parse()
// }
//
//
// private let url: NSURL
// private let completionHandler: GPXCompletionHandler
//
// private init(url: NSURL, completionHandler: GPXCompletionHandler){
// self.url = url
// self.completionHandler = completionHandler
// }
//
// private func complete(success: Boolean){
// dispatch_async(dispatch_get_main_queue()){
// self.completionHandler(success ? self : nil)
// }
// }
//
// private func fail(){
// complete(success: false)
// }
//
// private func successed(){
// complete(success: true)
// }
//
// private func parse(){
// let qos =
// }
} | mit | fbe92338a6bd636a5b26ddbac6b3b3d9 | 25.95082 | 81 | 0.544735 | 3.978208 | false | false | false | false |
mrfour0004/AVScanner | Sources/Util.swift | 1 | 1656 | //
// Util.swift
// AVScanner
//
// Created by Liang, KaiChih on 01/11/2017.
//
import Foundation
/// Prints the filename, function name, line number and textual representation of `object` and a newline character into the standard output if the build setting for "Active Complilation Conditions" (SWIFT_ACTIVE_COMPILATION_CONDITIONS) defines `DEBUG`.
///
/// The current thread is a prefix on the output. <UI> for the main thread, <BG> for anything else.
///
/// Only the first parameter needs to be passed to this funtion.
///
/// The textual representation is obtained from the `object` using `String(reflecting:)` which works for _any_ type. To provide a custom format for the output make your object conform to `CustomDebugStringConvertible` and provide your format in the `debugDescription` parameter.
/// - Parameters:
/// - object: The object whose textual representation will be printed. If this is an expression, it is lazily evaluated.
/// - file: The name of the file, defaults to the current file without the ".swift" extension.
/// - function: The name of the function, defaults to the function within which the call is made.
/// - line: The line number, defaults to the line number within the file that the call is made.
func loggingPrint<T>(_ object: @autoclosure () -> T, _ file: String = #file, _ function: String = #function, _ line: Int = #line) {
#if DEBUG
let value = object()
let fileURL = NSURL(string: file)?.lastPathComponent ?? "Unknown file"
let queue = Thread.isMainThread ? "UI" : "BG"
print("[AVScanner] <\(queue)> \(fileURL) \(function)[\(line)]: " + String(reflecting: value))
#endif
}
| mit | ed733d932c98b1f40ad9cc70bdbcfbf5 | 54.2 | 278 | 0.710145 | 4.068796 | false | false | false | false |
brentdax/swift | stdlib/public/core/ArrayCast.swift | 2 | 3425 | //===--- ArrayCast.swift - Casts and conversions for Array ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Because NSArray is effectively an [AnyObject], casting [T] -> [U]
// is an integral part of the bridging process and these two issues
// are handled together.
//
//===----------------------------------------------------------------------===//
/// Called by the casting machinery.
@_silgen_name("_swift_arrayDownCastIndirect")
internal func _arrayDownCastIndirect<SourceValue, TargetValue>(
_ source: UnsafePointer<Array<SourceValue>>,
_ target: UnsafeMutablePointer<Array<TargetValue>>) {
target.initialize(to: _arrayForceCast(source.pointee))
}
/// Implements `source as! [TargetElement]`.
///
/// - Note: When SourceElement and TargetElement are both bridged verbatim, type
/// checking is deferred until elements are actually accessed.
@inlinable // FIXME(sil-serialize-all)
public func _arrayForceCast<SourceElement, TargetElement>(
_ source: Array<SourceElement>
) -> Array<TargetElement> {
#if _runtime(_ObjC)
if _isClassOrObjCExistential(SourceElement.self)
&& _isClassOrObjCExistential(TargetElement.self) {
let src = source._buffer
if let native = src.requestNativeBuffer() {
if native.storesOnlyElementsOfType(TargetElement.self) {
// A native buffer that is known to store only elements of the
// TargetElement can be used directly
return Array(_buffer: src.cast(toBufferOf: TargetElement.self))
}
// Other native buffers must use deferred element type checking
return Array(_buffer:
src.downcast(toBufferWithDeferredTypeCheckOf: TargetElement.self))
}
return Array(_immutableCocoaArray: source._buffer._asCocoaArray())
}
#endif
return source.map { $0 as! TargetElement }
}
@_fixed_layout
@usableFromInline
internal struct _UnwrappingFailed : Error {
@inlinable
internal init() {}
}
extension Optional {
@inlinable // FIXME(sil-serialize-all)
internal func unwrappedOrError() throws -> Wrapped {
if let x = self { return x }
throw _UnwrappingFailed()
}
}
/// Called by the casting machinery.
@_silgen_name("_swift_arrayDownCastConditionalIndirect")
internal func _arrayDownCastConditionalIndirect<SourceValue, TargetValue>(
_ source: UnsafePointer<Array<SourceValue>>,
_ target: UnsafeMutablePointer<Array<TargetValue>>
) -> Bool {
if let result: Array<TargetValue> = _arrayConditionalCast(source.pointee) {
target.initialize(to: result)
return true
}
return false
}
/// Implements `source as? [TargetElement]`: convert each element of
/// `source` to a `TargetElement` and return the resulting array, or
/// return `nil` if any element fails to convert.
///
/// - Complexity: O(n), because each element must be checked.
@inlinable // FIXME(sil-serialize-all)
public func _arrayConditionalCast<SourceElement, TargetElement>(
_ source: [SourceElement]
) -> [TargetElement]? {
return try? source.map { try ($0 as? TargetElement).unwrappedOrError() }
}
| apache-2.0 | 0f84d16f51db9b2c8725465c249833f5 | 35.827957 | 80 | 0.688175 | 4.368622 | false | false | false | false |
honghaoz/UW-Quest-iOS | UW Quest/Model/User.swift | 1 | 5688 | //
// User.swift
// UW Quest
//
// Created by Honghao Zhang on 2014-09-15.
// Copyright (c) 2014 Honghao. All rights reserved.
//
import Foundation
private let _sharedUser = User()
class User {
var username: String = ""
var password: String = ""
var isRemembered: Bool = true
var isLoggedIn: Bool = false
var kUsername = "Username"
var kPassword = "Password"
var kIsRemembered = "Remembered"
var personalInformation: PersonalInformation = PersonalInformation()
var classSchedule: ClassSchedule!
init() {
logInfo("User inited")
}
class var sharedUser: User {
return _sharedUser
}
func save() {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(isRemembered, forKey: kIsRemembered)
defaults.setObject(username, forKey: kUsername)
defaults.setObject(password, forKey: kPassword)
defaults.synchronize()
}
func load() -> Bool {
let defaults = NSUserDefaults.standardUserDefaults()
self.isRemembered = defaults.boolForKey(kIsRemembered)
if self.isRemembered {
if let username: AnyObject = defaults.objectForKey(kUsername) {
self.username = username as! String
}
if let password: AnyObject = defaults.objectForKey(kPassword) {
self.password = password as! String
}
return true
}
return false
}
func login(success:(() -> ())?, failure:((errorMessage: String, error: NSError?) -> ())?) {
logInfo("Login: userid: \(username), password: \(password)")
assert(!username.isEmpty && !password.isEmpty, "userid or password must be non-empty")
Locator.sharedQuestClient.loginWithUsename(username, password: password, success: { (response, json) -> () in
self.isLoggedIn = true
success?()
ARAnalytics.event("Login successfully")
}) { (errorMessage, error) -> () in
self.isLoggedIn = false
failure?(errorMessage: errorMessage, error: error)
ARAnalytics.error(error, withMessage: errorMessage)
}
}
func getPersonalInformation(type: PersonalInformationType, success: (() -> ())?, failure:((errorMessage: String, error: NSError?) -> ())?) {
logVerbose()
if !self.isLoggedIn {
failure!(errorMessage: "User is not logged in", error: nil)
}
Locator.sharedQuestClient.getPersonalInformation(type, success: { (data) -> () in
if self.processPersonalInformation(type, data: data) {
success?()
} else {
failure?(errorMessage: "Init data failed", error: nil)
}
}) { (errorMessage, error) -> () in
failure?(errorMessage: errorMessage, error: error)
return
}
}
// User dataResponse (either Dict or Array) to init personal information
func processPersonalInformation(type: PersonalInformationType, data: AnyObject) -> Bool {
logDebug("Type: \(type.rawValue)")
logDebug("Data: \(data)")
switch type {
case .Addresses:
return self.personalInformation.initAddresses(data)
case .Names:
let json = JSON(data)
return self.personalInformation.initNames(json["Data"].rawValue, message: json["Message"].string)
case .PhoneNumbers:
return self.personalInformation.initPhoneNumbers(data, message: nil)
case .EmailAddresses:
return self.personalInformation.initEmailAddresses(data, message: nil)
case .EmergencyContacts:
return self.personalInformation.initEmergencyContacts(data, message: nil)
case .DemographicInformation:
return self.personalInformation.initDemographicInformation(data, message: nil)
case .CitizenshipImmigrationDocuments:
return self.personalInformation.initCitizenshipImmigrationDocument(data, message: nil)
default:
assert(false, "Wrong PersonalInformation Type")
}
return false
}
// func getMyAcademic(type: MyAcademicsType,
// success: (() -> ())?,
// failure:((errorMessage: String, error: NSError?) -> ())?) {
// if !self.isLoggedIn {
// failure!(errorMessage: "User is not logged in", error: nil)
// }
//
// Locator.client.getPersonalInformation(type, success: { (dataResponse, message) -> () in
// println("message: " + (message != nil ? message! : ""))
// if self.processPersonalInformation(type, data: dataResponse, message: message) {
// success?()
// } else {
// failure?(errorMessage: "Init data failed", error: nil)
// }
// }) { (errorMessage, error) -> () in
// failure?(errorMessage: errorMessage, error: error)
// return
// }
// }
func getMyClassScheduleTermList() {
// TODO
}
func getMyClassScheduleWithTermIndex(index: Int, success:(() -> ())?, failure:((errorMessage: String, error: NSError?) -> ())?) {
logVerbose("termIndex: \(index)")
Locator.sharedQuestClient.postMyClassScheduleWithIndex(index, success: { (response, json) -> () in
self.classSchedule = ClassSchedule(json: json!)
success?()
}, failure: { (errorMessage, error) -> () in
failure?(errorMessage: errorMessage, error: error)
})
}
} | apache-2.0 | 672ebffd73b54b8b325182afdcd42643 | 37.181208 | 144 | 0.588608 | 4.72818 | false | false | false | false |
zilaiyedaren/MLSwiftBasic | MLSwiftBasic/Classes/Meters/Mirror.swift | 2 | 4202 | //
// File.swift
// Mirror
//
// Created by Kostiantyn Koval on 05/07/15.
//
//
import Foundation
public struct MirrorItem {
public let name: String
public let type: Any.Type
public let value: Any
init(_ tup: (String, MirrorType)) {
self.name = tup.0
self.type = tup.1.valueType
self.value = tup.1.value
}
}
extension MirrorItem : Printable {
public var description: String {
return "\(name): \(type) = \(value)"
}
}
//MARK: -
public struct Mirror<T> {
private let mirror: MirrorType
let instance: T
public init (_ x: T) {
instance = x
mirror = reflect(x)
}
//MARK: - Type Info
/// Instance type full name, include Module
public var name: String {
return "\(instance.dynamicType)"
}
/// Instance type short name, just a type name, without Module
public var shortName: String {
let name = "\(instance.dynamicType)"
let shortName = name.convertOptionals()
return shortName.pathExtension
}
public var firstName: String {
let name = "\(instance.dynamicType)"
let shortName = name.convertOptionals()
return shortName.componentsSeparatedByString(".").first!
}
}
extension Mirror {
public var isClass: Bool {
return mirror.objectIdentifier != nil
}
public var isStruct: Bool {
return mirror.objectIdentifier == nil
}
public var isOptional: Bool {
return name.hasPrefix("Swift.Optional<")
}
public var isArray: Bool {
return name.hasPrefix("Swift.Array<")
}
public var isDictionary: Bool {
return name.hasPrefix("Swift.Dictionary<")
}
public var isSet: Bool {
return name.hasPrefix("Swift.Set<")
}
}
extension Mirror {
/// Type properties count
public var childrenCount: Int {
return mirror.count
}
public var memorySize: Int {
return sizeofValue(instance)
}
//MARK: - Children Inpection
/// Properties Names
public var names: [String] {
return map(self) { $0.name }
}
/// Properties Values
public var values: [Any] {
return map(self) { $0.value }
}
/// Properties Types
public var types: [Any.Type] {
return map(self) { $0.type }
}
/// Short style for type names
public var typesShortName: [String] {
return map(self) { "\($0.type)".convertOptionals().pathExtension }
}
/// Mirror types for every children property
public var children: [MirrorItem] {
return map(self) { $0 }
}
//MARK: - Quering
/// Returns a property value for a property name
public subscript (key: String) -> Any? {
let res = findFirst(self) { $0.name == key }
return res.map { $0.value }
}
/// Returns a property value for a property name with a Genereci type
/// No casting needed
public func get<U>(key: String) -> U? {
let res = findFirst(self) { $0.name == key }
return res.flatMap { $0.value as? U }
}
/// Convert to a dicitonary with [PropertyName : PropertyValue] notation
public var toDictionary: [String : Any] {
var result: [String : Any] = [ : ]
for item in self {
result[item.name] = item.value
}
return result
}
/// Convert to NSDictionary.
/// Useful for saving it to Plist
public var toNSDictionary: NSDictionary {
var result: [String : AnyObject] = [ : ]
for item in self {
result[item.name] = item.value as? AnyObject
}
return result
}
}
extension Mirror : CollectionType, SequenceType {
public func generate() -> IndexingGenerator<[MirrorItem]> {
return children.generate()
}
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return mirror.count
}
public subscript (i: Int) -> MirrorItem {
return MirrorItem(mirror[i])
}
}
extension String {
func contains(x: String) -> Bool {
return self.rangeOfString(x) != nil
}
func convertOptionals() -> String {
var x = self
while let range = x.rangeOfString("Swift.Optional<") {
if let endOfOptional = x.rangeOfString(">", range: range.startIndex..<x.endIndex) {
x.replaceRange(endOfOptional, with: "?")
}
x.removeRange(range)
}
return x
}
}
| mit | 8469625b85802963f018a3a9720a2b6a | 19.80198 | 89 | 0.624465 | 3.979167 | false | false | false | false |
remirobert/Dotzu-Objective-c | Pods/Dotzu/Dotzu/ResponseDataTableViewCell.swift | 3 | 671 | //
// DetailContentTableViewCell.swift
// exampleWindow
//
// Created by Remi Robert on 25/01/2017.
// Copyright © 2017 Remi Robert. All rights reserved.
//
import UIKit
class ResponseDataTableViewCell: UITableViewCell, LogCellProtocol {
@IBOutlet weak var textview: UITextView!
override func awakeFromNib() {
super.awakeFromNib()
textview.isUserInteractionEnabled = false
textview.textColor = UIColor.white
}
func configure(log: LogProtocol) {
guard let request = log as? LogRequest else {return}
guard let data = request.dataResponse else {return}
textview.text = "\(data.length) bytes"
}
}
| mit | 3648ee048893e952b0476557c7961c3b | 24.769231 | 67 | 0.685075 | 4.527027 | false | false | false | false |
apegroup/APEReactiveNetworking | APEReactiveNetworking/Source/Helpers/NetworkActivityIndicator.swift | 1 | 866 | //
// NetworkActivityIndicator.swift
// app-architecture
//
// Created by Dennis Korkchi on 2016-05-27.
// Copyright © 2016 Apegroup. All rights reserved.
//
import Foundation
import UIKit
class NetworkActivityIndicator {
//Singleton
static let sharedInstance = NetworkActivityIndicator()
//This prevents others from using the default '()' initializer for this class.
private init() {
enabled = false
}
private var count : Int = 0
var enabled : Bool {
didSet {
if enabled {
count += 1
} else {
count = max(0, (count - 1))
}
DispatchQueue.main.asyncAfter(deadline: .now() + 0.4) {
UIApplication.shared.isNetworkActivityIndicatorVisible = (self.count > 0)
}
}
}
}
| mit | cd13bd38c55ea25618523f92b8ca072f | 22.378378 | 89 | 0.559538 | 4.752747 | false | false | false | false |
lorentey/swift | test/Driver/Dependencies/chained-private-after-multiple.swift | 2 | 1439 | /// other --> main ==> yet-another
/// other ==>+ main ==> yet-another
// RUN: %empty-directory(%t)
// RUN: cp -r %S/Inputs/chained-private-after-multiple/* %t
// RUN: touch -t 201401240005 %t/*.swift
// Generate the build record...
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift ./yet-another.swift -module-name main -j1 -v
// ...then reset the .swiftdeps files.
// RUN: cp -r %S/Inputs/chained-private-after-multiple/*.swiftdeps %t
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./main.swift ./other.swift ./yet-another.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-FIRST %s
// CHECK-FIRST-NOT: warning
// CHECK-FIRST-NOT: Handled
// RUN: touch -t 201401240006 %t/other.swift
// RUN: cd %t && %swiftc_driver -c -driver-use-frontend-path "%{python};%S/Inputs/update-dependencies.py" -output-file-map %t/output.json -incremental -driver-always-rebuild-dependents ./yet-another.swift ./main.swift ./other.swift -module-name main -j1 -v 2>&1 | %FileCheck -check-prefix=CHECK-SECOND %s
// CHECK-SECOND-DAG: Handled other.swift
// CHECK-SECOND-DAG: Handled main.swift
// CHECK-SECOND: Handled yet-another.swift
| apache-2.0 | fd9be008f8ec333b063671c1d869bf90 | 61.565217 | 304 | 0.708131 | 3.1766 | false | false | true | false |
benlangmuir/swift | benchmark/single-source/DictionaryBridge.swift | 10 | 1786 | //===--- DictionaryBridge.swift -------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// benchmark to test the performance of bridging an NSDictionary to a
// Swift.Dictionary.
import Foundation
import TestsUtils
public let benchmarks =
BenchmarkInfo(
name: "DictionaryBridge",
runFunction: run_DictionaryBridge,
tags: [.validation, .api, .Dictionary, .bridging])
#if _runtime(_ObjC)
class Thing : NSObject {
required override init() {
let c = type(of: self).col()
check(c!.count == 10)
}
private class func col() -> [String : AnyObject]? {
let dict = NSMutableDictionary()
dict.setValue(1, forKey: "one")
dict.setValue(2, forKey: "two")
dict.setValue(3, forKey: "three")
dict.setValue(4, forKey: "four")
dict.setValue(5, forKey: "five")
dict.setValue(6, forKey: "six")
dict.setValue(7, forKey: "seven")
dict.setValue(8, forKey: "eight")
dict.setValue(9, forKey: "nine")
dict.setValue(10, forKey: "ten")
return NSDictionary(dictionary: dict) as? [String: AnyObject]
}
class func mk() -> Thing {
return self.init()
}
}
class Stuff {
var c: Thing = Thing.mk()
init() {
}
}
#endif
@inline(never)
public func run_DictionaryBridge(_ n: Int) {
#if _runtime(_ObjC)
for _ in 1...100*n {
autoreleasepool {
_ = Stuff()
}
}
#endif
}
| apache-2.0 | b34cf97e98b3bdd0c3fa2614d06b815b | 24.15493 | 80 | 0.606943 | 3.891068 | false | false | false | false |
DominikButz/DYAlertController | DYAlertController/DYActionCell.swift | 1 | 5144 | //
// DYActionCellTableViewCell.swift
// SimpleAlertTesting
//
// Created by Dominik Butz on 24/02/16.
// Copyright © 2016 Duoyun. All rights reserved.
//
import UIKit
class DYActionCell: UITableViewCell {
@IBOutlet weak var actionTitleLabel: UILabel!
@IBOutlet weak var actionImageView: UIImageView?
@IBOutlet weak var actionImageViewLeadingConstraint: NSLayoutConstraint!
@IBOutlet weak var actionTitleLeadingConstraint: NSLayoutConstraint!
var settings:DYAlertSettings.ActionCellSettings!
var hasAccessoryView = false
var style = ActionStyle.normal
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
if self.isSelected == selected {
// print("already selected or deselcted, returning")
return
}
super.setSelected(selected, animated: animated)
// print("set selected called")
if hasAccessoryView {
if selected {
self.accessoryType = UITableViewCell.AccessoryType.checkmark
self.tintColor = self.getColour(self.style, selected: true)
} else {
self.accessoryType = .none
self.tintColor = self.getColour(self.style, selected: false)
}
self.actionTitleLabel.textColor = self.tintColor
}
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
internal func configureCell(_ actionItem:DYAlertAction, hasAccessoryView:Bool, settings:DYAlertSettings.ActionCellSettings) {
// print("configure cell called")
self.actionTitleLabel.text = actionItem.title
self.actionTitleLabel.font = settings.actionCellFont
let iconImage = actionItem.iconImage
self.actionImageView!.image = iconImage?.withRenderingMode(.alwaysTemplate)
self.actionImageView!.contentMode = .scaleAspectFit
self.isUserInteractionEnabled = (actionItem.style != .disabled)
self.hasAccessoryView = hasAccessoryView
//print("has accessory view? \(hasAccessoryView)")
self.style = actionItem.style
self.settings = settings
if hasAccessoryView {
//has checkmark
self.selectionStyle = .none
self.tintColor = self.getColour(self.style, selected: actionItem.selected)
} else {
// no checkmark
self.selectionStyle = .gray
self.tintColor = self.getColour(self.style, selected: true)
self.moveViewElementsIfNeeded()
}
self.actionTitleLabel.textColor = self.tintColor
}
fileprivate func getColour(_ style:ActionStyle, selected:Bool)->UIColor {
switch style {
case .disabled:
return settings.disabledTintColor
case .normal:
if selected {
return settings.defaultTintColor
} else {
return settings.deselectedTintColor
}
case .destructive:
if selected {
return settings.destructiveTintColor
} else {
return settings.deselectedTintColor
}
}
}
open func moveViewElementsIfNeeded() {
// only called if checkmarks turned off
if let _ = actionImageView?.image {
// replace self.contentView.constraints[0].isActive = false // imageview leading
self.actionImageViewLeadingConstraint.isActive = false
let imageViewTrailing = NSLayoutConstraint(item: self.contentView, attribute: NSLayoutConstraint.Attribute.trailing, relatedBy: NSLayoutConstraint.Relation.equal, toItem: self.actionImageView!, attribute: NSLayoutConstraint.Attribute.trailing, multiplier: 1.0, constant: 10.0)
self.contentView.addConstraint(imageViewTrailing)
// replace self.contentView.constraints[1].constant = 5.0 // acitontitlelabel leading
self.actionTitleLeadingConstraint.constant = 5.0
} else {
actionImageView?.removeFromSuperview()
// replace self.contentView.constraints[1].isActive = false // acitontitlelabel leading
self.actionTitleLeadingConstraint.isActive = false
let centerLabelConstraint = NSLayoutConstraint(item: self.contentView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: actionTitleLabel, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1.0, constant: 0.0)
self.contentView.addConstraint(centerLabelConstraint)
}
}
}
| mit | 122b2a235b4ecca307578277e1e4c16c | 28.901163 | 288 | 0.621427 | 5.542026 | false | false | false | false |
mdab121/swift-fcm | Sources/FCM/FirebaseResponse.swift | 1 | 1678 | // (c) 2017 Kajetan Michal Dabrowski
// This code is licensed under MIT license (see LICENSE for details)
import Foundation
import Jay
/// This is a response that you will get from Firebase
public struct FirebaseResponse {
/// Indicates if everything was successful
public let success: Bool
/// Error(s) that occured while sending a message
public let error: FirebaseError?
// MARK: Internal and private methods
private enum ResponseKey: String {
case result = "results"
case messageId = "message_id"
case error = "error"
}
internal init(error: FirebaseError) {
self.success = false
self.error = error
}
internal init(data: Data?, statusCode: Int?, error: Error?) {
if let error = error {
//Error – don't parse the data
self.success = false
self.error = FirebaseError(error: error)
return
}
guard statusCode == 200 else {
self.success = false
self.error = FirebaseError(statusCode: statusCode)
return
}
guard let data = data,
let json = try? Jay().anyJsonFromData(Array<UInt8>(data)),
let dict = json as? [String: Any] else {
self.success = false
self.error = .invalidData
return
}
var messageIds: [String] = []
var errors: [FirebaseError] = []
let results = dict[ResponseKey.result.rawValue] as? [[String: Any]]
for result in results ?? [] {
if let id = result[ResponseKey.messageId.rawValue] as? String {
messageIds.append(id)
}
if let errorMessage = result[ResponseKey.error.rawValue] as? String {
errors.append(FirebaseError(message: errorMessage))
}
}
self.success = errors.isEmpty && !messageIds.isEmpty
self.error = FirebaseError(multiple: errors)
}
}
| mit | c98099ca5daae109aa7d4dd8e3cf7402 | 24.784615 | 72 | 0.691527 | 3.535865 | false | false | false | false |
justindeguzman/hackathons | YHack (Fall 2014)/ios/Wiwo/Wiwo/CheckoutViewController.swift | 1 | 1742 | //
// CheckoutViewController.swift
// Wiwo
//
// Created by Justin de Guzman on 11/1/14.
// Copyright (c) 2014 wiwo. All rights reserved.
//
import UIKit
import AudioToolbox
class CheckoutViewController: UIViewController {
@IBOutlet var storeTitleLabel: UILabel!
@IBOutlet var itemsTitleLabel: UILabel!
@IBOutlet var totalTitleLabel: UILabel!
@IBOutlet var storeLabel: UILabel!
@IBOutlet var itemsLabel: UILabel!
@IBOutlet var totalLabel: UILabel!
@IBOutlet var doneButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
var pvc = self.presentingViewController as ViewController
storeLabel.text = pvc.store
itemsLabel.text = "\(pvc.products.count)"
var priceCount : Int = 0
for product in pvc.products as [String] {
var price = pvc.prices[product]!.toInt()
priceCount = priceCount + price!
}
totalLabel.text = "$\(priceCount).00"
var url = NSURL(string:
"http://104.236.55.193:3000/purchases?amount=\(priceCount)")
var request = NSMutableURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(request, queue:
NSOperationQueue.mainQueue()) {(response, data, error) in
self.storeTitleLabel.hidden = false
self.itemsTitleLabel.hidden = false
self.totalTitleLabel.hidden = false
self.storeLabel.hidden = false
self.itemsLabel.hidden = false
self.totalLabel.hidden = false
self.doneButton.hidden = false
AudioServicesPlayAlertSound(SystemSoundID(1025))
}
}
@IBAction func close() {
self.presentingViewController?.dismissViewControllerAnimated(
true, completion: {
})
}
}
| gpl-2.0 | d1bdb4cdb3a1dd22da818b9a1738c4e0 | 25.8 | 66 | 0.666475 | 4.560209 | false | false | false | false |
xwu/swift | test/Interop/Cxx/value-witness-table/copy-constructors-irgen.swift | 5 | 2730 | // RUN: %target-swift-frontend -enable-cxx-interop -I %S/Inputs %s -emit-ir | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
import CopyConstructors
// CHECK-LABEL: define swiftcc void @"$s4main31testUserProvidedCopyConstructor3objSo03HascdeF0V_AEtAE_tF"
// CHECK: [[T0_DEST:%.*]] = bitcast %TSo30HasUserProvidedCopyConstructorV* [[ARG0:%[0-9]+]] to %struct.HasUserProvidedCopyConstructor*
// CHECK: [[T0_SRC:%.*]] = bitcast %TSo30HasUserProvidedCopyConstructorV* [[ARG2:%[0-9]+]] to %struct.HasUserProvidedCopyConstructor*
// CHECK: call void @_ZN30HasUserProvidedCopyConstructorC1ERKS_(%struct.HasUserProvidedCopyConstructor* [[T0_DEST]], %struct.HasUserProvidedCopyConstructor* [[T0_SRC]])
// CHECK: [[T1_DEST:%.*]] = bitcast %TSo30HasUserProvidedCopyConstructorV* [[ARG1:%[0-9]+]] to %struct.HasUserProvidedCopyConstructor*
// CHECK: [[T1_SRC:%.*]] = bitcast %TSo30HasUserProvidedCopyConstructorV* [[ARG2]] to %struct.HasUserProvidedCopyConstructor*
// CHECK: call void @_ZN30HasUserProvidedCopyConstructorC1ERKS_(%struct.HasUserProvidedCopyConstructor* [[T1_DEST]], %struct.HasUserProvidedCopyConstructor* [[T1_SRC]])
// CHECK: ret void
// CHECK-LABEL: define linkonce_odr void @_ZN30HasUserProvidedCopyConstructorC1ERKS_
public func testUserProvidedCopyConstructor(obj : HasUserProvidedCopyConstructor) -> (HasUserProvidedCopyConstructor, HasUserProvidedCopyConstructor) {
return (obj, obj)
}
// CHECK-LABEL: define swiftcc void @"$s4main26testDefaultCopyConstructor3defSo013HasNonTrivialcdE0V_AEtAE_tF"
// CHECK: call void @_ZN35HasNonTrivialDefaultCopyConstructorC1ERKS_
// CHECK: call void @_ZN35HasNonTrivialDefaultCopyConstructorC1ERKS_
// Make sure we call the copy constructor of our member (HasUserProvidedCopyConstructor)
// CHECK-LABEL: define linkonce_odr void @_ZN35HasNonTrivialDefaultCopyConstructorC1ERKS_
// CHECK: call void @_ZN35HasNonTrivialDefaultCopyConstructorC2ERKS_
public func testDefaultCopyConstructor(def : HasNonTrivialDefaultCopyConstructor) -> (HasNonTrivialDefaultCopyConstructor, HasNonTrivialDefaultCopyConstructor) {
return (def, def)
}
// CHECK-LABEL: define swiftcc void @"$s4main27testImplicitCopyConstructor3impSo013HasNonTrivialcdE0V_AEtAE_tF"
// CHECK: call void @_ZN36HasNonTrivialImplicitCopyConstructorC1ERKS_
// CHECK: call void @_ZN36HasNonTrivialImplicitCopyConstructorC1ERKS_
// Same as above.
// CHECK-LABEL: define linkonce_odr void @_ZN36HasNonTrivialImplicitCopyConstructorC1ERKS_
// CHECK: call void @_ZN36HasNonTrivialImplicitCopyConstructorC2ERKS_
public func testImplicitCopyConstructor(imp : HasNonTrivialImplicitCopyConstructor) -> (HasNonTrivialImplicitCopyConstructor, HasNonTrivialImplicitCopyConstructor) {
return (imp, imp)
}
| apache-2.0 | 2f5f1f6b1a3220cace014fa430bd99ae | 59.666667 | 168 | 0.803663 | 3.812849 | false | true | false | false |
JunDang/SwiftFoundation | Sources/SwiftFoundation/String.swift | 1 | 975 | //
// String.swift
// SwiftFoundation
//
// Created by Alsey Coleman Miller on 7/5/15.
// Copyright © 2015 PureSwift. All rights reserved.
//
public extension String {
init?(UTF8Data: Data) {
let data = UTF8Data
var string = ""
var generator = data.byteValue.generate()
var encoding = UTF8()
repeat {
switch encoding.decode(&generator) {
case .Result (let scalar):
string.append(scalar)
case .EmptyInput:
self = string
return
case .Error:
return nil
}
} while true
return nil
}
func toUTF8Data() -> Data {
return Data(byteValue: [] + utf8)
}
} | mit | 711abef826eabae1677e44b8ad051cee | 18.897959 | 52 | 0.396304 | 5.729412 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/PremiumDemoLegacyPhoneView.swift | 1 | 2609 | //
// PremiumDemoLegacyPhoneView.swift
// Telegram
//
// Created by Mike Renoir on 14.06.2022.
// Copyright © 2022 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import TelegramCore
import AppKit
import SwiftSignalKit
//
final class PremiumDemoLegacyPhoneView : View {
private let phoneView = ImageView()
private let videoView = MediaPlayerView()
private var player: MediaPlayer?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
phoneView.image = NSImage(named: "Icon_Premium_Iphone")?.precomposed()
addSubview(videoView)
videoView.cornerRadius = 0
addSubview(phoneView)
phoneView.sizeToFit()
}
enum Position {
case top
case bottom
}
private var position: Position = .top
var status: Signal<MediaPlayerStatus, NoError>?
func setup(context: AccountContext, video: TelegramMediaFile?, position: Position) {
self.position = position
if let video = video {
let mediaPlayer = MediaPlayer(postbox: context.account.postbox, reference: .standalone(resource: video.resource), streamable: true, video: true, preferSoftwareDecoding: false, enableSound: false, fetchAutomatically: true)
mediaPlayer.attachPlayerView(self.videoView)
self.player = mediaPlayer
mediaPlayer.play()
mediaPlayer.actionAtEnd = .loop(nil)
self.status = mediaPlayer.status
}
needsLayout = true
}
override func layout() {
super.layout()
let vsize = NSMakeSize(1170, 1754)
let videoSize = vsize.aspectFitted(NSMakeSize(phoneView.frame.width - 22, phoneView.frame.height - 22))
switch position {
case .top:
self.phoneView.centerX(y: 20)
self.videoView.frame = NSMakeRect(phoneView.frame.minX + 11, phoneView.frame.minY + 11, videoSize.width, videoSize.height)
self.videoView.positionFlags = [.top, .left, .right]
case .bottom:
self.phoneView.centerX(y: frame.height - phoneView.frame.height - 20)
self.videoView.frame = NSMakeRect(phoneView.frame.minX + 11, phoneView.frame.maxY - videoSize.height - 11, videoSize.width, videoSize.height)
self.videoView.positionFlags = [.bottom, .left, .right]
}
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| gpl-2.0 | eec29cd64775f525b2deef03007a22e6 | 30.804878 | 233 | 0.623466 | 4.624113 | false | false | false | false |
huangboju/Moots | UICollectionViewLayout/Blueprints-master/Tests/macOS/Helper.swift | 1 | 4610 | import Blueprints
import Cocoa
class MockDelegate: NSObject, NSCollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: NSCollectionView, layout collectionViewLayout: NSCollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> NSSize {
let height = indexPath.item % 2 == 1 ? 200 : 275
return CGSize(width: 200, height: height)
}
}
class Helper {
static func createHorizontalLayout(dataSource: NSCollectionViewDataSource, withItemsPerRow: CGFloat = 0.0) -> (collectionView: CollectionView, layout: HorizontalBlueprintLayout) {
let frame = CGRect(origin: .zero, size: CGSize(width: 200, height: 200))
let scrollView = NSScrollView()
let window = NSWindow()
scrollView.frame = frame
window.setFrame(frame, display: true)
let layout: HorizontalBlueprintLayout
if withItemsPerRow > 0.0 {
layout = HorizontalBlueprintLayout(
itemsPerRow: withItemsPerRow,
minimumInteritemSpacing: 10,
minimumLineSpacing: 10,
sectionInset: EdgeInsets(top: 10, left: 50, bottom: 10, right: 50))
} else {
layout = HorizontalBlueprintLayout(
minimumInteritemSpacing: 10,
minimumLineSpacing: 10,
sectionInset: EdgeInsets(top: 10, left: 50, bottom: 10, right: 50))
}
layout.itemSize = CGSize(width: 50, height: 50)
layout.estimatedItemSize = CGSize(width: 50, height: 50)
let collectionView = CollectionView(frame: frame, collectionViewLayout: layout)
collectionView.register(MockCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier.init(rawValue: "cell"))
collectionView.dataSource = dataSource
scrollView.documentView = collectionView
window.contentView = scrollView
return (collectionView: collectionView, layout: layout)
}
static func createVerticalLayout(dataSource: NSCollectionViewDataSource, withItemsPerRow: CGFloat = 0.0) -> (collectionView: CollectionView, layout: VerticalBlueprintLayout) {
let frame = CGRect(origin: .zero, size: CGSize(width: 200, height: 200))
let scrollView = NSScrollView()
let window = NSWindow()
window.setFrame(frame, display: true)
scrollView.frame = frame
let layout: VerticalBlueprintLayout
if withItemsPerRow > 0.0 {
layout = VerticalBlueprintLayout(
itemsPerRow: withItemsPerRow,
minimumInteritemSpacing: 10,
minimumLineSpacing: 10,
sectionInset: EdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
} else {
layout = VerticalBlueprintLayout(
minimumInteritemSpacing: 10,
minimumLineSpacing: 10,
sectionInset: EdgeInsets(top: 10, left: 10, bottom: 10, right: 10))
}
layout.itemSize = CGSize(width: 50, height: 50)
layout.estimatedItemSize = CGSize(width: 50, height: 50)
let collectionView = CollectionView(frame: frame, collectionViewLayout: layout)
collectionView.register(MockCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier.init(rawValue: "cell"))
collectionView.dataSource = dataSource
scrollView.documentView = collectionView
window.contentView = scrollView
return (collectionView: collectionView, layout: layout)
}
static func createVerticalMosaicLayout(dataSource: NSCollectionViewDataSource) -> (collectionView: CollectionView, layout: VerticalMosaicBlueprintLayout) {
let frame = CGRect(origin: .zero, size: CGSize(width: 200, height: 200))
let scrollView = NSScrollView()
let window = NSWindow()
window.setFrame(frame, display: true)
scrollView.frame = frame
let patterns = [
MosaicPattern(alignment: .left, direction: .vertical, amount: 2, multiplier: 0.5),
MosaicPattern(alignment: .left, direction: .horizontal, amount: 2, multiplier: 0.5),
MosaicPattern(alignment: .right, direction: .vertical, amount: 2, multiplier: 0.5)
]
let layout = VerticalMosaicBlueprintLayout(
minimumInteritemSpacing: 2,
minimumLineSpacing: 2,
sectionInset: EdgeInsets(top: 2, left: 2, bottom: 2, right: 2),
patterns: patterns)
layout.itemSize = CGSize(width: 50, height: 50)
layout.estimatedItemSize = CGSize(width: 50, height: 50)
let collectionView = CollectionView(frame: frame, collectionViewLayout: layout)
collectionView.register(MockCollectionViewItem.self, forItemWithIdentifier: NSUserInterfaceItemIdentifier.init(rawValue: "cell"))
collectionView.dataSource = dataSource
scrollView.documentView = collectionView
window.contentView = scrollView
return (collectionView: collectionView, layout: layout)
}
}
| mit | 0b127c120641dacf96e3fcade9e96767 | 42.490566 | 181 | 0.72885 | 4.832285 | false | false | false | false |
huangboju/QMUI.swift | QMUI.swift/QMUIKit/UIComponents/QMUIPopupMenuView.swift | 1 | 7650 | //
// QMUIPopupMenuView.swift
// QMUI.swift
//
// Created by 黄伯驹 on 2017/7/10.
// Copyright © 2017年 伯驹 黄. All rights reserved.
//
/**
* 用于弹出浮层里显示一行一行的菜单的控件。
* 使用方式:
* 1. 调用 init 方法初始化。
* 2. 按需设置分隔线、item 高度等样式。
* 3. 设置完样式后再通过 items 或 itemSections 添加菜单项。
* 4. 调用 layoutWithTargetView: 或 layoutWithTargetRectInScreenCoordinate: 来布局菜单(参考父类)。
* 5. 调用 showWithAnimated: 即可显示(参考父类)。
*/
class QMUIPopupMenuView: QMUIPopupContainerView {
var shouldShowItemSeparator: Bool = false
var shouldShowSectionSeparatorOnly: Bool = false
var separatorColor: UIColor = UIColorSeparator
var itemTitleFont: UIFont = UIFontMake(16)
var itemHighlightedBackgroundColor: UIColor = TableViewCellSelectedBackgroundColor
var padding: UIEdgeInsets = .zero
var itemHeight: CGFloat = 44
var imageMarginRight: CGFloat = 6
var separatorInset: UIEdgeInsets = .zero
var items: [QMUIPopupMenuItem] = [] {
didSet {
itemSections = [items]
}
}
var itemSections: [[QMUIPopupMenuItem]] = [] {
didSet {
configureItems()
}
}
private var scrollView: UIScrollView!
private var itemSeparatorLayers: [CALayer] = []
private func shouldShowSeparator(at row: Int, rowCount: Int, in section: Int, sectionCount: Int) -> Bool {
return (!shouldShowSectionSeparatorOnly && shouldShowItemSeparator && row < rowCount - 1) || (shouldShowSectionSeparatorOnly && row == rowCount - 1 && section < sectionCount - 1)
}
private func configureItems() {
var globalItemIndex = 0
// 移除所有 item
scrollView.qmui_removeAllSubviews()
let sectionCount = itemSections.count
for section in 0 ..< sectionCount {
let items = itemSections[section]
let rowCount = items.count
for row in 0 ..< rowCount {
let item = items[row]
item.button.titleLabel?.font = itemTitleFont
item.button.highlightedBackgroundColor = itemHighlightedBackgroundColor
item.button.imageEdgeInsets = UIEdgeInsets(top: 0, left: -imageMarginRight, bottom: 0, right: imageMarginRight)
item.button.contentEdgeInsets = UIEdgeInsets(top: 0, left: padding.left - item.button.imageEdgeInsets.left, bottom: 0, right: padding.right)
scrollView.addSubview(item.button)
// 配置分隔线,注意每一个 section 里的最后一行是不显示分隔线的
let shouldShowSeparatorAtRow = shouldShowSeparator(at: row, rowCount: rowCount, in: section, sectionCount: sectionCount)
if globalItemIndex < itemSeparatorLayers.count {
let separatorLayer = itemSeparatorLayers[globalItemIndex]
if shouldShowSeparatorAtRow {
separatorLayer.isHidden = false
separatorLayer.backgroundColor = separatorColor.cgColor
} else {
separatorLayer.isHidden = true
}
} else if shouldShowSeparatorAtRow {
let separatorLayer = CALayer()
separatorLayer.qmui_removeDefaultAnimations()
separatorLayer.backgroundColor = separatorColor.cgColor
scrollView.layer.addSublayer(separatorLayer)
itemSeparatorLayers.append(separatorLayer)
}
globalItemIndex += 1
}
}
}
override func didInitialized() {
super.didInitialized()
contentEdgeInsets = .zero
scrollView = UIScrollView()
scrollView.scrollsToTop = false
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
if #available(iOS 11, *) {
scrollView.contentInsetAdjustmentBehavior = .never
}
contentView.addSubview(scrollView)
updateAppearanceForPopupMenuView()
}
override func sizeThatFitsInContentView(_ size: CGSize) -> CGSize {
var result = size
var height = padding.verticalValue
for section in itemSections {
height += CGFloat(section.count) * itemHeight
}
result.height = min(height, size.height)
return result
}
override func layoutSubviews() {
super.layoutSubviews()
scrollView.frame = contentView.bounds
var minY = padding.top
let contentWidth = scrollView.bounds.width
var separatorIndex = 0
let sectionCount = itemSections.count
for section in 0 ..< sectionCount {
let items = itemSections[section]
let rowCount = items.count
for row in 0 ..< rowCount {
let button = items[row].button
button!.frame = CGRect(x: 0, y: minY, width: contentWidth, height: itemHeight)
minY = button!.frame.maxY
let shouldShowSeparatorAtRow = shouldShowSeparator(at: row, rowCount: rowCount, in: section, sectionCount: sectionCount)
if shouldShowSeparatorAtRow {
itemSeparatorLayers[separatorIndex].frame = CGRect(x: separatorInset.left,
y: minY - PixelOne + separatorInset.top - separatorInset.bottom,
width: contentWidth - separatorInset.horizontalValue,
height: PixelOne)
separatorIndex += 1
}
}
}
minY += padding.bottom
scrollView.contentSize = CGSize(width: contentWidth, height: minY)
}
}
extension QMUIPopupMenuView {
fileprivate func updateAppearanceForPopupMenuView() {
separatorColor = UIColorSeparator
itemTitleFont = UIFontMake(16)
itemHighlightedBackgroundColor = TableViewCellSelectedBackgroundColor
padding = UIEdgeInsets(top: cornerRadius / 2, left: 16, bottom: cornerRadius / 2, right: 16)
itemHeight = 44
imageMarginRight = 6
separatorInset = .zero
}
}
/**
* 配合 QMUIPopupMenuView 使用,用于表示一项菜单项。
* 支持显示图片和标题,以及点击事件的回调。
* 可在 QMUIPopupMenuView 里统一修改菜单项的样式,如果某个菜单项需要特殊调整,可获取到对应的 QMUIPopupMenuItem.button 并进行调整。
*/
class QMUIPopupMenuItem: NSObject {
var image: UIImage? {
didSet {
button.setImage(image, for: .normal)
}
}
var title: String? {
didSet {
button.setTitle(title, for: .normal)
}
}
var handler: (() -> Void)?
fileprivate(set) var button: QMUIButton!
init(image: UIImage?, title: String?, handler: (() -> Void)?) {
super.init()
self.image = image
self.title = title
self.handler = handler
button = QMUIButton(title: title, image: image)
button.contentHorizontalAlignment = .left
button.qmui_automaticallyAdjustTouchHighlightedInScrollView = true
button.addTarget(self, action: #selector(handleButtonEvent), for: .touchUpInside)
}
@objc
private func handleButtonEvent(_: QMUIButton) {
handler?()
}
}
| mit | b56533c496197c9e12a15d5266017f3d | 35.396985 | 186 | 0.608173 | 5.118728 | false | false | false | false |
qidafang/iOS_427studio | studio427/BlogListController.swift | 1 | 2076 | //
// BlogListController.swift
// studio427
//
// Created by 祁达方 on 15/10/20.
// Copyright © 2015年 祁达方. All rights reserved.
//
import UIKit
class BlogListController: UIViewController, UITableViewDataSource, UITableViewDelegate {
var rest:BlogListRest = BlogListRest();
var blogList:NSMutableArray = [];
@IBOutlet weak var theTableView: UITableView!
///初始化
override func viewDidLoad() {
rest.blogListController = self;
rest.getData();
}
///被rest回调
func reloadData(){
theTableView.dataSource = self;
theTableView.reloadData();
theTableView.delegate = self;
}
///决定表格显示几行的重要方法
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return blogList.count
}
///决定单元格内容的重要方法
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell! = tableView.dequeueReusableCellWithIdentifier("myCell")
if(cell == nil){
cell = UITableViewCell(style: .Default, reuseIdentifier: "myCell")
}
let index = blogList.count - 1 - indexPath.row;
cell.textLabel?.text = (blogList[index] as! NSMutableDictionary).valueForKey("title") as! String;
return cell
}
///点击单元格时触发
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let index = blogList.count - 1 - indexPath.row;
let id = (blogList[index] as! NSMutableDictionary).valueForKey("id") as! NSNumber;
NSLog("%d", id);
let sb:UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let blogDetail:BlogDetailController = sb.instantiateViewControllerWithIdentifier("blogDetail") as! BlogDetailController
blogDetail.id = id.stringValue;
showViewController(blogDetail, sender: nil);
}
}
| apache-2.0 | 7d2741d63ece23a7879f763081720997 | 29.045455 | 127 | 0.644478 | 4.755396 | false | false | false | false |
Karumi/BothamNetworking | BothamNetworkingTests/HTTPEncoderTests.swift | 1 | 1832 | //
// HTTPEncoderTests.swift
// BothamNetworking
//
// Created by Pedro Vicente Gomez on 29/12/15.
// Copyright © 2015 GoKarumi S.L. All rights reserved.
//
import Foundation
import XCTest
import Nimble
@testable import BothamNetworking
class HTTPEncoderTests: XCTestCase {
func testDoesNotEncodesBodyIfTheRequestDoesNotContainsContentTypeHeader() {
let request = givenAHTTPRequestWith(body: ["a": "b" as AnyObject])
let bodyNSData = HTTPEncoder.encodeBody(request)
expect(bodyNSData).to(beNil())
}
func testEncodesBodyUsingJsonEncodingIfTheRequestContainsJsonContentTypeHeader() {
let request = givenAHTTPRequestWith(
headers: ["Content-Type": "application/json"],
body: ["a": "b" as AnyObject]
)
let bodyNSData = HTTPEncoder.encodeBody(request)
let bodyString = String(data: bodyNSData!, encoding: String.Encoding.utf8)
expect(bodyString).to(equal("{\"a\":\"b\"}"))
}
func testEncodesParamsUsingFormEncodingIfTheRequestContainsFormContentTypeHeader() {
let request = givenAHTTPRequestWith(headers: ["Content-Type": "application/x-www-form-urlencoded"],
body: ["a": "b" as AnyObject, "c": 3 as AnyObject])
let bodyNSData = HTTPEncoder.encodeBody(request)
let bodyString = String(data: bodyNSData!, encoding: String.Encoding.utf8)
expect(bodyString).to(equal("a=b&c=3"))
}
private func givenAHTTPRequestWith(
headers: [String: String]? = nil,
parameters: [String: String]? = nil,
body: [String: AnyObject]? = nil) -> HTTPRequest {
return HTTPRequest(
url: "http://www.karumi.com",
parameters: parameters,
headers: headers,
httpMethod: .GET,
body: body)
}
}
| apache-2.0 | c062b977998778932538a5413c261c30 | 30.033898 | 107 | 0.652103 | 4.189931 | false | true | false | false |
andlabs/misctestprogs | ScratchMac.swift | 1 | 1294 | // 17 august 2015
import Cocoa
var keepAliveMainwin: NSWindow? = nil
func appLaunched() {
let mainwin = NSWindow(
contentRect: NSMakeRect(0, 0, 320, 240),
styleMask: (NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask),
backing: NSBackingStoreType.Buffered,
`defer`: true)
let contentView = mainwin.contentView!
mainwin.cascadeTopLeftFromPoint(NSMakePoint(20, 20))
mainwin.makeKeyAndOrderFront(mainwin)
keepAliveMainwin = mainwin
}
func addConstraint(view: NSView, _ constraint: String, _ views: [String: NSView]) {
let constraints = NSLayoutConstraint.constraintsWithVisualFormat(
constraint,
options: [],
metrics: nil,
views: views)
view.addConstraints(constraints)
}
class appDelegate : NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(note: NSNotification) {
appLaunched()
}
func applicationShouldTerminateAfterLastWindowClosed(app: NSApplication) -> Bool {
return true
}
}
func main() {
let app = NSApplication.sharedApplication()
app.setActivationPolicy(NSApplicationActivationPolicy.Regular)
// NSApplication.delegate is weak; if we don't use the temporary variable, the delegate will die before it's used
let delegate = appDelegate()
app.delegate = delegate
app.run()
}
main()
| mit | 1f105b547aeef125c2fffc0f58908271 | 26.531915 | 114 | 0.772798 | 3.969325 | false | false | false | false |
Ryan-Vanderhoef/Antlers | AppIdea/ViewControllers/FriendsViewController.swift | 1 | 8446 | //
// FriendsViewController.swift
// AppIdea
//
// Created by Ryan Vanderhoef on 7/23/15.
// Copyright (c) 2015 Ryan Vanderhoef. All rights reserved.
//
import UIKit
import Parse
class FriendsViewController: UIViewController {
@IBOutlet weak var friendsTableView: UITableView!
var users: [PFUser] = []//? // All users
// var followingUsers: [PFUser]? {
// didSet {
// friendsTableView.reloadData()
// }
// }
@IBOutlet weak var segmentedControl: UISegmentedControl!
@IBAction func segmentedControlAction(sender: AnyObject) {
viewDidAppear(true)
}
// @IBOutlet weak var segmentedControl: UISegmentedControl!
// @IBAction func segmentedControlAction(sender: AnyObject) {
//// println("seg pressed")
// viewDidAppear(true)
// }
override func viewDidLoad() {
super.viewDidLoad()
// self.friendsTableView.delegate = self
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
//let friendPostQuery = PFQuery(className: "FriendRelation")
// if segmentedControl.selectedSegmentIndex == 0 {
// // Only want my friends
// let friendPostQuery = PFQuery(className: "FriendRelation")
//// println("first: \(friendPostQuery)")
// friendPostQuery.whereKey("fromUser", equalTo: PFUser.currentUser()!)
//// println("second: \(friendPostQuery)")
// friendPostQuery.selectKeys(["toUser"])
//// println("thrid: \(friendPostQuery)")
// friendPostQuery.orderByAscending("fromUser")
//// println("fourth: \(friendPostQuery)")
// friendPostQuery.findObjectsInBackgroundWithBlock {(result: [AnyObject]?, error: NSError?) -> Void in
//// println("results: \(result)")
// self.users = result as? [PFUser] ?? []
//// println("in here")
//// println("\(self.users)")
// self.friendsTableView.reloadData()
// }
//
// }
// else if segmentedControl.selectedSegmentIndex == 1 {
// Want all users
// if segmentedControl.selectedSegmentIndex == 1{
let friendPostQuery = PFUser.query()!
friendPostQuery.whereKey("username", notEqualTo: PFUser.currentUser()!.username!) // exclude the current user
friendPostQuery.orderByAscending("username") // Order first by username, alphabetically
friendPostQuery.addAscendingOrder("ObjectId") // Then order by ObjectId, alphabetically
friendPostQuery.findObjectsInBackgroundWithBlock {(result: [AnyObject]?, error: NSError?) -> Void in
// println("qwerty: \(result)")
self.users = result as? [PFUser] ?? []
self.friendsTableView.reloadData()
println("\(self.users)")
}
// }
// else if segmentedControl.selectedSegmentIndex == 0 {
// println("my herd")
// let friendsPostQuery = PFQuery(className: "FriendRelation")
// friendsPostQuery.whereKey("fromUser", equalTo: PFUser.currentUser()!)
// friendsPostQuery.selectKeys(["toUser"])
// friendsPostQuery.findObjectsInBackgroundWithBlock {(result: [AnyObject]?, error: NSError?) -> Void in
// // println("qwerty: \(result)")
// var holding = result// as? [NSObject]
// println("holding : \(holding)")
//// var thing = holding![0]
//// println("thing : \(thing)")
//
// self.users = result as? [PFUser] ?? []
// self.friendsTableView.reloadData()
// println("\(self.users)")
// }
// }
// }
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
println("preparing for segue")
println("segue is \(segue.identifier)")
if segue.identifier == "segueToSelectedFawn" {
let friendViewController = segue.destinationViewController as! SelectedFriendViewController
let indexPath = friendsTableView.indexPathForSelectedRow()
self.friendsTableView.deselectRowAtIndexPath(indexPath!, animated: false)
let selectedFriend = users[indexPath!.row]
friendViewController.friend = selectedFriend
}
}
}
extension FriendsViewController: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.users/*?*/.count ?? 0
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("FriendCell") as! FriendsTableViewCell
// cell.titleLabel!.text = "\(moviePosts[indexPath.row].Title)"
// cell.yearLabel!.text = "\(moviePosts[indexPath.row].Year)"
// cell.statusLabel!.text = "\(moviePosts[indexPath.row].Status)"
cell.friendsLabel!.text = "\(self.users/*!*/[indexPath.row].username!)"
//cell.friendsLabel!.text = "hello"
// let query = PFQuery(className: "FriendRelation")
// let test = PFQuery(className: "user")
// println("good1")
// var name = test.getObjectInBackgroundWithId(users![indexPath.row].objectId!) as! PFObject
// println("good2")
// query.whereKey("toUser", equalTo: name)
// println("good3")
// query.whereKey("fromUser", equalTo: PFUser.currentUser()!)
// println("good4")
// query.findObjectsInBackgroundWithBlock {(result: [AnyObject]?, error: NSError?) -> Void in
//// println("qwerty: \(result)")
//// self.users = result as? [PFUser] ?? []
//// self.friendsTableView.reloadData()
// println("toUser: \(self.users![indexPath.row].username!)")
// println(result)
//
// }
// if segmentedControl.selectedSegmentIndex == 0 {
// // Color To Watch movies as gray
// if moviePosts[indexPath.row].Status == "To Watch" {
// cell.backgroundColor = UIColor(red: 128/255, green: 128/255, blue: 128/255, alpha: 0.06)
// }
// // Color Have Watched movies as white
// else if moviePosts[indexPath.row].Status == "Have Watched" {
// cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.16)
// }
// }
// else {
// // Color all movies white
// cell.backgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.16)
// }
//
// if moviePosts[indexPath.row].Status == "Have Watched" {
// // If a movie has been watched, show rating
// var rate = moviePosts[indexPath.row].Rating
// if rate == 1 {cell.ratingLabel!.text = "Rating: ★☆☆☆☆"}
// else if rate == 2 {cell.ratingLabel!.text = "Rating: ★★☆☆☆"}
// else if rate == 3 {cell.ratingLabel!.text = "Rating: ★★★☆☆"}
// else if rate == 4 {cell.ratingLabel!.text = "Rating: ★★★★☆"}
// else if rate == 5 {cell.ratingLabel!.text = "Rating: ★★★★★"}
// else {cell.ratingLabel!.text = ""}
//
// }
// else {
// // If a movie has not been watched, don't show a rating
// cell.ratingLabel!.text = ""
// }
return cell
}
@IBAction func unwindToSegueFriends(segue: UIStoryboardSegue) {
if let identifier = segue.identifier {
println("indentifier is \(identifier)")
}
}
}
| mit | 2416dbb733fb55d16dbdad3e5a68d987 | 39.365385 | 123 | 0.571701 | 4.550678 | false | false | false | false |
starhoshi/pi-chan | pi-chan/ViewControllers/Settings/Cell/SettingTableViewCell.swift | 1 | 1241 | //
// SettingTableViewCell.swift
// pi-chan
//
// Created by Kensuke Hoshikawa on 2016/04/17.
// Copyright © 2016年 star__hoshi. All rights reserved.
//
import UIKit
import Font_Awesome_Swift
class SettingTableViewCell: UITableViewCell {
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var icon: UIImageView!
var settingViewController: SettingsViewController?
var cellContent:CellContent!
override func awakeFromNib() {
super.awakeFromNib()
}
// FIXME: if else の書き方修正
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
if selected {
if cellContent.title == "Share" {
settingViewController?.showShareActivityView()
} else if cellContent.title == "Libraries" {
settingViewController?.goSettingsToAcknowledgements()
}else{
cellContent.tapped()
}
}
}
func setItems(cellContent:CellContent){
self.cellContent = cellContent
titleLabel.text = cellContent.title
icon.setFAIconWithName(cellContent.icon, textColor: UIColor.esaGreen())
self.accessoryType = cellContent.cellType
self.selectionStyle = cellContent.cellType == .None ? .None : .Default
}
}
| mit | 8ba52ae7a8d49e2002e0c689781b120f | 26.863636 | 75 | 0.71044 | 4.394265 | false | false | false | false |
Paladinfeng/leetcode | leetcode/Add Binary/main.swift | 1 | 1629 | //
// main.swift
// Add Binary
//
// Created by xuezhaofeng on 01/11/2017.
// Copyright © 2017 paladinfeng. All rights reserved.
//
import Foundation
class Solution {
func addBinary(_ a: String, _ b: String) -> String {
let arrayA = a.characters.flatMap({Int(String($0))})
var countA = arrayA.count - 1;
let arrayB = b.characters.flatMap({Int(String($0))})
var countB = arrayB.count - 1;
var result = ""
var carryValue = 0
var temp = 0
while countA >= 0 || countB >= 0 || carryValue > 0 {
// if countA == 0 {
// resultArray.append(arrayA[0])
// break
// }
//
// if countB == 0 {
// resultArray.append(arrayB[0])
// break
// }
//
// temp = arrayA[countA] + arrayB[countB] + carryValue
//
// if temp == 2 {
// temp = 0
// carryValue = 1
// }
//
// resultArray.append(temp)
//
// countA -= 1
// countB -= 1
temp = carryValue;
if countA >= 0 {
temp += arrayA[countA]
countA -= 1
}
if countB >= 0 {
temp += arrayB[countB]
countB -= 1
}
carryValue = temp / 2
temp = temp % 2
result = String(temp) + result
}
return result
}
}
let result = Solution().addBinary("11", "1");
print(result)
| mit | 6d325039586f6df93c1b92bcd740a357 | 22.594203 | 65 | 0.415233 | 4 | false | false | false | false |
1457792186/JWSwift | 熊猫TV2/XMTV/Classes/Main/Controller/BaseEntertainmentVC.swift | 2 | 3019 | //
// BaseEntertainmentVC.swift
// XMTV
//
// Created by Mac on 2017/1/11.
// Copyright © 2017年 Mac. All rights reserved.
//
import UIKit
class BaseEntertainmentVC: BaseVC {
var baseVM: BaseVM!
lazy var collectionView : UICollectionView = {[unowned self] in
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.sectionInset = UIEdgeInsets(top: kItemMargin, left: kItemMargin, bottom: 0, right: kItemMargin)
let collectionView = UICollectionView(frame: self.view.bounds, collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
collectionView.register(UINib(nibName: "CollectionNormalCell", bundle: nil), forCellWithReuseIdentifier: NormalCellID)
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
// MARK: -
extension BaseEntertainmentVC {
override func setupUI() {
contentView = collectionView
view.addSubview(collectionView)
super.setupUI()
}
}
// MARK: - loadData
extension BaseEntertainmentVC {
func loadData() {}
}
// MARK: - UICollectionView代理数据源方法
extension BaseEntertainmentVC : UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
if baseVM.anchorGroups.count > 0 {
return baseVM.anchorGroups[section].anchors.count
} else {
return 0
}
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NormalCellID, for: indexPath) as! CollectionNormalCell
cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
}
extension BaseEntertainmentVC : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
// anchor.isVertical == 0 ? pushNormalRoomVc(anchor) : presentShowRoomVc(anchor)
}
// private func presentShowRoomVc(_ anchor : AnchorModel) {
// let showVc = ShowRoomVC()
// showVc.anchor = anchor
// present(showVc, animated: true, completion: nil)
// }
//
// private func pushNormalRoomVc(_ anchor : AnchorModel) {
// let normalVc = NormalRoomVC()
// normalVc.anchor = anchor
// navigationController?.pushViewController(normalVc, animated: true)
// }
}
| apache-2.0 | 20bcc854148a7c6258cf1ab3dfa2b66e | 31.630435 | 129 | 0.680879 | 5.11414 | false | false | false | false |
lerigos/music-service | iOS_9/Pods/PhoneNumberKit/PhoneNumberKit/ParseManager.swift | 3 | 6157 | //
// ParseManager.swift
// PhoneNumberKit
//
// Created by Roy Marmelstein on 01/11/2015.
// Copyright © 2015 Roy Marmelstein. All rights reserved.
//
import Foundation
/**
Manager for parsing flow.
*/
class ParseManager {
let metadata = Metadata.sharedInstance
let parser = PhoneNumberParser()
let regex = RegularExpressions.sharedInstance
private var multiParseArray = SynchronizedArray<PhoneNumber>()
/**
Parse a string into a phone number object with a custom region. Can throw.
- Parameter rawNumber: String to be parsed to phone number struct.
- Parameter region: ISO 639 compliant region code.
*/
func parsePhoneNumber(rawNumber: String, region: String) throws -> PhoneNumber {
// Make sure region is in uppercase so that it matches metadata (1)
let region = region.uppercaseString
// Extract number (2)
var nationalNumber = rawNumber
let matches = try self.regex.phoneDataDetectorMatches(rawNumber)
if let phoneNumber = matches.first?.phoneNumber {
nationalNumber = phoneNumber
}
// Strip and extract extension (3)
let numberExtension = self.parser.stripExtension(&nationalNumber)
// Country code parse (4)
guard var regionMetadata = self.metadata.metadataPerCountry[region] else {
throw PhoneNumberError.InvalidCountryCode
}
var countryCode: UInt64 = 0
do {
countryCode = try self.parser.extractCountryCode(nationalNumber, nationalNumber: &nationalNumber, metadata: regionMetadata)
}
catch {
do {
let plusRemovedNumberString = self.regex.replaceStringByRegex(PhoneNumberPatterns.leadingPlusCharsPattern, string: nationalNumber as String)
countryCode = try self.parser.extractCountryCode(plusRemovedNumberString, nationalNumber: &nationalNumber, metadata: regionMetadata)
}
catch {
throw PhoneNumberError.InvalidCountryCode
}
}
if countryCode == 0 {
countryCode = regionMetadata.countryCode
}
// Nomralized number (5)
let normalizedNationalNumber = self.parser.normalizePhoneNumber(nationalNumber)
nationalNumber = normalizedNationalNumber
// If country code is not default, grab correct metadata (6)
if countryCode != regionMetadata.countryCode, let countryMetadata = self.metadata.metadataPerCode[countryCode] {
regionMetadata = countryMetadata
}
// National Prefix Strip (7)
self.parser.stripNationalPrefix(&nationalNumber, metadata: regionMetadata)
// Test number against general number description for correct metadata (8)
if let generalNumberDesc = regionMetadata.generalDesc where (self.regex.hasValue(generalNumberDesc.nationalNumberPattern) == false || self.parser.isNumberMatchingDesc(nationalNumber, numberDesc: generalNumberDesc) == false) {
throw PhoneNumberError.NotANumber
}
// Finalize remaining parameters and create phone number object (9)
let leadingZero = nationalNumber.hasPrefix("0")
guard let finalNationalNumber = UInt64(nationalNumber) else{
throw PhoneNumberError.NotANumber
}
let phoneNumber = PhoneNumber(countryCode: countryCode, leadingZero: leadingZero, nationalNumber: finalNationalNumber, numberExtension: numberExtension, rawNumber: rawNumber)
return phoneNumber
}
// Parse task
/**
Fastest way to parse an array of phone numbers. Uses custom region code.
- Parameter rawNumbers: An array of raw number strings.
- Parameter region: ISO 639 compliant region code.
- Returns: An array of valid PhoneNumber objects.
*/
func parseMultiple(rawNumbers: [String], region: String, testCallback: (()->())? = nil) -> [PhoneNumber] {
let rawNumbersCopy = rawNumbers
self.multiParseArray = SynchronizedArray<PhoneNumber>()
let queue = NSOperationQueue()
var operationArray: [ParseOperation<PhoneNumber>] = []
let completionOperation = ParseOperation<Bool>()
completionOperation.onStart { asyncOp in
asyncOp.finish(with: true)
}
completionOperation.whenFinished { asyncOp in
}
for (index, rawNumber) in rawNumbersCopy.enumerate() {
let parseTask = parseOperation(rawNumber, region:region)
parseTask.whenFinished { operation in
if let phoneNumber = operation.output.value {
self.multiParseArray.append(phoneNumber)
}
}
operationArray.append(parseTask)
completionOperation.addDependency(parseTask)
if index == rawNumbers.count/2 {
testCallback?()
}
}
queue.addOperations(operationArray, waitUntilFinished: false)
queue.addOperations([completionOperation], waitUntilFinished: true)
let localMultiParseArray = self.multiParseArray
return localMultiParseArray.array
}
/**
Single parsing task, used as an element of parseMultiple.
- Parameter rawNumbers: An array of raw number strings.
- Parameter region: ISO 639 compliant region code.
- Returns: Parse operation with an implementation handler and no completion handler.
*/
func parseOperation(rawNumber: String, region: String) -> ParseOperation<PhoneNumber> {
let operation = ParseOperation<PhoneNumber>()
operation.onStart { asyncOp in
let phoneNumber = try self.parsePhoneNumber(rawNumber, region: region)
asyncOp.finish(with: phoneNumber)
}
return operation
}
}
/**
Thread safe Swift array generic that locks on write.
*/
class SynchronizedArray<T> {
var array: [T] = []
private let accessQueue = dispatch_queue_create("SynchronizedArrayAccess", DISPATCH_QUEUE_SERIAL)
func append(newElement: T) {
dispatch_async(self.accessQueue) {
self.array.append(newElement)
}
}
}
| apache-2.0 | c030da7cfa5f621e9950f4349091ed58 | 41.75 | 233 | 0.669753 | 5.168766 | false | false | false | false |
zeroleaf/LeetCode | LeetCode/LeetCodeTests/7_ReverseIntegerSpec.swift | 1 | 2185 | //
// ReverseIntegerSpec.swift
// LeetCode
//
// Created by zeroleaf on 16/1/24.
// Copyright © 2016年 zeroleaf. All rights reserved.
//
import XCTest
import Quick
import Nimble
class ReverseInteger {
func reverse(x: Int) -> Int {
var result = 0
var val = x
while val != 0 {
let tail = val % 10
let newResult = result &* 10 &+ tail
if (newResult - tail) / 10 != result {
return 0
}
result = newResult
val /= 10
}
return result
}
}
class ReverseIntegerSpec: QuickSpec {
override func spec() {
describe("Reverse Integer") {
var s: ReverseInteger!
beforeEach {
s = ReverseInteger()
}
it("Zero") {
expect(s.reverse(0)).to(equal(0))
}
it("One") {
expect(s.reverse(1)).to(equal(1))
}
it("Positive Value") {
expect(s.reverse(123)).to(equal(321))
}
it("Positive value 2") {
expect(s.reverse(1534236469)).to(equal(9646324351))
}
it("Positive With Zero ending") {
expect(s.reverse(10100)).to(equal(101))
}
it("Positive Max") {
expect(s.reverse(Int.max)).to(equal(7085774586302733229))
}
it("Positive overflow") {
expect(s.reverse(7085774586302733299)).to(equal(0))
}
it("Negetive Value") {
expect(s.reverse(-123)).to(equal(-321))
}
it("Negetive with zero ending") {
expect(s.reverse(-10100)).to(equal(-101))
}
it("Negetive Min") {
expect(s.reverse(Int.min)).to(equal(-8085774586302733229))
}
it("Expect value is Min max") {
expect(s.reverse(-8085774586302733229)).to(equal(Int.min))
}
it("Negetive overflow") {
expect(s.reverse(-8085774586302733299)).to(equal(0))
}
}
}
}
| mit | d8a579cc2b7a8cce307881288c0572f8 | 21.494845 | 74 | 0.462878 | 4.063315 | false | false | false | false |
mas-cli/mas | Sources/MasKit/ExternalCommands/OpenSystemCommand.swift | 1 | 497 | //
// OpenSystemCommand.swift
// MasKit
//
// Created by Ben Chatelain on 1/2/19.
// Copyright © 2019 mas-cli. All rights reserved.
//
import Foundation
/// Wrapper for the external open system command.
/// https://ss64.com/osx/open.html
struct OpenSystemCommand: ExternalCommand {
var binaryPath: String
let process = Process()
let stdoutPipe = Pipe()
let stderrPipe = Pipe()
init(binaryPath: String = "/usr/bin/open") {
self.binaryPath = binaryPath
}
}
| mit | 5f9faa57d4af9ecc0527a19fabb3484d | 19.666667 | 50 | 0.665323 | 3.674074 | false | false | false | false |
adapter00/ADTouchTracker | ADTouchTracker/Classes/TouchView.swift | 1 | 1436 | //
// TouchView.swift
// Pods
//
// Created by adapter00 on 2016/11/06.
//
//
import Foundation
import UIKit
/// Touch View Builder, Hold and Remove view instance
internal class TouchViewBuilder {
static let sharedInstance = TouchViewBuilder()
fileprivate let viewSize = CGSize(width: 40, height: 40)
fileprivate var viewHolder = [TapFingerView]()
fileprivate init() { }
func buildByPoint(_ points:[CGPoint]) -> [TapFingerView] {
self.viewHolder.forEach{ $0.removeFromSuperview()}
self.viewHolder = p.flatMap{
let view = TapFingerView(frame: CGRect(origin: $0, size: viewSize))
view.center = $0
return view
}
return self.viewHolder
}
func resetTouchView() {
self.viewHolder.forEach{ $0.removeFromSuperview()}
}
}
protocol TapConfig {
var viewBackGroundColor: UIColor? { get }
}
/// Touch View
internal class TapFingerView:UIView,TapConfig {
var viewBackGroundColor: UIColor? {
return UIColor(colorLiteralRed: 0, green: 0, blue: 0, alpha: 0.5)
}
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = viewBackGroundColor
self.layer.masksToBounds = true
self.layer.cornerRadius = min(self.frame.width, self.frame.height) / 2
}
required init?(coder aDecoder: NSCoder) {
fatalError("you need not called")
}
}
| mit | 67e0f2ae9a3f17deb1be5bea5919bdca | 25.592593 | 79 | 0.64415 | 4.079545 | false | false | false | false |
WLChopSticks/weiboCopy | weiboCopy/weiboCopy/Classes/Module/Discovery/CHSDiscoveryController.swift | 2 | 3073 | //
// CHSDiscoveryController.swift
// weiboCopy
//
// Created by 王 on 15/12/12.
// Copyright © 2015年 王. All rights reserved.
//
import UIKit
class CHSDiscoveryController: CHSBaseViewController {
override func viewDidLoad() {
super.viewDidLoad()
guestView?.setUpThePages("登录后,最新、最热微博尽在掌握,不再会与实事潮流擦肩而过", imageNmae: "visitordiscover_image_message")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | f544b685c6dc6871c773accd6511111b | 31.717391 | 157 | 0.681063 | 5.243902 | false | false | false | false |
kirthika/AuthenticationLibrary | Carthage/Checkouts/KeychainAccess/Examples/Playground-iOS.playground/section-1.swift | 1 | 3238 | import UIKit
import XCPlayground
import KeychainAccess
var keychain: Keychain
/***************
* Instantiation
***************/
/* for Application Password */
keychain = Keychain(service: "com.example.github-token")
/* for Internet Password */
let url = URL(string: "https://github.com")!
keychain = Keychain(server: url, protocolType: .https)
/**************
* Adding items
**************/
/* subscripting */
keychain["kishikawakatsumi"] = "01234567-89ab-cdef-0123-456789abcdef"
/* set method */
try? keychain.set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi")
/*****************
* Obtaining items
*****************/
var token: String?
/* subscripting (automatically convert to String) */
token = keychain["kishikawakatsumi"]
/* get method */
// as String
token = try! keychain.get("kishikawakatsumi")
token = try! keychain.getString("kishikawakatsumi")
// as Data
let data = try! keychain.getData("kishikawakatsumi")
/****************
* Removing items
****************/
/* subscripting */
keychain["kishikawakatsumi"] = nil
/* remove method */
try? keychain.remove("kishikawakatsumi")
/****************
* Error handling
****************/
/* set */
do {
try keychain.set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi")
} catch let error {
print("error: \(error.localizedDescription)")
}
/* get */
// First, get the failable (value or error) object
do {
let token = try keychain.get("kishikawakatsumi")
} catch let error {
print("error: \(error.localizedDescription)")
}
/* remove */
do {
try keychain.remove("kishikawakatsumi")
} catch let error {
print("error: \(error.localizedDescription)")
}
/*******************
* Label and Comment
*******************/
keychain = Keychain(server: URL(string: "https://github.com")!, protocolType: .https)
.label("github.com (kishikawakatsumi)")
.comment("github access token")
/***************
* Configuration
***************/
/* for background application */
let background = Keychain(service: "com.example.github-token")
.accessibility(.afterFirstUnlock)
/* for forground application */
let forground = Keychain(service: "com.example.github-token")
.accessibility(.whenUnlocked)
/* Sharing Keychain Items */
let shared = Keychain(service: "com.example.github-token", accessGroup: "12ABCD3E4F.shared")
/* Synchronizing Keychain items with iCloud */
let iCloud = Keychain(service: "com.example.github-token")
.synchronizable(true)
/* One-Shot configuration change */
try? keychain
.accessibility(.afterFirstUnlock)
.synchronizable(true)
.set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi")
try? keychain
.accessibility(.whenUnlocked)
.set("01234567-89ab-cdef-0123-456789abcdef", key: "kishikawakatsumi")
/***********
* Debugging
***********/
/* Display all stored items if print keychain object */
keychain = Keychain(server: URL(string: "https://github.com")!, protocolType: .https)
print("\(keychain)")
/* Obtaining all stored keys */
let keys = keychain.allKeys()
for key in keys {
print("key: \(key)")
}
/* Obtaining all stored items */
let items = keychain.allItems()
for item in items {
print("item: \(item)")
}
| mit | 9eb3f2c0d1ae22549d6e3f24a923d590 | 21.486111 | 92 | 0.648548 | 3.953602 | false | false | false | false |
Limon-O-O/Lego | Frameworks/LegoAPI/LegoAPI/LegoAPI.swift | 1 | 972 | //
// LegoAPI.swift
// LegoAPI
//
// Created by Limon on 16/03/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Moya
import MoyaSugar
protocol LegoAPI: SugarTargetType {}
extension LegoAPI {
public var baseURL: URL {
return URL(string: "https://\(ServiceConfigure.apiHost)/v1")!
}
public var parameterEncoding: Moya.ParameterEncoding {
if self.method == .get || self.method == .head {
return URLEncoding.default
}
else {
return JSONEncoding.default
}
}
public var headers: [String: String]? {
var assigned: [String: String] = [
"User-Agent": ServiceConfigure.userAgent,
"Accept-Language": ServiceConfigure.language
]
if let token = ServiceConfigure.accessToken {
assigned["Lego-TOKEN"] = token
}
return assigned
}
public var task: Task {
return .request
}
}
| mit | abd08dff5880be7896fede4428faf6a9 | 20.108696 | 69 | 0.589083 | 4.35426 | false | true | false | false |
apple/swift | stdlib/private/StdlibUnittest/SymbolLookup.swift | 1 | 1750 | //===--- SymbolLookup.swift -----------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2019 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(WASI)
import WASILibc
#elseif os(Windows)
import CRT
import WinSDK
#else
#error("Unsupported platform")
#endif
#if canImport(Darwin) || os(OpenBSD) || os(FreeBSD)
let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: -2)
#elseif os(Linux) || os(WASI)
let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: 0)
#elseif os(Android)
#if arch(arm) || arch(i386)
let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: 0xffffffff as UInt)
#elseif arch(arm64) || arch(x86_64)
let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: 0)
#else
#error("Unsupported platform")
#endif
#elseif os(Windows)
let hStdlibCore: HMODULE = GetModuleHandleA("swiftCore.dll")!
#elseif os(WASI)
// WASI doesn't support dynamic linking yet.
#else
#error("Unsupported platform")
#endif
public func pointerToSwiftCoreSymbol(name: String) -> UnsafeMutableRawPointer? {
#if os(Windows)
return unsafeBitCast(GetProcAddress(hStdlibCore, name),
to: UnsafeMutableRawPointer?.self)
#elseif os(WASI)
fatalError("\(#function) is not supported on WebAssembly/WASI")
#else
return dlsym(RTLD_DEFAULT, name)
#endif
}
| apache-2.0 | 43b1d8f121f122d80af6c68d56d57d5e | 30.818182 | 80 | 0.675429 | 4.117647 | false | false | false | false |
lorentey/swift | test/SILOptimizer/access_marker_mandatory.swift | 16 | 3686 | // RUN: %target-swift-frontend -module-name access_marker_mandatory -parse-as-library -Xllvm -sil-full-demangle -emit-sil -Onone -enforce-exclusivity=checked %s | %FileCheck %s
public struct S {
var i: Int
var o: AnyObject
}
// CHECK-LABEL: sil [noinline] @$s23access_marker_mandatory5initSyAA1SVSi_yXltF : $@convention(thin) (Int, @guaranteed AnyObject) -> @owned S {
// CHECK: bb0(%0 : $Int, %1 : $AnyObject):
// CHECK: [[STK:%.*]] = alloc_stack $S, var, name "s"
// CHECK: cond_br %{{.*}}, bb1, bb2
// CHECK: bb1:
// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[STK]] : $*S
// CHECK: store %{{.*}} to [[WRITE]] : $*S
// CHECK: end_access [[WRITE]]
// CHECK: bb2:
// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[STK]] : $*S
// CHECK: store %{{.*}} to [[WRITE]] : $*S
// CHECK: end_access [[WRITE]]
// CHECK: bb3:
// CHECK: [[READ:%.*]] = begin_access [read] [static] [[STK]] : $*S
// CHECK: [[RET:%.*]] = load [[READ]] : $*S
// CHECK: end_access [[READ]]
// CHECK: destroy_addr [[STK]]
// CHECK: dealloc_stack [[STK]]
// CHECK: return [[RET]] : $S
// CHECK-LABEL: } // end sil function '$s23access_marker_mandatory5initSyAA1SVSi_yXltF'
@inline(never)
public func initS(_ x: Int, _ o: AnyObject) -> S {
var s: S
if x == 0 {
s = S(i: 1, o: o)
} else {
s = S(i: x, o: o)
}
return s
}
@inline(never)
func takeS(_ s: S) {}
// CHECK-LABEL: sil @$s23access_marker_mandatory14modifyAndReadS1oyyXl_tF : $@convention(thin) (@guaranteed AnyObject) -> () {
// CHECK: bb0(%0 : $AnyObject):
// CHECK: [[STK:%.*]] = alloc_stack $S, var, name "s"
// CHECK: [[FINIT:%.*]] = function_ref @$s23access_marker_mandatory5initSyAA1SVSi_yXltF : $@convention(thin) (Int, @guaranteed AnyObject) -> @owned S
// CHECK: [[INITS:%.*]] = apply [[FINIT]](%{{.*}}, %0) : $@convention(thin) (Int, @guaranteed AnyObject) -> @owned S
// CHECK: store [[INITS]] to [[STK]] : $*S
// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[STK]] : $*S
// CHECK: [[ADDRI:%.*]] = struct_element_addr [[WRITE]] : $*S, #S.i
// CHECK: store %{{.*}} to [[ADDRI]] : $*Int
// CHECK: end_access [[WRITE]]
// CHECK: [[FTAKE:%.*]] = function_ref @$s23access_marker_mandatory5takeSyyAA1SVF : $@convention(thin) (@guaranteed S) -> ()
// CHECK: apply [[FTAKE]](%{{.*}}) : $@convention(thin) (@guaranteed S) -> ()
// CHECK-LABEL: } // end sil function '$s23access_marker_mandatory14modifyAndReadS1oyyXl_tF'
public func modifyAndReadS(o: AnyObject) {
var s = initS(3, o)
s.i = 42
takeS(s)
}
// Test capture promotion followed by stack promotion.
// Access enforcement selection must run after capture promotion
// so that we never stack promote something with dynamic access.
// Otherwise, we may try to convert the access to [deinit] which
// doesn't make sense dynamically.
//
// CHECK-LABEL: sil hidden @$s23access_marker_mandatory19captureStackPromoteSiycyF : $@convention(thin) () -> @owned @callee_guaranteed () -> Int {
// CHECK-LABEL: bb0:
// CHECK: [[STK:%.*]] = alloc_stack $Int, var, name "x"
// CHECK: [[WRITE:%.*]] = begin_access [modify] [static] [[STK]] : $*Int
// CHECK: store %{{.*}} to [[WRITE]] : $*Int
// CHECK: end_access [[WRITE]] : $*Int
// CHECK: [[F:%.*]] = function_ref @$s23access_marker_mandatory19captureStackPromoteSiycyFSiycfU_Tf2i_n : $@convention(thin) (Int) -> Int
// CHECK: [[C:%.*]] = partial_apply [callee_guaranteed] [[F]](%{{.*}}) : $@convention(thin) (Int) -> Int
// CHECK: dealloc_stack [[STK]] : $*Int
// CHECK: return [[C]] : $@callee_guaranteed () -> Int
// CHECK-LABEL: } // end sil function '$s23access_marker_mandatory19captureStackPromoteSiycyF'
func captureStackPromote() -> () -> Int {
var x = 1
x = 2
let f = { x }
return f
}
| apache-2.0 | 1668bfa12030959c7b354ae539eedb6f | 43.409639 | 176 | 0.615844 | 3.185825 | false | false | false | false |
dnevera/IMProcessing | IMPTests/IMPGeometryTest/IMPGeometryTest/Classes/IMPBlender.swift | 1 | 2557 | //
// IMPBlender.swift
// IMPGeometryTest
//
// Created by denis svinarchuk on 07.05.16.
// Copyright © 2016 ImageMetalling. All rights reserved.
//
#if os(iOS)
import UIKit
#else
import Cocoa
#endif
import Metal
import simd
import IMProcessing
public class IMPBlender: NSObject, IMPContextProvider {
public let vertexName:String
public let fragmentName:String
public var context:IMPContext!
public lazy var library:MTLLibrary = {
return self.context.defaultLibrary
}()
public lazy var pipeline:MTLRenderPipelineState? = {
do {
let renderPipelineDescription = MTLRenderPipelineDescriptor()
renderPipelineDescription.vertexDescriptor = self.vertexDescriptor
renderPipelineDescription.colorAttachments[0].pixelFormat = .RGBA8Unorm
renderPipelineDescription.colorAttachments[0].blendingEnabled = true
renderPipelineDescription.colorAttachments[0].rgbBlendOperation = .Add
renderPipelineDescription.colorAttachments[0].alphaBlendOperation = .Add
renderPipelineDescription.colorAttachments[0].sourceRGBBlendFactor = .SourceColor
renderPipelineDescription.colorAttachments[0].sourceAlphaBlendFactor = .SourceAlpha
renderPipelineDescription.colorAttachments[0].destinationRGBBlendFactor = .One
renderPipelineDescription.colorAttachments[0].destinationAlphaBlendFactor = .One
renderPipelineDescription.vertexFunction = self.context.defaultLibrary.newFunctionWithName(self.vertexName)
renderPipelineDescription.fragmentFunction = self.context.defaultLibrary.newFunctionWithName(self.fragmentName)
return try self.context.device.newRenderPipelineStateWithDescriptor(renderPipelineDescription)
}
catch let error as NSError{
fatalError(" *** IMPGraphics: \(error)")
}
}()
public required init(context:IMPContext, vertex:String, fragment:String, vertexDescriptor:MTLVertexDescriptor? = nil) {
self.context = context
self.vertexName = vertex
self.fragmentName = fragment
}
lazy var vertexDescriptor:MTLVertexDescriptor = {
var v = MTLVertexDescriptor()
v.attributes[0].format = .UChar4;
v.attributes[0].bufferIndex = 0;
v.attributes[0].offset = 0;
v.layouts[0].stride = 4 * sizeof(UInt8)
return v
}()
}
| mit | 24da5788385b456b32cb2ccc51bca8a2 | 34.013699 | 123 | 0.676839 | 5.291925 | false | false | false | false |
vector-im/vector-ios | RiotSwiftUI/Modules/Template/TemplateAdvancedRoomsExample/TemplateRoomChat/TemplateRoomChatViewModel.swift | 1 | 4797 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import SwiftUI
import Combine
@available(iOS 14, *)
typealias TemplateRoomChatViewModelType = StateStoreViewModel<TemplateRoomChatViewState,
Never,
TemplateRoomChatViewAction>
@available(iOS 14, *)
class TemplateRoomChatViewModel: TemplateRoomChatViewModelType, TemplateRoomChatViewModelProtocol {
enum Constants {
static let maxTimeBeforeNewBubble: TimeInterval = 5*60
}
// MARK: - Properties
// MARK: Private
private let templateRoomChatService: TemplateRoomChatServiceProtocol
// MARK: Public
var callback: ((TemplateRoomChatViewModelAction) -> Void)?
// MARK: - Setup
init(templateRoomChatService: TemplateRoomChatServiceProtocol) {
self.templateRoomChatService = templateRoomChatService
super.init(initialViewState: Self.defaultState(templateRoomChatService: templateRoomChatService))
setupMessageObserving()
setupRoomInitializationObserving()
}
private func setupRoomInitializationObserving() {
templateRoomChatService
.roomInitializationStatus
.sink { [weak self] status in
self?.state.roomInitializationStatus = status
}
.store(in: &cancellables)
}
private func setupMessageObserving() {
templateRoomChatService
.chatMessagesSubject
.map(Self.makeBubbles(messages:))
.sink { [weak self] bubbles in
self?.state.bubbles = bubbles
}
.store(in: &cancellables)
}
private static func defaultState(templateRoomChatService: TemplateRoomChatServiceProtocol) -> TemplateRoomChatViewState {
let bindings = TemplateRoomChatViewModelBindings(messageInput: "")
return TemplateRoomChatViewState(roomInitializationStatus: .notInitialized, roomName: templateRoomChatService.roomName, bubbles: [], bindings: bindings)
}
private static func makeBubbles(messages: [TemplateRoomChatMessage]) -> [TemplateRoomChatBubble] {
var bubbleOrder = [String]()
var bubbleMap = [String:TemplateRoomChatBubble]()
messages.enumerated().forEach { i, message in
// New message content
let messageItem = TemplateRoomChatBubbleItem(
id: message.id,
timestamp: message.timestamp,
content: .message(message.content)
)
if i > 0,
let lastBubbleId = bubbleOrder.last,
var lastBubble = bubbleMap[lastBubbleId],
lastBubble.sender.id == message.sender.id,
let interveningTime = lastBubble.items.last?.timestamp.timeIntervalSince(message.timestamp),
abs(interveningTime) < Constants.maxTimeBeforeNewBubble
{
// if the last bubble's last message was within
// the last 5 minutes append
let item = TemplateRoomChatBubbleItem(
id: message.id,
timestamp: message.timestamp,
content: .message(message.content)
)
lastBubble.items.append(item)
bubbleMap[lastBubble.id] = lastBubble
} else {
// else create a new bubble and add the message as the first item
let bubble = TemplateRoomChatBubble(
id: message.id,
sender: message.sender,
items: [messageItem]
)
bubbleOrder.append(bubble.id)
bubbleMap[bubble.id] = bubble
}
}
return bubbleOrder.compactMap({ bubbleMap[$0] })
}
// MARK: - Public
override func process(viewAction: TemplateRoomChatViewAction) {
switch viewAction {
case .done:
callback?(.done)
case .sendMessage:
templateRoomChatService.send(textMessage: state.bindings.messageInput)
state.bindings.messageInput = ""
}
}
}
| apache-2.0 | cfc3f4b3bf600ce6d1ac7bb6a34c2238 | 36.771654 | 160 | 0.613508 | 5.231189 | false | false | false | false |
ryanspillsbury90/HaleMeditates | ios/Hale Meditates/JournalViewController.swift | 1 | 3591 | //
// JournalViewController.swift
// Hale Meditates
//
// Created by Ryan Pillsbury on 7/11/15.
// Copyright (c) 2015 koait. All rights reserved.
//
import UIKit
class JournalViewController: UIViewController, UITextViewDelegate {
@IBOutlet weak var textView: UITextView!
@IBOutlet weak var addJournalLabel: UILabel!
@IBOutlet weak var finishedButton: UIButton!
@IBOutlet weak var calendarDateLabel: UILabel!
@IBOutlet weak var meditationDurationTimesLabel: UILabel!
@IBOutlet weak var meditationDurationLabel: UILabel!
var model: JournalEntry?
override func viewDidLoad() {
super.viewDidLoad()
textView.contentInset.top = -16;
textView.delegate = self;
if (model != nil) {
calendarDateLabel.text = model!.startDateString;
meditationDurationTimesLabel.text = "\(model!.getStartTime) - \(model!.getEndTime)"
meditationDurationLabel.text = model!.totalTime;
textView.text = model?.entry
if (model!.entry != nil && (model!.entry!).characters.count > 0) {
self.addJournalLabel.text = "Tap to Edit Entry";
} else {
self.addJournalLabel.hidden = true;
}
}
self.textView.textColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5);
}
var firstShow = true;
override func viewWillAppear(animated: Bool) {
if (firstShow && self.addJournalLabel.text == "Tap to Edit Entry") {
UIView.animateWithDuration(1.5, delay: 1.0, options: [], animations: ({
self.addJournalLabel.alpha = 0.0;
}), completion: nil);
} else if (firstShow && self.addJournalLabel.text == "Add Journal") {
self.textView.becomeFirstResponder()
}
firstShow = false;
super.viewWillAppear(animated);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textViewShouldBeginEditing(textView: UITextView) -> Bool {
self.addJournalLabel.hidden = true;
self.finishedButton.hidden = false;
self.textView.textColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 1.0);
return true;
}
@IBAction func handleFinishButtonPressed() {
self.textView.resignFirstResponder()
self.finishedButton.hidden = true;
if (self.textView.text == "") {
self.addJournalLabel.hidden = false;
}
self.textView.textColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5);
}
@IBAction func exitView() {
self.navigationController?.popViewControllerAnimated(true);
}
@IBAction func saveJournalAndExit() {
model?.entry = textView.text;
if model?.id != nil {
API.editJournalEntry(self.model!, callback: {(success: Bool) in
self.exitView();
});
} else {
API.addJournalEntry(self.model!, callback: {(success: Bool) in
self.exitView();
});
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| mit | d2a08e8b5fba706402968c7600d9a1b5 | 31.645455 | 106 | 0.604845 | 4.505646 | false | false | false | false |
uasys/swift | test/SILGen/access_marker_gen.swift | 4 | 5592 | // RUN: %target-swift-frontend -parse-as-library -Xllvm -sil-full-demangle -enforce-exclusivity=checked -emit-silgen -enable-sil-ownership %s | %FileCheck %s
func modify<T>(_ x: inout T) {}
public struct S {
var i: Int
var o: AnyObject?
}
// CHECK-LABEL: sil hidden [noinline] @_T017access_marker_gen5initSAA1SVyXlSgF : $@convention(thin) (@owned Optional<AnyObject>) -> @owned S {
// CHECK: bb0(%0 : @owned $Optional<AnyObject>):
// CHECK: [[BOX:%.*]] = alloc_box ${ var S }, var, name "s"
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [var] [[BOX]] : ${ var S }
// CHECK: [[ADDR:%.*]] = project_box [[MARKED_BOX]] : ${ var S }, 0
// CHECK: cond_br %{{.*}}, bb1, bb2
// CHECK: bb1:
// CHECK: [[ACCESS1:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S
// CHECK: assign %{{.*}} to [[ACCESS1]] : $*S
// CHECK: end_access [[ACCESS1]] : $*S
// CHECK: bb2:
// CHECK: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S
// CHECK: assign %{{.*}} to [[ACCESS2]] : $*S
// CHECK: end_access [[ACCESS2]] : $*S
// CHECK: bb3:
// CHECK: [[ACCESS3:%.*]] = begin_access [read] [unknown] [[ADDR]] : $*S
// CHECK: [[RET:%.*]] = load [copy] [[ACCESS3]] : $*S
// CHECK: end_access [[ACCESS3]] : $*S
// CHECK: return [[RET]] : $S
// CHECK-LABEL: } // end sil function '_T017access_marker_gen5initSAA1SVyXlSgF'
@inline(never)
func initS(_ o: AnyObject?) -> S {
var s: S
if o == nil {
s = S(i: 0, o: nil)
} else {
s = S(i: 1, o: o)
}
return s
}
@inline(never)
func takeS(_ s: S) {}
// CHECK-LABEL: sil @_T017access_marker_gen14modifyAndReadSyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: %[[BOX:.*]] = alloc_box ${ var S }, var, name "s"
// CHECK: %[[ADDRS:.*]] = project_box %[[BOX]] : ${ var S }, 0
// CHECK: %[[ACCESS1:.*]] = begin_access [modify] [unknown] %[[ADDRS]] : $*S
// CHECK: %[[ADDRI:.*]] = struct_element_addr %15 : $*S, #S.i
// CHECK: assign %{{.*}} to %[[ADDRI]] : $*Int
// CHECK: end_access %[[ACCESS1]] : $*S
// CHECK: %[[ACCESS2:.*]] = begin_access [read] [unknown] %[[ADDRS]] : $*S
// CHECK: %{{.*}} = load [copy] %[[ACCESS2]] : $*S
// CHECK: end_access %[[ACCESS2]] : $*S
// CHECK-LABEL: } // end sil function '_T017access_marker_gen14modifyAndReadSyyF'
public func modifyAndReadS() {
var s = initS(nil)
s.i = 42
takeS(s)
}
var global = S(i: 0, o: nil)
func readGlobal() -> AnyObject? {
return global.o
}
// CHECK-LABEL: sil hidden @_T017access_marker_gen10readGlobalyXlSgyF
// CHECK: [[ADDRESSOR:%.*]] = function_ref @_T017access_marker_gen6globalAA1SVvau :
// CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]()
// CHECK-NEXT: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*S
// CHECK-NEXT: [[T2:%.*]] = begin_access [read] [dynamic] [[T1]]
// CHECK-NEXT: [[T3:%.*]] = struct_element_addr [[T2]] : $*S, #S.o
// CHECK-NEXT: [[T4:%.*]] = load [copy] [[T3]]
// CHECK-NEXT: end_access [[T2]]
// CHECK-NEXT: return [[T4]]
public struct HasTwoStoredProperties {
var f: Int = 7
var g: Int = 9
// CHECK-LABEL: sil hidden @_T017access_marker_gen22HasTwoStoredPropertiesV027noOverlapOnAssignFromPropToM0yyF : $@convention(method) (@inout HasTwoStoredProperties) -> ()
// CHECK: [[ACCESS1:%.*]] = begin_access [read] [unknown] [[SELF_ADDR:%.*]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[G_ADDR:%.*]] = struct_element_addr [[ACCESS1]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.g
// CHECK-NEXT: [[G_VAL:%.*]] = load [trivial] [[G_ADDR]] : $*Int
// CHECK-NEXT: end_access [[ACCESS1]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[F_ADDR:%.*]] = struct_element_addr [[ACCESS2]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.f
// CHECK-NEXT: assign [[G_VAL]] to [[F_ADDR]] : $*Int
// CHECK-NEXT: end_access [[ACCESS2]] : $*HasTwoStoredProperties
mutating func noOverlapOnAssignFromPropToProp() {
f = g
}
}
class C {
final var x: Int = 0
}
func testClassInstanceProperties(c: C) {
let y = c.x
c.x = y
}
// CHECK-LABEL: sil hidden @_T017access_marker_gen27testClassInstancePropertiesyAA1CC1c_tF :
// CHECK: [[C:%.*]] = begin_borrow %0 : $C
// CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[CX]] : $*Int
// CHECK-NEXT: [[Y:%.*]] = load [trivial] [[ACCESS]]
// CHECK-NEXT: end_access [[ACCESS]]
// CHECK: [[C:%.*]] = begin_borrow %0 : $C
// CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[CX]] : $*Int
// CHECK-NEXT: assign [[Y]] to [[ACCESS]]
// CHECK-NEXT: end_access [[ACCESS]]
class D {
var x: Int = 0
}
// materializeForSet callback
// CHECK-LABEL: sil private [transparent] @_T017access_marker_gen1DC1xSivmytfU_
// CHECK: end_unpaired_access [dynamic] %1 : $*Builtin.UnsafeValueBuffer
// materializeForSet
// CHECK-LABEL: sil hidden [transparent] @_T017access_marker_gen1DC1xSivm
// CHECK: [[T0:%.*]] = ref_element_addr %2 : $D, #D.x
// CHECK-NEXT: begin_unpaired_access [modify] [dynamic] [[T0]] : $*Int
func testDispatchedClassInstanceProperty(d: D) {
modify(&d.x)
}
// CHECK-LABEL: sil hidden @_T017access_marker_gen35testDispatchedClassInstancePropertyyAA1DC1d_tF
// CHECK: [[D:%.*]] = begin_borrow %0 : $D
// CHECK: [[METHOD:%.*]] = class_method [[D]] : $D, #D.x!materializeForSet.1
// CHECK: apply [[METHOD]]({{.*}}, [[D]])
// CHECK-NOT: begin_access
// CHECK: end_borrow [[D]] from %0 : $D
| apache-2.0 | f12fbfb5e8b2505438ed2cbb41f17bb6 | 39.817518 | 171 | 0.597997 | 3.045752 | false | false | false | false |
denivip/Waveform | Source/Utility/Buffer.swift | 1 | 2293 | //
// Buffer.swift
// Channel Performance test
//
// Created by developer on 15/04/16.
// Copyright © 2016 developer. All rights reserved.
//
import Foundation
public
class Buffer {
typealias DefaultNumberType = Double
var maxValue = -Double.infinity
var minValue = Double.infinity
var count = 0
var buffer: UnsafeMutablePointer<Void> = nil
var _buffer: UnsafeMutablePointer<DefaultNumberType> = nil
private var space = 0
func appendValue(value: Double) {
if maxValue < value { maxValue = value }
if minValue > value { minValue = value }
if space == count {
let newSpace = max(space * 2, 16)
self.moveSpaceTo(newSpace)
_buffer = UnsafeMutablePointer<DefaultNumberType>(buffer)
}
(UnsafeMutablePointer<DefaultNumberType>(buffer) + count).initialize(value)
count += 1
}
private
func moveSpaceTo(newSpace: Int) {
let newPtr = UnsafeMutablePointer<DefaultNumberType>.alloc(newSpace)
newPtr.moveInitializeFrom(UnsafeMutablePointer<DefaultNumberType>(buffer), count: count)
buffer.dealloc(count)
buffer = UnsafeMutablePointer<Void>(newPtr)
space = newSpace
}
func valueAtIndex(index: Int) -> Double {
return _buffer[index]
}
}
final
class GenericBuffer<T: NumberType>: Buffer {
var __buffer: UnsafeMutablePointer<T> = nil
override final func appendValue(value: Double) {
if maxValue < value { maxValue = value }
if minValue > value { minValue = value }
if space == count {
let newSpace = max(space * 2, 16)
self.moveSpaceTo(newSpace)
}
(__buffer + count).initialize(T(value))
count += 1
}
override final func moveSpaceTo(newSpace: Int) {
let newPtr = UnsafeMutablePointer<T>.alloc(newSpace)
newPtr.moveInitializeFrom(__buffer, count: count)
__buffer.dealloc(count)
__buffer = newPtr
space = newSpace
}
override final func valueAtIndex(index: Int) -> Double {
return __buffer[index].double
}
deinit {
__buffer.destroy(space)
__buffer.dealloc(space)
}
} | mit | 1c6d387cdb92eb025ef45a1af3af5b24 | 26.626506 | 96 | 0.608202 | 4.511811 | false | false | false | false |
ngageoint/mage-ios | Mage/UserSummaryView.swift | 1 | 2459 | //
// UserSummaryView.swift
// MAGE
//
// Created by Daniel Barela on 7/5/21.
// Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
import CoreImage
import Kingfisher
class UserSummaryView: CommonSummaryView<User, UserActionsDelegate> {
private weak var user: User?;
private var userActionsDelegate: UserActionsDelegate?;
private var didSetUpConstraints = false;
lazy var avatarImage: UIImageView = {
let avatarImage = UserAvatarUIImageView(image: nil);
avatarImage.configureForAutoLayout();
avatarImage.autoSetDimensions(to: CGSize(width: 48, height: 48));
return avatarImage;
}()
override var itemImage: UIImageView {
get { return avatarImage }
set { avatarImage = newValue }
}
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
override init(imageOverride: UIImage? = nil, hideImage: Bool = false) {
super.init(imageOverride: imageOverride, hideImage: hideImage);
isUserInteractionEnabled = false;
}
override func applyTheme(withScheme scheme: MDCContainerScheming?) {
super.applyTheme(withScheme: scheme);
guard let scheme = scheme else {
return
}
avatarImage.tintColor = scheme.colorScheme.onSurfaceColor.withAlphaComponent(0.87);
}
override func populate(item: User, actionsDelegate: UserActionsDelegate? = nil) {
self.user = item;
self.userActionsDelegate = actionsDelegate;
if (self.imageOverride != nil) {
avatarImage.image = self.imageOverride;
} else {
self.avatarImage.kf.indicatorType = .activity;
(avatarImage as! UserAvatarUIImageView).setUser(user: item);
let cacheOnly = DataConnectionUtilities.shouldFetchAvatars();
(avatarImage as! UserAvatarUIImageView).showImage(cacheOnly: cacheOnly);
}
primaryField.text = item.name;
// we do not want the date to word break so we replace all spaces with a non word breaking spaces
var timeText = "";
if let itemDate: NSDate = item.location?.timestamp as NSDate? {
timeText = itemDate.formattedDisplay().uppercased().replacingOccurrences(of: " ", with: "\u{00a0}") ;
}
timestamp.text = timeText;
}
}
| apache-2.0 | 3c9bba64326433a7219ebb269bc17fbe | 33.138889 | 113 | 0.650936 | 4.985801 | false | false | false | false |
younthu/FuturesStatus | FuturesStatus/FuturesStatus/Settings.swift | 1 | 1393 | //
// Settings.swift
// FuturesStatus
//
// Created by Andrew(Zhiyong) Yang on 5/10/16.
// Copyright © 2016 FoolDragon. All rights reserved.
//
import Cocoa
import ReactiveCocoa
let kItemNameKey = "Settings.ItemName.key";
class Settings: NSObject {
var refreshInSeconds:NSInteger = 1
var itemName:MutableProperty< String > = MutableProperty("");
static var _sharedInstance:Settings = Settings.createSharedInstance();
private class func createSharedInstance () -> Settings {
let instance = Settings();
// loading nsdefault values
if let itemName = NSUserDefaults.standardUserDefaults().valueForKey(kItemNameKey) {
// NSLog("Get saved value %@", itemName);
NSLog("Get value %@", itemName as! String);
instance.itemName.value = itemName as! String;
}
instance.itemName.signal.observeNext { (newValue :String) in
NSLog("Saving new value %@", newValue);
NSUserDefaults.standardUserDefaults().setValue(newValue, forKey: kItemNameKey)
NSUserDefaults.standardUserDefaults().synchronize();
}
return instance;
}
class func sharedInstance() -> Settings{
return _sharedInstance;
}
override init() {
self.itemName = MutableProperty<String>("AG1606");
}
}
| apache-2.0 | 930154bb86e4bb1828b680784b5a1b39 | 29.26087 | 91 | 0.625718 | 5.098901 | false | false | false | false |
SwiftAndroid/swift | stdlib/public/SDK/AppKit/AppKit.swift | 2 | 3139 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Foundation
@_exported import AppKit
extension NSCursor : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .image(image)
}
}
internal struct _NSViewQuickLookState {
static var views = Set<NSView>()
}
extension NSView : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
// if you set NSView.needsDisplay, you can get yourself in a recursive scenario where the same view
// could need to draw itself in order to get a QLObject for itself, which in turn if your code was
// instrumented to log on-draw, would cause yourself to get back here and so on and so forth
// until you run out of stack and crash
// This code checks that we aren't trying to log the same view recursively - and if so just returns
// an empty view, which is probably a safer option than crashing
// FIXME: is there a way to say "cacheDisplayInRect butDoNotRedrawEvenIfISaidSo"?
if _NSViewQuickLookState.views.contains(self) {
return .view(NSImage())
} else {
_NSViewQuickLookState.views.insert(self)
let result: PlaygroundQuickLook
if let b = bitmapImageRepForCachingDisplay(in: bounds) {
cacheDisplay(in: bounds, to: b)
result = .view(b)
} else {
result = .view(NSImage())
}
_NSViewQuickLookState.views.remove(self)
return result
}
}
}
// Overlays for variadics.
public extension NSGradient {
convenience init?(colorsAndLocations objects: (NSColor, CGFloat)...) {
self.init(
colors: objects.map { $0.0 },
atLocations: objects.map { $0.1 },
colorSpace: NSColorSpace.genericRGB())
}
}
// Fix the ARGV type of NSApplicationMain, which nonsensically takes
// argv as a const char**.
@_silgen_name("NSApplicationMain")
public func NSApplicationMain(
_ argc: Int32, _ argv: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>
) -> Int32
extension NSColor : _ColorLiteralConvertible {
public required convenience init(colorLiteralRed red: Float, green: Float,
blue: Float, alpha: Float) {
self.init(srgbRed: CGFloat(red), green: CGFloat(green),
blue: CGFloat(blue), alpha: CGFloat(alpha))
}
}
public typealias _ColorLiteralType = NSColor
extension NSImage : _ImageLiteralConvertible {
private convenience init!(failableImageLiteral name: String) {
self.init(named: name)
}
public required convenience init(imageLiteral name: String) {
self.init(failableImageLiteral: name)
}
}
public typealias _ImageLiteralType = NSImage
| apache-2.0 | 702bb1211b14b55f4c954bcf5cf6a670 | 33.877778 | 103 | 0.673781 | 4.582482 | false | false | false | false |
lanserxt/teamwork-ios-sdk | TeamWorkClient/TeamWorkClient/Requests/TWApiClient+Files.swift | 1 | 17337 | //
// TWApiClient+Invoices.swift
// TeamWorkClient
//
// Created by Anton Gubarenko on 02.02.17.
// Copyright © 2017 Anton Gubarenko. All rights reserved.
//
import Foundation
import Alamofire
extension TWApiClient{
func getFilesForTask(taskId: String, _ responseBlock: @escaping (Bool, Int, [FileProject]?, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getFilesForTask.path, taskId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = MultipleResponseContainer<FileProject>.init(rootObjectName: TWApiClientConstants.APIPath.getFilesForTask.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, responseContainer.rootObjects, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
func getFilesForProject(projectId: String, _ responseBlock: @escaping (Bool, Int, [FileProject]?, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getFilesForProject.path, projectId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = MultipleResponseContainer<FileProject>.init(rootObjectName: TWApiClientConstants.APIPath.getFilesForProject.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, responseContainer.rootObjects, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
func getFile(fileId: String, _ responseBlock: @escaping (Bool, Int, File?, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getFile.path, fileId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<File>.init(rootObjectName: TWApiClientConstants.APIPath.getFile.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, responseContainer.rootObject, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
func addFileToProject(file: File, projectId: String, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
let parameters: [String : Any] = ["file" : file.dictionaryRepresentation() as! [String : Any]]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.addFileToProject.path, file.id!), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<File>.init(rootObjectName: TWApiClientConstants.APIPath.addFileToProject.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func addNewFileVersionToFile(file: File, fileversion: [String: Any], _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
let parameters: [String : Any] = ["fileversion" : fileversion ]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.addNewFileVersionToFile.path, file.id!), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<File>.init(rootObjectName: TWApiClientConstants.APIPath.addNewFileVersionToFile.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func deleteFileFromProject(file: File, _ responseBlock: @escaping (Bool, Int, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.deleteFileFromProject.path, file.id!), method: HTTPMethod.delete, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<Category>.init(rootObjectName: TWApiClientConstants.APIPath.deleteFileFromProject.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, nil)
} else {
responseBlock (false, 0, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, error)
}
}
}
func getShortUrlForSharingFile(fileId: String, _ responseBlock: @escaping (Bool, Int, String?, Error?) -> Void){
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getShortUrlForSharingFile.path, fileId), method: HTTPMethod.get, parameters: nil, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<File>.init(rootObjectName: TWApiClientConstants.APIPath.getShortUrlForSharingFile.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, JSON.object(forKey: "id") as! String?, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
func copyFileToAnotherProject(projectId: String, _ responseBlock: @escaping (Bool, Int, String?, Error?) -> Void){
let parameters: [String : Any] = ["projectId" : projectId ]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.getShortUrlForSharingFile.path, projectId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<File>.init(rootObjectName: TWApiClientConstants.APIPath.getShortUrlForSharingFile.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, JSON.object(forKey: "id") as! String?, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
func moveFileToAnotherProject(projectId: String, _ responseBlock: @escaping (Bool, Int, String?, Error?) -> Void){
let parameters: [String : Any] = ["projectId" : projectId]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.moveFileToAnotherProject.path, projectId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<File>.init(rootObjectName: TWApiClientConstants.APIPath.moveFileToAnotherProject.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, JSON.object(forKey: "id") as! String?, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
func updateProjectLogo(projectId: String, fileRef: String, _ responseBlock: @escaping (Bool, Int, String?, Error?) -> Void){
let parameters: [String : Any] = ["project" : ["logoPendingFileRef" : fileRef]]
Alamofire.request(kSiteUrl + String.init(format: TWApiClientConstants.APIPath.updateProjectLogo.path, projectId), method: HTTPMethod.put, parameters: parameters, encoding: URLEncoding.default, headers: nil)
.validate(statusCode: 200..<300)
.validate(contentType: [kContentType])
.authenticate(user: kApiToken, password: kAuthPass)
.responseJSON { response in
switch response.result {
case .success:
if let result = response.result.value {
let JSON = result as! NSDictionary
if let responseContainer = ResponseContainer<File>.init(rootObjectName: TWApiClientConstants.APIPath.updateProjectLogo.rootElement, dictionary: JSON){
if (responseContainer.status == TWApiStatusCode.OK){
responseBlock (true, 200, JSON.object(forKey: "id") as! String?, nil)
} else {
responseBlock (false, 0, nil, TWApiClientErrors.ResponseStatusNotOK)
}
}
else
{
responseBlock (false, 0, nil, TWApiClientErrors.ResponseValidationError)
}
}
case .failure(let error):
print(error)
responseBlock(false, (response.response?.statusCode)!, nil, error)
}
}
}
}
| mit | c1bb7e9b9fd6332070cef2cc38511c0d | 53.860759 | 222 | 0.533053 | 6.015267 | false | false | false | false |
cassandrakane-minted/swipeFavoriteMintedArtMobileApp2 | Example/Koloda/BackgroundAnimationViewController.swift | 1 | 7590 | //
// BackgroundAnimationViewController.swift
// Koloda
//
// Created by Eugene Andreyev on 7/11/15.
// Copyright (c) 2015 CocoaPods. All rights reserved.
//
import UIKit
import Koloda
import pop
import Alamofire
// TODO: hookup with backend
private var designInfosOverlayViews: [OverlayView] = []
private let numberOfCards: UInt = UInt(designInfosOverlayViews.count)
private let frameAnimationSpringBounciness: CGFloat = 9
private let frameAnimationSpringSpeed: CGFloat = 16
private let kolodaCountOfVisibleCards = 2
private let kolodaAlphaValueSemiTransparent: CGFloat = 0.1
class BackgroundAnimationViewController: UIViewController {
@IBOutlet weak var kolodaView: CustomKolodaView!
//MARK: Lifecycle
override func viewDidLoad() {
getBackendData(setDisplayInfos)
}
private func getBackendData(completionHandler: (designInfo: [[String : String]]) -> ()) {
Alamofire.request(.GET, "http://424b91e6.ngrok.io/api/hack_designs")
.responseJSON {response in
completionHandler(designInfo: response.result.value as! [[String : String]])
}
}
private func setDisplayInfos(info: [[String : String]]) {
let designInfos = info
designInfosOverlayViews = constructOverlayViews(designInfos)
struct defaultsKeys {
static let keyOne = "designInfos"
static let keyTwo = "currentIndex"
}
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(designInfos, forKey: defaultsKeys.keyOne)
defaults.setInteger(0, forKey: defaultsKeys.keyTwo)
defaults.synchronize()
super.viewDidLoad()
kolodaView.alphaValueSemiTransparent = kolodaAlphaValueSemiTransparent
kolodaView.countOfVisibleCards = kolodaCountOfVisibleCards
kolodaView.delegate = self
kolodaView.dataSource = self
kolodaView.animator = BackgroundKolodaAnimator(koloda: kolodaView)
self.modalTransitionStyle = UIModalTransitionStyle.FlipHorizontal
}
private func constructOverlayViews(infos: [[String: String]]) -> [OverlayView] {
var designOverlayViews: [OverlayView] = []
for info in infos {
let designOverlayView = OverlayView()
designOverlayView.designInfo = info
designOverlayViews.append(designOverlayView)
}
return designOverlayViews
}
//MARK: IBActions
@IBAction func leftButtonTapped() {
kolodaView?.swipe(SwipeResultDirection.Left)
}
@IBAction func rightButtonTapped() {
kolodaView?.swipe(SwipeResultDirection.Right)
}
@IBAction func undoButtonTapped() {
kolodaView?.revertAction()
}
}
//MARK: KolodaViewDelegate
extension BackgroundAnimationViewController: KolodaViewDelegate {
func kolodaDidRunOutOfCards(koloda: KolodaView) {
kolodaView.resetCurrentCardIndex()
}
func koloda(koloda: KolodaView, didSelectCardAtIndex index: UInt) {
UIApplication.sharedApplication().openURL(NSURL(string: "")!)
}
func kolodaShouldApplyAppearAnimation(koloda: KolodaView) -> Bool {
return true
}
func kolodaShouldMoveBackgroundCard(koloda: KolodaView) -> Bool {
return false
}
func kolodaShouldTransparentizeNextCard(koloda: KolodaView) -> Bool {
return true
}
func koloda(kolodaBackgroundCardAnimation koloda: KolodaView) -> POPPropertyAnimation? {
let animation = POPSpringAnimation(propertyNamed: kPOPViewFrame)
animation.springBounciness = frameAnimationSpringBounciness
animation.springSpeed = frameAnimationSpringSpeed
return animation
}
}
//MARK: KolodaViewDataSource
extension BackgroundAnimationViewController: KolodaViewDataSource {
func kolodaNumberOfCards(koloda: KolodaView) -> UInt {
return numberOfCards
}
func koloda(koloda: KolodaView, viewForCardAtIndex index: UInt) -> UIView {
let designInfo = designInfosOverlayViews[Int(index)].designInfo
let screenBounds: CGRect = UIScreen.mainScreen().bounds;
let mainView = UIView(frame: CGRectMake(0, 0, screenBounds.size.width - 20, screenBounds.size.height - 220))
//get design UIImageView
var designImage = UIImage()
let designImageView = UIImageView(frame: CGRectMake(0, 50, mainView.bounds.size.width, mainView.bounds.size.height - 140))
if let url = NSURL(string: designInfo["designImgUrl"]!) {
if let data = NSData(contentsOfURL: url) {
designImage = UIImage(data: data)!
designImageView.image = designImage
designImageView.contentMode = UIViewContentMode.ScaleAspectFit
}
}
//get design title UILabel
let designNameLabel = UILabel(frame: CGRectMake(0, 20, mainView.bounds.size.width, 20))
designNameLabel.text = designInfo["designName"]
designNameLabel.textAlignment = NSTextAlignment.Center
designNameLabel.font = UIFont(name: "Helvetica Neue", size: 20)
//create UIView for artist attribution
let artistAttributionView = UIView(frame: CGRectMake(mainView.bounds.size.width / 5, mainView.bounds.size.height - 70, mainView.bounds.size.width / 2, 50))
let artistAttributionTextView = UIView(frame: CGRectMake(artistAttributionView.bounds.size.width / 3, 0, artistAttributionView.bounds.size.width * (2/3), 50))
//get artist profile UIImageView
let artistProfileImageView = UIImageView(frame: CGRectMake(0, 0, 50, 50))
if let url = NSURL(string: designInfo["artistProfileImgUrl"]!) {
if let data = NSData(contentsOfURL: url) {
let artistProfileImage = UIImage(data: data)!
artistProfileImageView.image = artistProfileImage
artistProfileImageView.contentMode = UIViewContentMode.ScaleAspectFit;
artistProfileImageView.layer.cornerRadius = artistProfileImageView.frame.size.width/2
artistProfileImageView.clipsToBounds = true
}
}
//get artist name UILabel
let artistNameLabel = UILabel(frame: CGRectMake(0, 0, artistAttributionView.bounds.size.width, 20))
artistNameLabel.text = "by " + designInfo["artistName"]!
artistNameLabel.textAlignment = NSTextAlignment.Left
artistNameLabel.font = UIFont(name: "Helvetica Neue", size: 16)
//get artist location UILabel
let artistLocationLabel = UILabel(frame: CGRectMake(0, 30, artistAttributionView.bounds.size.width, 20))
artistLocationLabel.text = designInfo["artistLocation"]
artistLocationLabel.textAlignment = NSTextAlignment.Left
artistLocationLabel.font = UIFont(name: "Helvetica Neue", size: 16)
//construct artist attribution view
artistAttributionTextView.addSubview(artistNameLabel)
artistAttributionTextView.addSubview(artistLocationLabel)
artistAttributionView.addSubview(artistAttributionTextView)
artistAttributionView.addSubview(artistProfileImageView)
//construct main view
mainView.addSubview(designImageView)
mainView.addSubview(designNameLabel)
mainView.addSubview(artistAttributionView)
return mainView
}
func koloda(koloda: KolodaView, viewForCardOverlayAtIndex index: UInt) -> OverlayView? {
return NSBundle.mainBundle().loadNibNamed("CustomOverlayView",
owner: self, options: nil)[0] as? OverlayView
}
}
| mit | 39e726719b8c7778d1265df5b11da596 | 37.527919 | 166 | 0.694598 | 5.073529 | false | false | false | false |
xeieshan/GoogleLoginManager | GoogleLoginManager/GoogleLoginManagerSwift.swift | 1 | 4126 | //
// GoogleLoginManagerSwift.swift
// GoogleLoginManager
//
// Created by <#Developer Name#> on 21/03/2017.
// Copyright © 2017 <#Project Team#>. All rights reserved.
//
import Foundation
import GoogleSignIn
import Google
protocol GoogleLoginManagerDelegate {
func didLogin();
func didLogout();
func didDisconnect();
}
class GoogleLoginManager : NSObject,GIDSignInDelegate,GIDSignInUIDelegate {
var delegate: GoogleLoginManagerDelegate?
var loggedUser: GIDGoogleUser?
static let sharedLoginManager: GoogleLoginManager = GoogleLoginManager()
class func handleURL(_ url: URL, sourceApplication: String, annotation: AnyObject) -> Bool {
return GIDSignIn.sharedInstance().handle(url as URL!, sourceApplication: sourceApplication, annotation: annotation)
}
func tryLoginWith(_ delegate: GoogleLoginManagerDelegate) {
self.delegate = delegate
var configureError: NSError?
GGLContext.sharedInstance().configureWithError(&configureError)
if configureError != nil {
print("Error configuring the Google context: \(configureError)")
}
GIDSignIn.sharedInstance().uiDelegate = self
GIDSignIn.sharedInstance().delegate = self
GIDSignIn.sharedInstance().signIn()
}
func tryLogout() {
GIDSignIn.sharedInstance().disconnect()
}
// MARK: -
// MARK: GIDSignInDelegate
// MARK: -
// The sign-in flow has finished and was successful if |error| is |nil|.
open func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
// Perform any operations on signed in user here.
print("name=\(user.profile.name)")
print("accessToken=\(user.authentication.accessToken)")
GoogleLoginManager.sharedLoginManager.loggedUser = user
if GIDSignIn.sharedInstance().currentUser.authentication == nil {
if (self.delegate != nil) {
self.delegate?.didLogout()
}
} else {
if (self.delegate != nil) {
self.delegate?.didLogin()
}
}
}
// This callback is triggered after the disconnect call that revokes data
// access to the user's resources has completed.
// Finished disconnecting |user| from the app successfully if |error| is |nil|.
open func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!){
// Perform any operations when the user disconnects from app here.
print("didDisconnectWithUser")
if (self.delegate != nil) {
self.delegate?.didDisconnect()
}
}
// MARK: -
// MARK: GIDSignInUIDelegate
// MARK: -
// Stop the UIActivityIndicatorView animation that was started when the user
// pressed the Sign In button
// The sign-in flow has finished selecting how to proceed, and the UI should no longer display
// a spinner or other "please wait" element.
open func sign(inWillDispatch signIn: GIDSignIn!, error: Error!) {
}
// If implemented, this method will be invoked when sign in needs to display a view controller.
// The view controller should be displayed modally (via UIViewController's |presentViewController|
// method, and not pushed unto a navigation controller's stack.
open func sign(_ signIn: GIDSignIn!, present viewController: UIViewController!) {
let vc: UIViewController = (self.delegate as? UIViewController)!
vc.present(viewController, animated: true, completion: nil)
}
// If implemented, this method will be invoked when sign in needs to dismiss a view controller.
// Typically, this should be implemented by calling |dismissViewController| on the passed
// view controller.
open func sign(_ signIn: GIDSignIn!, dismiss viewController: UIViewController!) {
let vc: UIViewController = (self.delegate as? UIViewController)!
vc.dismiss(animated: true, completion: {
})
}
}
| apache-2.0 | b09888db26ae5510fb24705b56561583 | 35.504425 | 123 | 0.659636 | 5.130597 | false | true | false | false |
Ansem717/MotivationalModel | MotivationalModel/MotivationalModel/Room.swift | 1 | 2219 | //
// Room.swift
// MotivationalModel
//
// Created by Andy Malik on 2/26/16.
// Copyright © 2016 VanguardStrategiesInc. All rights reserved.
//
import Foundation
class Room: NSObject, NSCoding {
var title: String
var subtitles: [String : String]
var abbreviation: String
var userText: String?
var descript: String
var buttons: [String]
init(title: String, subtitles: [String : String], abbreviation: String, userText: String? = "", descript: String, buttons: [String]) {
self.title = title
self.subtitles = subtitles
self.abbreviation = abbreviation
self.userText = userText
self.descript = descript
self.buttons = buttons
}
convenience required init?(coder aDecoder: NSCoder) {
guard let title = aDecoder.decodeObjectForKey("title") as? String else { fatalError("Title is not a string") }
guard let subtitles = aDecoder.decodeObjectForKey("subtitles") as? [String : String] else { fatalError("Object at key subtitles is __ \(aDecoder.decodeObjectForKey("subtitles")) __") }
guard let abbreviation = aDecoder.decodeObjectForKey("abbreviation") as? String else { fatalError("abbreviation is not a string") }
guard let userText = aDecoder.decodeObjectForKey("userText") as? String else { fatalError("User Text is not a string") }
guard let descript = aDecoder.decodeObjectForKey("descript") as? String else { fatalError("descript is not a string") }
guard let buttons = aDecoder.decodeObjectForKey("buttons") as? [String] else { fatalError("buttons is not a [string]") }
self.init(title: title, subtitles: subtitles, abbreviation: abbreviation, userText: userText, descript: descript, buttons: buttons)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(self.title, forKey: "title")
aCoder.encodeObject(self.subtitles, forKey: "subtitles")
aCoder.encodeObject(self.abbreviation, forKey: "abbreviation")
aCoder.encodeObject(self.userText, forKey: "userText")
aCoder.encodeObject(self.descript, forKey: "descript")
aCoder.encodeObject(self.buttons, forKey: "buttons")
}
}
| mit | dabfc9a2bbd655ebda1b5fb802720cb2 | 43.36 | 193 | 0.682146 | 4.545082 | false | false | false | false |
jasonsturges/swift-prototypes | SpriteKit2dDrawing/SpriteKit2dDrawing/GameViewController.swift | 2 | 1405 | //
// GameViewController.swift
// SpriteKit2dDrawing
//
// Created by Jason Sturges on 1/13/17.
// Copyright © 2017 Jason Sturges. All rights reserved.
//
import UIKit
import SpriteKit
import GameplayKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
if let view = self.view as! SKView? {
// Load the SKScene from 'GameScene.sks'
if let scene = SKScene(fileNamed: "GameScene") {
// Set the scale mode to scale to fit the window
scene.scaleMode = .aspectFill
// Present the scene
view.presentScene(scene)
}
view.ignoresSiblingOrder = true
view.showsFPS = true
view.showsNodeCount = true
}
}
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if UIDevice.current.userInterfaceIdiom == .phone {
return .allButUpsideDown
} else {
return .all
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override var prefersStatusBarHidden: Bool {
return true
}
}
| mit | 9839a1a0a889c1898feff6aa499c50a8 | 24.527273 | 77 | 0.583333 | 5.505882 | false | false | false | false |
andybest/SLisp | Sources/SLispCore/builtins/String.swift | 1 | 3059 | /*
MIT License
Copyright (c) 2016 Andy Best
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
class StringBuiltins : Builtins {
override init(parser: Parser) {
super.init(parser: parser)
}
override func namespaceName() -> String {
return "string"
}
override func initBuiltins(environment: Environment) -> [String: BuiltinDef] {
addBuiltin("capitalize", docstring: """
capitalize
(str)
Capitalizes the string
""") { args, parser, env throws in
if args.count != 1 {
throw LispError.runtime(msg: "'capitalize' requires one argument")
}
guard case let .string(str) = args[0] else {
throw LispError.runtime(msg: "'captitalize' requires a string argument")
}
return .string(str.capitalized)
}
addBuiltin("upper-case", docstring: """
upper-case
(str)
Converts the string to upper case
""") { args, parser, env throws in
if args.count != 1 {
throw LispError.runtime(msg: "'upper-case' requires one argument")
}
guard case let .string(str) = args[0] else {
throw LispError.runtime(msg: "'upper-case' requires a string argument")
}
return .string(str.uppercased())
}
addBuiltin("lower-case", docstring: """
lower-case
(str)
Converts the string to lower case
""") { args, parser, env throws in
if args.count != 1 {
throw LispError.runtime(msg: "'lower-case' requires one argument")
}
guard case let .string(str) = args[0] else {
throw LispError.runtime(msg: "'lower-case' requires a string argument")
}
return .string(str.lowercased())
}
return builtins
}
}
| mit | 19d66f1c7809147cfab7a195705fa44d | 32.988889 | 88 | 0.606407 | 4.878788 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/Settings/LinkOpening/BrowserOpening.swift | 1 | 5111 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireSystem
import UIKit
private let log = ZMSLog(tag: "link opening")
enum BrowserOpeningOption: Int, LinkOpeningOption {
case safari, chrome, firefox, snowhaze, brave
typealias ApplicationOptionEnum = BrowserOpeningOption
static var settingKey: SettingKey = .browserOpeningRawValue
static var defaultPreference: ApplicationOptionEnum = .safari
static var allOptions: [BrowserOpeningOption] {
return [.safari, .chrome, .firefox, .snowhaze, .brave]
}
var displayString: String {
switch self {
case .safari: return "open_link.browser.option.safari".localized
case .chrome: return "open_link.browser.option.chrome".localized
case .firefox: return "open_link.browser.option.firefox".localized
case .snowhaze: return "open_link.browser.option.snowhaze".localized
case .brave: return "open_link.browser.option.brave".localized
}
}
var isAvailable: Bool {
switch self {
case .safari: return true
case .chrome: return UIApplication.shared.chromeInstalled
case .firefox: return UIApplication.shared.firefoxInstalled
case .snowhaze: return UIApplication.shared.snowhazeInstalled
case .brave: return UIApplication.shared.braveInstalled
}
}
}
extension URL {
func openAsLink() -> Bool {
log.debug("Trying to open \"\(self)\" in thrid party browser")
let saved = BrowserOpeningOption.storedPreference
log.debug("Saved option to open a regular link: \(saved.displayString)")
let app = UIApplication.shared
switch saved {
case .safari: return false
case .chrome:
guard let url = chromeURL, app.canOpenURL(url) else { return false }
log.debug("Trying to open chrome app using \"\(url)\"")
app.open(url)
case .firefox:
guard let url = firefoxURL, app.canOpenURL(url) else { return false }
log.debug("Trying to open firefox app using \"\(url)\"")
app.open(url)
case .snowhaze:
guard let url = snowhazeURL, app.canOpenURL(url) else { return false }
log.debug("Trying to open snowhaze app using \"\(url)\"")
app.open(url)
case .brave:
guard let url = braveURL, app.canOpenURL(url) else { return false }
log.debug("Trying to open brave app using \"\(url)\"")
app.open(url)
}
return true
}
}
// MARK: - Private
fileprivate extension UIApplication {
var chromeInstalled: Bool {
return canHandleScheme("googlechrome://")
}
var firefoxInstalled: Bool {
return canHandleScheme("firefox://")
}
var snowhazeInstalled: Bool {
return canHandleScheme("shtps://")
}
var braveInstalled: Bool {
return canHandleScheme("brave://")
}
}
extension URL {
var chromeURL: URL? {
if absoluteString.contains("http://") {
return URL(string: "googlechrome://\(absoluteString.replacingOccurrences(of: "http://", with: ""))")
}
if absoluteString.contains("https://") {
return URL(string: "googlechromes://\(absoluteString.replacingOccurrences(of: "https://", with: ""))")
}
return URL(string: "googlechrome://\(absoluteString)")
}
var percentEncodingString: String {
return absoluteString.addingPercentEncoding(withAllowedCharacters: .alphanumerics)!
}
var firefoxURL: URL? {
return URL(string: "firefox://open-url?url=\(percentEncodingString)")
}
var snowhazeURL: URL? {
// Reference: https://github.com/snowhaze/SnowHaze-iOS/blob/master/SnowHaze/Info.plist
if absoluteString.contains("http://") {
return URL(string: "shtp://\(absoluteString.replacingOccurrences(of: "http://", with: ""))")
}
if absoluteString.contains("https://") {
return URL(string: "shtps://\(absoluteString.replacingOccurrences(of: "https://", with: ""))")
}
return URL(string: "shtp://\(absoluteString)")
}
var braveURL: URL? {
// Reference: https://github.com/brave/ios-open-thirdparty-browser/blob/master/OpenInThirdPartyBrowser/OpenInThirdPartyBrowserControllerSwift.swift
return URL(string: "brave://open-url?url=\(percentEncodingString)")
}
}
| gpl-3.0 | 9265eb0b24795d61e95bf0550a2035b4 | 33.533784 | 155 | 0.648797 | 4.383362 | false | true | false | false |
congpc/AutolayoutExamples | AutolayoutExamplesTests/AutolayoutExamplesTests.swift | 1 | 22508 | //
// AutolayoutExamplesTests.swift
// AutolayoutExamplesTests
//
// Created by Pham Chi Cong on 6/16/16.
// Copyright © 2016 Pham Chi Cong. All rights reserved.
//
import XCTest
class AutolayoutExamplesTests: XCTestCase {
let storyboard: UIStoryboard = UIStoryboard.init(name: "Main", bundle: NSBundle.init(identifier: "congpc.ios.AutolayoutExamples"))
let minPinLabelTag = 101
let maxPinLabelTag = 109
let minAlignmentLabelTag = 101
let maxAlignmentLabelTag = 107
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
//MARK: - Helpers
func createPinLabelRect(tag:Int) -> CGRect {
if Device.IS_12_9_INCHES() == true {
//12.9 inch
switch tag {
case 102:
//Right top
return CGRectMake(931.5, 40.0, 72.5, 20.0)
case 103:
//Right bottom
return CGRectMake(902.5, 1326.0, 101.5, 20.0)
case 104:
//Left bottom
return CGRectMake(20.0, 1326.0, 90.5, 20.0)
case 105:
//Left CenterY
return CGRectMake(20.0, 673.0, 96.0, 20.0)
case 106:
//CenterX Top
return CGRectMake(465.0, 40.0, 94.0, 20.0)
case 107:
//Right CenterY
return CGRectMake(897.0, 673.0, 107.0, 20.0)
case 108:
//CenterX Bottom
return CGRectMake(451.0, 1326.0, 122.5, 20.0)
case 109:
//Center
return CGRectMake(486.5, 673.0, 51.5, 20.0)
default:
//Left top
return CGRectMake(20.0, 40.0, 61.5, 20.0)
}
}
else if Device.isPad() == true {
//7.9 inch or 9.7 inch
switch tag {
case 102:
//Right top
return CGRectMake(675.0, 40.0, 73.0, 20.0)
case 103:
//Right bottom
return CGRectMake(646.0, 984.0, 102.0, 20.0)
case 104:
//Left bottom
return CGRectMake(20.0, 984.0, 91.0, 20.0)
case 105:
//Left CenterY
return CGRectMake(20.0, 502.0, 96.0, 20.0)
case 106:
//CenterX Top
return CGRectMake(337.0, 40.0, 94.0, 20.0)
case 107:
//Right CenterY
return CGRectMake(641.0, 502.0, 107.0, 20.0)
case 108:
//CenterX Bottom
return CGRectMake(323.0, 984.0, 123.0, 20.0)
case 109:
//Center
return CGRectMake(358.0, 502.0, 52.0, 20.0)
default:
//Left top
return CGRectMake(20.0, 40.0, 62.0, 20.0)
}
}
else if Device.IS_5_5_INCHES() == true {
//5.5 inch
switch tag {
case 102:
//Right top
return CGRectMake(321.33333333333326, 36.0, 72.666666666666686, 20)
case 103:
//Right bottom
return CGRectMake(292.66666666666674, 700.0, 101.33333333333331, 20)
case 104:
//Left bottom
return CGRectMake(19.999999999999993, 700.0, 90.333333333333329, 20)
case 105:
//Left CenterY
return CGRectMake(20, 358, 96, 20)
case 106:
//CenterX Top
return CGRectMake(160, 36.0, 94, 20)
case 107:
//Right CenterY
return CGRectMake(287, 358, 107, 20)
case 108:
//CenterX Bottom
return CGRectMake(145.66666666666669, 700.0, 122.66666666666666, 20)
case 109:
//Center
return CGRectMake(181.33333333333334, 358, 51.333333333333314, 20)
default:
//Left top
return CGRectMake(20, 36.0, 61.666666666666671, 20)
}
}
else if Device.IS_4_7_INCHES() == true {
//4.7 inch
switch tag {
case 102:
//Right top
return CGRectMake(286.5, 36, 72.5, 20)
case 103:
//Right bottom
return CGRectMake(257.5, 631, 101.5, 20)
case 104:
//Left bottom
return CGRectMake(16, 631, 90.5, 20)
case 105:
//Left CenterY
return CGRectMake(16, 323.5, 96, 20)
case 106:
//CenterX Top
return CGRectMake(140.5, 36, 94, 20)
case 107:
//Right CenterY
return CGRectMake(252, 323.5, 107, 20)
case 108:
//CenterX Bottom
return CGRectMake(126.5, 631, 122.5, 20)
case 109:
//Center
return CGRectMake(162, 323.5, 51.5, 20)
default:
//Left top
return CGRectMake(16, 36, 61.5, 20)
}
}
else if Device.IS_4_INCHES() == true {
//iPhone 4 inch
switch tag {
case 102:
//Right top
return CGRectMake(231.5, 36, 72.5, 20)
case 103:
//Right bottom
return CGRectMake(202.5, 532, 101.5, 20)
case 104:
//Left bottom
return CGRectMake(16, 532, 90.5, 20)
case 105:
//Left CenterY
return CGRectMake(16, 274, 96, 20)
case 106:
//CenterX Top
return CGRectMake(113, 36, 94, 20)
case 107:
//Right CenterY
return CGRectMake(197, 274, 107, 20)
case 108:
//CenterX Bottom
return CGRectMake(99, 532, 122.5, 20)
case 109:
//Center
return CGRectMake(134.5, 274, 51.5, 20)
default:
//Left top
return CGRectMake(16, 36, 61.5, 20)
}
}
else {
//iPhone 3.5 inch
switch tag {
case 102:
//Right top
return CGRectMake(231.5, 36, 72.5, 20)
case 103:
//Right bottom
return CGRectMake(202.5, 444.0, 101.5, 20.0)
case 104:
//Left bottom
return CGRectMake(16.0, 444.0, 90.5, 20.0)
case 105:
//Left CenterY
return CGRectMake(16.0, 230.0, 96.0, 20.0)
case 106:
//CenterX Top
return CGRectMake(113, 36, 94, 20)
case 107:
//Right CenterY
return CGRectMake(197.0, 230.0, 107.0, 20.0)
case 108:
//CenterX Bottom
return CGRectMake(99.0, 444.0, 122.5, 20.0)
case 109:
//Center
return CGRectMake(134.5, 230.0, 51.5, 20.0)
default:
//Left top
return CGRectMake(16, 36, 61.5, 20)
}
}
}
func createAlignmentLabelRect(tag:Int) -> CGRect {
if Device.IS_12_9_INCHES() == true {
//12.9 inch
switch tag {
case 102:
//2:Top Edges
return CGRectMake(126.5, 40.0, 94.5, 20.0)
case 103:
//3:Leading + Trailing Edges
return CGRectMake(20.0, 130.0, 201.0, 20.0)
case 104:
//4:Bottom Edges
return CGRectMake(880.5, 70.0, 123.5, 20.0)
case 105:
//5:CenterX
return CGRectMake(136.0, 190.0, 76.0, 50.0)
case 106:
//6:CenterY
return CGRectMake(20.0, 205.0, 76.5, 20.0)
case 107:
//7:Baseline
return CGRectMake(935.0, 220.0, 79.0, 20.0)
default:
//1:Left top
return CGRectMake(20.0, 40.0, 76.0, 50.0)
}
}
else if Device.isPad() == true {
//7.9 inch or 9.7 inch
switch tag {
case 102:
//2:Top Edges
return CGRectMake(126.0, 40.0, 95.0, 20.0)
case 103:
//3:Leading + Trailing Edges
return CGRectMake(20.0, 130.0, 201.0, 20.0)
case 104:
//4:Bottom Edges
return CGRectMake(624.0, 70.0, 124.0, 20.0)
case 105:
//5:CenterX
return CGRectMake(136.0, 190.0, 76.0, 50.0)
case 106:
//6:CenterY
return CGRectMake(20.0, 205.0, 77.0, 20.0)
case 107:
//7:Baseline
return CGRectMake(679.0, 220.0, 79.0, 20.0)
default:
//1:Left top
return CGRectMake(20.0, 40.0, 76.0, 50.0)
}
}
else if Device.IS_5_5_INCHES() == true {
//5.5 inch
switch tag {
case 102:
//2:Top Edges
return CGRectMake(126.33333333333331, 36.0, 94.666666666666671, 20.0)
case 103:
//3:Leading + Trailing Edges
return CGRectMake(20.0, 126.0, 201.0, 20.0)
case 104:
//4:Bottom Edges
return CGRectMake(270.66666666666674, 66.0, 123.33333333333331, 20.0)
case 105:
//5:CenterX
return CGRectMake(136.0, 186.0, 75.666666666666657, 50.0)
case 106:
//6:CenterY
return CGRectMake(20.0, 201.0, 76.333333333333329, 20.0)
case 107:
//7:Baseline
return CGRectMake(325.0, 216.0, 79.0, 20.0)
default:
//1:Left top
return CGRectMake(20.0, 36.0, 75.666666666666671, 50.0)
}
}
else if Device.IS_4_7_INCHES() == true {
//iPhone 4.7 inch
switch tag {
case 102:
//2:Top Edges
return CGRectMake(122.5, 36, 94.5, 20)
case 103:
//3:Leading + Trailing Edges
return CGRectMake(16, 126, 201, 20)
case 104:
//4:Bottom Edges
return CGRectMake(235.5, 66, 123.5, 20)
case 105:
//5:CenterX
return CGRectMake(132, 186, 76, 50.0)
case 106:
//6:CenterY
return CGRectMake(16.0, 201.0, 76.5, 20.0)
case 107:
//7:Baseline
return CGRectMake(290.0, 216.0, 79.0, 20.0)
default:
//1:Left top
return CGRectMake(16.0, 36.0, 76.0, 50.0)
}
}
else if Device.IS_4_INCHES() == true {
//iPhone 4 inch
switch tag {
case 102:
//2:Top Edges
return CGRectMake(122.5, 36, 94.5, 20)
case 103:
//3:Leading + Trailing Edges
return CGRectMake(16, 126, 201, 20)
case 104:
//4:Bottom Edges
return CGRectMake(180.5, 66.0, 123.5, 20.0)
case 105:
//5:CenterX
return CGRectMake(132, 186, 76, 50.0)
case 106:
//6:CenterY
return CGRectMake(16.0, 201.0, 76.5, 20.0)
case 107:
//7:Baseline
return CGRectMake(235.0, 216.0, 79.0, 20.0)
default:
//1:Left top
return CGRectMake(16.0, 36.0, 76.0, 50.0)
}
}
else {
//iPhone 3.5 inch
switch tag {
case 102:
//2:Top Edges
return CGRectMake(122.5, 36, 94.5, 20)
case 103:
//3:Leading + Trailing Edges
return CGRectMake(16, 126, 201, 20)
case 104:
//4:Bottom Edges
return CGRectMake(180.5, 66.0, 123.5, 20.0)
case 105:
//5:CenterX
return CGRectMake(132, 186, 76, 50.0)
case 106:
//6:CenterY
return CGRectMake(16.0, 201.0, 76.5, 20.0)
case 107:
//7:Baseline
return CGRectMake(235.0, 216.0, 79.0, 20.0)
default:
//1:Left top
return CGRectMake(16.0, 36.0, 76.0, 50.0)
}
}
}
func createRatioLabelRect(tag:Int) -> CGRect {
if Device.isPad() == true {
//iPad
switch tag {
case 102:
//2:View 2
return CGRectMake(110, 40, 140, 210)
default:
//1:View 1
return CGRectMake(20, 40, 70, 70)
}
}
else if Device.IS_5_5_INCHES() == true {
//5.5 inch
switch tag {
case 102:
//2:View 2
return CGRectMake(110, 36, 140, 210)
default:
//1:View 1
return CGRectMake(20, 36, 70, 70)
}
}
else {
//4.7 inch, 4 inch, 3.5 inch
switch tag {
case 102:
//2:View 2
return CGRectMake(106, 36, 140, 210)
default:
//1:View 1
return CGRectMake(16, 36, 70, 70)
}
}
}
//MARK: - PinViewControllers
func testAutolayout_Pin_Storyboard() {
let viewController = storyboard.instantiateViewControllerWithIdentifier("pinViewController1")
UIApplication.sharedApplication().keyWindow?.rootViewController = viewController
viewController.view.layoutIfNeeded()
for i in minPinLabelTag...maxPinLabelTag {
let subView = viewController.view.viewWithTag(i)
let rect1 = (subView?.frame)!
let rect2 = self.createPinLabelRect((subView?.tag)!)
let result = CGRectEqualToRect(rect1, rect2)
if result == false {
print("\(rect1) - \(rect2)")
}
XCTAssertTrue(result, "[\(i) tag] Label '\(subView)' is wrong position")
}
}
func testAutolayout_Pin_LayoutConstraint() {
let viewController = storyboard.instantiateViewControllerWithIdentifier("pinViewController2")
UIApplication.sharedApplication().keyWindow?.rootViewController = viewController
viewController.view.layoutIfNeeded()
for i in minPinLabelTag...maxPinLabelTag {
let subView = viewController.view.viewWithTag(i)
let rect1 = (subView?.frame)!
let rect2 = self.createPinLabelRect((subView?.tag)!)
let result = CGRectEqualToRect(rect1, rect2)
if result == false {
print("\(rect1) - \(rect2)")
}
XCTAssertTrue(result, "Label with tag \(i) is wrong position")
}
}
func testAutolayout_Pin_VisualFormatLanguage() {
let viewController = storyboard.instantiateViewControllerWithIdentifier("pinViewController3")
UIApplication.sharedApplication().keyWindow?.rootViewController = viewController
viewController.view.layoutIfNeeded()
for i in minPinLabelTag...maxPinLabelTag {
let subView = viewController.view.viewWithTag(i)
let rect1 = (subView?.frame)!
let rect2 = self.createPinLabelRect((subView?.tag)!)
let result = CGRectEqualToRect(rect1, rect2)
if result == false {
print("\(rect1) - \(rect2)")
}
XCTAssertTrue(result, "Label with tag \(i) is wrong position")
}
}
func testAutolayout_Pin_LayoutAnchor() {
let viewController = storyboard.instantiateViewControllerWithIdentifier("pinViewController4")
UIApplication.sharedApplication().keyWindow?.rootViewController = viewController
viewController.view.layoutIfNeeded()
for i in minPinLabelTag...maxPinLabelTag {
let subView = viewController.view.viewWithTag(i)
let rect1 = (subView?.frame)!
let rect2 = self.createPinLabelRect((subView?.tag)!)
let result = CGRectEqualToRect(rect1, rect2)
if result == false {
print("\(rect1) - \(rect2)")
}
XCTAssertTrue(result, "Label with tag \(i) is wrong position")
}
}
//MARK: - AlignmentViewControllers
func testAutolayout_Alignment_Storyboard() {
let viewController = storyboard.instantiateViewControllerWithIdentifier("alignmentViewController1")
UIApplication.sharedApplication().keyWindow?.rootViewController = viewController
viewController.view.layoutIfNeeded()
for i in minAlignmentLabelTag...maxAlignmentLabelTag {
let subView = viewController.view.viewWithTag(i)
let rect1 = (subView?.frame)!
let rect2 = self.createAlignmentLabelRect((subView?.tag)!)
let result = CGRectEqualToRect(rect1, rect2)
if result == false {
print("\(rect1) - \(rect2)")
}
XCTAssertTrue(result, "Label with tag \(i) is wrong position")
}
}
func testAutolayout_Alignment_LayoutConstraint() {
let viewController = storyboard.instantiateViewControllerWithIdentifier("alignmentViewController2")
UIApplication.sharedApplication().keyWindow?.rootViewController = viewController
viewController.view.layoutIfNeeded()
for i in minAlignmentLabelTag...maxAlignmentLabelTag {
let subView = viewController.view.viewWithTag(i)
let rect1 = (subView?.frame)!
let rect2 = self.createAlignmentLabelRect((subView?.tag)!)
let result = CGRectEqualToRect(rect1, rect2)
if result == false {
print("\(rect1) - \(rect2)")
}
XCTAssertTrue(result, "Label with tag \(i) is wrong position")
}
}
func testAutolayout_Alignment_VisualFormatLanguage() {
let viewController = storyboard.instantiateViewControllerWithIdentifier("alignmentViewController3")
UIApplication.sharedApplication().keyWindow?.rootViewController = viewController
viewController.view.layoutIfNeeded()
for i in minAlignmentLabelTag...maxAlignmentLabelTag {
let subView = viewController.view.viewWithTag(i)
let rect1 = (subView?.frame)!
let rect2 = self.createAlignmentLabelRect((subView?.tag)!)
let result = CGRectEqualToRect(rect1, rect2)
if result == false {
print("\(rect1) - \(rect2)")
}
XCTAssertTrue(result, "Label with tag \(i) is wrong position")
}
}
func testAutolayout_Alignment_LayoutAnchor() {
let viewController = storyboard.instantiateViewControllerWithIdentifier("alignmentViewController4")
UIApplication.sharedApplication().keyWindow?.rootViewController = viewController
viewController.view.layoutIfNeeded()
for i in minAlignmentLabelTag...maxAlignmentLabelTag {
let subView = viewController.view.viewWithTag(i)
let rect1 = (subView?.frame)!
let rect2 = self.createAlignmentLabelRect((subView?.tag)!)
let result = CGRectEqualToRect(rect1, rect2)
if result == false {
print("\(rect1) - \(rect2)")
}
XCTAssertTrue(result, "Label with tag \(i) is wrong position")
}
}
//MARK: - RatioViewControllers
func testAutolayout_Ratio_Storyboard() {
let viewController = storyboard.instantiateViewControllerWithIdentifier("ratioViewController1")
UIApplication.sharedApplication().keyWindow?.rootViewController = viewController
viewController.view.layoutIfNeeded()
for i in 101...102 {
let subView = viewController.view.viewWithTag(i)
let rect1 = (subView?.frame)!
let rect2 = self.createRatioLabelRect((subView?.tag)!)
let result = CGRectEqualToRect(rect1, rect2)
if result == false {
print("\(rect1) - \(rect2)")
}
XCTAssertTrue(result, "Label with tag \(i) is wrong position")
}
}
func testAutolayout_Ratio_LayoutConstraint() {
let viewController = storyboard.instantiateViewControllerWithIdentifier("ratioViewController2")
UIApplication.sharedApplication().keyWindow?.rootViewController = viewController
viewController.view.layoutIfNeeded()
for i in 101...102 {
let subView = viewController.view.viewWithTag(i)
let rect1 = (subView?.frame)!
let rect2 = self.createRatioLabelRect((subView?.tag)!)
let result = CGRectEqualToRect(rect1, rect2)
if result == false {
print("\(rect1) - \(rect2)")
}
XCTAssertTrue(result, "Label with tag \(i) is wrong position")
}
}
func testAutolayout_Ratio_LayoutAnchor() {
let viewController = storyboard.instantiateViewControllerWithIdentifier("ratioViewController3")
UIApplication.sharedApplication().keyWindow?.rootViewController = viewController
viewController.view.layoutIfNeeded()
for i in 101...102 {
let subView = viewController.view.viewWithTag(i)
let rect1 = (subView?.frame)!
let rect2 = self.createRatioLabelRect((subView?.tag)!)
let result = CGRectEqualToRect(rect1, rect2)
if result == false {
print("\(rect1) - \(rect2)")
}
XCTAssertTrue(result, "Label with tag \(i) is wrong position")
}
}
}
| mit | 7ef3f26cbb0e61761261aef8d80cda25 | 36.079077 | 134 | 0.500511 | 4.598897 | false | false | false | false |
jakarmy/swift-summary | The Swift Summary Book.playground/Pages/07 Closures.xcplaygroundpage/Contents.swift | 1 | 3730 | /*:
[Previous](@previous) | [Next](@next)
****
Copyright (c) 2016 Juan Antonio Karmy.
Licensed under MIT License
Official Apple documentation available at [Swift Language Reference](https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/)
See Juan Antonio Karmy - [karmy.co](http://karmy.co) | [@jkarmy](http://twitter.com/jkarmy)
****
*/
/*:
# CLOSURES
*/
/*:
## INLINE CLOSURES
*/
var array = ["John", "Tim", "Steve"]
var reversed = array.sorted(by: {(s1: String, s2: String) -> Bool in return s1 > s2})
//: Using type inference, we can omit the params and return types. This is true when passing closures as params to a function.
reversed = array.sorted(by: {s1, s2 in return s1 > s2})
//: In case of single-expression closures, the return value is implicit, thus the return expression can be omitted.
reversed = array.sorted(by: {s1, s2 in s1 == s2})
/*: In the previous examples, the names of the closure's params were explicit.
You can use the $X variables to refer to params for the closure
This eliminates the need for the first params list, which makes the body the only relevant part.
*/
reversed = array.sorted(by: {$0 == $1})
//: We can even take this to an extreme. String defines its own implementation for the ">" operator, which is really all the closure does.
reversed = array.sorted(by: >)
//: ## TRAILING CLOSURES
func someFunctionThatTakesAClosure(closure: () -> ()) {
// function body goes here
}
/*:
Closures which are too long to be defined inline.
Here's how you call this function without using a trailing closure:
*/
someFunctionThatTakesAClosure(closure: {
// closure's body goes here
})
//: Here's how you call this function with a trailing closure instead:
someFunctionThatTakesAClosure() {
// trailing closure's body goes here
}
//Sorting function with inline closure:
array.sort() {$0 == $1}
//: **Note**: In case the function doesn't take any params other than a trailing closure, there's no need for parenthesis.
let digitNames = [
0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
]
let numbers = [16, 58, 510]
let stringsArray = numbers.map {
(number) -> String in
var number = number
var output = ""
while number > 0 {
output = digitNames[number % 10]! + output //Note how the optional value returned from the dic subscript is force-unwrapped, since a value is guaranteed.
number /= 10
}
return output
}
//: ## AUTOCLOSURES
/*:
An autoclosure is a closure that is automatically created to wrap an expression that’s being passed as an argument to a function.
It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it.
This syntactic convenience lets you omit braces around a function’s parameter by writing a normal expression instead of an explicit closure.
An autoclosure lets you delay evaluation, because the code inside isn’t run until you call the closure.
*/
var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
let customerProvider = { customersInLine.remove(at: 0) }
//: Traditional way
func serve(customer customerProvider: () -> String) {
print("Now serving \(customerProvider())!") //The closure is called here!
}
serve(customer: { customersInLine.remove(at: 0) } )
//: **@autoclosure** way
func serve(customer customerProvider: @autoclosure () -> String) {
print("Now serving \(customerProvider())!")
}
serve(customer: customersInLine.remove(at: 0)) //We are not required to use the curly braces, since the code will be wrapped in a closure thanks to @autoclosure
| mit | e985aad1c40572027783480e31d78b3e | 33.110092 | 169 | 0.700646 | 3.844881 | false | false | false | false |
ancilmarshall/iOS | LocationMaps/CLLocationManagerDemoSwift/CLLocationManagerDemoSwift/ViewController.swift | 1 | 1815 | //
// ViewController.swift
// CLLocationManagerDemoSwift
//
// Created by Ancil on 10/4/15.
// Copyright © 2015 Ancil Marshall. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController {
@IBOutlet weak var lonLabel:UILabel!
@IBOutlet weak var latLabel:UILabel!
@IBOutlet weak var markLabel:UILabel!
let locationManager = CLLocationManager()
override func viewDidLoad() {
super.viewDidLoad()
if !CLLocationManager.locationServicesEnabled() {
return
}
locationManager.delegate = self
beginLocationUpdatesIfPossible()
}
func beginLocationUpdatesIfPossible() {
switch CLLocationManager.authorizationStatus() {
case .Denied, .Restricted:
return
case .NotDetermined:
locationManager.requestAlwaysAuthorization()
return
case .AuthorizedAlways, .AuthorizedWhenInUse:
break
}
locationManager.startUpdatingLocation()
}
}
extension ViewController: CLLocationManagerDelegate {
func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
beginLocationUpdatesIfPossible()
}
func locationManager(manager: CLLocationManager,
didFailWithError error: NSError){
print("Location manager failed with error = \(error)")
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.first!
lonLabel.text = "\(location.coordinate.longitude)"
latLabel.text = "\(location.coordinate.latitude)"
}
}
| gpl-2.0 | 484d7e9173780464cd41cf2de46b7944 | 24.194444 | 114 | 0.638368 | 6.046667 | false | false | false | false |
hq7781/MoneyBook | Pods/ChartsRealm/ChartsRealm/Classes/Data/RealmLineScatterCandleRadarDataSet.swift | 2 | 1949 | //
// RealmLineScatterCandleRadarDataSet.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import Charts
import Realm
import Realm.Dynamic
open class RealmLineScatterCandleRadarDataSet: RealmBarLineScatterCandleBubbleDataSet, ILineScatterCandleRadarChartDataSet
{
// MARK: - Data functions and accessors
// MARK: - Styling functions and accessors
/// Enables / disables the horizontal highlight-indicator. If disabled, the indicator is not drawn.
open var drawHorizontalHighlightIndicatorEnabled = true
/// Enables / disables the vertical highlight-indicator. If disabled, the indicator is not drawn.
open var drawVerticalHighlightIndicatorEnabled = true
/// - returns: `true` if horizontal highlight indicator lines are enabled (drawn)
open var isHorizontalHighlightIndicatorEnabled: Bool { return drawHorizontalHighlightIndicatorEnabled }
/// - returns: `true` if vertical highlight indicator lines are enabled (drawn)
open var isVerticalHighlightIndicatorEnabled: Bool { return drawVerticalHighlightIndicatorEnabled }
/// Enables / disables both vertical and horizontal highlight-indicators.
/// :param: enabled
open func setDrawHighlightIndicators(_ enabled: Bool)
{
drawHorizontalHighlightIndicatorEnabled = enabled
drawVerticalHighlightIndicatorEnabled = enabled
}
// MARK: NSCopying
open override func copyWithZone(_ zone: NSZone?) -> AnyObject
{
let copy = super.copyWithZone(zone) as! RealmLineScatterCandleRadarDataSet
copy.drawHorizontalHighlightIndicatorEnabled = drawHorizontalHighlightIndicatorEnabled
copy.drawVerticalHighlightIndicatorEnabled = drawVerticalHighlightIndicatorEnabled
return copy
}
}
| mit | 83824a3bb5fe6fe5bad6415ed7aa0d72 | 35.773585 | 122 | 0.749615 | 5.835329 | false | false | false | false |
swift-server/http | Sources/HTTP/HTTPResponse.swift | 1 | 16809 | // This source file is part of the Swift.org Server APIs open source project
//
// Copyright (c) 2017 Swift Server API project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
//
import Foundation
import Dispatch
/// A structure representing the headers for a HTTP response, without the body of the response.
public struct HTTPResponse {
/// HTTP response version
public var httpVersion: HTTPVersion
/// HTTP response status
public var status: HTTPResponseStatus
/// HTTP response headers
public var headers: HTTPHeaders
}
/// HTTPResponseWriter provides functions to create an HTTP response
public protocol HTTPResponseWriter: class {
/// Writer function to create the headers for an HTTP response
/// - Parameter status: The status code to include in the HTTP response
/// - Parameter headers: The HTTP headers to include in the HTTP response
/// - Parameter completion: Closure that is called when the HTTP headers have been written to the HTTP respose
func writeHeader(status: HTTPResponseStatus, headers: HTTPHeaders, completion: @escaping (Result) -> Void)
/// Writer function to write a trailer header as part of the HTTP response
/// - Parameter trailers: The trailers to write as part of the HTTP response
/// - Parameter completion: Closure that is called when the trailers has been written to the HTTP response
/// This is not currently implemented
func writeTrailer(_ trailers: HTTPHeaders, completion: @escaping (Result) -> Void)
/// Writer function to write data to the body of the HTTP response
/// - Parameter data: The data to write as part of the HTTP response
/// - Parameter completion: Closure that is called when the data has been written to the HTTP response
func writeBody(_ data: UnsafeHTTPResponseBody, completion: @escaping (Result) -> Void)
/// Writer function to complete the HTTP response
/// - Parameter completion: Closure that is called when the HTTP response has been completed
func done(completion: @escaping (Result) -> Void)
/// abort: Abort the HTTP response
func abort()
}
/// Convenience methods for HTTP response writer.
extension HTTPResponseWriter {
/// Convenience function to write the headers for an HTTP response without a completion handler
/// - See: `writeHeader(status:headers:completion:)`
public func writeHeader(status: HTTPResponseStatus, headers: HTTPHeaders) {
writeHeader(status: status, headers: headers) { _ in }
}
/// Convenience function to write a HTTP response with no headers or completion handler
/// - See: `writeHeader(status:headers:completion:)`
public func writeHeader(status: HTTPResponseStatus) {
writeHeader(status: status, headers: [:])
}
/// Convenience function to write a trailer header as part of the HTTP response without a completion handler
/// - See: `writeTrailer(_:completion:)`
public func writeTrailer(_ trailers: HTTPHeaders) {
writeTrailer(trailers) { _ in }
}
/// Convenience function for writing `data` to the body of the HTTP response without a completion handler.
/// - See: writeBody(_:completion:)
public func writeBody(_ data: UnsafeHTTPResponseBody) {
return writeBody(data) { _ in }
}
/// Convenience function to complete the HTTP response without a completion handler.
/// - See: done(completion:)
public func done() {
done { _ in }
}
}
/// The response status for the HTTP response
/// - See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml for more information
public struct HTTPResponseStatus: Equatable, CustomStringConvertible, ExpressibleByIntegerLiteral {
/// The status code, eg. 200 or 404
public let code: Int
/// The reason phrase for the status code
public let reasonPhrase: String
/// Creates an HTTP response status
/// - Parameter code: The status code used for the response status
/// - Parameter reasonPhrase: The reason phrase to use for the response status
public init(code: Int, reasonPhrase: String) {
self.code = code
self.reasonPhrase = reasonPhrase
}
/// Creates an HTTP response status
/// The reason phrase is added for the status code, or "http_(code)" if the code is not well known
/// - Parameter code: The status code used for the response status
public init(code: Int) {
self.init(code: code, reasonPhrase: HTTPResponseStatus.defaultReasonPhrase(forCode: code))
}
/// :nodoc:
public init(integerLiteral: Int) {
self.init(code: integerLiteral)
}
/* all the codes from http://www.iana.org/assignments/http-status-codes */
/// 100 Continue
public static let `continue` = HTTPResponseStatus(code: 100)
/// 101 Switching Protocols
public static let switchingProtocols = HTTPResponseStatus(code: 101)
/// 200 OK
public static let ok = HTTPResponseStatus(code: 200)
/// 201 Created
public static let created = HTTPResponseStatus(code: 201)
/// 202 Accepted
public static let accepted = HTTPResponseStatus(code: 202)
/// 203 Non-Authoritative Information
public static let nonAuthoritativeInformation = HTTPResponseStatus(code: 203)
/// 204 No Content
public static let noContent = HTTPResponseStatus(code: 204)
/// 205 Reset Content
public static let resetContent = HTTPResponseStatus(code: 205)
/// 206 Partial Content
public static let partialContent = HTTPResponseStatus(code: 206)
/// 207 Multi-Status
public static let multiStatus = HTTPResponseStatus(code: 207)
/// 208 Already Reported
public static let alreadyReported = HTTPResponseStatus(code: 208)
/// 226 IM Used
public static let imUsed = HTTPResponseStatus(code: 226)
/// 300 Multiple Choices
public static let multipleChoices = HTTPResponseStatus(code: 300)
/// 301 Moved Permanently
public static let movedPermanently = HTTPResponseStatus(code: 301)
/// 302 Found
public static let found = HTTPResponseStatus(code: 302)
/// 303 See Other
public static let seeOther = HTTPResponseStatus(code: 303)
/// 304 Not Modified
public static let notModified = HTTPResponseStatus(code: 304)
/// 305 Use Proxy
public static let useProxy = HTTPResponseStatus(code: 305)
/// 307 Temporary Redirect
public static let temporaryRedirect = HTTPResponseStatus(code: 307)
/// 308 Permanent Redirect
public static let permanentRedirect = HTTPResponseStatus(code: 308)
/// 400 Bad Request
public static let badRequest = HTTPResponseStatus(code: 400)
/// 401 Unauthorized
public static let unauthorized = HTTPResponseStatus(code: 401)
/// 402 Payment Required
public static let paymentRequired = HTTPResponseStatus(code: 402)
/// 403 Forbidden
public static let forbidden = HTTPResponseStatus(code: 403)
/// 404 Not Found
public static let notFound = HTTPResponseStatus(code: 404)
/// 405 Method Not Allowed
public static let methodNotAllowed = HTTPResponseStatus(code: 405)
/// 406 Not Acceptable
public static let notAcceptable = HTTPResponseStatus(code: 406)
/// 407 Proxy Authentication Required
public static let proxyAuthenticationRequired = HTTPResponseStatus(code: 407)
/// 408 Request Timeout
public static let requestTimeout = HTTPResponseStatus(code: 408)
/// 409 Conflict
public static let conflict = HTTPResponseStatus(code: 409)
/// 410 Gone
public static let gone = HTTPResponseStatus(code: 410)
/// 411 Length Required
public static let lengthRequired = HTTPResponseStatus(code: 411)
/// 412 Precondition Failed
public static let preconditionFailed = HTTPResponseStatus(code: 412)
/// 413 Payload Too Large
public static let payloadTooLarge = HTTPResponseStatus(code: 413)
/// 414 URI Too Long
public static let uriTooLong = HTTPResponseStatus(code: 414)
/// 415 Unsupported Media Type
public static let unsupportedMediaType = HTTPResponseStatus(code: 415)
/// 416 Range Not Satisfiable
public static let rangeNotSatisfiable = HTTPResponseStatus(code: 416)
/// 417 Expectation Failed
public static let expectationFailed = HTTPResponseStatus(code: 417)
/// 421 Misdirected Request
public static let misdirectedRequest = HTTPResponseStatus(code: 421)
/// 422 Unprocessable Entity
public static let unprocessableEntity = HTTPResponseStatus(code: 422)
/// 423 Locked
public static let locked = HTTPResponseStatus(code: 423)
/// 424 Failed Dependency
public static let failedDependency = HTTPResponseStatus(code: 424)
/// 426 Upgrade Required
public static let upgradeRequired = HTTPResponseStatus(code: 426)
/// 428 Precondition Required
public static let preconditionRequired = HTTPResponseStatus(code: 428)
/// 429 Too Many Requests
public static let tooManyRequests = HTTPResponseStatus(code: 429)
/// 431 Request Header Fields Too Large
public static let requestHeaderFieldsTooLarge = HTTPResponseStatus(code: 431)
/// 451 Unavailable For Legal Reasons
public static let unavailableForLegalReasons = HTTPResponseStatus(code: 451)
/// 500 Internal Server Error
public static let internalServerError = HTTPResponseStatus(code: 500)
/// 501 Not Implemented
public static let notImplemented = HTTPResponseStatus(code: 501)
/// 502 Bad Gateway
public static let badGateway = HTTPResponseStatus(code: 502)
/// 503 Service Unavailable
public static let serviceUnavailable = HTTPResponseStatus(code: 503)
/// 504 Gateway Timeout
public static let gatewayTimeout = HTTPResponseStatus(code: 504)
/// 505 HTTP Version Not Supported
public static let httpVersionNotSupported = HTTPResponseStatus(code: 505)
/// 506 Variant Also Negotiates
public static let variantAlsoNegotiates = HTTPResponseStatus(code: 506)
/// 507 Insufficient Storage
public static let insufficientStorage = HTTPResponseStatus(code: 507)
/// 508 Loop Detected
public static let loopDetected = HTTPResponseStatus(code: 508)
/// 510 Not Extended
public static let notExtended = HTTPResponseStatus(code: 510)
/// 511 Network Authentication Required
public static let networkAuthenticationRequired = HTTPResponseStatus(code: 511)
// swiftlint:disable cyclomatic_complexity switch_case_on_newline
static func defaultReasonPhrase(forCode code: Int) -> String {
switch code {
case 100: return "Continue"
case 101: return "Switching Protocols"
case 200: return "OK"
case 201: return "Created"
case 202: return "Accepted"
case 203: return "Non-Authoritative Information"
case 204: return "No Content"
case 205: return "Reset Content"
case 206: return "Partial Content"
case 207: return "Multi-Status"
case 208: return "Already Reported"
case 226: return "IM Used"
case 300: return "Multiple Choices"
case 301: return "Moved Permanently"
case 302: return "Found"
case 303: return "See Other"
case 304: return "Not Modified"
case 305: return "Use Proxy"
case 307: return "Temporary Redirect"
case 308: return "Permanent Redirect"
case 400: return "Bad Request"
case 401: return "Unauthorized"
case 402: return "Payment Required"
case 403: return "Forbidden"
case 404: return "Not Found"
case 405: return "Method Not Allowed"
case 406: return "Not Acceptable"
case 407: return "Proxy Authentication Required"
case 408: return "Request Timeout"
case 409: return "Conflict"
case 410: return "Gone"
case 411: return "Length Required"
case 412: return "Precondition Failed"
case 413: return "Payload Too Large"
case 414: return "URI Too Long"
case 415: return "Unsupported Media Type"
case 416: return "Range Not Satisfiable"
case 417: return "Expectation Failed"
case 421: return "Misdirected Request"
case 422: return "Unprocessable Entity"
case 423: return "Locked"
case 424: return "Failed Dependency"
case 426: return "Upgrade Required"
case 428: return "Precondition Required"
case 429: return "Too Many Requests"
case 431: return "Request Header Fields Too Large"
case 451: return "Unavailable For Legal Reasons"
case 500: return "Internal Server Error"
case 501: return "Not Implemented"
case 502: return "Bad Gateway"
case 503: return "Service Unavailable"
case 504: return "Gateway Timeout"
case 505: return "HTTP Version Not Supported"
case 506: return "Variant Also Negotiates"
case 507: return "Insufficient Storage"
case 508: return "Loop Detected"
case 510: return "Not Extended"
case 511: return "Network Authentication Required"
default: return "http_\(code)"
}
}
/// :nodoc:
public var description: String {
return "\(code) \(reasonPhrase)"
}
/// - The `Class` representing the class of status code for this response status
public var `class`: Class {
return Class(code: code)
}
/// The class of a `HTTPResponseStatus` code
/// - See: https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml for more information
public enum Class {
/// Informational: the request was received, and is continuing to be processed
case informational
/// Success: the action was successfully received, understood, and accepted
case successful
/// Redirection: further action must be taken in order to complete the request
case redirection
/// Client Error: the request contains bad syntax or cannot be fulfilled
case clientError
/// Server Error: the server failed to fulfill an apparently valid request
case serverError
/// Invalid: the code does not map to a well known status code class
case invalidStatus
init(code: Int) {
switch code {
case 100..<200: self = .informational
case 200..<300: self = .successful
case 300..<400: self = .redirection
case 400..<500: self = .clientError
case 500..<600: self = .serverError
default: self = .invalidStatus
}
}
}
// [RFC2616, section 4.4]
var bodyAllowed: Bool {
switch code {
case 100..<200: return false
case 204: return false
case 304: return false
default: return true
}
}
var suppressedHeaders: [HTTPHeaders.Name] {
if self == .notModified {
return ["Content-Type", "Content-Length", "Transfer-Encoding"]
} else if !bodyAllowed {
return ["Content-Length", "Transfer-Encoding"]
} else {
return []
}
}
/// :nodoc:
public static func == (lhs: HTTPResponseStatus, rhs: HTTPResponseStatus) -> Bool {
return lhs.code == rhs.code
}
}
/// :nodoc:
public protocol UnsafeHTTPResponseBody {
func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R
}
/// :nodoc:
extension UnsafeRawBufferPointer: UnsafeHTTPResponseBody {
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try body(self)
}
}
/// :nodoc:
public protocol HTTPResponseBody: UnsafeHTTPResponseBody {}
extension Data: HTTPResponseBody {
/// :nodoc:
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try withUnsafeBytes { try body(UnsafeRawBufferPointer(start: $0, count: count)) }
}
}
extension DispatchData: HTTPResponseBody {
/// :nodoc:
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try withUnsafeBytes { try body(UnsafeRawBufferPointer(start: $0, count: count)) }
}
}
extension String: HTTPResponseBody {
/// :nodoc:
public func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R {
return try ContiguousArray(utf8).withUnsafeBytes(body)
}
}
| apache-2.0 | c01e2a81c2394451b25ab863a98629f8 | 41.98977 | 114 | 0.676483 | 4.919227 | false | false | false | false |
RayTao/CoreAnimation_Collection | CoreAnimation_Collection/TransformController.swift | 1 | 14791 | //
// TransformController.swift
// CoreAnimation_Collection
//
// Created by ray on 16/1/6.
// Copyright © 2016年 ray. All rights reserved.
//
import UIKit
import GLKit
class AffineTransformController: UIViewController {
let layerView = UIImageView.init(image: R.image.snowman())
let transformSegment = UISegmentedControl.init(items: ["rotation45","combineTransform","MakeShear"])
override func viewDidLoad() {
super.viewDidLoad()
let imageSize = layerView.image?.size
layerView.backgroundColor = UIColor.white
layerView.frame = CGRect(x: 50, y: 50, width: (imageSize?.width)!, height: (imageSize?.height)!)
self.view.addSubview(layerView)
transformSegment.center = CGPoint(x: self.view.center.x, y: self.view.frame.maxY - 50)
transformSegment.addTarget(self, action: #selector(AffineTransformController.changeTransform(_:)), for: .valueChanged)
self.view.addSubview(transformSegment)
transformSegment.selectedSegmentIndex = 0
changeTransform(transformSegment)
}
func changeTransform(_ segment: UISegmentedControl) {
let selecedIndex = segment.selectedSegmentIndex
let title = segment.titleForSegment(at: selecedIndex)!
var transform = CGAffineTransform.identity;
if (title.hasPrefix("rotation45")) {
transform = rotation45Transform()
} else if (title.hasPrefix("combineTransform")){
transform = combineTransform()
} else if (title.hasPrefix("CGAffineTrans")){
transform = CGAffineTransformMakeShear(1.0, y: 0.0);
}
//apply transform to layer
self.layerView.layer.setAffineTransform(transform);
}
func rotation45Transform() -> CGAffineTransform {
//rotate the layer 45 degrees
return CGAffineTransform(rotationAngle: CGFloat(Double.pi / 4))
}
func combineTransform() -> CGAffineTransform {
var transform = CGAffineTransform.identity;
//scale by 50%
transform = transform.scaledBy(x: 0.5, y: 0.5);
//rotate by 30 degrees
transform = transform.rotated(by: CGFloat( Double.pi / 180.0 * 30.0));
//translate by 200 points
transform = transform.translatedBy(x: 200, y: 0);
return transform
}
func CGAffineTransformMakeShear(_ x: CGFloat,y: CGFloat) -> CGAffineTransform {
var transform = CGAffineTransform.identity;
transform.c = -x;
transform.b = y;
return transform;
}
}
/// 设置M34实现透视投影
class CATransform3DM34Controller: UIViewController {
let layerView = UIImageView.init(image: R.image.snowman())
override func viewDidLoad() {
super.viewDidLoad()
let imageSize = layerView.image?.size
layerView.backgroundColor = UIColor.white
layerView.frame = CGRect(x: 50, y: 90, width: (imageSize?.width)!, height: (imageSize?.height)!)
self.view.addSubview(layerView)
let transformSegment = UISegmentedControl.init(items: ["透视off","透视on"])
transformSegment.center = CGPoint(x: self.view.center.x, y: self.view.frame.maxY - 50)
transformSegment.addTarget(self, action: #selector(CATransform3DM34Controller.changeSwitch(_:)), for: .valueChanged)
self.view.addSubview(transformSegment)
}
func changeSwitch(_ segment: UISegmentedControl) {
var transform = CATransform3DIdentity;
if (segment.selectedSegmentIndex != 0) {
transform.m34 = -1.0 / 500.0
}
//rotate by 45 degrees along the Y axis
transform = CATransform3DRotate(transform, CGFloat(Double.pi / 4), 0, 1, 0);
self.layerView.layer.transform = transform;
}
}
/// 设置sublayertransform对子视图、图层做变换,保证所有图层公用一个灭点
class SublayerTransformController: UIViewController {
let containerView = UIView()
let layerView1 = UIImageView.init(frame: CGRect(x: 20, y: 65, width: 140, height: 140))
let layerView2 = UIImageView.init(frame: CGRect(x: 165, y: 65, width: 140, height: 140))
override func viewDidLoad() {
super.viewDidLoad()
containerView.frame = self.view.bounds
layerView1.image = R.image.snowman()
layerView2.image = R.image.snowman()
layerView1.backgroundColor = UIColor.white
layerView2.backgroundColor = layerView1.backgroundColor
layerView1.center.y = containerView.center.y
layerView2.center.y = containerView.center.y
containerView.addSubview(layerView1)
containerView.addSubview(layerView2)
self.view.addSubview(self.containerView)
//apply perspective transform to container
var perspective = CATransform3DIdentity;
perspective.m34 = -1.0 / 500.0;
self.containerView.layer.sublayerTransform = perspective;
//rotate layerView1 by 45 degrees along the Y axis
let transform1 = CATransform3DMakeRotation(CGFloat(Double.pi / 4), 0, 1, 0);
self.layerView1.layer.transform = transform1;
//rotate layerView2 by 45 degrees along the Y axis
let transform2 = CATransform3DMakeRotation(-CGFloat(Double.pi / 4), 0, 1, 0);
self.layerView2.layer.transform = transform2;
}
}
/// DoubleSided 决定视图是否需要绘制背面
class DoubleSidedController: UIViewController {
let layerView = UIImageView.init(image: R.image.snowman())
let transformSegment = UISegmentedControl.init(items: ["DoubleSided off","DoubleSided on"])
override func viewDidLoad() {
super.viewDidLoad()
let imageSize = layerView.image?.size
layerView.backgroundColor = UIColor.white
layerView.frame = CGRect(x: 50, y: 90, width: (imageSize?.width)!, height: (imageSize?.height)!)
self.view.addSubview(layerView)
transformSegment.center = CGPoint(x: self.view.center.x, y: self.view.frame.maxY - 50)
transformSegment.addTarget(self, action: #selector(CATransform3DM34Controller.changeSwitch(_:)), for: .valueChanged)
self.view.addSubview(transformSegment)
}
func changeSwitch(_ segment: UISegmentedControl) {
var transform = CATransform3DIdentity;
if (segment.selectedSegmentIndex != 0) {
self.layerView.layer.isDoubleSided = true
} else {
self.layerView.layer.isDoubleSided = false
}
//rotate by 45 degrees along the Y axis
transform = CATransform3DRotate(transform, CGFloat(Double.pi), 0, 1, 0);
self.layerView.layer.transform = transform;
}
}
/// 通过旋转展现扁平化特性
class flattenController: UIViewController {
let outerView = UIView.init(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
let innerView = UIView.init(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
override func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(outerView)
outerView.addSubview(innerView)
outerView.backgroundColor = UIColor.white
innerView.backgroundColor = UIColor.red
outerView.center = self.view.center
let transformSegment = UISegmentedControl.init(items: ["RotateZ ","RotateY","RotateX","Normal"])
transformSegment.center = CGPoint(x: self.view.center.x, y: self.view.frame.maxY - 50)
transformSegment.addTarget(self, action: #selector(CATransform3DM34Controller.changeSwitch(_:)), for: .valueChanged)
self.view.addSubview(transformSegment)
}
func changeSwitch(_ segment: UISegmentedControl) {
let selectedIndex = segment.selectedSegmentIndex
var outer = CATransform3DIdentity;
var inner = CATransform3DIdentity;
if selectedIndex == 0 {
outer = CATransform3DRotate(outer,CGFloat(Double.pi / 4), 0, 0, 1);
inner = CATransform3DRotate(inner,-CGFloat(Double.pi / 4), 0, 0, 1);
} else if selectedIndex == 1 {
outer.m34 = -1.0 / 500.0;
inner.m34 = -1.0 / 500.0;
outer = CATransform3DRotate(outer,CGFloat(Double.pi / 4), 0, 1, 0);
inner = CATransform3DRotate(inner,-CGFloat(Double.pi / 4), 0, 1, 0);
} else if selectedIndex == 2 {
outer.m34 = -1.0 / 500.0;
inner.m34 = -1.0 / 500.0;
outer = CATransform3DRotate(outer,CGFloat(Double.pi / 4), 1, 0, 0);
inner = CATransform3DRotate(inner,-CGFloat(Double.pi / 4), 1, 0, 0);
}
self.outerView.layer.transform = outer;
self.innerView.layer.transform = inner;
}
}
/// 通过3D布局和计算光源阴影展现固体特征
class Object3DController: UIViewController {
let containerView = UIView.init(frame: CGRect(x: 0, y: 0, width: 300, height: 300))
var faces: [UIView] = []
let switching = UISwitch()
override func viewDidLoad() {
super.viewDidLoad()
switching.center = CGPoint(x: self.view.center.x,y: self.view.frame.maxY - 50)
switching.addTarget(self, action: #selector(Object3DController.rotation(_:)), for: .valueChanged)
self.view.addSubview(switching)
self.view.addSubview(containerView)
containerView.center = self.view.center
for i in 0...5 {
let cubeFace = UIView.init(frame: CGRect(x: 0, y: 0, width: 200, height: 200))
cubeFace.backgroundColor = UIColor.white
let label = UIButton.init(frame: CGRect(x: 50, y: 50, width: 100, height: 100))
label.setTitle(String(i + 1), for: UIControlState())
let color = CGFloat(CGFloat(arc4random())/CGFloat(RAND_MAX))
let color1 = CGFloat(CGFloat(arc4random())/CGFloat(RAND_MAX))
let color2 = CGFloat(CGFloat(arc4random())/CGFloat(RAND_MAX))
label.setTitleColor(UIColor(red: color, green: color1, blue: color2, alpha: 1), for: UIControlState())
label.titleLabel?.font = UIFont.systemFont(ofSize: 22.0)
if i == 2 {
cubeFace.isUserInteractionEnabled = true
label.layer.borderColor = UIColor.purple.cgColor
label.layer.borderWidth = 1.0
label.addTarget(self, action: #selector(Object3DController.changeBackgroundcolor(_:)), for: .touchUpInside)
} else {
cubeFace.isUserInteractionEnabled = false
}
cubeFace.addSubview(label)
faces.append(cubeFace)
}
//add cube face 1
var transform = CATransform3DMakeTranslation(0, 0, 100);
addFace(0, transform: transform)
//add cube face 2
transform = CATransform3DMakeTranslation(100, 0, 0);
transform = CATransform3DRotate(transform, CGFloat(Double.pi / 2), 0, 1, 0);
addFace(1, transform: transform)
//add cube face 3
//move this code after the setup for face no. 6 to enable button
transform = CATransform3DMakeTranslation(0, -100, 0);
transform = CATransform3DRotate(transform, CGFloat(Double.pi / 2), 1, 0, 0);
addFace(2, transform: transform)
//add cube face 4
transform = CATransform3DMakeTranslation(0, 100, 0);
transform = CATransform3DRotate(transform, -CGFloat(Double.pi / 2), 1, 0, 0);
addFace(3, transform: transform)
//add cube face 5
transform = CATransform3DMakeTranslation(-100, 0, 0);
transform = CATransform3DRotate(transform, -CGFloat(Double.pi / 2), 0, 1, 0);
addFace(4, transform: transform)
//add cube face 6
transform = CATransform3DMakeTranslation(0, 0, -100);
transform = CATransform3DRotate(transform, CGFloat(Double.pi), 0, 1, 0);
addFace(5, transform: transform)
}
func changeBackgroundcolor(_ changedButton: UIButton) {
changedButton.backgroundColor = UIColor.blue
}
func addFace(_ index: Int,transform: CATransform3D) {
self.containerView.addSubview(self.faces[index])
let containerSize = self.containerView.bounds.size;
self.faces[index].center = CGPoint(x: containerSize.width / 2.0,
y: containerSize.height / 2.0);
self.faces[index].layer.transform = transform
//apply lighting
self.applyLightingToFace(self.faces[index].layer)
}
func matrixFrom3DTransformation(_ transform: CATransform3D) -> GLKMatrix4 {
let matrix = GLKMatrix4Make(Float(transform.m11), Float(transform.m12), Float(transform.m13), Float(transform.m14),
Float(transform.m21), Float(transform.m22), Float(transform.m23), Float(transform.m24),
Float(transform.m31), Float(transform.m32), Float(transform.m33), Float(transform.m34),
Float(transform.m41), Float(transform.m42), Float(transform.m43), Float(transform.m44));
return matrix;
}
func applyLightingToFace(_ face: CALayer) {
//add lighting layer
let layer = CALayer()
layer.frame = face.bounds;
face.addSublayer(layer);
//convert face transform to matrix
//(GLKMatrix4 has the same structure as CATransform3D)
let transform = face.transform;
let matrix4 = matrixFrom3DTransformation(transform)
let matrix3 = GLKMatrix4GetMatrix3(matrix4);
//get face normal
var normal = GLKVector3Make(0, 0, 1);
normal = GLKMatrix3MultiplyVector3(matrix3, normal);
normal = GLKVector3Normalize(normal);
//get dot product with light direction
let light = GLKVector3Normalize(GLKVector3Make( 0, 1, -0.5));
let dotProduct = GLKVector3DotProduct(light, normal);
//set lighting layer opacity
let shadow: CGFloat = 1.0 + CGFloat(dotProduct) - 0.5;
let color = UIColor.init(white: 0, alpha: shadow)
layer.backgroundColor = color.cgColor;
}
func rotation(_ switcher: UISwitch) {
//set up the container sublayer transform
var perspective = CATransform3DIdentity;
if switcher.isOn {
perspective.m34 = -1.0 / 500.0;
perspective = CATransform3DRotate(perspective, -CGFloat(Double.pi / 4), 1, 0, 0);
perspective = CATransform3DRotate(perspective, -CGFloat(Double.pi / 4), 0, 1, 0);
}
self.containerView.layer.sublayerTransform = perspective;
}
}
| mit | 6e9fb7cb00eeb2295220c8a571500ffa | 38.233244 | 126 | 0.63209 | 4.337285 | false | false | false | false |
149393437/Templates | Templates/Project Templates/Mac/Application/Game.xctemplate/SpriteKit_AppDelegate.swift | 1 | 1793 | //
// ___FILENAME___
// ___PACKAGENAME___
//
// Created by ___FULLUSERNAME___ on ___DATE___.
// Copyright (c) ___YEAR___ ___ORGANIZATIONNAME___. All rights reserved.
//
import Cocoa
import SpriteKit
extension SKNode {
class func unarchiveFromFile(file : NSString) -> SKNode? {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks") {
var sceneData = NSData(contentsOfFile: path, options: .DataReadingMappedIfSafe, error: nil)!
var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
archiver.finishDecoding()
return scene
} else {
return nil
}
}
}
@NSApplicationMain
class ___FILEBASENAME___: NSObject, NSApplicationDelegate {
@IBOutlet weak var window: NSWindow!
@IBOutlet weak var skView: SKView!
func applicationDidFinishLaunching(aNotification: NSNotification) {
/* Pick a size for the scene */
if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
self.skView!.presentScene(scene)
/* Sprite Kit applies additional optimizations to improve rendering performance */
self.skView!.ignoresSiblingOrder = true
self.skView!.showsFPS = true
self.skView!.showsNodeCount = true
}
}
func applicationShouldTerminateAfterLastWindowClosed(sender: NSApplication) -> Bool {
return true
}
}
| mit | e3645c58b908ccebc2c7ca8ad9b802e0 | 32.203704 | 104 | 0.624094 | 5.568323 | false | false | false | false |
bmoliveira/BOShareComposer | BOShareComposer/Classes/UIImage+Download.swift | 1 | 1000 | //
// UIImage+Download.swift
// Pods
//
// Created by Bruno Oliveira on 20/07/16.
//
//
import UIKit
extension UIImageView {
func setImage(withUrl url: NSURL) {
let session = NSURLSession.sharedSession()
let request = NSMutableURLRequest(URL: url, cachePolicy: .ReturnCacheDataElseLoad,
timeoutInterval: 10)
let task = session.dataTaskWithRequest(request) { (data, response, error) in
dispatch_async(dispatch_get_main_queue()) {
guard let data = data where error == nil else {
self.image = nil
return
}
self.fadeSetImage(UIImage(data: data))
}
}
task.resume()
}
func fadeSetImage(image:UIImage?)
{
UIView.transitionWithView(self,
duration: 0.3,
options: .TransitionCrossDissolve,
animations: {
self.image = image
}, completion: nil)
}
}
| mit | 5f43fb7ffce07c3a0b261d8c6008beed | 25.315789 | 86 | 0.55 | 4.739336 | false | false | false | false |
PhilJay/SugarRecord | example/SugarRecordExample/Shared/Controllers/StacksTableViewController.swift | 1 | 1986 | //
// StacksTableViewController.swift
// SugarRecordExample
//
// Created by Robert Dougan on 10/12/14.
// Copyright (c) 2014 Robert Dougan. All rights reserved.
//
import UIKit
class StacksTableViewController: UITableViewController {
var stacks: [String] = [
"CoreData",
"RestKit",
"Realm",
"iCloud"
]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.stacks.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("StackCell", forIndexPath: indexPath) as UITableViewCell
cell.textLabel?.text = self.stacks[indexPath.row]
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
var viewController: UITableViewController?
let stack = self.stacks[indexPath.row]
switch (stack) {
case "CoreData":
viewController = CoreDataTableViewController()
case "RestKit":
viewController = RestKitTableViewController()
case "Realm":
viewController = RealmTableViewController()
case "iCloud":
viewController = iCloudViewController()
default:
println("View Controller not found for stack: \(stack)")
}
if (viewController != nil) {
self.navigationController!.pushViewController(viewController!, animated: true)
}
}
}
| mit | eef751845d0a395de2876aee3fbdfe84 | 27.782609 | 119 | 0.632931 | 5.578652 | false | false | false | false |
LiveFlightApp/Connect-OSX | LiveFlight/Controllers/JoystickViewController.swift | 1 | 5848 | //
// JoystickViewController.swift
// LiveFlight
//
// Created by Cameron Carmichael Alonso on 11/10/15.
// Copyright © 2015 Cameron Carmichael Alonso. All rights reserved.
//
import Cocoa
class JoystickViewController: NSViewController {
@IBOutlet weak var pitchLabel: NSTextField!
@IBOutlet weak var rollLabel: NSTextField!
@IBOutlet weak var throttleLabel: NSTextField!
@IBOutlet weak var rudderLabel: NSTextField!
@IBOutlet weak var joystickName: NSTextField!
@IBOutlet weak var joystickRecognised: NSTextField!
@IBOutlet var allClearView: Status!
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(changeLabelValues(notification:)), name:NSNotification.Name(rawValue: "changeLabelValues"), object: nil)
//this is a hack, to avoid having to create a new NSNotification object
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "changeLabelValues"), object: nil)
}
@objc func changeLabelValues(notification:NSNotification) {
allClearView!.isHidden = true
let pitch = UserDefaults.standard.integer(forKey: "pitch")
let roll = UserDefaults.standard.integer(forKey: "roll")
let throttle = UserDefaults.standard.integer(forKey: "throttle")
let rudder = UserDefaults.standard.integer(forKey: "rudder")
if pitch != -2 {
pitchLabel.stringValue = "Axis \(String(pitch))"
}
if roll != -2 {
rollLabel.stringValue = "Axis \(String(roll))"
}
if throttle != -2 {
throttleLabel.stringValue = "Axis \(String(throttle))"
}
if rudder != -2 {
rudderLabel.stringValue = "Axis \(String(rudder))"
}
if joystickConfig.joystickConnected == true {
// remove duplicate words from name
// some manufacturers include name in product name too
var joystickNameArray = joystickConfig.connectedJoystickName.characters.split{$0 == " "}.map(String.init)
var filter = Dictionary<String,Int>()
var len = joystickNameArray.count
for index in 0..<len {
let value = joystickNameArray[index]
if (filter[value] != nil) {
joystickNameArray.remove(at: (index - 1))
len -= 1
}else{
filter[value] = 1
}
}
joystickName.stringValue = joystickNameArray.joined(separator: " ")
let mapStatus = UserDefaults.standard.integer(forKey: "mapStatus")
if mapStatus == -2 {
joystickRecognised.stringValue = "Using custom-assigned values for axes."
} else if mapStatus == 0 {
joystickRecognised.stringValue = "Using generic joystick values. These may not work correctly."
} else if mapStatus == 1 {
joystickRecognised.stringValue = "Using accurate values for your joystick (provided by LiveFlight)."
allClearView!.isHidden = false
} else {
joystickRecognised.stringValue = "Using generic joystick values. These may not work correctly."
}
} else {
joystickName.stringValue = "No joystick connected"
joystickRecognised.stringValue = "Plug a joystick in via USB to get started."
}
}
/*
Actions for setting axes
========================
*/
@IBAction func pitch(sender: AnyObject) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "tryPitch"), object: nil)
pitchLabel.stringValue = "Move the stick forwards and backwards"
UserDefaults.standard.set(-2, forKey: "mapStatus")
}
@IBAction func roll(sender: AnyObject) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "tryRoll"), object: nil)
rollLabel.stringValue = "Move the stick from side to side"
UserDefaults.standard.set(-2, forKey: "mapStatus")
}
@IBAction func throttle(sender: AnyObject) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "tryThrottle"), object: nil)
throttleLabel.stringValue = "Move the lever forwards and backwards"
UserDefaults.standard.set(-2, forKey: "mapStatus")
}
@IBAction func rudder(sender: AnyObject) {
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "tryRudder"), object: nil)
rudderLabel.stringValue = "Twist/move the rudder"
UserDefaults.standard.set(-2, forKey: "mapStatus")
}
/*
Actions for clearing saved axes
========================
*/
@IBAction func clear(sender: AnyObject) {
// remove saved axes
UserDefaults.standard.set(-2, forKey: "pitch")
UserDefaults.standard.set(-2, forKey: "roll")
UserDefaults.standard.set(-2, forKey: "throttle")
UserDefaults.standard.set(-2, forKey: "rudder")
UserDefaults.standard.set(-2, forKey: "mapStatus")
// update labels
pitchLabel.stringValue = "No axis assigned"
rollLabel.stringValue = "No axis assigned"
throttleLabel.stringValue = "No axis assigned"
rudderLabel.stringValue = "No axis assigned"
}
}
| gpl-3.0 | ddf253831cd71c7d38a8263c06ba87e3 | 33.803571 | 177 | 0.5791 | 4.868443 | false | false | false | false |
crsantos/swift-openweathermapsdk | OpenWeatherMapSDK/API/Models/Environment.swift | 1 | 877 | //
// Environment.swift
// OpenWeatherMapSDK
//
// Created by Carlos Santos on 27/09/14.
// Copyright (c) 2014 Carlos Santos. All rights reserved.
//
import Foundation
public class Environment {
var grnd_level: Double!
var humidity: Double!
var pressure: Double!
var sea_level: Double!
var temp: Double!
var temp_max: Double!
var temp_min: Double!
init(
grnd_level: Double,
humidity: Double,
pressure: Double,
sea_level: Double,
temp: Double,
temp_max: Double,
temp_min: Double){
self.grnd_level = grnd_level
self.humidity = humidity
self.pressure = pressure
self.sea_level = sea_level
self.temp = temp
self.temp_max = temp_max
self.temp_min = temp_min
}
} | mit | 4e4de72c35b8ac772fa0b8b9997228ba | 21.512821 | 58 | 0.551881 | 3.897778 | false | false | false | false |
hilen/TimedSilver | Sources/Foundation/NSRange+TSExtension.swift | 2 | 2960 | //
// NSRange+TSExtension.swift
// TimedSilver
// Source: https://github.com/hilen/TimedSilver
//
// Created by Hilen on 9/15/16.
// Copyright © 2016 Hilen. All rights reserved.
//
import Foundation
public extension NSRange {
/**
Init with location and length
- parameter ts_location: location
- parameter ts_length: length
- returns: NSRange
*/
init(ts_location:Int, ts_length:Int) {
self.init()
self.location = ts_location
self.length = ts_length
}
/**
Init with location and length
- parameter ts_location: location
- parameter ts_length: length
- returns: NSRange
*/
init(_ ts_location:Int, _ ts_length:Int) {
self.init()
self.location = ts_location
self.length = ts_length
}
/**
Init from Range
- parameter ts_range: Range
- returns: NSRange
*/
init(ts_range:Range <Int>) {
self.init()
self.location = ts_range.lowerBound
self.length = ts_range.upperBound - ts_range.lowerBound
}
/**
Init from Range
- parameter ts_range: Range
- returns: NSRange
*/
init(_ ts_range:Range <Int>) {
self.init()
self.location = ts_range.lowerBound
self.length = ts_range.upperBound - ts_range.lowerBound
}
/// Get NSRange start index
var ts_startIndex:Int { get { return location } }
/// Get NSRange end index
var ts_endIndex:Int { get { return location + length } }
/// Convert NSRange to Range
var ts_asRange:Range<Int> { get { return location..<location + length } }
/// Check empty
var ts_isEmpty:Bool { get { return length == 0 } }
/**
Check NSRange contains index
- parameter index: index
- returns: Bool
*/
func ts_contains(index:Int) -> Bool {
return index >= location && index < ts_endIndex
}
/**
Get NSRange's clamp Index
- parameter index: index
- returns: Bool
*/
func ts_clamp(index:Int) -> Int {
return max(self.ts_startIndex, min(self.ts_endIndex - 1, index))
}
/**
Check NSRange intersects another NSRange
- parameter range: NSRange
- returns: Bool
*/
func ts_intersects(range:NSRange) -> Bool {
return NSIntersectionRange(self, range).ts_isEmpty == false
}
/**
Get the two NSRange's intersection
- parameter range: NSRange
- returns: NSRange
*/
func ts_intersection(range:NSRange) -> NSRange {
return NSIntersectionRange(self, range)
}
/**
Get the two NSRange's union value
- parameter range: NSRange
- returns: NSRange
*/
func ts_union(range:NSRange) -> NSRange {
return NSUnionRange(self, range)
}
}
| mit | 96778e338a055e92b1893aa62d174585 | 21.08209 | 77 | 0.558973 | 4.300872 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.