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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
PandaraWen/DJIDemoKit | DJIDemoKit/DDKRCViewController.swift | 1 | 10388 | //
// DDKRCViewController.swift
// RCReplay
//
// Created by Pandara on 2017/9/4.
// Copyright © 2017年 Pandara. All rights reserved.
//
import UIKit
import SnapKit
import DJISDK
public class DDKRCViewController: UIViewController {
fileprivate var leftTopLabel: UILabel!
fileprivate var leftLabel: UILabel!
fileprivate var rightTopLabel: UILabel!
fileprivate var rightLabel: UILabel!
fileprivate var leftContainer: UIView!
fileprivate var rightContainer: UIView!
fileprivate let _viColor = UIColor(r: 0, g: 140, b: 1, a: 1)
fileprivate let _stickSize = 10
fileprivate var leftStickV: UIView!
fileprivate var leftStickH: UIView!
fileprivate var rightStickV: UIView!
fileprivate var rightStickH: UIView!
public override func viewDidLoad() {
super.viewDidLoad()
self.setupSubviews()
self.view.backgroundColor = UIColor.white
self.leftLabel.text = "0"
self.leftTopLabel.text = "0"
self.rightTopLabel.text = "0"
self.rightLabel.text = "0"
DDKComponentHelper.fetchRemoteController()?.delegate = self
}
public override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
return .landscape
}
}
// MARK: Private methods
fileprivate extension DDKRCViewController {
enum StickType {
case left
case right
}
func moveLeftStick(top: Float, left: Float) {
self.moveStick(stickType: .left, top: top, left: left)
}
func moveRightStick(top: Float, left: Float) {
self.moveStick(stickType: .right, top: top, left: left)
}
private func moveStick(stickType: StickType, top: Float, left: Float) {
var stickV: UIView
var stickH: UIView
switch stickType {
case .left:
stickH = self.leftStickH
stickV = self.leftStickV
case .right:
stickH = self.rightStickH
stickV = self.rightStickV
}
stickV.snp.updateConstraints { (make) in
if top > 0 {
// Top
make.top.equalTo(Float(75 - _stickSize / 2) * (1 - top))
make.bottom.equalTo(-(75 - _stickSize / 2))
} else {
// Bottom
make.top.equalTo((75 - _stickSize / 2))
make.bottom.equalTo(-Float(75 - _stickSize / 2) * (1 + top))
}
}
stickH.snp.updateConstraints { (make) in
if left > 0 {
// right
make.left.equalTo(75 - _stickSize / 2)
make.right.equalTo(-Float(75 - _stickSize / 2) * (1 - left))
} else {
// left
make.left.equalTo(Float(75 - _stickSize / 2) * (1 + left))
make.right.equalTo(-(75 - _stickSize / 2))
}
}
}
}
// MARK: UI
fileprivate extension DDKRCViewController {
func setupSubviews() {
self.setupLeftContainer()
self.setupLeftStick()
self.setupRightContainer()
self.setupRightStick()
}
func setupLeftContainer() {
self.leftContainer = {
let view = UIView()
view.backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0.96, alpha: 1)
view.layer.cornerRadius = 75
self.view.addSubview(view)
view.snp.makeConstraints({ (make) in
make.centerY.equalTo(self.view)
make.left.equalTo(self.view).offset(110)
make.size.equalTo(CGSize(width: 150, height: 150))
})
return view
}()
self.leftTopLabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15)
label.textColor = UIColor.ddkVIBlue
self.view.addSubview(label)
label.snp.makeConstraints({ (make) in
make.centerX.equalTo(self.leftContainer)
make.bottom.equalTo(self.leftContainer.snp.top).offset(-10)
})
return label
}()
self.leftLabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15)
label.textColor = UIColor.ddkVIBlue
self.view.addSubview(label)
label.snp.makeConstraints({ (make) in
make.centerY.equalTo(self.leftContainer)
make.right.equalTo(self.leftContainer.snp.left).offset(-10)
})
return label
}()
let vertical = UIView()
vertical.backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0.94, alpha: 1)
vertical.layer.cornerRadius = 5
self.leftContainer.addSubview(vertical)
vertical.snp.makeConstraints { (make) in
make.top.bottom.centerX.equalTo(self.leftContainer)
make.width.equalTo(10)
}
let horizontal = UIView()
horizontal.backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0.94, alpha: 1)
horizontal.layer.cornerRadius = 5
self.leftContainer.addSubview(horizontal)
horizontal.snp.makeConstraints { (make) in
make.left.right.centerY.equalTo(self.leftContainer)
make.height.equalTo(10)
}
}
func setupLeftStick() {
self.leftStickV = {
let view = UIView()
view.backgroundColor = _viColor
self.leftContainer.addSubview(view)
view.layer.cornerRadius = 5
view.snp.makeConstraints { (make) in
make.top.left.equalTo(self.leftContainer).offset(75 - _stickSize / 2)
make.bottom.right.equalTo(self.leftContainer).offset(-(75 - _stickSize / 2))
}
return view
}()
self.leftStickH = {
let view = UIView()
view.backgroundColor = _viColor
self.leftContainer.addSubview(view)
view.layer.cornerRadius = 5
view.snp.makeConstraints { (make) in
make.top.left.equalTo(self.leftContainer).offset(75 - _stickSize / 2)
make.bottom.right.equalTo(self.leftContainer).offset(-(75 - _stickSize / 2))
}
return view
}()
}
func setupRightContainer() {
self.rightContainer = {
let view = UIView()
view.backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0.96, alpha: 1)
view.layer.cornerRadius = 75
self.view.addSubview(view)
view.snp.makeConstraints({ (make) in
make.centerY.equalTo(self.view)
make.right.equalTo(self.view).offset(-110)
make.size.equalTo(CGSize(width: 150, height: 150))
})
return view
}()
self.rightTopLabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15)
label.textColor = UIColor.ddkVIBlue
self.view.addSubview(label)
label.snp.makeConstraints({ (make) in
make.centerX.equalTo(self.rightContainer)
make.bottom.equalTo(self.rightContainer.snp.top).offset(-10)
})
return label
}()
self.rightLabel = {
let label = UILabel()
label.font = UIFont.systemFont(ofSize: 15)
label.textColor = UIColor.ddkVIBlue
self.view.addSubview(label)
label.snp.makeConstraints({ (make) in
make.centerY.equalTo(self.rightContainer)
make.left.equalTo(self.rightContainer.snp.right).offset(10)
})
return label
}()
let vertical = UIView()
vertical.backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0.94, alpha: 1)
vertical.layer.cornerRadius = 5
self.rightContainer.addSubview(vertical)
vertical.snp.makeConstraints { (make) in
make.top.bottom.centerX.equalTo(self.rightContainer)
make.width.equalTo(10)
}
let horizontal = UIView()
horizontal.backgroundColor = UIColor(hue: 0, saturation: 0, brightness: 0.94, alpha: 1)
horizontal.layer.cornerRadius = 5
self.rightContainer.addSubview(horizontal)
horizontal.snp.makeConstraints { (make) in
make.left.right.centerY.equalTo(self.rightContainer)
make.height.equalTo(10)
}
}
func setupRightStick() {
self.rightStickV = {
let view = UIView()
view.backgroundColor = _viColor
view.layer.cornerRadius = 5
self.rightContainer.addSubview(view)
view.snp.makeConstraints { (make) in
make.top.left.equalTo(self.rightContainer).offset(75 - _stickSize / 2)
make.bottom.right.equalTo(self.rightContainer).offset(-(75 - _stickSize / 2))
}
return view
}()
self.rightStickH = {
let view = UIView()
view.backgroundColor = _viColor
view.layer.cornerRadius = 5
self.rightContainer.addSubview(view)
view.snp.makeConstraints { (make) in
make.top.left.equalTo(self.rightContainer).offset(75 - _stickSize / 2)
make.bottom.right.equalTo(self.rightContainer).offset(-(75 - _stickSize / 2))
}
return view
}()
}
}
extension DDKRCViewController: DJIRemoteControllerDelegate {
public func remoteController(_ rc: DJIRemoteController, didUpdate state: DJIRCHardwareState) {
let leftV = state.leftStick.verticalPosition
let leftH = state.leftStick.horizontalPosition
self.moveLeftStick(top: Float(leftV) / 660.0, left: Float(leftH) / 660.0)
self.leftTopLabel.text = "\(leftV)"
self.leftLabel.text = "\(leftH)"
let rightV = state.rightStick.verticalPosition
let rightH = state.rightStick.horizontalPosition
self.moveRightStick(top: Float(rightV) / 660.0, left: Float(rightH) / 660.0)
self.rightTopLabel.text = "\(rightV)"
self.rightLabel.text = "\(rightH)"
}
}
| mit | 5561b152bdb12f8cdd3bee56736a4aa6 | 34.084459 | 98 | 0.566972 | 4.417269 | false | false | false | false |
STShenZhaoliang/iOS-GuidesAndSampleCode | 精通Swift设计模式/Chapter 18/SportsStore/SportsStore/ViewController.swift | 1 | 3948 | import UIKit
class ProductTableCell : UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var descriptionLabel: UILabel!
@IBOutlet weak var stockStepper: UIStepper!
@IBOutlet weak var stockField: UITextField!
var product:Product?;
}
var handler = { (p:Product) in
println("Change: \(p.name) \(p.stockLevel) items in stock");
};
class ViewController: UIViewController, UITableViewDataSource {
@IBOutlet weak var totalStockLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
var productStore = ProductDataStore();
override func viewDidLoad() {
super.viewDidLoad();
displayStockTotal();
let bridge = EventBridge(callback: updateStockLevel);
productStore.callback = bridge.inputCallback;
}
func updateStockLevel(name:String, level:Int) {
for cell in self.tableView.visibleCells() {
if let pcell = cell as? ProductTableCell {
if pcell.product?.name == name {
pcell.stockStepper.value = Double(level);
pcell.stockField.text = String(level);
}
}
}
self.displayStockTotal();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
func tableView(tableView: UITableView,
numberOfRowsInSection section: Int) -> Int {
return productStore.products.count;
}
func tableView(tableView: UITableView,
cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let product = productStore.products[indexPath.row];
let cell = tableView.dequeueReusableCellWithIdentifier("ProductCell")
as ProductTableCell;
cell.product = productStore.products[indexPath.row];
cell.nameLabel.text = product.name;
cell.descriptionLabel.text = product.productDescription;
cell.stockStepper.value = Double(product.stockLevel);
cell.stockField.text = String(product.stockLevel);
return cell;
}
@IBAction func stockLevelDidChange(sender: AnyObject) {
if var currentCell = sender as? UIView {
while (true) {
currentCell = currentCell.superview!;
if let cell = currentCell as? ProductTableCell {
if let product = cell.product? {
if let stepper = sender as? UIStepper {
product.stockLevel = Int(stepper.value);
} else if let textfield = sender as? UITextField {
if let newValue = textfield.text.toInt()? {
product.stockLevel = newValue;
}
}
cell.stockStepper.value = Double(product.stockLevel);
cell.stockField.text = String(product.stockLevel);
productLogger.logItem(product);
StockServerFactory.getStockServer()
.setStockLevel(product.name, stockLevel: product.stockLevel);
}
break;
}
}
displayStockTotal();
}
}
func displayStockTotal() {
let finalTotals:(Int, Double) = productStore.products.reduce((0, 0.0),
{(totals, product) -> (Int, Double) in
return (
totals.0 + product.stockLevel,
totals.1 + product.stockValue
);
});
let formatted = StockTotalFacade.formatCurrencyAmount(finalTotals.1,
currency: StockTotalFacade.Currency.EUR);
totalStockLabel.text = "\(finalTotals.0) Products in Stock. "
+ "Total Value: \(formatted!)";
}
}
| mit | 8f285766d0c0bf1c9d0e82a66e038d19 | 36.245283 | 89 | 0.561803 | 5.299329 | false | false | false | false |
xinan/big-brother | bigbrother-iphone/BigBrother/SwiftIO/SocketIOClient.swift | 1 | 15452 | //
// SocketIOClient.swift
// Socket.IO-Swift
//
// Created by Erik Little on 11/23/14.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public class SocketIOClient: NSObject {
let socketURL:NSMutableString!
let ackQueue = dispatch_queue_create("ackQueue".cStringUsingEncoding(NSUTF8StringEncoding),
DISPATCH_QUEUE_SERIAL)
let handleQueue = dispatch_queue_create("handleQueue".cStringUsingEncoding(NSUTF8StringEncoding),
DISPATCH_QUEUE_SERIAL)
let emitQueue = dispatch_queue_create("emitQueue".cStringUsingEncoding(NSUTF8StringEncoding),
DISPATCH_QUEUE_SERIAL)
let reconnectAttempts:Int!
private lazy var params = [String: AnyObject]()
private var ackHandlers = [SocketAckHandler]()
private var anyHandler:((AnyHandler) -> Void)?
private var _closed = false
private var _connected = false
private var _connecting = false
private var currentReconnectAttempt = 0
private var forcePolling = false
private var handlers = [SocketEventHandler]()
private var paramConnect = false
private var _secure = false
private var _sid:String?
private var _reconnecting = false
private var reconnectTimer:NSTimer?
internal var currentAck = -1
internal var waitingData = [SocketEvent]()
public var closed:Bool {
return self._closed
}
public var connected:Bool {
return self._connected
}
public var connecting:Bool {
return self._connecting
}
public var engine:SocketEngine?
public var nsp:String?
public var reconnects = true
public var reconnecting:Bool {
return self._reconnecting
}
public var reconnectWait = 10
public var secure:Bool {
return self._secure
}
public var sid:String? {
return self._sid
}
public init(socketURL:String, opts:[String: AnyObject]? = nil) {
var mutURL = RegexMutable(socketURL)
if mutURL["https://"].matches().count != 0 {
self._secure = true
}
mutURL = mutURL["http://"] ~= ""
mutURL = mutURL["https://"] ~= ""
self.socketURL = mutURL
// Set options
if opts != nil {
if let reconnects = opts!["reconnects"] as? Bool {
self.reconnects = reconnects
}
if let reconnectAttempts = opts!["reconnectAttempts"] as? Int {
self.reconnectAttempts = reconnectAttempts
} else {
self.reconnectAttempts = -1
}
if let reconnectWait = opts!["reconnectWait"] as? Int {
self.reconnectWait = abs(reconnectWait)
}
if let nsp = opts!["nsp"] as? String {
self.nsp = nsp
}
if let polling = opts!["forcePolling"] as? Bool {
self.forcePolling = polling
}
} else {
self.reconnectAttempts = -1
}
super.init()
self.engine = SocketEngine(client: self, forcePolling: self.forcePolling)
}
// Closes the socket
public func close() {
self._closed = true
self._connecting = false
self._connected = false
self._reconnecting = false
self.engine?.close()
}
// Connects to the server
public func connect() {
if self.closed {
println("Warning! This socket was previously closed. This might be dangerous!")
self._closed = false
}
self.engine?.open()
}
// Connect to the server using params
public func connectWithParams(params:[String: AnyObject]) {
if self.closed {
println("Warning! This socket was previously closed. This might be dangerous!")
self._closed = false
}
self.params = params
self.paramConnect = true
self.engine?.open(opts: params)
}
func didConnect() {
self._closed = false
self._connected = true
self._connecting = false
self._reconnecting = false
self.currentReconnectAttempt = 0
self.reconnectTimer?.invalidate()
self.reconnectTimer = nil
self._sid = self.engine?.sid
// Don't handle as internal because something crazy could happen where
// we disconnect before it's handled
self.handleEvent("connect", data: nil, isInternalMessage: false)
}
// Server wants us to die
func didForceClose() {
self._closed = true
self._connected = false
self.reconnects = false
self._connecting = false
self._reconnecting = false
self.handleEvent("disconnect", data: "closed", isInternalMessage: true)
}
// Sends a message with multiple args
// If a message contains binary we have to send those
// seperately.
public func emit(event:String, _ args:AnyObject...) {
if !self.connected {
return
}
dispatch_async(self.emitQueue) {[weak self] in
self?._emit(event, args)
return
}
}
// Objc doesn't have variadics
public func emitObjc(event:String, _ args:[AnyObject]) {
self.emit(event, args)
}
public func emitWithAck(event:String, _ args:AnyObject...) -> SocketAckHandler {
if !self.connected {
return SocketAckHandler(event: "fail")
}
self.currentAck++
let ackHandler = SocketAckHandler(event: event, ackNum: self.currentAck)
self.ackHandlers.append(ackHandler)
dispatch_async(self.emitQueue) {[weak self] in
self?._emit(event, args, ack: true)
return
}
return ackHandler
}
public func emitWithAckObjc(event:String, _ args:[AnyObject]) -> SocketAckHandler {
return self.emitWithAck(event, args)
}
private func _emit(event:String, _ args:[AnyObject], ack:Bool = false) {
var frame:SocketEvent
var str:String
let (items, hasBinary, emitDatas) = SocketParser.parseEmitArgs(args)
if !self.connected {
return
}
if hasBinary {
if !ack {
str = SocketEvent.createMessageForEvent(event, withArgs: items,
hasBinary: true, withDatas: emitDatas.count, toNamespace: self.nsp)
} else {
str = SocketEvent.createMessageForEvent(event, withArgs: items,
hasBinary: true, withDatas: emitDatas.count, toNamespace: self.nsp, wantsAck: self.currentAck)
}
self.engine?.send(str, datas: emitDatas)
} else {
if !ack {
str = SocketEvent.createMessageForEvent(event, withArgs: items, hasBinary: false,
withDatas: 0, toNamespace: self.nsp)
} else {
str = SocketEvent.createMessageForEvent(event, withArgs: items, hasBinary: false,
withDatas: 0, toNamespace: self.nsp, wantsAck: self.currentAck)
}
self.engine?.send(str)
}
}
// If the server wants to know that the client received data
func emitAck(ack:Int, withData data:[AnyObject]?, withAckType ackType:Int) {
dispatch_async(self.ackQueue) {[weak self] in
if self == nil || !self!.connected || data == nil {
return
}
let (items, hasBinary, emitDatas) = SocketParser.parseEmitArgs(data!)
var str:String
if !hasBinary {
if self?.nsp == nil {
str = SocketEvent.createAck(ack, withArgs: items,
withAckType: 3, withNsp: "/")
} else {
str = SocketEvent.createAck(ack, withArgs: items,
withAckType: 3, withNsp: self!.nsp!)
}
self?.engine?.send(str)
} else {
if self?.nsp == nil {
str = SocketEvent.createAck(ack, withArgs: items,
withAckType: 6, withNsp: "/", withBinary: emitDatas.count)
} else {
str = SocketEvent.createAck(ack, withArgs: items,
withAckType: 6, withNsp: self!.nsp!, withBinary: emitDatas.count)
}
self?.engine?.send(str, datas: emitDatas)
}
}
}
// Called when the socket gets an ack for something it sent
func handleAck(ack:Int, data:AnyObject?) {
self.ackHandlers = self.ackHandlers.filter {handler in
if handler.ackNum != ack {
return true
} else {
if data is NSArray {
handler.executeAck(data as? NSArray)
} else if data != nil {
handler.executeAck([data!])
} else {
handler.executeAck(nil)
}
return false
}
}
}
// Handles events
public func handleEvent(event:String, data:AnyObject?, isInternalMessage:Bool = false,
wantsAck ack:Int? = nil, withAckType ackType:Int = 3) {
// println("Should do event: \(event) with data: \(data)")
if !self.connected && !isInternalMessage {
return
}
dispatch_async(dispatch_get_main_queue()) {[weak self] in
self?.anyHandler?((event, data))
return
}
for handler in self.handlers {
if handler.event == event {
if data is NSArray {
if ack != nil {
handler.executeCallback(data as? NSArray, withAck: ack!,
withAckType: ackType, withSocket: self)
} else {
handler.executeCallback(data as? NSArray)
}
} else {
// Trying to do a ternary expression in the executeCallback method
// seemed to crash Swift
var dataArr:NSArray? = nil
if let data:AnyObject = data {
dataArr = [data]
}
if ack != nil {
handler.executeCallback(dataArr, withAck: ack!,
withAckType: ackType, withSocket: self)
} else {
handler.executeCallback(dataArr)
}
}
}
}
}
// Should be removed and moved to SocketEngine
func joinNamespace() {
if self.nsp != nil {
self.engine?.send("0/\(self.nsp!)")
}
}
// Adds handler for an event
public func on(name:String, callback:NormalCallback) {
let handler = SocketEventHandler(event: name, callback: callback)
self.handlers.append(handler)
}
// Adds a handler for any event
public func onAny(handler:(AnyHandler) -> Void) {
self.anyHandler = handler
}
// Opens the connection to the socket
public func open() {
self.connect()
}
func parseSocketMessage(msg:String) {
SocketParser.parseSocketMessage(msg, socket: self)
}
func parseBinaryData(data:NSData) {
SocketParser.parseBinaryData(data, socket: self)
}
// Something happened while polling
func pollingDidFail(err:NSError?) {
if !self.reconnecting {
self._connected = false
self.handleEvent("reconnect", data: err?.localizedDescription, isInternalMessage: true)
self.tryReconnect()
}
}
// We lost connection and should attempt to reestablish
func tryReconnect() {
if self.reconnectAttempts != -1 && self.currentReconnectAttempt + 1 > self.reconnectAttempts {
self.didForceClose()
return
} else if self.connected {
self._connecting = false
self._reconnecting = false
return
}
if self.reconnectTimer == nil {
self._reconnecting = true
dispatch_async(dispatch_get_main_queue()) {[weak self] in
if self == nil {
return
}
self?.reconnectTimer = NSTimer.scheduledTimerWithTimeInterval(Double(self!.reconnectWait),
target: self!, selector: "tryReconnect", userInfo: nil, repeats: true)
return
}
}
self.handleEvent("reconnectAttempt", data: self.reconnectAttempts - self.currentReconnectAttempt,
isInternalMessage: true)
self.currentReconnectAttempt++
if self.paramConnect {
self.connectWithParams(self.params)
} else {
self.connect()
}
}
// Called when the socket is closed
func webSocketDidCloseWithCode(code:Int, reason:String!, wasClean:Bool) {
self._connected = false
self._connecting = false
if self.closed || !self.reconnects {
self.didForceClose()
} else {
self.handleEvent("reconnect", data: reason, isInternalMessage: true)
self.tryReconnect()
}
}
// Called when an error occurs.
func webSocketDidFailWithError(error:NSError!) {
self._connected = false
self._connecting = false
self.handleEvent("error", data: error.localizedDescription, isInternalMessage: true)
if self.closed || !self.reconnects {
self.didForceClose()
} else if !self.reconnecting {
self.handleEvent("reconnect", data: error.localizedDescription, isInternalMessage: true)
self.tryReconnect()
}
}
} | mit | 9e6f34d948adc0465da6eeda52f273d9 | 33.725843 | 114 | 0.551579 | 4.971686 | false | false | false | false |
maxim-pervushin/HyperHabit | HyperHabit/HyperHabit/Scenes/Settings/SettingsViewController.swift | 1 | 5027 | //
// Created by Maxim Pervushin on 04/12/15.
// Copyright (c) 2015 Maxim Pervushin. All rights reserved.
//
import UIKit
class SettingsViewController: ThemedViewController {
// MARK: SettingsViewController @IB
@IBOutlet weak var themeNameLabel: UILabel?
@IBOutlet weak var authenticationStatusLabel: UILabel?
@IBOutlet weak var toggleAuthenticationLabel: UILabel?
@IBOutlet weak var generateTestDataContainer: UIView?
@IBAction func toggleAuthenticationAction(sender: AnyObject) {
App.authenticated ? logOut() : logIn()
}
@IBAction func generateTestDataAction(sender: AnyObject) {
generateTestData()
}
// MARK: SettingsViewController
private let dataSource = SettingsDataSource()
private func logOut() {
let alert = UIAlertController(title: "Log Out", message: "Do you want to delete local data?", preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: "Keep", style: .Default, handler: {
_ in
App.logOut() {
success, error in
self.updateUI()
}
}))
alert.addAction(UIAlertAction(title: "Delete", style: .Destructive, handler: {
_ in
App.logOut() {
success, error in
self.dataSource.clearCache()
self.updateUI()
}
}))
alert.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
private func logIn() {
performSegueWithIdentifier("ShowLogIn", sender: self)
}
private func updateUI() {
if App.authenticated {
authenticationStatusLabel?.text = App.username
toggleAuthenticationLabel?.text = "Log Out"
} else {
authenticationStatusLabel?.text = "Not Authenticated"
toggleAuthenticationLabel?.text = "Log In"
}
themeNameLabel?.text = App.themeManager.theme.name
}
override func viewDidLoad() {
super.viewDidLoad()
#if ( arch(i386) || arch(x86_64)) && os(iOS)
generateTestDataContainer?.hidden = false
#else
generateTestDataContainer?.hidden = true
#endif
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateUI()
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let logInViewController = segue.destinationViewController as? LogInViewController {
logInViewController.completionHandler = {
self.dismissViewControllerAnimated(true, completion: nil)
self.updateUI()
}
}
super.prepareForSegue(segue, sender: sender)
}
}
extension SettingsViewController {
func generateTestData() {
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) {
let groupIdentifier = "group.hyperhabit"
if let contentDirectory = NSFileManager.defaultManager().containerURLForSecurityApplicationGroupIdentifier(groupIdentifier)?.path as? NSString {
let files = ["habits.plist", "habitsToSave.plist", "reports.plist", "reportsToSave.plist"]
for file in files {
if let path = NSBundle.mainBundle().pathForResource(file, ofType: nil) {
let toPath = contentDirectory.stringByAppendingPathComponent("/\(file)")
try? NSFileManager.defaultManager().copyItemAtPath(path, toPath: toPath)
}
}
}
// // Habits
// print("Generating habits...")
// let meditate = Habit(name: "Meditate", definition: "", repeatsTotal: 1, active: true)
// let exercise = Habit(name: "Exercise", definition: "Make 100 push ups", repeatsTotal: 1, active: true)
// let eat = Habit(name: "Eat more vegetables", definition: "", repeatsTotal: 1, active: true)
// let drink = Habit(name: "Drink more water", definition: "At least 2 litres", repeatsTotal: 1, active: true)
// let read = Habit(name: "Read", definition: "", repeatsTotal: 1, active: true)
// let habits = [meditate, exercise, eat, drink, read]
// for habit in habits {
// App.dataProvider.saveHabit(habit)
// }
// print("Done.")
//
// // Reports
// print("Generating reports...")
// let today = NSDate()
// for index in -31 ... 0 {
// let date = today.dateByAddingDays(index)
// for habit in habits {
// let report = Report(habit: habit, repeatsDone: arc4random_uniform(10) > 2 ? habit.repeatsTotal : 0, date: date)
// App.dataProvider.saveReport(report)
// }
// print("index: \(index + 31 ) of 31")
// }
// print("Done.")
}
}
} | mit | c8f78d0d53ee602195335861bf8d6b4d | 36.244444 | 156 | 0.593396 | 4.805927 | false | false | false | false |
rainsun/HelloWorld | Swift Weather/ViewController.swift | 1 | 7468 | //
// ViewController.swift
// Swift Weather
//
// Created by Lv Conggang on 14/9/24.
// Copyright (c) 2014年 Lv Conggang. All rights reserved.
//
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
let locationManager:CLLocationManager = CLLocationManager()
@IBOutlet weak var location: UILabel!
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var temprature: UILabel!
@IBOutlet weak var loading: UILabel!
@IBOutlet weak var loadingIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
self.loadingIndicator.startAnimating()
let background = UIImage(named:"background.png")
self.view.backgroundColor = UIColor(patternImage: background)
if(ios8()) {
locationManager.requestAlwaysAuthorization()
}
locationManager.startUpdatingLocation()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func ios8() ->Bool {
return UIDevice.currentDevice().systemVersion == "8.0"
}
func updateWeatherInfo(latitude:CLLocationDegrees, longitude:CLLocationDegrees) {
let manager = AFHTTPRequestOperationManager()
let url = "http://api.openweathermap.org/data/2.5/weather"
let params = ["lat": latitude, "lon":longitude]
manager.GET(
url,
parameters: params,
success: {
(operation:AFHTTPRequestOperation!,
respondsObject: AnyObject!) in println("JSON: " + respondsObject.description!)
self.updateUISuccess(respondsObject as NSDictionary!)
},
failure: {
(operation: AFHTTPRequestOperation!, error: NSError!) in println("Error: " + error.localizedDescription )
})
}
// Converts a Weather Condition into one of our icons.
// Refer to: http://bugs.openweathermap.org/projects/api/wiki/Weather_Condition_Codes
func updateWeatherIcon(condition: Int, nightTime: Bool) {
// Thunderstorm
if (condition < 300) {
if nightTime {
self.icon.image = UIImage(named: "tstorm1_night")
} else {
self.icon.image = UIImage(named: "tstorm1")
}
}
// Drizzle
else if (condition < 500) {
self.icon.image = UIImage(named: "light_rain")
}
// Rain / Freezing rain / Shower rain
else if (condition < 600) {
self.icon.image = UIImage(named: "shower3")
}
// Snow
else if (condition < 700) {
self.icon.image = UIImage(named: "snow4")
}
// Fog / Mist / Haze / etc.
else if (condition < 771) {
if nightTime {
self.icon.image = UIImage(named: "fog_night")
} else {
self.icon.image = UIImage(named: "fog")
}
}
// Tornado / Squalls
else if (condition < 800) {
self.icon.image = UIImage(named: "tstorm3")
}
// Sky is clear
else if (condition == 800) {
if (nightTime){
self.icon.image = UIImage(named: "sunny_night") // sunny night?
}
else {
self.icon.image = UIImage(named: "sunny")
}
}
// few / scattered / broken clouds
else if (condition < 804) {
if (nightTime){
self.icon.image = UIImage(named: "cloudy2_night")
}
else{
self.icon.image = UIImage(named: "cloudy2")
}
}
// overcast clouds
else if (condition == 804) {
self.icon.image = UIImage(named: "overcast")
}
// Extreme
else if ((condition >= 900 && condition < 903) || (condition > 904 && condition < 1000)) {
self.icon.image = UIImage(named: "tstorm3")
}
// Cold
else if (condition == 903) {
self.icon.image = UIImage(named: "snow5")
}
// Hot
else if (condition == 904) {
self.icon.image = UIImage(named: "sunny")
}
// Weather condition is not available
else {
self.icon.image = UIImage(named: "dunno")
}
}
func updateUISuccess(jsonResult: NSDictionary!) {
self.loadingIndicator.stopAnimating()
self.loadingIndicator.hidden = true
self.loading.text = nil
if let tempResult = ((jsonResult["main"]? as NSDictionary)["temp"] as? Double) {
var temperature:Double
if let sys = (jsonResult["sys"]? as? NSDictionary){
if let country = (sys["country"] as? String){
if country == "US" {
temperature = round(((tempResult - 273.15) * 1.8) + 32)
} else {
temperature = round(tempResult - 273.15)
}
self.temprature.text = "\(temperature)°"
self.temprature.font = UIFont.boldSystemFontOfSize(60)
}
if let name = jsonResult["name"] as? String {
self.location.font = UIFont.boldSystemFontOfSize(25)
self.location.text = name
}
if let weather = jsonResult["weather"]? as? NSArray {
var condition = (weather[0] as NSDictionary)["id"] as Int
var sunrise = sys["sunrise"] as Double
var sunset = sys["sunset"] as Double
var nightTime = false
var now = NSDate().timeIntervalSince1970
// println(nowAsLong)
if (now < sunrise || now > sunset) {
nightTime = true
}
self.updateWeatherIcon(condition, nightTime: nightTime)
return
}
} else {
self.loading.text = "Error"
}
}
else {
self.loading.text = "Error"
}
}
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
var location:CLLocation = locations[locations.count-1] as CLLocation
if(location.horizontalAccuracy > 0) {
println(location.coordinate.latitude)
println(location.coordinate.longitude)
self.updateWeatherInfo(location.coordinate.latitude, longitude: location.coordinate.longitude)
locationManager.stopUpdatingLocation()
}
}
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println(error)
self.loading.text = "GEO Error!"
}
}
| gpl-2.0 | b12f7632d5650fc644eedd2790321424 | 33.243119 | 121 | 0.522706 | 5.134113 | false | false | false | false |
Paladinfeng/leetcode | leetcode/Pascal's Triangle/main.swift | 1 | 901 | //
// main.swift
// Pascal's Triangle
//
// Created by xuezhaofeng on 31/01/2018.
// Copyright © 2018 paladinfeng. All rights reserved.
//
import Foundation
class Solution {
func generate(_ numRows: Int) -> [[Int]] {
var result = [[Int]]()
if numRows == 0 {
return result;
}
for i in 0..<numRows {
var current = [Int]()
//填数
for j in 0...i {
// i 列 j 行
if (i > 1 && j > 0 && j < i) {
print(result[i-1][j], result[i-1][j-1])
current.append(result[i-1][j] + result[i-1][j-1])
} else {
current.append(1)
}
//print(current)
}
result.append(current)
}
return result
}
}
let result = Solution().generate(100)
print(result)
| mit | c2efa1e5a3b76bd60ad2b1f0a6aeedae | 23.108108 | 69 | 0.434978 | 3.763713 | false | false | false | false |
LetItPlay/iOSClient | blockchainapp/ChannelPresenter.swift | 1 | 3180 | //
// ChannelPresenter.swift
// blockchainapp
//
// Created by Aleksey Tyurnin on 11/12/2017.
// Copyright © 2017 Ivan Gorbulin. All rights reserved.
//
import Foundation
import RealmSwift
protocol ChannelPresenterDelegate: class {
func followUpdate()
}
class ChannelPresenter {
var tracks: [[Track]] = []
var token: NotificationToken?
var station: Station!
var currentTrackID: Int?
weak var view: ChannelViewController?
var subManager = SubscribeManager.shared
init(station: Station) {
self.station = station
let realm = try! Realm()
let results = realm.objects(Track.self).filter("station == \(station.id)").sorted(byKeyPath: "publishedAt", ascending: false)
token = results.observe({ [weak self] (changes: RealmCollectionChange) in
let filter: (Track) -> Bool = {$0.station == self?.station.id}
switch changes {
case .initial:
// Results are now populated and can be accessed without blocking the UI
self?.tracks = [Array(results)]
case .update(_, _, _, _):
// Query results have changed, so apply them to the UITableView
self?.tracks = [Array(results).filter(filter)]
case .error(let error):
// An error occurred while opening the Realm file on the background worker thread
fatalError("\(error)")
}
self?.view?.update()
})
NotificationCenter.default.addObserver(self,
selector: #selector(trackPlayed(notification:)),
name: AudioController.AudioStateNotification.playing.notification(),
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(trackPaused(notification:)),
name: AudioController.AudioStateNotification.paused.notification(),
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(subscribed(notification:)),
name: SubscribeManager.NotificationName.added.notification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(unsubscribed(notification:)),
name: SubscribeManager.NotificationName.deleted.notification,
object: nil)
self.getData()
}
func getData() {
DownloadManager.shared.requestTracks(all: true, success: { (feed) in
}) { (err) in
}
}
deinit {
NotificationCenter.default.removeObserver(self)
token?.invalidate()
}
func followPressed() {
subManager.addOrDelete(station: self.station.id)
}
@objc func trackPlayed(notification: Notification) {
if let id = notification.userInfo?["ItemID"] as? String, let index = self.tracks.first?.index(where: {$0.audiotrackId() == id}) {
self.view?.currentIndex = index
self.view?.update()
}
}
@objc func trackPaused(notification: Notification) {
if let id = notification.userInfo?["ItemID"] as? String, let _ = self.tracks.first?.index(where: {$0.audiotrackId() == id}) {
self.view?.currentIndex = -1
self.view?.update()
}
}
@objc func subscribed(notification: Notification) {
self.view?.followUpdate()
}
@objc func unsubscribed(notification: Notification) {
self.view?.followUpdate()
}
}
| mit | 71ae12397a80187de453e76d6bc0a92a | 27.9 | 131 | 0.676313 | 3.891065 | false | false | false | false |
janardhan1212/Virtual-Tourist | Virtual Tourist/CoreDataStack.swift | 1 | 1099 | //
// CoreDataStack.swift
// Virtual Tourist
//
// Created by Denis Ricard on 2016-10-22.
// Copyright © 2016 Hexaedre. All rights reserved.
//
import Foundation
import CoreData
class CoreDataStack {
private let modelName: String
init(modelName: String) {
self.modelName = modelName
}
private lazy var storeContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: self.modelName)
container.loadPersistentStores { (storeDescription, error) in
if let error = error as NSError? {
print("Unresolved error loading persistent store: \(error), \(error.userInfo)")
}
}
return container
}()
lazy var managedContext: NSManagedObjectContext = {
return self.storeContainer.viewContext
}()
func saveContext() {
guard managedContext.hasChanges else { return }
do {
try managedContext.save()
} catch let error as NSError {
print("Could not save context: \(error), \(error.userInfo)")
}
}
}
| mit | 712dc624f3126fc39da4af0073dac3c7 | 22.361702 | 91 | 0.62204 | 4.990909 | false | false | false | false |
seungprk/PenguinJump | Archive/PenguinJumpSwipePrototype/PenguinJump/GameViewController.swift | 1 | 704 | //
// GameViewController.swift
// PenguinJump
//
// Created by Matthew Tso on 5/13/16.
// Copyright (c) 2016 De Anza. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let scene = GameScene(size: view.bounds.size)
let skView = view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.showsPhysics = true
skView.ignoresSiblingOrder = true
scene.scaleMode = .ResizeFill
skView.presentScene(scene)
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| bsd-2-clause | e78cb276e8845c0b6e672321d3d35079 | 22.466667 | 53 | 0.632102 | 4.662252 | false | false | false | false |
MartinOSix/DemoKit | dSwift/SwiftDemoKit/SwiftDemoKit/LinerLayout.swift | 1 | 5010 | //
// LinerLayout.swift
// SwiftDemoKit
//
// Created by runo on 17/5/16.
// Copyright © 2017年 com.runo. All rights reserved.
//
import UIKit
/*自定义layout
1.UICollectionViewLayoutAttributes:该属性是所有cell的frame都由该属性的相关设置完成的。修改该属性即修改了cell相关属性。
2.UICollectionViewFlowLayout:完成collectionView的布局需要设置该属性。
3.prepare():需要重新布局前,都会调用该方法,一般重写该方法做一些准备工作,比如计算好所有cell布局,并且缓存下来,需要的时候直接取即可
4.layoutAttributesForElementsInRect(rect: CGRect):该方法紧随prepare()后调用,用于获取rect范围内所有cell的布局。该方法必须重写,提供相应rect范围内cell的所有布局的UICollectionViewLayoutAttributes,如果已经计算好,就直接返回。如果只返回rect范围内的cell的布局,而不是全部cell的布局,需要设置一下
5.shouldInvalidateLayoutForBoundsChange(newBounds: CGRect):当collectionView的bounds变化时会调用该方法。如果布局是会时刻变化的,需要在滚动过程中重新布局,需要返回true,否则false
*返回true的时候,collectionview的layout设置为invalidate,将会使collectionview重新调用上面的preparelayout()方法重新获得布局
*同时,当屏幕旋转的时候,collectionview的bounds也会调用该方法,如果设置为false,不会达到屏幕适配效果
*collectionview执行delete,insert,reload等,不会调用该方法,会调用prepare()重新获得布局
6.需要设置collectionview的滚动范围collectionviewcontensize(),自定义时,必须重写该方法,返回正确的滚动范围
7.如下方法也建议重写:
自定义cell布局的时候重写
public func layoutAttributesForItemAtIndexPath(indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?
自定义SupplementaryView的时候重写
public func layoutAttributesForSupplementaryViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?
自定义DecorationView的时候重写
public func layoutAttributesForDecorationViewOfKind(elementKind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionViewLayoutAttributes?
8.public func targetContentOffsetForProposedContentOffset(proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint:这个方法是当collectionView将停止滚动的时候调用, 我们可以重写它来实现, collectionView停在指定的位置(比如照片浏览的时候, 你可以通过这个实现居中显示照片)
*/
class LinerLayout: UICollectionViewFlowLayout {
//缓存布局
private var layoutAttributes = [UICollectionViewLayoutAttributes]()
override func prepare() {
super.prepare()
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
let superlayoutAttributes = super.layoutAttributesForElements(in: rect)!
let collectionViewCenterX = collectionView!.bounds.width * 0.5
superlayoutAttributes.forEach { (attributes) in
let copyLayout = attributes.copy() as! UICollectionViewLayoutAttributes
//中心点横向距离差
let deltaX = abs(collectionViewCenterX - copyLayout.center.x + collectionView!.contentOffset.x)
//计算屏幕内的cell的transform
if deltaX < kScreenWidth-80+20{
let offset = deltaX/(kScreenWidth-80+20)
let scale = 1 - (0.1 * offset)
copyLayout.transform = CGAffineTransform(scaleX: scale, y: scale)
}else {
copyLayout.transform = CGAffineTransform(scaleX: 0.9, y: 0.9)
}
layoutAttributes.append(copyLayout)
}
return layoutAttributes
}
override func shouldInvalidateLayout(forBoundsChange newBounds: CGRect) -> Bool {
return true
}
override func targetContentOffset(forProposedContentOffset proposedContentOffset: CGPoint, withScrollingVelocity velocity: CGPoint) -> CGPoint {
// 计算最终的可见范围
var rect = CGRect.zero;
rect.origin = proposedContentOffset;
rect.size = (self.collectionView?.frame.size)!;
let attributes = layoutAttributesForElements(in: rect)
let centerX = proposedContentOffset.x + (self.collectionView?.bounds.size.width)! * 0.5;
//获取最小间距
var minDetal = kScreenWidth;
for attrs in attributes! {
if (abs(minDetal) > abs(attrs.center.x - centerX)) {
minDetal = attrs.center.x - centerX;
}
}
// 在原有offset的基础上进行微调
return CGPoint.init(x: proposedContentOffset.x + minDetal, y: proposedContentOffset.y)
}
}
| apache-2.0 | a21a4fa301483ca6289abe7adc6ff3c2 | 34.495575 | 236 | 0.723012 | 4.427152 | false | false | false | false |
cooliean/CLLKit | XLForm/Examples/Swift/SwiftExample/AppDelegate.swift | 8 | 3464 | //
// AppDelegate.swift
// SwiftExample
//
// Created by Martin Barreto on 3/10/15.
// Copyright (c) 2014-2015 Xmartlabs. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Declare custom rows
XLFormViewController.cellClassesForRowDescriptorTypes()[XLFormRowDescriptorTypeRate] = "XLFormRatingCell"
XLFormViewController.cellClassesForRowDescriptorTypes()[XLFormRowDescriptorTypeFloatLabeledTextField] = FloatLabeledTextFieldCell.self
XLFormViewController.cellClassesForRowDescriptorTypes()[XLFormRowDescriptorTypeWeekDays] = "XLFormWeekDaysCell"
XLFormViewController.cellClassesForRowDescriptorTypes()[XLFormRowDescriptorTypeSegmentedInline] = InlineSegmentedCell.self
XLFormViewController.cellClassesForRowDescriptorTypes()[XLFormRowDescriptorTypeSegmentedControl] = InlineSegmentedControl.self
XLFormViewController.inlineRowDescriptorTypesForRowDescriptorTypes()[XLFormRowDescriptorTypeSegmentedInline] = XLFormRowDescriptorTypeSegmentedControl
// Override point for customization after application launch.
self.window = UIWindow.init(frame: UIScreen.mainScreen().bounds)
// Override point for customization after application launch.
self.window!.backgroundColor = .whiteColor()
// load the initial form form Storybiard
let storyboard = UIStoryboard.init(name:"iPhoneStoryboard", bundle:nil)
self.window!.rootViewController = storyboard.instantiateInitialViewController()
self.window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | 777e19afaa30275664b22af7142cde48 | 53.984127 | 285 | 0.76761 | 5.891156 | false | false | false | false |
RoRoche/iOSSwiftStarter | iOSSwiftStarter/Pods/Nimble/Sources/Nimble/Matchers/Match.swift | 111 | 1024 | import Foundation
#if _runtime(_ObjC)
/// A Nimble matcher that succeeds when the actual string satisfies the regular expression
/// described by the expected string.
public func match(expectedValue: String?) -> NonNilMatcherFunc<String> {
return NonNilMatcherFunc { actualExpression, failureMessage in
failureMessage.postfixMessage = "match <\(stringify(expectedValue))>"
if let actual = try actualExpression.evaluate() {
if let regexp = expectedValue {
return actual.rangeOfString(regexp, options: .RegularExpressionSearch) != nil
}
}
return false
}
}
extension NMBObjCMatcher {
public class func matchMatcher(expected: NSString) -> NMBMatcher {
return NMBObjCMatcher(canMatchNil: false) { actualExpression, failureMessage in
let actual = actualExpression.cast { $0 as? String }
return try! match(expected.description).matches(actual, failureMessage: failureMessage)
}
}
}
#endif
| apache-2.0 | 3f3906567b47b3ce106634144975cbb0 | 33.133333 | 99 | 0.679688 | 5.417989 | false | false | false | false |
hughbe/swift | stdlib/public/core/SetAlgebra.swift | 4 | 26063 | //===--- SetAlgebra.swift - Protocols for set operations ------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
//
//
//===----------------------------------------------------------------------===//
/// A type that provides mathematical set operations.
///
/// You use types that conform to the `SetAlgebra` protocol when you need
/// efficient membership tests or mathematical set operations such as
/// intersection, union, and subtraction. In the standard library, you can
/// use the `Set` type with elements of any hashable type, or you can easily
/// create bit masks with `SetAlgebra` conformance using the `OptionSet`
/// protocol. See those types for more information.
///
/// - Note: Unlike ordinary set types, the `Element` type of an `OptionSet` is
/// identical to the `OptionSet` type itself. The `SetAlgebra` protocol is
/// specifically designed to accommodate both kinds of set.
///
/// Conforming to the SetAlgebra Protocol
/// =====================================
///
/// When implementing a custom type that conforms to the `SetAlgebra` protocol,
/// you must implement the required initializers and methods. For the
/// inherited methods to work properly, conforming types must meet the
/// following axioms. Assume that `S` is a custom type that conforms to the
/// `SetAlgebra` protocol, `x` and `y` are instances of `S`, and `e` is of
/// type `S.Element`---the type that the set holds.
///
/// - `S() == []`
/// - `x.intersection(x) == x`
/// - `x.intersection([]) == []`
/// - `x.union(x) == x`
/// - `x.union([]) == x`
/// - `x.contains(e)` implies `x.union(y).contains(e)`
/// - `x.union(y).contains(e)` implies `x.contains(e) || y.contains(e)`
/// - `x.contains(e) && y.contains(e)` if and only if
/// `x.intersection(y).contains(e)`
/// - `x.isSubset(of: y)` if and only if `y.isSuperset(of: x)`
/// - `x.isStrictSuperset(of: y)` if and only if
/// `x.isSuperset(of: y) && x != y`
/// - `x.isStrictSubset(of: y)` if and only if `x.isSubset(of: y) && x != y`
public protocol SetAlgebra : Equatable, ExpressibleByArrayLiteral {
// FIXME: write tests for SetAlgebra
/// A type for which the conforming type provides a containment test.
associatedtype Element
/// Creates an empty set.
///
/// This initializer is equivalent to initializing with an empty array
/// literal. For example, you create an empty `Set` instance with either
/// this initializer or with an empty array literal.
///
/// var emptySet = Set<Int>()
/// print(emptySet.isEmpty)
/// // Prints "true"
///
/// emptySet = []
/// print(emptySet.isEmpty)
/// // Prints "true"
init()
/// Returns a Boolean value that indicates whether the given element exists
/// in the set.
///
/// This example uses the `contains(_:)` method to test whether an integer is
/// a member of a set of prime numbers.
///
/// let primes: Set = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]
/// let x = 5
/// if primes.contains(x) {
/// print("\(x) is prime!")
/// } else {
/// print("\(x). Not prime.")
/// }
/// // Prints "5 is prime!"
///
/// - Parameter member: An element to look for in the set.
/// - Returns: `true` if `member` exists in the set; otherwise, `false`.
func contains(_ member: Element) -> Bool
/// Returns a new set with the elements of both this and the given set.
///
/// In the following example, the `attendeesAndVisitors` set is made up
/// of the elements of the `attendees` and `visitors` sets:
///
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors = ["Marcia", "Nathaniel"]
/// let attendeesAndVisitors = attendees.union(visitors)
/// print(attendeesAndVisitors)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept.
///
/// let initialIndices = Set(0..<5)
/// let expandedIndices = initialIndices.union([2, 3, 6, 7])
/// print(expandedIndices)
/// // Prints "[2, 4, 6, 7, 0, 1, 3]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set with the unique elements of this set and `other`.
///
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), which of these elements is present
/// in the result is unspecified.
func union(_ other: Self) -> Self
/// Returns a new set with the elements that are common to both this set and
/// the given set.
///
/// In the following example, the `bothNeighborsAndEmployees` set is made up
/// of the elements that are in *both* the `employees` and `neighbors` sets.
/// Elements that are in only one or the other are left out of the result of
/// the intersection.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let bothNeighborsAndEmployees = employees.intersection(neighbors)
/// print(bothNeighborsAndEmployees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
///
/// - Note: if this set and `other` contain elements that are equal but
/// distinguishable (e.g. via `===`), which of these elements is present
/// in the result is unspecified.
func intersection(_ other: Self) -> Self
/// Returns a new set with the elements that are either in this set or in the
/// given set, but not in both.
///
/// In the following example, the `eitherNeighborsOrEmployees` set is made up
/// of the elements of the `employees` and `neighbors` sets that are not in
/// both `employees` *and* `neighbors`. In particular, the names `"Bethany"`
/// and `"Eric"` do not appear in `eitherNeighborsOrEmployees`.
///
/// let employees: Set = ["Alicia", "Bethany", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani"]
/// let eitherNeighborsOrEmployees = employees.symmetricDifference(neighbors)
/// print(eitherNeighborsOrEmployees)
/// // Prints "["Diana", "Forlani", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
func symmetricDifference(_ other: Self) -> Self
/// Inserts the given element in the set if it is not already present.
///
/// If an element equal to `newMember` is already contained in the set, this
/// method has no effect. In this example, a new element is inserted into
/// `classDays`, a set of days of the week. When an existing element is
/// inserted, the `classDays` set does not change.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.wednesday, .friday]
/// print(classDays.insert(.monday))
/// // Prints "(true, .monday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// print(classDays.insert(.friday))
/// // Prints "(false, .friday)"
/// print(classDays)
/// // Prints "[.friday, .wednesday, .monday]"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: `(true, newMember)` if `newMember` was not contained in the
/// set. If an element equal to `newMember` was already contained in the
/// set, the method returns `(false, oldMember)`, where `oldMember` is the
/// element that was equal to `newMember`. In some cases, `oldMember` may
/// be distinguishable from `newMember` by identity comparison or some
/// other means.
@discardableResult
mutating func insert(
_ newMember: Element
) -> (inserted: Bool, memberAfterInsert: Element)
/// Removes the given element and any elements subsumed by the given element.
///
/// - Parameter member: The element of the set to remove.
/// - Returns: For ordinary sets, an element equal to `member` if `member` is
/// contained in the set; otherwise, `nil`. In some cases, a returned
/// element may be distinguishable from `newMember` by identity comparison
/// or some other means.
///
/// For sets where the set type and element type are the same, like
/// `OptionSet` types, this method returns any intersection between the set
/// and `[member]`, or `nil` if the intersection is empty.
@discardableResult
mutating func remove(_ member: Element) -> Element?
/// Inserts the given element into the set unconditionally.
///
/// If an element equal to `newMember` is already contained in the set,
/// `newMember` replaces the existing element. In this example, an existing
/// element is inserted into `classDays`, a set of days of the week.
///
/// enum DayOfTheWeek: Int {
/// case sunday, monday, tuesday, wednesday, thursday,
/// friday, saturday
/// }
///
/// var classDays: Set<DayOfTheWeek> = [.monday, .wednesday, .friday]
/// print(classDays.update(with: .monday))
/// // Prints "Optional(.monday)"
///
/// - Parameter newMember: An element to insert into the set.
/// - Returns: For ordinary sets, an element equal to `newMember` if the set
/// already contained such a member; otherwise, `nil`. In some cases, the
/// returned element may be distinguishable from `newMember` by identity
/// comparison or some other means.
///
/// For sets where the set type and element type are the same, like
/// `OptionSet` types, this method returns any intersection between the
/// set and `[newMember]`, or `nil` if the intersection is empty.
@discardableResult
mutating func update(with newMember: Element) -> Element?
/// Adds the elements of the given set to the set.
///
/// In the following example, the elements of the `visitors` set are added to
/// the `attendees` set:
///
/// var attendees: Set = ["Alicia", "Bethany", "Diana"]
/// let visitors: Set = ["Marcia", "Nathaniel"]
/// attendees.formUnion(visitors)
/// print(attendees)
/// // Prints "["Diana", "Nathaniel", "Bethany", "Alicia", "Marcia"]"
///
/// If the set already contains one or more elements that are also in
/// `other`, the existing members are kept.
///
/// var initialIndices = Set(0..<5)
/// initialIndices.formUnion([2, 3, 6, 7])
/// print(initialIndices)
/// // Prints "[2, 4, 6, 7, 0, 1, 3]"
///
/// - Parameter other: A set of the same type as the current set.
mutating func formUnion(_ other: Self)
/// Removes the elements of this set that aren't also in the given set.
///
/// In the following example, the elements of the `employees` set that are
/// not also members of the `neighbors` set are removed. In particular, the
/// names `"Alicia"`, `"Chris"`, and `"Diana"` are removed.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.formIntersection(neighbors)
/// print(employees)
/// // Prints "["Bethany", "Eric"]"
///
/// - Parameter other: A set of the same type as the current set.
mutating func formIntersection(_ other: Self)
/// Removes the elements of the set that are also in the given set and adds
/// the members of the given set that are not already in the set.
///
/// In the following example, the elements of the `employees` set that are
/// also members of `neighbors` are removed from `employees`, while the
/// elements of `neighbors` that are not members of `employees` are added to
/// `employees`. In particular, the names `"Alicia"`, `"Chris"`, and
/// `"Diana"` are removed from `employees` while the names `"Forlani"` and
/// `"Greta"` are added.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.formSymmetricDifference(neighbors)
/// print(employees)
/// // Prints "["Diana", "Chris", "Forlani", "Alicia", "Greta"]"
///
/// - Parameter other: A set of the same type.
mutating func formSymmetricDifference(_ other: Self)
//===--- Requirements with default implementations ----------------------===//
/// Returns a new set containing the elements of this set that do not occur
/// in the given set.
///
/// In the following example, the `nonNeighbors` set is made up of the
/// elements of the `employees` set that are not elements of `neighbors`:
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let nonNeighbors = employees.subtracting(neighbors)
/// print(nonNeighbors)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
func subtracting(_ other: Self) -> Self
/// Returns a Boolean value that indicates whether the set is a subset of
/// another set.
///
/// Set *A* is a subset of another set *B* if every member of *A* is also a
/// member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isSubset(of: employees))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
func isSubset(of other: Self) -> Bool
/// Returns a Boolean value that indicates whether the set has no members in
/// common with the given set.
///
/// In the following example, the `employees` set is disjoint with the
/// `visitors` set because no name appears in both sets.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]
/// print(employees.isDisjoint(with: visitors))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set has no elements in common with `other`;
/// otherwise, `false`.
func isDisjoint(with other: Self) -> Bool
/// Returns a Boolean value that indicates whether the set is a superset of
/// the given set.
///
/// Set *A* is a superset of another set *B* if every member of *B* is also a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(employees.isSuperset(of: attendees))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a superset of `possibleSubset`;
/// otherwise, `false`.
func isSuperset(of other: Self) -> Bool
/// A Boolean value that indicates whether the set has no elements.
var isEmpty: Bool { get }
/// Creates a new set from a finite sequence of items.
///
/// Use this initializer to create a new set from an existing sequence, like
/// an array or a range:
///
/// let validIndices = Set(0..<7).subtracting([2, 4, 5])
/// print(validIndices)
/// // Prints "[6, 0, 1, 3]"
///
/// - Parameter sequence: The elements to use as members of the new set.
init<S : Sequence>(_ sequence: S) where S.Element == Element
/// Removes the elements of the given set from this set.
///
/// In the following example, the elements of the `employees` set that are
/// also members of the `neighbors` set are removed. In particular, the
/// names `"Bethany"` and `"Eric"` are removed from `employees`.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.subtract(neighbors)
/// print(employees)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
mutating func subtract(_ other: Self)
}
/// `SetAlgebra` requirements for which default implementations
/// are supplied.
///
/// - Note: A type conforming to `SetAlgebra` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension SetAlgebra {
/// Creates a new set from a finite sequence of items.
///
/// Use this initializer to create a new set from an existing sequence, like
/// an array or a range:
///
/// let validIndices = Set(0..<7).subtracting([2, 4, 5])
/// print(validIndices)
/// // Prints "[6, 0, 1, 3]"
///
/// - Parameter sequence: The elements to use as members of the new set.
public init<S : Sequence>(_ sequence: S)
where S.Element == Element {
self.init()
for e in sequence { insert(e) }
}
/// Removes the elements of the given set from this set.
///
/// In the following example, the elements of the `employees` set that are
/// also members of the `neighbors` set are removed. In particular, the
/// names `"Bethany"` and `"Eric"` are removed from `employees`.
///
/// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// employees.subtract(neighbors)
/// print(employees)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
public mutating func subtract(_ other: Self) {
self.formIntersection(self.symmetricDifference(other))
}
/// Returns a Boolean value that indicates whether the set is a subset of
/// another set.
///
/// Set *A* is a subset of another set *B* if every member of *A* is also a
/// member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isSubset(of: employees))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a subset of `other`; otherwise, `false`.
public func isSubset(of other: Self) -> Bool {
return self.intersection(other) == self
}
/// Returns a Boolean value that indicates whether the set is a superset of
/// the given set.
///
/// Set *A* is a superset of another set *B* if every member of *B* is also a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(employees.isSuperset(of: attendees))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a superset of `other`; otherwise,
/// `false`.
public func isSuperset(of other: Self) -> Bool {
return other.isSubset(of: self)
}
/// Returns a Boolean value that indicates whether the set has no members in
/// common with the given set.
///
/// In the following example, the `employees` set is disjoint with the
/// `visitors` set because no name appears in both sets.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let visitors: Set = ["Marcia", "Nathaniel", "Olivia"]
/// print(employees.isDisjoint(with: visitors))
/// // Prints "true"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set has no elements in common with `other`;
/// otherwise, `false`.
public func isDisjoint(with other: Self) -> Bool {
return self.intersection(other).isEmpty
}
/// Returns a new set containing the elements of this set that do not occur
/// in the given set.
///
/// In the following example, the `nonNeighbors` set is made up of the
/// elements of the `employees` set that are not elements of `neighbors`:
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"]
/// let nonNeighbors = employees.subtract(neighbors)
/// print(nonNeighbors)
/// // Prints "["Diana", "Chris", "Alicia"]"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: A new set.
public func subtracting(_ other: Self) -> Self {
return self.intersection(self.symmetricDifference(other))
}
/// A Boolean value that indicates whether the set has no elements.
public var isEmpty: Bool {
return self == Self()
}
/// Returns a Boolean value that indicates whether this set is a strict
/// superset of the given set.
///
/// Set *A* is a strict superset of another set *B* if every member of *B* is
/// also a member of *A* and *A* contains at least one element that is *not*
/// a member of *B*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(employees.isStrictSuperset(of: attendees))
/// // Prints "true"
///
/// // A set is never a strict superset of itself:
/// print(employees.isStrictSuperset(of: employees))
/// // Prints "false"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a strict superset of `other`; otherwise,
/// `false`.
public func isStrictSuperset(of other: Self) -> Bool {
return self.isSuperset(of: other) && self != other
}
/// Returns a Boolean value that indicates whether this set is a strict
/// subset of the given set.
///
/// Set *A* is a strict subset of another set *B* if every member of *A* is
/// also a member of *B* and *B* contains at least one element that is not a
/// member of *A*.
///
/// let employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"]
/// let attendees: Set = ["Alicia", "Bethany", "Diana"]
/// print(attendees.isStrictSubset(of: employees))
/// // Prints "true"
///
/// // A set is never a strict subset of itself:
/// print(attendees.isStrictSubset(of: attendees))
/// // Prints "false"
///
/// - Parameter other: A set of the same type as the current set.
/// - Returns: `true` if the set is a strict subset of `other`; otherwise,
/// `false`.
public func isStrictSubset(of other: Self) -> Bool {
return other.isStrictSuperset(of: self)
}
}
extension SetAlgebra where Element == ArrayLiteralElement {
/// Creates a set containing the elements of the given array literal.
///
/// Do not call this initializer directly. It is used by the compiler when
/// you use an array literal. Instead, create a new set using an array
/// literal as its value by enclosing a comma-separated list of values in
/// square brackets. You can use an array literal anywhere a set is expected
/// by the type context.
///
/// Here, a set of strings is created from an array literal holding only
/// strings:
///
/// let ingredients: Set = ["cocoa beans", "sugar", "cocoa butter", "salt"]
/// if ingredients.isSuperset(of: ["sugar", "salt"]) {
/// print("Whatever it is, it's bound to be delicious!")
/// }
/// // Prints "Whatever it is, it's bound to be delicious!"
///
/// - Parameter arrayLiteral: A list of elements of the new set.
public init(arrayLiteral: Element...) {
self.init(arrayLiteral)
}
}
@available(*, unavailable, renamed: "SetAlgebra")
public typealias SetAlgebraType = SetAlgebra
extension SetAlgebra {
@available(*, unavailable, renamed: "intersection(_:)")
public func intersect(_ other: Self) -> Self {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "symmetricDifference(_:)")
public func exclusiveOr(_ other: Self) -> Self {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "formUnion(_:)")
public mutating func unionInPlace(_ other: Self) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "formIntersection(_:)")
public mutating func intersectInPlace(_ other: Self) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "formSymmetricDifference(_:)")
public mutating func exclusiveOrInPlace(_ other: Self) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "isSubset(of:)")
public func isSubsetOf(_ other: Self) -> Bool {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "isDisjoint(with:)")
public func isDisjointWith(_ other: Self) -> Bool {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "isSuperset(of:)")
public func isSupersetOf(_ other: Self) -> Bool {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "subtract(_:)")
public mutating func subtractInPlace(_ other: Self) {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "isStrictSuperset(of:)")
public func isStrictSupersetOf(_ other: Self) -> Bool {
Builtin.unreachable()
}
@available(*, unavailable, renamed: "isStrictSubset(of:)")
public func isStrictSubsetOf(_ other: Self) -> Bool {
Builtin.unreachable()
}
}
| apache-2.0 | e435b46eb66251c8da24309e34b565ee | 40.173776 | 83 | 0.622837 | 4.018347 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureSettings/Sources/FeatureSettingsUI/SettingsComponents/BadgeCellPresenters/TierLimitsCellPresenter.swift | 1 | 1276 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import FeatureSettingsDomain
import PlatformUIKit
import RxRelay
import RxSwift
/// A `BadgeCellPresenting` class for showing the user's Swap Limits
final class TierLimitsCellPresenter: BadgeCellPresenting {
private typealias AccessibilityId = Accessibility.Identifier.Settings.SettingsCell
// MARK: - Properties
let accessibility: Accessibility = .id(AccessibilityId.AccountLimits.title)
let labelContentPresenting: LabelContentPresenting
let badgeAssetPresenting: BadgeAssetPresenting
var isLoading: Bool {
isLoadingRelay.value
}
// MARK: - Private Properties
private let isLoadingRelay = BehaviorRelay<Bool>(value: true)
private let disposeBag = DisposeBag()
// MARK: - Setup
init(tiersProviding: TierLimitsProviding) {
labelContentPresenting = TierLimitsLabelContentPresenter(provider: tiersProviding, descriptors: .settings)
badgeAssetPresenting = DefaultBadgeAssetPresenter(
interactor: TierLimitsBadgeInteractor(limitsProviding: tiersProviding)
)
badgeAssetPresenting.state
.map(\.isLoading)
.bindAndCatch(to: isLoadingRelay)
.disposed(by: disposeBag)
}
}
| lgpl-3.0 | 52e7b1ed915d312a448b9918f2c3af6f | 31.692308 | 114 | 0.735686 | 5.402542 | false | false | false | false |
elpassion/el-space-ios | ELSpaceTests/TestDoubles/Mocks/GoogleSignInMock.swift | 1 | 851 | //
// Created by Bartlomiej Guminiak on 12/06/2017.
// Copyright © 2017 El Passion. All rights reserved.
//
@testable
import ELSpace
import GoogleSignIn
class GoogleSignInMock: GoogleSignInProtocol {
var signInCalled = false
var disconnectCalled = false
var didCallSignInSilently = false
var didCallAuthInKeychain = false
var authInKeychainResult = false
// MARK: - GoogleSignInProtocol
weak var delegate: GIDSignInDelegate!
weak var uiDelegate: GIDSignInUIDelegate!
func signIn() {
signInCalled = true
}
func disconnect() {
disconnectCalled = true
}
func signInSilently() {
didCallSignInSilently = true
}
func hasAuthInKeychain() -> Bool {
didCallAuthInKeychain = true
return authInKeychainResult
}
var hostedDomain: String!
}
| gpl-3.0 | 91f20b6809cdc9d1654f7ec65190d4d6 | 18.767442 | 53 | 0.68 | 4.569892 | false | false | false | false |
Schwenger/SwiftUtil | Sources/SwiftUtil/Datastructures/MultiMap.swift | 1 | 1232 | //
// MultiMap.swift
// SwiftUtil
//
// Created by Maximilian Schwenger on 21.06.17.
//
// TODO: Introduce removal operation.
public struct MultiMap<Key: Hashable, Coll: Collection> : Sequence {
public typealias Value = Coll.Element
var dict: [Key: Coll]
let empty: Coll
let join: (Coll, Value) -> Coll
public init(empty: Coll, join: @escaping (Coll, Value) -> Coll) {
self.empty = empty
self.dict = [Key: Coll]()
self.join = join
}
public subscript(key: Key) -> Coll {
get {
return dict[key] ?? self.empty
}
set {
self[key] = newValue
}
}
/*
Adds `val` to the collection associated with `key`.
*/
public mutating func add(val: Value, to key: Key) {
let coll = self[key]
self[key] = self.join(coll, val)
}
/*
Removes `key` from the map, and thus any reference to the collection it was
formerly associated with.
*/
public mutating func removeKey(key: Key) {
dict.removeValue(forKey: key)
}
public func makeIterator() -> DictionaryIterator<Key,Coll> {
return self.dict.makeIterator()
}
}
| mit | 39d5dd5ffbf12e27e4d3013272f95f76 | 22.692308 | 80 | 0.5625 | 3.85 | false | false | false | false |
recoveryrecord/SurveyNative | Example/SurveyNative/MyViewController.swift | 1 | 2077 | //
// MyViewController.swift
// SurveyNativeExample
//
// Created by Nora Mullaney on 2/23/17.
// Copyright © 2017 recoveryrecord. All rights reserved.
//
import UIKit
import SurveyNative
class MyViewController: SurveyViewController, SurveyAnswerDelegate, CustomConditionDelegate, ValidationFailedDelegate {
override func viewDidLoad() {
super.viewDidLoad()
self.setSurveyAnswerDelegate(self)
self.setCustomConditionDelegate(self)
self.setValidationFailedDelegate(self)
}
override func surveyJsonFile() -> String {
return "ExampleQuestions"
}
override func surveyTitle() -> String {
return "Example Survey"
}
func question(for id: String, answer: Any) {
print("Question: \(id) has answer (maybe is complete): \(answer)")
if (surveyQuestions!.isQuestionFullyAnswered(id)) {
print("Question: \(id) is complete")
}
}
func isConditionMet(answers: [String: Any], extra: [String: Any]?) -> Bool {
let id = extra!["id"] as! String
if id == "check_age" {
if let birthYearStr = answers["birthyear"] as? String, let ageStr = answers["age"] as? String {
let birthYear = Int(birthYearStr)
let age = Int(ageStr)
let wiggleRoom = extra!["wiggle_room"] as? Int
let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year], from: date)
let currentYear = components.year
return abs(birthYear! + age! - currentYear!) > wiggleRoom!
} else {
return false
}
} else {
Logger.log("Unknown custom condition check: \(id)")
return false
}
}
func validationFailed(message: String) {
let alert = UIAlertController(title: nil, message: message, preferredStyle: UIAlertController.Style.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertAction.Style.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
| mit | e8ef06c47db7c45670a1cc24a2961eef | 31.952381 | 119 | 0.635356 | 4.343096 | false | false | false | false |
mightydeveloper/swift | utils/benchmark/BST/lfsr.swift | 9 | 705 | // Linear function shift register.
//
// This is just to drive benchmarks. I don't make any claim about its
// strength. According to Wikipedia, it has the maximal period for a
// 32-bit register.
class LFSR {
// Set the register to some seed that I pulled out of a hat.
var lfsr = 0xb78978e7
func shift() {
lfsr = (lfsr >> 1) ^ (-(lfsr & 1) & 0xD0000001)
}
func randInt() -> Int {
var result = 0
for i in 0..<32 {
result = (result << 1) | lfsr & 1
shift()
}
return result
}
}
func test() {
var lfsr = LFSR()
var rands = Dictionary<Int, Bool>()
for i in 0..<1000 {
let r = lfsr.randInt()
assert(!rands[r])
rands[r] = true
print(r)
}
}
| apache-2.0 | 93918b2f0ae2e11f4a35d4bb2514e599 | 21.03125 | 69 | 0.587234 | 3.263889 | false | false | false | false |
lorentey/swift | test/IRGen/dynamic_self_metadata.swift | 6 | 2301 | // RUN: %target-swift-frontend %s -emit-ir -parse-as-library | %FileCheck %s
// REQUIRES: CPU=x86_64
// FIXME: Not a SIL test because we can't parse dynamic Self in SIL.
// <rdar://problem/16931299>
// CHECK: [[TYPE:%.+]] = type <{ [8 x i8] }>
@inline(never) func id<T>(_ t: T) -> T {
return t
}
// CHECK-LABEL: define hidden swiftcc void @"$s21dynamic_self_metadata2idyxxlF"
protocol P {
associatedtype T
}
extension P {
func f() {}
}
struct G<T> : P {
var t: T
}
class C {
class func fromMetatype() -> Self? { return nil }
// CHECK-LABEL: define hidden swiftcc i64 @"$s21dynamic_self_metadata1CC12fromMetatypeACXDSgyFZ"(%swift.type* swiftself)
// CHECK: ret i64 0
func fromInstance() -> Self? { return nil }
// CHECK-LABEL: define hidden swiftcc i64 @"$s21dynamic_self_metadata1CC12fromInstanceACXDSgyF"(%T21dynamic_self_metadata1CC* swiftself)
// CHECK: ret i64 0
func dynamicSelfArgument() -> Self? {
return id(nil)
}
// CHECK-LABEL: define hidden swiftcc i64 @"$s21dynamic_self_metadata1CC0A12SelfArgumentACXDSgyF"(%T21dynamic_self_metadata1CC* swiftself)
// CHECK: [[GEP1:%.+]] = getelementptr {{.*}} %0
// CHECK: [[TYPE1:%.+]] = load {{.*}} [[GEP1]]
// CHECK: [[T0:%.+]] = call swiftcc %swift.metadata_response @"$sSqMa"(i64 0, %swift.type* [[TYPE1]])
// CHECK: [[TYPE2:%.+]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: call swiftcc void @"$s21dynamic_self_metadata2idyxxlF"({{.*}}, %swift.type* [[TYPE2]])
func dynamicSelfConformingType() -> Self? {
_ = G(t: self).f()
return nil
}
// CHECK-LABEL: define hidden swiftcc i64 @"$s21dynamic_self_metadata1CC0A18SelfConformingTypeACXDSgyF"(%T21dynamic_self_metadata1CC* swiftself)
// CHECK: [[SELF_GEP:%.+]] = getelementptr {{.*}} %0
// CHECK: [[SELF_TYPE:%.+]] = load {{.*}} [[SELF_GEP]]
// CHECK: [[METADATA_RESPONSE:%.*]] = call swiftcc %swift.metadata_response @"$s21dynamic_self_metadata1GVMa"(i64 0, %swift.type* [[SELF_TYPE]])
// CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[METADATA_RESPONSE]], 0
// CHECK: call i8** @swift_getWitnessTable(%swift.protocol_conformance_descriptor* bitcast ({{.*}} @"$s21dynamic_self_metadata1GVyxGAA1PAAMc" to %swift.protocol_conformance_descriptor*), %swift.type* [[METADATA]], i8*** undef)
}
| apache-2.0 | 76528cd20974e2dacd04e1892e38c1ff | 40.089286 | 228 | 0.661017 | 3.36896 | false | false | false | false |
belatrix/iOSAllStarsRemake | AllStars/AllStars/iPhone/Classes/Login/LogInGuestEmailViewController.swift | 1 | 3332 | //
// LogInGuestEmailViewController.swift
// AllStars
//
// Created by Flavio Franco Tunqui on 7/1/16.
// Copyright © 2016 Belatrix SF. All rights reserved.
//
import UIKit
class LogInGuestEmailViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var edtEmail : UITextField!
@IBOutlet weak var actRegister : UIActivityIndicatorView!
@IBOutlet weak var imgRegister : UIImageView!
@IBOutlet weak var viewEdtEmail : UIView!
@IBOutlet weak var btnRegister : UIButton!
@IBOutlet weak var lblSocialNetworkMessage : UILabel!
var fullName : String = ""
var socialNetworkType : Int = 0
var socialNetworkId : String = ""
override func viewDidLoad() {
super.viewDidLoad()
setViews()
}
// MARK: - UI
func setViews() {
viewEdtEmail.backgroundColor = UIColor.colorPrimary()
btnRegister.backgroundColor = UIColor.colorPrimary()
let image = UIImage(named: "mail")
imgRegister.image = image?.imageWithRenderingMode(.AlwaysTemplate)
imgRegister.tintColor = UIColor.colorPrimary()
if (socialNetworkType == 1) {
lblSocialNetworkMessage.text = "facebook_profile_message".localized
} else if (socialNetworkType == 2) {
lblSocialNetworkMessage.text = "twitter_profile_message".localized
}
}
func lockScreen() {
self.view.userInteractionEnabled = false
self.actRegister.startAnimating()
}
func unlockScreen() {
self.view.userInteractionEnabled = true
self.actRegister.stopAnimating()
}
// MARK: - IBActions
@IBAction func btnRegisterTUI(sender: UIButton) {
self.view.endEditing(true)
self.createParticipant(fullName, email: edtEmail.text!, socialNetworkType: 1, socialNetworkId: socialNetworkId)
}
@IBAction func btnBackTUI(sender: UIButton) {
self.view.endEditing(true)
self.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func tapCloseKeyboard(sender: AnyObject) {
self.view.endEditing(true)
}
// MARK: - WebServices
func createParticipant(fullName : String?, email : String?, socialNetworkType : Int, socialNetworkId : String) -> Void {
lockScreen()
LogInBC.createParticipant(fullName, email: email, socialNetworkType: socialNetworkType, socialNetworkId: socialNetworkId) { (userGuest, fieldsCompleted) in
self.unlockScreen()
if (fieldsCompleted) {
let sb = UIStoryboard(name: "TabBar", bundle: nil)
let guestTabController = sb.instantiateViewControllerWithIdentifier("GuestTabBarViewController") as! UITabBarController
self.presentViewController(guestTabController, animated: true, completion: nil)
}
}
}
// MARK: - UITextFieldDelegate
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
self.createParticipant(fullName, email: edtEmail.text!, socialNetworkType: 1, socialNetworkId: socialNetworkId)
return true
}
} | mit | 6df2b8c7105ccda45826da5d619b31db | 33.350515 | 163 | 0.637046 | 5.009023 | false | false | false | false |
vector-im/vector-ios | Riot/Modules/Common/ActivityIndicator/UIKit/LabelledActivityIndicatorView.swift | 1 | 3742 | //
// Copyright 2021 New Vector Ltd
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
import UIKit
import MatrixSDK
final class LabelledActivityIndicatorView: UIView, Themable {
private enum Constants {
static let padding = UIEdgeInsets(top: 20, left: 40, bottom: 15, right: 40)
static let activityIndicatorScale = CGFloat(1.5)
static let cornerRadius: CGFloat = 12.0
static let stackBackgroundOpacity: CGFloat = 0.9
static let stackSpacing: CGFloat = 15
static let backgroundOpacity: CGFloat = 0.5
}
private let stackBackgroundView: UIView = {
let view = UIView()
view.layer.cornerRadius = Constants.cornerRadius
view.alpha = Constants.stackBackgroundOpacity
return view
}()
private let stackView: UIStackView = {
let stack = UIStackView()
stack.axis = .vertical
stack.distribution = .fill
stack.alignment = .center
stack.spacing = Constants.stackSpacing
return stack
}()
private let activityIndicator: UIActivityIndicatorView = {
let view = UIActivityIndicatorView()
view.transform = .init(scaleX: Constants.activityIndicatorScale, y: Constants.activityIndicatorScale)
view.startAnimating()
return view
}()
private let label: UILabel = {
return UILabel()
}()
init(text: String) {
super.init(frame: .zero)
setup(text: text)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup(text: String) {
setupStackView()
label.text = text
}
private func setupStackView() {
addSubview(stackView)
stackView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
stackView.centerXAnchor.constraint(equalTo: centerXAnchor),
stackView.centerYAnchor.constraint(equalTo: centerYAnchor)
])
stackView.addArrangedSubview(activityIndicator)
stackView.addArrangedSubview(label)
insertSubview(stackBackgroundView, belowSubview: stackView)
stackBackgroundView.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
stackBackgroundView.topAnchor.constraint(equalTo: stackView.topAnchor, constant: -Constants.padding.top),
stackBackgroundView.bottomAnchor.constraint(equalTo: stackView.bottomAnchor, constant: Constants.padding.bottom),
stackBackgroundView.leadingAnchor.constraint(equalTo: stackView.leadingAnchor, constant: -Constants.padding.left),
stackBackgroundView.trailingAnchor.constraint(equalTo: stackView.trailingAnchor, constant: Constants.padding.right)
])
}
func update(theme: Theme) {
backgroundColor = theme.colors.primaryContent.withAlphaComponent(Constants.backgroundOpacity)
stackBackgroundView.backgroundColor = theme.colors.system
activityIndicator.color = theme.colors.secondaryContent
label.font = theme.fonts.calloutSB
label.textColor = theme.colors.secondaryContent
}
}
| apache-2.0 | bcf5548aa7cb683276e16ab0cd78a256 | 36.42 | 127 | 0.689471 | 5.233566 | false | false | false | false |
krzysztofzablocki/Sourcery | SourceryTests/Parsing/FileParser + TypeNameSpec.swift | 1 | 8882 | import Quick
import Nimble
#if SWIFT_PACKAGE
@testable import SourceryLib
#else
@testable import Sourcery
#endif
import SourceryFramework
import SourceryRuntime
class TypeNameSpec: QuickSpec {
override func spec() {
describe("TypeName") {
func typeName(_ code: String) -> TypeName {
let wrappedCode =
"""
struct Wrapper {
var myFoo: \(code)
}
"""
guard let parser = try? makeParser(for: wrappedCode) else { fail(); return TypeName(name: "") }
let result = try? parser.parse()
let variable = result?.types.first?.variables.first
return variable?.typeName ?? TypeName(name: "")
}
func typeNameFromTypealias(_ code: String) -> TypeName {
let wrappedCode = "typealias Wrapper = \(code)"
guard let parser = try? makeParser(for: wrappedCode) else { fail(); return TypeName(name: "") }
let result = try? parser.parse()
return result?.typealiases.first?.typeName ?? TypeName(name: "")
}
context("given optional type with short syntax") {
it("reports optional true") {
expect(typeName("Int?").isOptional).to(beTrue())
expect(typeName("Int!").isOptional).to(beTrue())
expect(typeName("Int?").isImplicitlyUnwrappedOptional).to(beFalse())
expect(typeName("Int!").isImplicitlyUnwrappedOptional).to(beTrue())
}
it("reports non-optional type for unwrappedTypeName") {
expect(typeName("Int?").unwrappedTypeName).to(equal("Int"))
expect(typeName("Int!").unwrappedTypeName).to(equal("Int"))
}
}
context("given inout type") {
it("reports correct unwrappedTypeName") {
expect(typeName("inout String").unwrappedTypeName).to(equal("String"))
}
}
context("given optional type with long generic syntax") {
it("reports optional true") {
expect(typeName("Optional<Int>").isOptional).to(beTrue())
expect(typeName("Optional<Int>").isImplicitlyUnwrappedOptional).to(beFalse())
}
it("reports non-optional type for unwrappedTypeName") {
expect(typeName("Optional<Int>").unwrappedTypeName).to(equal("Int"))
}
}
context("given type wrapped with extra closures") {
it("unwraps it completely") {
expect(typeName("(Int)").unwrappedTypeName).to(equal("Int"))
expect(typeName("(Int)?").unwrappedTypeName).to(equal("Int"))
expect(typeName("(Int, Int)").unwrappedTypeName).to(equal("(Int, Int)"))
expect(typeName("(Int)").unwrappedTypeName).to(equal("Int"))
expect(typeName("((Int, Int))").unwrappedTypeName).to(equal("(Int, Int)"))
expect(typeName("((Int, Int) -> ())").unwrappedTypeName).to(equal("(Int, Int) -> ()"))
}
}
context("given tuple type") {
it("reports tuple correctly") {
expect(typeName("(Int, Int)").isTuple).to(beTrue())
expect(typeName("(Int, Int)?").isTuple).to(beTrue())
expect(typeName("(Int)").isTuple).to(beFalse())
expect(typeName("Int").isTuple).to(beFalse())
expect(typeName("(Int) -> (Int)").isTuple).to(beFalse())
expect(typeName("(Int, Int) -> (Int)").isTuple).to(beFalse())
expect(typeName("(Int, (Int, Int) -> (Int))").isTuple).to(beTrue())
expect(typeName("(Int, (Int, Int))").isTuple).to(beTrue())
expect(typeName("(Int, (Int) -> (Int -> Int))").isTuple).to(beTrue())
}
}
context("given array type") {
it("reports array correctly") {
expect(typeName("Array<Int>").isArray).to(beTrue())
expect(typeName("[Int]").isArray).to(beTrue())
expect(typeName("[[Int]]").isArray).to(beTrue())
expect(typeName("[[Int: Int]]").isArray).to(beTrue())
}
it("reports dictionary correctly") {
expect(typeName("[Int]").isDictionary).to(beFalse())
expect(typeName("[[Int]]").isDictionary).to(beFalse())
expect(typeName("[[Int: Int]]").isDictionary).to(beFalse())
}
}
context("given dictionary type") {
context("as name") {
it("reports dictionary correctly") {
expect(typeName("Dictionary<Int, Int>").isDictionary).to(beTrue())
expect(typeName("[Int: Int]").isDictionary).to(beTrue())
expect(typeName("[[Int]: [Int]]").isDictionary).to(beTrue())
expect(typeName("[Int: [Int: Int]]").isDictionary).to(beTrue())
}
it("reports array correctly") {
expect(typeName("[Int: Int]").isArray).to(beFalse())
expect(typeName("[[Int]: [Int]]").isArray).to(beFalse())
expect(typeName("[Int: [Int: Int]]").isArray).to(beFalse())
}
}
}
context("given closure type") {
it("reports closure correctly") {
expect(typeName("() -> ()").isClosure).to(beTrue())
expect(typeName("(() -> ())?").isClosure).to(beTrue())
expect(typeName("(Int, Int) -> ()").isClosure).to(beTrue())
expect(typeName("() -> (Int, Int)").isClosure).to(beTrue())
expect(typeName("() -> (Int) -> (Int)").isClosure).to(beTrue())
expect(typeName("((Int) -> (Int)) -> ()").isClosure).to(beTrue())
expect(typeName("(Foo<String>) -> Bool").isClosure).to(beTrue())
expect(typeName("(Int) -> Foo<Bool>").isClosure).to(beTrue())
expect(typeName("(Foo<String>) -> Foo<Bool>").isClosure).to(beTrue())
expect(typeName("((Int, Int) -> (), Int)").isClosure).to(beFalse())
expect(typeNameFromTypealias("(Foo) -> Bar").isClosure).to(beTrue())
expect(typeNameFromTypealias("(Foo) -> Bar & Baz").isClosure).to(beTrue())
}
it("reports optional status correctly") {
expect(typeName("() -> ()").isOptional).to(beFalse())
expect(typeName("() -> ()?").isOptional).to(beFalse())
expect(typeName("() -> ()!").isImplicitlyUnwrappedOptional).to(beFalse())
expect(typeName("(() -> ()!)").isImplicitlyUnwrappedOptional).to(beFalse())
expect(typeName("Optional<()> -> ()").isOptional).to(beFalse())
expect(typeName("(() -> ()?)").isOptional).to(beFalse())
expect(typeName("(() -> ())?").isOptional).to(beTrue())
expect(typeName("(() -> ())!").isImplicitlyUnwrappedOptional).to(beTrue())
expect(typeName("Optional<() -> ()>").isOptional).to(beTrue())
}
}
context("given closure type inside generic type") {
it("reports closure correctly") {
expect(typeName("Foo<() -> ()>").isClosure).to(beFalse())
expect(typeName("Foo<(String) -> Bool>").isClosure).to(beFalse())
expect(typeName("Foo<(String) -> Bool?>").isClosure).to(beFalse())
expect(typeName("Foo<(Bar<String>) -> Bool>").isClosure).to(beFalse())
expect(typeName("Foo<(Bar<String>) -> Bar<Bool>>").isClosure).to(beFalse())
}
}
context("given closure type with attributes") {
it("removes attributes in unwrappedTypeName") {
expect(typeName("@escaping (@escaping ()->())->()").unwrappedTypeName).to(equal("(@escaping () -> ()) -> ()"))
}
it("orders attributes alphabetically") {
expect(typeName("@escaping @autoclosure () -> String").asSource).to(equal("@autoclosure @escaping () -> String"))
expect(typeName("@escaping @autoclosure () -> String").description).to(equal("@autoclosure @escaping () -> String"))
}
}
}
}
}
| mit | 8c6b29f29cade877fc12e09ccdb9e4e1 | 50.045977 | 136 | 0.490993 | 5.110472 | false | false | false | false |
JohnCoates/Aerial | Aerial/Source/Views/PrefPanel/InfoSettingsView.swift | 1 | 3365 | //
// InfoSettingsView.swift
// Aerial
//
// Created by Guillaume Louel on 14/02/2020.
// Copyright © 2020 Guillaume Louel. All rights reserved.
//
import Cocoa
class InfoSettingsView: NSView {
@IBOutlet weak var fadeInOutTextModePopup: NSPopUpButton!
@IBOutlet var highQualityTextRendering: NSButton!
@IBOutlet var changeCornerMargins: NSButton!
@IBOutlet var marginHorizontalTextfield: NSTextField!
@IBOutlet var marginVerticalTextfield: NSTextField!
// Shadows
@IBOutlet var shadowRadiusTextField: NSTextField!
@IBOutlet var shadowRadiusFormatter: NumberFormatter!
@IBOutlet var shadowOpacitySlider: NSSlider!
@IBOutlet var shadowOffsetXTextfield: NSTextField!
@IBOutlet var shadowOffsetYTextfield: NSTextField!
@IBOutlet var shadowOffsetXFormatter: NumberFormatter!
@IBOutlet var shadowOffsetYFormatter: NumberFormatter!
func setStates() {
// Margins override
if PrefsInfo.overrideMargins {
changeCornerMargins.state = .on
marginHorizontalTextfield.isEnabled = true
marginVerticalTextfield.isEnabled = true
}
highQualityTextRendering.state = PrefsInfo.highQualityTextRendering ? .on : .off
marginHorizontalTextfield.stringValue = String(PrefsInfo.marginX)
marginVerticalTextfield.stringValue = String(PrefsInfo.marginY)
fadeInOutTextModePopup.selectItem(at: PrefsInfo.fadeModeText.rawValue)
shadowRadiusFormatter.allowsFloats = false
shadowRadiusTextField.stringValue = String(PrefsInfo.shadowRadius)
shadowOpacitySlider.doubleValue = Double(PrefsInfo.shadowOpacity * 100)
shadowOffsetXTextfield.doubleValue = Double(PrefsInfo.shadowOffsetX)
shadowOffsetYTextfield.doubleValue = Double(PrefsInfo.shadowOffsetY)
}
// MARK: - Shadows
@IBAction func highQualityTextRenderingChange(_ sender: NSButton) {
PrefsInfo.highQualityTextRendering = sender.state == .on
}
@IBAction func shadowRadiusChange(_ sender: NSTextField) {
PrefsInfo.shadowRadius = Int(sender.intValue)
}
@IBAction func shadowOpacityChange(_ sender: NSSlider) {
PrefsInfo.shadowOpacity = Float(sender.intValue)/100
}
@IBAction func shadowOffsetXChange(_ sender: NSTextField) {
PrefsInfo.shadowOffsetX = CGFloat(sender.doubleValue)
}
@IBAction func shadowOffsetYChange(_ sender: NSTextField) {
PrefsInfo.shadowOffsetY = CGFloat(sender.doubleValue)
}
// MARK: - Fades
@IBAction func fadeInOutTextModePopupChange(_ sender: NSPopUpButton) {
debugLog("UI fadeInOutTextMode: \(sender.indexOfSelectedItem)")
PrefsInfo.fadeModeText = FadeMode(rawValue: sender.indexOfSelectedItem)!
}
// MARK: - Margins
@IBAction func changeMarginsToCornerClick(_ sender: NSButton) {
let onState = sender.state == .on
debugLog("UI changeMarginsToCorner: \(onState)")
marginHorizontalTextfield.isEnabled = onState
marginVerticalTextfield.isEnabled = onState
PrefsInfo.overrideMargins = onState
}
@IBAction func marginXChange(_ sender: NSTextField) {
PrefsInfo.marginX = Int(sender.stringValue) ?? 50
}
@IBAction func marginYChange(_ sender: NSTextField) {
PrefsInfo.marginY = Int(sender.stringValue) ?? 50
}
}
| mit | a1d7b8a20c7f7b18599251d36e3a6e54 | 33.326531 | 88 | 0.717598 | 4.925329 | false | false | false | false |
Draveness/DKChainableAnimationKit | DKChainableAnimationKit/Classes/DKKeyframeAnimationFunction.swift | 1 | 8085 |
//
// DKKeyframeAnimationFunction.swift
// DKChainableAnimationKit
//
// Copyright (c) 2015年 Draveness. All rights reserved.
// This is a swift port for https://github.com/NachoSoto/NSBKeyframeAnimation/blob/master/NSBKeyframeAnimation/Classes/NSBKeyframeAnimation/NSBKeyframeAnimationFunctions.c file.
import UIKit
typealias DKKeyframeAnimationFunctionBlock = (Double, Double, Double, Double) -> Double
func DKKeyframeAnimationFunctionLinear(_ t: Double, b: Double, c: Double, d: Double) -> Double {
let t = t / d
return c * t + b
}
func DKKeyframeAnimationFunctionEaseInQuad(_ t: Double, b: Double, c: Double, d: Double) -> Double {
let t = t / d
return c * t * t + b;
}
func DKKeyframeAnimationFunctionEaseOutQuad(_ t: Double, b: Double, c: Double, d: Double) -> Double {
let t = t / d
return -c * t * (t - 2) + b;
}
func DKKeyframeAnimationFunctionEaseInOutQuad(_ t: Double, b: Double, c: Double, d: Double) -> Double {
var t = t / (d / 2)
if t < 1 {
return c / 2 * t * t + b;
}
t -= 1
return -c / 2 * ((t) * (t - 2) - 1) + b;
}
func DKKeyframeAnimationFunctionEaseInCubic(_ t: Double, b: Double, c: Double, d: Double) -> Double {
let t = t / d
return c * t * t * t + b;
}
func DKKeyframeAnimationFunctionEaseOutCubic(_ t: Double, b: Double, c: Double, d: Double) -> Double {
let t = t / d - 1
return c * (t * t * t + 1) + b;
}
func DKKeyframeAnimationFunctionEaseInOutCubic(_ t: Double, b: Double, c: Double, d: Double) -> Double {
var t = t / (d / 2)
if t < 1 {
return c / 2 * t * t * t + b;
} else {
t -= 2
return c / 2 * (t * t * t + 2) + b;
}
}
func DKKeyframeAnimationFunctionEaseInQuart(_ t: Double, b: Double, c: Double, d: Double) -> Double {
let t = t / d
return c * t * t * t * t + b;
}
func DKKeyframeAnimationFunctionEaseOutQuart(_ t: Double, b: Double, c: Double, d: Double) -> Double {
let t = t / d - 1
return -c * (t * t * t * t - 1) + b;
}
func DKKeyframeAnimationFunctionEaseInOutQuart(_ t: Double, b: Double, c: Double, d: Double) -> Double {
var t = t / (d / 2)
if t < 1 {
return c / 2 * t * t * t * t + b;
} else {
t -= 2
return -c / 2 * (t * t * t * t - 2) + b;
}
}
func DKKeyframeAnimationFunctionEaseInQuint(_ t: Double, b: Double, c: Double, d: Double) -> Double {
let t = t / d
return c * t * t * t * t * t + b;
}
func DKKeyframeAnimationFunctionEaseOutQuint(_ t: Double, b: Double, c: Double, d: Double) -> Double {
let t = t / d - 1
return c * (t * t * t * t * t + 1) + b;
}
func DKKeyframeAnimationFunctionEaseInOutQuint(_ t: Double, b: Double, c: Double, d: Double) -> Double {
var t = t / (d / 2)
if t < 1 {
return c / 2 * t * t * t * t * t + b;
} else {
t -= 2
return c / 2 * (t * t * t * t * t + 2) + b;
}
}
func DKKeyframeAnimationFunctionEaseInSine(_ t: Double, b: Double, c: Double, d: Double) -> Double {
return -c * cos(t / d * (Double.pi / 2)) + c + b;
}
func DKKeyframeAnimationFunctionEaseOutSine(_ t: Double, b: Double, c: Double, d: Double) -> Double {
return c * sin(t / d * (Double.pi / 2)) + b;
}
func DKKeyframeAnimationFunctionEaseInOutSine(_ t: Double, b: Double, c: Double, d: Double) -> Double {
return -c / 2 * (cos(Double.pi * t / d) - 1) + b;
}
func DKKeyframeAnimationFunctionEaseInExpo(_ t: Double, b: Double, c: Double, d: Double) -> Double {
return (t==0) ? b : c * pow(2, 10 * (t / d - 1)) + b;
}
func DKKeyframeAnimationFunctionEaseOutExpo(_ t: Double, b: Double, c: Double, d: Double) -> Double {
return (t == d) ? b+c : c * (-pow(2, -10 * t / d) + 1) + b;
}
func DKKeyframeAnimationFunctionEaseInOutExpo(_ t: Double, b: Double, c: Double, d: Double) -> Double {
if t == 0 {
return b
}
if t == d {
return b + c
}
var t = t / (d / 2)
if t < 1 {
return c / 2 * pow(2, 10 * (t - 1)) + b
}
t -= 1
return c / 2 * (-pow(2, -10 * t) + 2) + b
}
func DKKeyframeAnimationFunctionEaseInCirc(_ t: Double, b: Double, c: Double, d: Double) -> Double {
let t = t / d
return -c * (sqrt(1 - t * t) - 1) + b;
}
func DKKeyframeAnimationFunctionEaseOutCirc(_ t: Double, b: Double, c: Double, d: Double) -> Double {
let t = t / d - 1
return c * sqrt(1 - t * t) + b
}
func DKKeyframeAnimationFunctionEaseInOutCirc(_ t: Double, b: Double, c: Double, d: Double) -> Double {
var t = t / (d / 2)
if t < 1 {
return -c / 2 * (sqrt(1 - t * t) - 1) + b
}
t -= 2
return c / 2 * (sqrt(1 - t * t) + 1) + b
}
func DKKeyframeAnimationFunctionEaseInElastic(_ t: Double, b: Double, c: Double, d: Double) -> Double {
var s = 1.70158
var p = 0.0
var a = c
if t == 0 {
return b
}
var t = t / d
if t == 1 {
return b + c
}
if p == 0.0 {
p = d * 0.3
}
if a < fabs(c) {
a = c
s = p / 4
} else {
s = p / (2 * Double.pi) * asin (c / a)
}
t -= 1
return -(a * pow(2, 10 * t) * sin((t * d - s) * (2 * Double.pi) / p )) + b;
}
func DKKeyframeAnimationFunctionEaseOutElastic(_ t: Double, b: Double, c: Double, d: Double) -> Double {
var s = 1.70158
var p = 0.0
var a = c
if t == 0 {
return b
}
var t = t / d
if t == 1 {
return b + c
}
if p == 0.0 {
p = d * 0.3
}
if a < fabs(c) {
a = c
s = p / 4
} else {
s = p / (2 * Double.pi) * asin (c / a)
}
t -= 1
return (a * pow(2, 10 * t) * sin((t * d - s) * (2 * Double.pi) / p)) + b;
}
func DKKeyframeAnimationFunctionEaseInOutElastic(_ t: Double, b: Double, c: Double, d: Double) -> Double {
var s = 1.70158
var p = 0.0
var a = c;
if t == 0 {
return b
}
var t = t / d
if t == 2 {
return b + c
}
if p == 0.0 {
p = d * 0.3 * 1.5
}
if a < fabs(c) {
a = c
s = p / 4
} else {
s = p / (2 * Double.pi) * asin (c / a)
}
if t < 1 {
t -= 1
return -0.5 * (a * pow(2,10 * t) * sin( (t * d - s) * (2 * Double.pi) / p )) + b
} else {
t -= 1
return a * pow(2,-10 * t) * sin( (t * d - s) * (2 * Double.pi) / p ) * 0.5 + c + b
}
}
func DKKeyframeAnimationFunctionEaseInBack(_ t: Double, b: Double, c: Double, d: Double) -> Double {
let s = 1.70158
let t = t / d
return c * t * t * ((s + 1) * t - s) + b;
}
func DKKeyframeAnimationFunctionEaseOutBack(_ t: Double, b: Double, c: Double, d: Double) -> Double {
let s = 1.70158
let t = t / d - 1
return c * (t * t * ((s + 1) * t + s) + 1) + b;
}
func DKKeyframeAnimationFunctionEaseInOutBack(_ t: Double, b: Double, c: Double, d: Double) -> Double {
var s = 1.70158
var t = t / (d / 2)
if t < 1 {
s *= 1.525
return c / 2 * (t * t * ((s + 1) * t - s)) + b;
} else {
t -= 2
s *= 1.525
return c / 2 * (t * t * ((s + 1) * t + s) + 2) + b;
}
}
func DKKeyframeAnimationFunctionEaseInBounce(_ t: Double, b: Double, c: Double, d: Double) -> Double {
return c - DKKeyframeAnimationFunctionEaseOutBounce(d - t, b: 0, c: c, d: d) + b;
}
func DKKeyframeAnimationFunctionEaseOutBounce(_ t: Double, b: Double, c: Double, d: Double) -> Double {
var t = t / d
if t < 1 / 2.75 {
return c * (7.5625 * t * t) + b;
} else if t < 2 / 2.75 {
t -= 1.5 / 2.75
return c * (7.5625 * t * t + 0.75) + b;
} else if t < 2.5 / 2.75 {
t -= 2.25 / 2.75
return c * (7.5625 * t * t + 0.9375) + b;
} else {
t -= 2.625 / 2.75
return c * (7.5625 * t * t + 0.984375) + b;
}
}
func DKKeyframeAnimationFunctionEaseInOutBounce(_ t: Double, b: Double, c: Double, d: Double) -> Double {
if t < d / 2 {
return DKKeyframeAnimationFunctionEaseInBounce (t * 2, b: 0, c: c, d: d) * 0.5 + b;
} else {
return DKKeyframeAnimationFunctionEaseOutBounce(t * 2 - d, b: 0, c: c, d: d) * 0.5 + c * 0.5 + b;
}
}
| mit | ba4e6d61e595c67ac06ea0f4127a8075 | 27.561837 | 178 | 0.518496 | 2.987066 | false | false | false | false |
ibari/ios-yelp | Yelp/YelpClient.swift | 1 | 3286 | //
// YelpClient.swift
// Yelp
//
// Created by Timothy Lee on 9/19/14.
// Copyright (c) 2014 Timothy Lee. All rights reserved.
//
import UIKit
// You can register for Yelp API keys here: http://www.yelp.com/developers/manage_api_keys
let yelpConsumerKey = "vxKwwcR_NMQ7WaEiQBK_CA"
let yelpConsumerSecret = "33QCvh5bIF5jIHR5klQr7RtBDhQ"
let yelpToken = "uRcRswHFYa1VkDrGV6LAW2F8clGh5JHV"
let yelpTokenSecret = "mqtKIxMIR4iBtBPZCmCLEb-Dz3Y"
enum YelpSortMode: Int {
case BestMatched = 0, Distance, HighestRated
}
class YelpClient: BDBOAuth1RequestOperationManager {
var accessToken: String!
var accessSecret: String!
class var sharedInstance : YelpClient {
struct Static {
static var token : dispatch_once_t = 0
static var instance : YelpClient? = nil
}
dispatch_once(&Static.token) {
Static.instance = YelpClient(consumerKey: yelpConsumerKey, consumerSecret: yelpConsumerSecret, accessToken: yelpToken, accessSecret: yelpTokenSecret)
}
return Static.instance!
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
init(consumerKey key: String!, consumerSecret secret: String!, accessToken: String!, accessSecret: String!) {
self.accessToken = accessToken
self.accessSecret = accessSecret
var baseUrl = NSURL(string: "http://api.yelp.com/v2/")
super.init(baseURL: baseUrl, consumerKey: key, consumerSecret: secret);
var token = BDBOAuth1Credential(token: accessToken, secret: accessSecret, expiration: nil)
self.requestSerializer.saveAccessToken(token)
}
func searchWithTerm(term: String, completion: ([Business]!, NSError!) -> Void) -> AFHTTPRequestOperation {
return searchWithTerm(term, sort: nil, categories: nil, radius: nil, deals: nil, completion: completion)
}
func searchWithTerm(term: String, sort: YelpSortMode?, categories: [String]?, radius: NSNumber?, deals: Bool?, completion: ([Business]!, NSError!) -> Void) -> AFHTTPRequestOperation {
// For additional parameters, see http://www.yelp.com/developers/documentation/v2/search_api
// Default the location to San Francisco
var parameters: [String : AnyObject] = ["term": term, "ll": "37.785771,-122.406165"]
if sort != nil {
parameters["sort"] = sort!.rawValue
}
if categories != nil && categories!.count > 0 {
parameters["category_filter"] = ",".join(categories!)
}
if deals != nil {
parameters["deals_filter"] = deals!
}
if radius != nil {
parameters["radius_filter"] = radius
}
println(parameters)
return self.GET("search", parameters: parameters, success: { (operation: AFHTTPRequestOperation!, response: AnyObject!) -> Void in
var dictionaries = response["businesses"] as? [NSDictionary]
if dictionaries != nil {
completion(Business.businesses(array: dictionaries!), nil)
}
}, failure: { (operation: AFHTTPRequestOperation!, error: NSError!) -> Void in
completion(nil, error)
})
}
}
| gpl-2.0 | 25edb1f72a21fc6ee5e3dc1be6d4d2ae | 36.340909 | 185 | 0.637858 | 4.273082 | false | false | false | false |
ngageoint/mage-ios | Mage/ObservationCompactView.swift | 1 | 5052 | //
// ObservationCompactView.swift
// MAGE
//
// Created by Daniel Barela on 5/28/21.
// Copyright © 2021 National Geospatial Intelligence Agency. All rights reserved.
//
import Foundation
class ObservationCompactView: UIView {
private var constructed = false;
private var didSetUpConstraints = false;
private var observation: Observation?;
private weak var actionsDelegate: ObservationActionsDelegate?;
private var scheme: MDCContainerScheming?;
private var cornerRadius:CGFloat = 0.0;
private var includeAttachments: Bool = false;
private lazy var stackView: PassThroughStackView = {
let stackView = PassThroughStackView(forAutoLayout: ());
stackView.axis = .vertical
stackView.alignment = .fill
stackView.spacing = 0
stackView.distribution = .fill
stackView.directionalLayoutMargins = .zero;
stackView.isLayoutMarginsRelativeArrangement = false;
stackView.translatesAutoresizingMaskIntoConstraints = false;
stackView.clipsToBounds = true;
return stackView;
}()
public lazy var importantView: ObservationImportantView = {
let importantView = ObservationImportantView(observation: self.observation, cornerRadius: self.cornerRadius);
return importantView;
}()
private lazy var observationSummaryView: ObservationSummaryView = {
let summary = ObservationSummaryView();
summary.isUserInteractionEnabled = false;
return summary;
}()
private lazy var observationActionsView: ObservationListActionsView = {
let actions = ObservationListActionsView(observation: self.observation, observationActionsDelegate: actionsDelegate, scheme: nil);
return actions;
}();
private lazy var attachmentSlideshow: AttachmentSlideShow = {
let actions = AttachmentSlideShow();
actions.isUserInteractionEnabled = true;
return actions;
}();
required init(coder aDecoder: NSCoder) {
fatalError("This class does not support NSCoding")
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let result = super.hitTest(point, with: event)
if result == self { return nil }
return result
}
init(cornerRadius: CGFloat, includeAttachments: Bool = false, actionsDelegate: ObservationActionsDelegate? = nil, scheme: MDCContainerScheming? = nil) {
super.init(frame: CGRect.zero);
translatesAutoresizingMaskIntoConstraints = false;
self.cornerRadius = cornerRadius;
self.actionsDelegate = actionsDelegate;
self.scheme = scheme;
self.includeAttachments = includeAttachments;
construct()
}
func applyTheme(withScheme scheme: MDCContainerScheming?) {
self.scheme = scheme;
importantView.applyTheme(withScheme: scheme);
observationSummaryView.applyTheme(withScheme: scheme);
observationActionsView.applyTheme(withScheme: scheme);
attachmentSlideshow.applyTheme(withScheme: scheme);
}
@objc public func configure(observation: Observation, scheme: MDCContainerScheming?, actionsDelegate: ObservationActionsDelegate?, attachmentSelectionDelegate: AttachmentSelectionDelegate?) {
self.observation = observation;
self.actionsDelegate = actionsDelegate;
if (observation.isImportant) {
importantView.populate(observation: observation);
importantView.isHidden = false;
} else {
importantView.isHidden = true;
}
observationSummaryView.populate(observation: observation);
observationActionsView.populate(observation: observation, delegate: actionsDelegate);
attachmentSlideshow.applyTheme(withScheme: scheme)
if includeAttachments, let attachments = observation.attachments, attachments.filter({ attachment in
attachment.url != nil
}).count > 0 {
attachmentSlideshow.populate(observation: observation, attachmentSelectionDelegate: attachmentSelectionDelegate);
attachmentSlideshow.isHidden = false;
} else {
attachmentSlideshow.isHidden = true;
}
applyTheme(withScheme: scheme);
}
func prepareForReuse() {
attachmentSlideshow.clear()
}
override func updateConstraints() {
if (!didSetUpConstraints) {
stackView.autoPinEdgesToSuperviewEdges();
didSetUpConstraints = true;
}
super.updateConstraints();
}
func construct() {
if (!constructed) {
self.addSubview(stackView)
self.stackView.addArrangedSubview(importantView);
self.stackView.addArrangedSubview(observationSummaryView);
self.stackView.addArrangedSubview(attachmentSlideshow);
self.stackView.addArrangedSubview(observationActionsView);
setNeedsUpdateConstraints();
constructed = true;
}
}
}
| apache-2.0 | f91ff815390331cd9a913c7bc6d9279a | 38.155039 | 195 | 0.681845 | 5.739773 | false | false | false | false |
radimhalfar/testables | Testables/PossibleVehicles/FastCar.swift | 1 | 789 | //
// FastCar.swift
// Testables
//
// Created by Radim Halfar on 30.01.17.
// Copyright © 2017 Inloop, s.r.o. All rights reserved.
//
import Foundation
class FastCar: Vehicle {
fileprivate var _brand: BrandType = .unknown
fileprivate var _drivingState: DrivingState
var numberOfWheels: Int { return 4 }
var maxSpeed: Float { return 344.0 }
var brand: BrandType { return _brand }
required init(brand: BrandType) {
self._brand = brand
self._drivingState = StillDrivingState()
}
}
extension FastCar {
var state: DrivingState { return _drivingState }
func drive() {
_drivingState = MovingDrivingState()
}
func stop() {
_drivingState = StillDrivingState()
}
}
| mit | 242006dee679f6288145511bc8047b5a | 18.7 | 56 | 0.609137 | 3.94 | false | false | false | false |
J3D1-WARR10R/WikiRaces | WikiRaces/Shared/Race View Controllers/Other/VisualEffectViewController.swift | 2 | 1624 | //
// VisualEffectViewController.swift
// WikiRaces
//
// Created by Andrew Finke on 8/5/17.
// Copyright © 2017 Andrew Finke. All rights reserved.
//
import UIKit
import WKRUIKit
internal class VisualEffectViewController: UIViewController {
// MARK: - Properties
private let visualEffectView = UIVisualEffectView(effect: UIBlurEffect.wkrBlurEffect)
final var contentView: UIView {
return visualEffectView.contentView
}
// MARK: - View Life Cycle
override func loadView() {
self.view = visualEffectView
}
override func viewDidLoad() {
super.viewDidLoad()
guard let nav = navigationController else { return }
nav.navigationBar.setBackgroundImage(UIImage(), for: .default)
nav.navigationBar.shadowImage = UIImage()
nav.navigationBar.isTranslucent = true
nav.view.backgroundColor = .clear
}
// MARK: - Interface
func configure(hostingView: UIView) {
hostingView.backgroundColor = .clear
hostingView.translatesAutoresizingMaskIntoConstraints = false
let contraints = [
hostingView.leftAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.leftAnchor),
hostingView.rightAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.rightAnchor),
hostingView.topAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.topAnchor),
hostingView.bottomAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.bottomAnchor)
]
contentView.addSubview(hostingView)
NSLayoutConstraint.activate(contraints)
}
}
| mit | de2683947877ddfb7f741cb1e29a9019 | 31.46 | 102 | 0.707332 | 5.321311 | false | false | false | false |
overtake/TelegramSwift | Telegram-Mac/GroupCallVolumeMenuItem.swift | 1 | 4684 | //
// GroupCallVolumeMenuItem.swift
// Telegram
//
// Created by Mike Renoir on 27.01.2022.
// Copyright © 2022 Telegram. All rights reserved.
//
import Foundation
import TGUIKit
import TelegramCore
import Postbox
import SwiftSignalKit
final class GroupCallVolumeMenuItem : ContextMenuItem {
private let didUpdateValue:((CGFloat, Bool)->Void)?
private let volume: CGFloat
init(volume: CGFloat, _ didUpdateValue:((CGFloat, Bool)->Void)? = nil) {
self.volume = volume
self.didUpdateValue = didUpdateValue
super.init("")
}
required init(coder decoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func rowItem(presentation: AppMenu.Presentation, interaction: AppMenuBasicItem.Interaction) -> TableRowItem {
return GroupCallVolumeMenuRowItem(.zero, presentation: presentation, interaction: interaction, menuItem: self, volume: volume, didUpdateValue: self.didUpdateValue)
}
}
private final class GroupCallVolumeMenuRowItem : AppMenuBasicItem {
fileprivate let didUpdateValue:((CGFloat, Bool)->Void)?
fileprivate let volume: CGFloat
init(_ initialSize: NSSize, presentation: AppMenu.Presentation, interaction: AppMenuBasicItem.Interaction, menuItem: ContextMenuItem, volume: CGFloat, didUpdateValue:((CGFloat, Bool)->Void)?) {
self.didUpdateValue = didUpdateValue
self.volume = volume
super.init(initialSize, presentation: presentation, menuItem: menuItem, interaction: interaction)
}
override func viewClass() -> AnyClass {
return GroupCallVolumeMenuRowView.self
}
override var effectiveSize: NSSize {
return NSMakeSize(200, super.effectiveSize.height)
}
override var height: CGFloat {
return 28
}
}
private final class GroupCallVolumeMenuRowView : AppMenuBasicItemView {
let volumeControl = VolumeMenuItemView(frame: NSMakeRect(0, 0, 200, 26))
private var drawable_muted: AppMenuAnimatedImage?
private var drawable: AppMenuAnimatedImage?
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(volumeControl)
containerView.set(handler: { [weak self] _ in
self?.drawable?.updateState(.Hover)
}, for: .Hover)
containerView.set(handler: { [weak self] _ in
self?.drawable?.updateState(.Highlight)
}, for: .Highlight)
containerView.set(handler: { [weak self] _ in
self?.drawable?.updateState(.Normal)
}, for: .Normal)
containerView.set(handler: { [weak self] _ in
self?.drawable?.updateState(.Other)
}, for: .Other)
}
deinit {
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layout() {
super.layout()
let x: CGFloat = 11 + 18
volumeControl.setFrameSize(contentSize.width - x - 2, 26)
volumeControl.centerY(x: x)
self.drawable?.centerY(x: 11)
self.drawable_muted?.centerY(x: 11)
}
override func set(item: TableRowItem, animated: Bool = false) {
super.set(item: item, animated: animated)
guard let item = item as? GroupCallVolumeMenuRowItem else {
return
}
volumeControl.value = item.volume
volumeControl.lineColor = item.presentation.borderColor
volumeControl.didUpdateValue = { [weak item, weak self] value, sync in
item?.didUpdateValue?(value, sync)
self?.updateValue(value)
}
if self.drawable == nil, let menuItem = item.menuItem {
self.drawable = AppMenuAnimatedImage(LocalAnimatedSticker.menu_speaker, NSColor(0xffffff), menuItem)
self.drawable?.setFrameSize(NSMakeSize(18, 18))
self.addSubview(self.drawable!)
}
if self.drawable_muted == nil, let menuItem = item.menuItem {
self.drawable_muted = AppMenuAnimatedImage(LocalAnimatedSticker.menu_speaker_muted, NSColor(0xffffff), menuItem)
self.drawable_muted?.setFrameSize(NSMakeSize(18, 18))
self.addSubview(self.drawable_muted!)
}
self.drawable?.change(opacity: item.volume > 0 ? 1 : 0, animated: animated)
self.drawable_muted?.change(opacity: item.volume > 0 ? 0 : 1, animated: animated)
needsLayout = true
}
private func updateValue(_ value: CGFloat) {
self.drawable?.change(opacity: value > 0 ? 1 : 0)
self.drawable_muted?.change(opacity: value > 0 ? 0 : 1)
}
}
| gpl-2.0 | df7470ae7c2cf9d8c810a7f4b78e56a5 | 33.433824 | 197 | 0.648302 | 4.609252 | false | false | false | false |
wikimedia/wikipedia-ios | Wikipedia/Code/ArticleViewController+TableOfContents.swift | 1 | 3502 | import CocoaLumberjackSwift
extension ArticleViewController : ArticleTableOfContentsDisplayControllerDelegate {
func getVisibleSection(with completion: @escaping (_ sectionID: Int, _ anchor: String) -> Void) {
webView.evaluateJavaScript("window.wmf.elementLocation.getFirstOnScreenSection(\(navigationBar.visibleHeight))") { (result, error) in
guard
let info = result as? [String: Any],
let sectionId = info["id"] as? Int,
let anchor = info["anchor"] as? String
else {
DDLogError("Error getting first on screen section: \(String(describing: error))")
completion(-1, "")
return
}
completion(sectionId, anchor)
}
}
func hideTableOfContents() {
tableOfContentsController.hide(animated: true)
toolbarController.update()
if tableOfContentsController.viewController.displayMode == .inline {
updateArticleMargins()
}
}
func showTableOfContents() {
tableOfContentsController.show(animated: true)
toolbarController.update()
if tableOfContentsController.viewController.displayMode == .inline {
updateArticleMargins()
}
}
var tableOfContentsDisplaySide: TableOfContentsDisplaySide {
return tableOfContentsSemanticContentAttribute == .forceRightToLeft ? .right : .left
}
var tableOfContentsSemanticContentAttribute: UISemanticContentAttribute {
return MWKLanguageLinkController.semanticContentAttribute(forContentLanguageCode: articleURL.wmf_contentLanguageCode)
}
func tableOfContentsDisplayControllerDidRecreateTableOfContentsViewController() {
updateTableOfContentsInsets()
}
func tableOfContentsControllerWillDisplay(_ controller: TableOfContentsViewController) {
}
public func tableOfContentsController(_ controller: TableOfContentsViewController, didSelectItem item: TableOfContentsItem) {
switch tableOfContentsController.viewController.displayMode {
case .inline:
scroll(to: item.anchor, animated: true)
dispatchOnMainQueueAfterDelayInSeconds(1) {
self.webView.wmf_accessibilityCursor(toFragment: item.anchor)
}
case .modal:
scroll(to: item.anchor, animated: true)
// Don't dismiss immediately - it looks jarring - let the user see the ToC selection before dismissing
dispatchOnMainQueueAfterDelayInSeconds(0.15) {
self.hideTableOfContents()
// HAX: This is terrible, but iOS events not under our control would steal our focus if we didn't wait long enough here and due to problems in UIWebView, we cannot work around it either.
dispatchOnMainQueueAfterDelayInSeconds(1.5) {
self.webView.wmf_accessibilityCursor(toFragment: item.anchor)
}
}
}
}
public func tableOfContentsControllerDidCancel(_ controller: TableOfContentsViewController) {
tableOfContentsController.hide(animated: true)
}
public var tableOfContentsArticleLanguageURL: URL? {
let articleNSURL = self.articleURL as NSURL
if articleNSURL.wmf_isNonStandardURL {
return NSURL.wmf_URL(withDefaultSiteAndLanguageCode: "en")
} else {
return articleNSURL.wmf_site
}
}
}
| mit | d933ba982033e02b8032dbed55ce5ffe | 41.192771 | 202 | 0.66305 | 5.856187 | false | false | false | false |
pascaljette/PokeBattleDemo | PokeBattleDemo/PokeBattleDemo/PokeApi/Fetchers/MultiplePokemonTypeFetcher.swift | 1 | 5979 | // The MIT License (MIT)
//
// Copyright (c) 2015 pascaljette
//
// 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
/// Delegate for a multiple pokemon type fetcher.
protocol MultiplePokemonTypeFetcherDelegate: class {
/// Called after the fetch operation has completed.
///
/// - parameter fetcher: Reference on the fetcher that has completed the operation.
/// - parameter success: True if the operation succeeded, false otherwise.
/// - parameter result: The retrieved type array if successful, nil otherwise.
/// - parameter error: Error object if the operation failed, nil if it succeeded.
func didGetPokemonTypeArray(fetcher: MultiplePokemonTypeFetcher, success: Bool, result: [PokemonType]?, error: NSError?)
}
/// Only supports random fetching now.
class MultiplePokemonTypeFetcher {
//
// MARK: Stored properties
//
/// Weak reference on the delegate.
weak var delegate: MultiplePokemonTypeFetcherDelegate?
/// Internal reference on pokemon type fetchers. References must be kept here
/// so they don't get deallocated when they go out of function scope.
private var pokemonTypeFetchers: [PokemonTypeFetcher] = []
/// Store the pokemon type identifiers from initialisation.
private let pokemonTypeIdentifiers: [PokemonTypeIdentifier]
/// Internal reference on the pokemon type array to pass to the delegate.
private var pokemonTypeArray: [PokemonType]?
/// Internal reference on the success flag to pass to the delegate.
private var success: Bool = true
/// Internal reference on the error object to pass to the delegate.
private var error: NSError?
/// Dispatch group for thread synchronisation.
private let dispatchGroup = dispatch_group_create();
//
// MARK: Initialization
//
/// Initialise with an array of pokemon type identifiers. A fetcher
/// will be created for every single type identifier in the array.
///
/// - parameter pokemonTypeIdentifiers: Array of type identifiers for which to retrieve detailed info.
init(pokemonTypeIdentifiers: [PokemonTypeIdentifier]) {
self.pokemonTypeIdentifiers = pokemonTypeIdentifiers
}
}
extension MultiplePokemonTypeFetcher {
//
// MARK: Public functions
//
/// Fetch the data and calls the delegate on completion.
func fetch() {
resetResults()
for typeIdentifier in self.pokemonTypeIdentifiers {
let typeFetcher = PokemonTypeFetcher(pokemonTypeIdentifier: typeIdentifier)
typeFetcher.delegate = self
pokemonTypeFetchers.append(typeFetcher)
dispatch_group_enter(dispatchGroup)
typeFetcher.fetch()
}
dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0)) { [weak self] in
guard let strongSelf = self else {
return
}
dispatch_group_wait(strongSelf.dispatchGroup, DISPATCH_TIME_FOREVER)
strongSelf.delegate?.didGetPokemonTypeArray(strongSelf
, success: strongSelf.success
, result: strongSelf.pokemonTypeArray
, error: strongSelf.error)
}
}
}
extension MultiplePokemonTypeFetcher : PokemonTypeFetcherDelegate {
//
// MARK: PokemonTypeFetcherDelegate implementation
//
/// Called after the fetch operation has completed.
///
/// - parameter fetcher: Reference on the fetcher that has completed the operation.
/// - parameter success: True if the operation succeeded, false otherwise.
/// - parameter result: The retrieved type if successful, nil otherwise.
/// - parameter error: Error object if the operation failed, nil if it succeeded.
func didGetPokemonType(fetcher: PokemonTypeFetcher, success: Bool, result: PokemonType?, error: NSError?) {
defer {
dispatch_group_leave(dispatchGroup)
pokemonTypeFetchers = pokemonTypeFetchers.filter( { $0 !== fetcher} )
}
guard let pokemonTypeInstance = result where success == true else {
self.success = false
self.error = error
self.pokemonTypeArray = nil
return
}
if self.pokemonTypeArray == nil {
self.pokemonTypeArray = []
}
self.pokemonTypeArray!.append(pokemonTypeInstance)
}
}
extension MultiplePokemonTypeFetcher {
//
// MARK: Private utility functions
//
/// Reset all previously obtained results
private func resetResults() {
pokemonTypeArray = nil
success = true
error = nil
}
}
| mit | 445f003adbbb0bfd928b99a6196b7e01 | 33.761628 | 124 | 0.656632 | 5.281802 | false | false | false | false |
DadosAbertosBrasil/swift-radar-politico | swift-radar-político/View/DiarioPoliticoTableViewController.swift | 1 | 3437 | //
// DiarioPoliticoTableViewController.swift
// swift-radar-político
//
// Created by Ulysses on 3/14/16.
// Copyright © 2016 Francisco José A. C. Souza. All rights reserved.
//
import UIKit
class DiarioPoliticoTableViewController: UITableViewController, DiarioDataControllerDelegate {
private var isLoadingData = false
override func viewDidLoad() {
super.viewDidLoad()
DiarioDataController.sharedInstance.delegate = self
self.tableView.backgroundColor = UIColor(netHex: Constants.background)
}
override func viewWillAppear(animated: Bool) {
self.tableView.reloadData()
self.navigationController?.navigationBar.topItem?.title = "Votações Na Câmara"
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let detalhesView = segue.destinationViewController as! DetalhesProposicaoViewController
detalhesView.loadProposicao(sender as! CDProposicao)
}
// MARK: - Table view Delegate
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1 + (isLoadingData == true ? 1 : 0)
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (section == 0 ? DiarioDataController.sharedInstance.lastLoadedProposition : 1)
}
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
//TODO: calculate dynamic height
return CGFloat((240)+((40)*DeputadosDataController.sharedInstance.getNumberOfFollowedDeputados())) + 20
}
override func scrollViewDidScroll(scrollView: UIScrollView) {
let currentOffset = scrollView.contentOffset.y
let maximumOffset = scrollView.contentSize.height - scrollView.frame.size.height
// Change 10.0 to adjust the distance from bottom
if (maximumOffset - currentOffset <= 10.0) {
DiarioDataController.sharedInstance.loadNextPageOfPropositions()
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell:UITableViewCell
if indexPath.section == 0{
cell = tableView.dequeueReusableCellWithIdentifier("VotacaoCell", forIndexPath: indexPath) as! VotacaoCell
(cell as! VotacaoCell).loadWithVotacao(DiarioDataController.sharedInstance.proposicoes[indexPath.row])
}else{
cell = tableView.dequeueReusableCellWithIdentifier("LoadingCell", forIndexPath: indexPath)
(cell.viewWithTag(1) as! UIActivityIndicatorView).startAnimating()
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if indexPath.section == 0{
self.performSegueWithIdentifier("DetalhesProposicao", sender: DiarioDataController.sharedInstance.proposicoes[indexPath.row])
}
}
//MARK:DiarioDataControllerDelegate
func didUpdateData() {
self.tableView.reloadData()
}
func willLoadData() {
isLoadingData = true
self.tableView.reloadData()
}
func didStopLoadData() {
isLoadingData = false
self.tableView.reloadData()
}
}
| gpl-2.0 | ac20df2e7b26dd0b6534db29b508d375 | 33.656566 | 137 | 0.678519 | 5.105655 | false | false | false | false |
Obisoft2017/BeautyTeamiOS | BeautyTeam/BeautyTeam/TeamEventCell.swift | 1 | 3980 | //
// TeamEventCell.swift
// BeautyTeam
//
// Created by Carl Lee on 4/24/16.
// Copyright © 2016 Shenyang Obisoft Technology Co.Ltd. All rights reserved.
//
import UIKit
class TeamEventCell: UITableViewCell, CustomPresentCellProtocol {
var titleLabel: UILabel?
var projectImageView: UIImageView?
var projectLabel: UILabel?
var timeImageView: UIImageView?
var timeLabel: UILabel?
var emergencyLabel: UILabel?
var locationImageView: UIImageView?
var locationLabel: UILabel?
required init(reuseIdentifier: String) {
super.init(style: .Default, reuseIdentifier: reuseIdentifier)
let fontAwesomeSize = CGSize(width: 12, height: 12)
self.titleLabel = UILabel(frame: CGRectMake(10, 10, 300, 20))
self.titleLabel?.font = UIFont.systemFontOfSize(20)
// 80 227 194
self.projectImageView = UIImageView(frame: CGRectMake(10, 40, 12, 12))
self.projectImageView?.image = UIImage.fontAwesomeIconWithName(.Tag, textColor: UIColor(red: 80/255, green: 227/255, blue: 194/255, alpha: 1), size: fontAwesomeSize)
self.projectLabel = UILabel(frame: CGRectMake(30, 40, 12, 12))
self.projectLabel?.textColor = UIColor(red: 80/255, green: 227/255, blue: 194/255, alpha: 1)
self.projectLabel?.font = UIFont.systemFontOfSize(12)
// 74 144 226
self.timeImageView = UIImageView(frame: CGRectMake(10, 70, 12, 12))
self.timeImageView?.image = UIImage.fontAwesomeIconWithName(.ClockO, textColor: UIColor(red: 74/255, green: 144/255, blue: 226/255, alpha: 1), size: fontAwesomeSize)
self.timeLabel = UILabel(frame: CGRectMake(30, 70, 300, 12))
self.timeLabel?.font = UIFont.systemFontOfSize(12)
// 208 2 27
self.emergencyLabel = UILabel(frame: CGRectMake(310, 70, 100, 12))
self.emergencyLabel?.font = UIFont.boldSystemFontOfSize(12)
// 0 0 0
self.locationImageView = UIImageView(frame: CGRectMake(10, 110, 12, 12))
self.locationImageView?.image = UIImage.fontAwesomeIconWithName(.LocationArrow, textColor: UIColor.blackColor(), size: fontAwesomeSize)
self.locationLabel = UILabel(frame: CGRectMake(30, 110, 300, 12))
self.locationLabel?.font = UIFont.systemFontOfSize(12)
self.contentView.addSubview(titleLabel!)
self.contentView.addSubview(projectImageView!)
self.contentView.addSubview(projectLabel!)
self.contentView.addSubview(timeImageView!)
self.contentView.addSubview(timeLabel!)
self.contentView.addSubview(emergencyLabel!)
self.contentView.addSubview(locationImageView!)
self.contentView.addSubview(locationLabel!)
}
func assignValue(title: String, project: String, happenTime: NSDate, endTime: NSDate, location: String) {
self.titleLabel?.text = title
self.projectLabel?.text = project
let happenTimeStr = ObiBeautyTeam.ObiDateFormatter().stringFromDate(happenTime)
let endTimeStr = ObiBeautyTeam.ObiDateFormatter().stringFromDate(endTime)
let combinedTimeStr = "\(happenTimeStr) - \(endTimeStr)"
let combinedAttrStr = NSMutableAttributedString(string: combinedTimeStr)
combinedAttrStr.setAttributes([NSForegroundColorAttributeName : UIColor(red: 74/255, green: 144/255, blue: 226/255, alpha: 1)], range: NSMakeRange(0, combinedTimeStr.characters.count))
self.timeLabel?.attributedText = combinedAttrStr
self.locationLabel?.text = location
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
}
| apache-2.0 | cc3360fa179182121118282d6432d613 | 41.784946 | 192 | 0.679568 | 4.411308 | false | false | false | false |
JGiola/swift-package-manager | Sources/PackageModel/BuildSettings.swift | 1 | 5625 | /*
This source file is part of the Swift.org open source project
Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
Licensed under Apache License v2.0 with Runtime Library Exception
See http://swift.org/LICENSE.txt for license information
See http://swift.org/CONTRIBUTORS.txt for Swift project authors
*/
import Basic
public enum BuildConfiguration: String {
case debug
case release
public var dirname: String {
switch self {
case .debug: return "debug"
case .release: return "release"
}
}
}
/// A build setting condition.
public protocol BuildSettingsCondition {}
/// Namespace for build settings.
public enum BuildSettings {
/// Build settings declarations.
public struct Declaration: Hashable {
// Swift.
public static let SWIFT_ACTIVE_COMPILATION_CONDITIONS: Declaration = .init("SWIFT_ACTIVE_COMPILATION_CONDITIONS")
public static let OTHER_SWIFT_FLAGS: Declaration = .init("OTHER_SWIFT_FLAGS")
// C family.
public static let GCC_PREPROCESSOR_DEFINITIONS: Declaration = .init("GCC_PREPROCESSOR_DEFINITIONS")
public static let HEADER_SEARCH_PATHS: Declaration = .init("HEADER_SEARCH_PATHS")
public static let OTHER_CFLAGS: Declaration = .init("OTHER_CFLAGS")
public static let OTHER_CPLUSPLUSFLAGS: Declaration = .init("OTHER_CPLUSPLUSFLAGS")
// Linker.
public static let OTHER_LDFLAGS: Declaration = .init("OTHER_LDFLAGS")
public static let LINK_LIBRARIES: Declaration = .init("LINK_LIBRARIES")
public static let LINK_FRAMEWORKS: Declaration = .init("LINK_FRAMEWORKS")
/// The declaration name.
public let name: String
private init(_ name: String) {
self.name = name
}
/// The list of settings that are considered as unsafe build settings.
public static let unsafeSettings: Set<Declaration> = [
OTHER_CFLAGS, OTHER_CPLUSPLUSFLAGS, OTHER_SWIFT_FLAGS, OTHER_LDFLAGS,
]
}
/// Platforms condition implies that an assignment is valid on these platforms.
public struct PlatformsCondition: BuildSettingsCondition {
public var platforms: [Platform] {
didSet {
assert(!platforms.isEmpty, "List of platforms should not be empty")
}
}
public init() {
self.platforms = []
}
}
/// A configuration condition implies that an assignment is valid on
/// a particular build configuration.
public struct ConfigurationCondition: BuildSettingsCondition {
public var config: BuildConfiguration
public init(_ config: BuildConfiguration) {
self.config = config
}
}
/// An individual build setting assignment.
public struct Assignment {
/// The assignment value.
public var value: [String]
// FIXME: This should be a set but we need Equatable existential (or AnyEquatable) for that.
/// The condition associated with this assignment.
public var conditions: [BuildSettingsCondition]
public init() {
self.conditions = []
self.value = []
}
}
/// Build setting assignment table which maps a build setting to a list of assignments.
public struct AssignmentTable {
public private(set) var assignments: [Declaration: [Assignment]]
public init() {
assignments = [:]
}
/// Add the given assignment to the table.
mutating public func add(_ assignment: Assignment, for decl: Declaration) {
// FIXME: We should check for duplicate assignments.
assignments[decl, default: []].append(assignment)
}
}
/// Provides a view onto assignment table with a given set of bound parameters.
///
/// This class can be used to get the assignments matching the bound parameters.
public final class Scope {
/// The assignment table.
public let table: AssignmentTable
/// The bound platform.
public let boundPlatform: Platform
/// The bound build configuration.
public let boundConfig: BuildConfiguration
public init(_ table: AssignmentTable, boundCondition: (Platform, BuildConfiguration)) {
self.table = table
self.boundPlatform = boundCondition.0
self.boundConfig = boundCondition.1
}
/// Evaluate the given declaration and return the values matching the bound parameters.
public func evaluate(_ decl: Declaration) -> [String] {
// Return nil if there is no entry for this declaration.
guard let assignments = table.assignments[decl] else {
return []
}
var values: [String] = []
// Add values from each assignment if it satisfies the bound parameters.
for assignment in assignments {
if let configCondition = assignment.conditions.compactMap({ $0 as? ConfigurationCondition }).first {
if configCondition.config != boundConfig {
continue
}
}
if let platformsCondition = assignment.conditions.compactMap({ $0 as? PlatformsCondition }).first {
if !platformsCondition.platforms.contains(boundPlatform) {
continue
}
}
values += assignment.value
}
return values
}
}
}
| apache-2.0 | a30cb054eba7eebb629d63aa93179015 | 33.509202 | 121 | 0.621156 | 5.095109 | false | true | false | false |
sublimter/Meijiabang | KickYourAss/KickYourAss/ArtistDetailFile/artistdDetailCell/ZXY_ArtistDetailCommentCell.swift | 3 | 1651 | //
// ZXY_ArtistDetailCommentCell.swift
// KickYourAss
//
// Created by 宇周 on 15/1/29.
// Copyright (c) 2015年 宇周. All rights reserved.
//
import UIKit
let ZXY_ArtistDetailCommentCellID = "ZXY_ArtistDetailCommentCellID"
class ZXY_ArtistDetailCommentCell: UITableViewCell {
@IBOutlet weak var headerImg: UIImageView!
@IBOutlet weak var nameLBL: UILabel!
@IBOutlet weak var desLbl: UILabel!
@IBOutlet weak var rateView: UIView!
@IBOutlet weak var timeLbl: UILabel!
@IBOutlet var rateItems: [UIImageView]!
override func awakeFromNib() {
super.awakeFromNib()
self.headerImg.layer.cornerRadius = CGRectGetWidth(self.headerImg.frame) / 2
self.headerImg.layer.masksToBounds = true
// Initialization code
}
override func setSelected(selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
func setRateValue(rateValue : Int)
{
var tempValue = rateValue
if(rateValue >= rateItems.count)
{
tempValue = rateItems.count
}
for var i = 0 ; i < self.rateItems.count ; i++
{
if(i < tempValue)
{
var currentImgV = self.rateItems[i]
currentImgV.image = UIImage(named: "nailartist_down")
}
else
{
var currentImgV = self.rateItems[i]
currentImgV.image = UIImage(named: "nailartist_up")
}
}
}
}
| mit | 1e1f66c5e59163af7ebe1967e9a3a084 | 23.492537 | 84 | 0.578306 | 4.435135 | false | false | false | false |
kay-kim/stitch-examples | todo/ios/Pods/FacebookCore/Sources/Core/GraphRequest/GraphRequest.swift | 6 | 3168 | // Copyright (c) 2016-present, Facebook, Inc. All rights reserved.
//
// You are hereby granted a non-exclusive, worldwide, royalty-free license to use,
// copy, modify, and distribute this software in source code or binary form for use
// in connection with the web services and APIs provided by Facebook.
//
// As with any software that integrates with the Facebook platform, your use of
// this software is subject to the Facebook Developer Principles and Policies
// [http://developers.facebook.com/policy/]. This copyright notice shall be
// included in all copies or substantial portions of the software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import Foundation
import FBSDKCoreKit
/**
Represents a request to the Facebook Graph API.
`GraphRequest` encapsulates the components of a request (the Graph API path, the parameters, error recovery behavior)
and should be used in conjunction with `GraphRequestConnection` to issue the request.
Nearly all Graph APIs require an access token.
Unless specified, the `AccessToken.current` is used. Therefore, most requests
will require login first (see `LoginManager` in `FacebookLogin.framework`).
*/
public struct GraphRequest: GraphRequestProtocol {
public typealias Response = GraphResponse
/// The Graph API endpoint to use for the request, e.g. `"me"`.
public let graphPath: String
/// The request parameters.
public var parameters: [String : Any]?
/// The `AccessToken` used by the request to authenticate.
public let accessToken: AccessToken?
/// The `HTTPMethod` to use for the request, e.g. `.GET`/`.POST`/`.DELETE`.
public let httpMethod: GraphRequestHTTPMethod
/// Graph API Version to use, e.g. `"2.7"`. Default: `GraphAPIVersion.defaultVersion`.
public let apiVersion: GraphAPIVersion
/**
Initializes a new instance of graph request.
- parameter graphPath: The Graph API endpoint to use for the request.
- parameter parameters: Optional parameters dictionary.
- parameter accessToken: Optional authentication token to use. Defaults to `AccessToken.current`.
- parameter httpMethod: Optional `GraphRequestHTTPMethod` to use for the request. Defaults to `.GET`.
- parameter apiVersion: Optional Graph API version to use. Defaults to `GraphAPIVersion.Default`.
*/
public init(graphPath: String,
parameters: [String : Any] = [:],
accessToken: AccessToken? = AccessToken.current,
httpMethod: GraphRequestHTTPMethod = .GET,
apiVersion: GraphAPIVersion = .defaultVersion) {
self.graphPath = graphPath
self.parameters = parameters
self.accessToken = accessToken
self.httpMethod = httpMethod
self.apiVersion = apiVersion
}
}
| apache-2.0 | 40d339182aa79f3bdfa762daa8667006 | 43.619718 | 118 | 0.741162 | 4.693333 | false | false | false | false |
Ankoma22/Analytics | Analytics/Analytics/Analytics.swift | 1 | 2188 | //
// Analytics.swift
// Analytics
//
// Created by Andrej Malyhin on 7/25/17.
// Copyright © 2017 Ankoma Inc. All rights reserved.
//
import Foundation
public enum Provider {
case mixpanel
case amplitude
case fabric
}
public struct ProviderInfo {
let provider: Provider
let token: String?
let classes: [Any]?
init(provider: Provider, token: String? = nil, classes: [Any]? = nil) {
self.provider = provider
self.token = token
self.classes = classes
}
}
public final class Analytics {
public static let shared = Analytics()
fileprivate var providers: [AnalyticProvider] = []
public func setup(withAnalyticsProviders providers: [ProviderInfo]) {
for info in providers {
switch info.provider {
case .mixpanel: setupMixpanel(info.token!)
case .amplitude: setupAmplitude(info.token!)
case .fabric: setupFabric(info.classes!)
}
}
}
public func registerForRemoteNotifications(withToken token: Data) {
providers.forEach { provider in
provider.registerForRemoteNotifications(withToken: token)
}
}
public func track(_ event: String, params: [String: Any]? = nil) {
providers.forEach { provider in
provider.track(event, params: params)
}
}
public func set(property: String, to: String) {
providers.forEach { provider in
provider.set(property: property, to: to)
}
}
fileprivate func setupMixpanel(_ token: String) {
#if HAS_MIXPANEL
let mixpanelProvider = MixpanelProvider(withToken: token)
providers.append(mixpanelProvider)
#endif//HAS_MIXPANEL
}
fileprivate func setupAmplitude(_ token: String) {
#if HAS_AMPLITUDE
let amplitudeProvider = AmplitudeProvider(withToken: token)
providers.append(amplitudeProvider)
#endif//HAS_AMPLITUDE
}
fileprivate func setupFabric(_ kitClasses: [Any]) {
#if HAS_FABRIC
let fabricProvider = FabricProvider(withKitClasses: kitClasses)
providers.append(fabricProvider)
#endif//HAS_FABRIC
}
}
| mit | 0833547836d8c395ee544aff6673b7a1 | 25.349398 | 75 | 0.638775 | 4.365269 | false | false | false | false |
spritekitbook/spritekitbook-swift | Chapter 4/Start/SpaceRunner/SpaceRunner/GameScene.swift | 4 | 1635 | //
// GameScene.swift
// SpaceRunner
//
// Created by Jeremy Novak on 8/18/16.
// Copyright © 2016 Spritekit Book. All rights reserved.
//
import SpriteKit
class GameScene: SKScene {
// MARK: - Private instance variables
private var sceneLabel:SKLabelNode?
// MARK: - Init
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(size: CGSize) {
super.init(size: size)
}
override func didMove(to view: SKView) {
self.setup()
}
// MARK: - Setup
private func setup() {
self.backgroundColor = SKColor.black
sceneLabel = SKLabelNode(fontNamed: "Arial")
sceneLabel?.text = "GameScene"
sceneLabel?.fontSize = 32.0
sceneLabel?.fontColor = SKColor.white
sceneLabel?.position = CGPoint(x: kViewSize.width / 2, y: kViewSize.height / 2)
self.addChild(sceneLabel!)
}
// MARK: - Update
override func update(_ currentTime: TimeInterval) {
}
// MARK: - Touch Handling
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let touch:UITouch = touches.first! as UITouch
let touchLocation = touch.location(in: self)
if sceneLabel!.contains(touchLocation) {
loadScene()
}
}
// MARK: - Load Scene
private func loadScene() {
let scene = GameOverScene(size: kViewSize)
let transition = SKTransition.fade(with: SKColor.black, duration: 0.5)
self.view?.presentScene(scene, transition: transition)
}
}
| apache-2.0 | c950205ed60dcb213e5f9509d0e1a176 | 24.936508 | 87 | 0.600979 | 4.368984 | false | false | false | false |
itribs/RBCActionSheet | RBCActionSheetExample/RBCActionSheetExample/ViewController.swift | 1 | 2462 | //
// ViewController.swift
// RBCActionSheetExample
//
// Created by 黄泽新 on 16/6/8.
// Copyright © 2016年 Ribs. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func general(sender: UIButton) {
let actionSheet = RBCActionSheet(desc: "选择你的性别咯")
actionSheet.addItemWithTitle("男", buttonType: .Default) { actionSheet in
}
actionSheet.addItemWithTitle("女", buttonType: .Default) { actionSheet in
}
actionSheet.addItemWithTitle("取消", buttonType: .Cancel)
actionSheet.willShowHandler = { actionSheet in
print("willShowHandler")
}
actionSheet.didShowHandler = { actionSheet in
print("didShowHandler")
}
actionSheet.willHideHandler = { actionSheet, selectedItemIndex in
print("willHideHandler selected index : \(selectedItemIndex)")
}
actionSheet.didHideHandler = { actionSheet, selectedItemIndex in
print("didHideHandler selected index : \(selectedItemIndex)")
}
actionSheet.show()
}
@IBAction func titleView(sender: UIButton) {
let actionSheet = RBCActionSheet(title: "标题栏", leftItem: nil, rightItem: RBCActionSheetItem(buttonTitle: "取消", handler: { actionSheet in
actionSheet.dismiss()
}))
actionSheet.addItemWithTitle("还有啥的", buttonType: .Default) { actionSheet in
}
actionSheet.addItemWithTitle("确认", buttonType: .Destructive) { actionSheet in
}
actionSheet.show()
}
@IBAction func center(sender: UIButton) {
let actionSheet = RBCActionSheet(desc: "提醒\n你的钱掉了")
actionSheet.animationType = .Center
actionSheet.addItemWithTitle("谢谢", buttonType: .Destructive)
actionSheet.addItemWithTitle("不要了", buttonType: .Cancel)
actionSheet.show()
}
@IBAction func custom(sender: UIButton) {
let actionSheet = RBCActionSheet(title: "输入你那啥")
let dp = UIDatePicker()
dp.frame.size.height = 200
dp.autoresizingMask = .FlexibleWidth
actionSheet.addItemWithView(dp)
actionSheet.addItemWithTitle("取消", buttonType: .Cancel)
actionSheet.show()
}
}
| mit | b935ef35629b310ea4800c1ad16f4535 | 31.930556 | 144 | 0.628427 | 4.828921 | false | false | false | false |
b3log/symphony-ios | HPApp/MenuControl.swift | 1 | 3113 | //
// MenuControl.swift
// HPApp
//
// Created by André Schneider on 04.02.15.
// Copyright (c) 2015 Meng To. All rights reserved.
//
import UIKit
@IBDesignable class MenuControl: UIControl {
@IBInspectable var color: UIColor = UIColor.whiteColor() {
didSet {
topView.backgroundColor = color
centerView.backgroundColor = color
bottomView.backgroundColor = color
}
}
var isDisplayingMenu: Bool { return centerView.alpha == 1 }
private let topView = UIView()
private let centerView = UIView()
private let bottomView = UIView()
override func layoutSubviews() {
if subviews.isEmpty {
addTarget()
setUp()
}
}
func closeAnimation() {
UIView.animateWithDuration(
0.7,
delay: 0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.7,
options: .CurveEaseOut,
animations: {
self.centerView.alpha = 0
self.topView.transform = CGAffineTransformMakeRotation(CGFloat(-M_PI_4)*5)
self.topView.center = self.centerView.center
self.bottomView.transform = CGAffineTransformMakeRotation(CGFloat(M_PI_4)*5)
self.bottomView.center = self.centerView.center
},
completion: nil)
}
func menuAnimation() {
UIView.animateWithDuration(
0.7,
delay: 0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 0.5,
options: .CurveEaseInOut,
animations: {
self.centerView.alpha = 1
self.topView.transform = CGAffineTransformIdentity
self.bottomView.transform = CGAffineTransformIdentity
let centerX = self.bounds.midX
self.topView.center = CGPoint(x: centerX, y: self.topView.bounds.midY)
self.bottomView.center = CGPoint(x: centerX, y: self.bounds.maxY - self.bottomView.bounds.midY)
},
completion: nil)
}
func touchUpInside() {
isDisplayingMenu ? closeAnimation() : menuAnimation()
}
// MARK: Private Methods
private func addTarget() {
addTarget(self, action: "touchUpInside", forControlEvents: .TouchUpInside)
}
private func setUp() {
backgroundColor = UIColor.clearColor()
let height = CGFloat(2)
let width = bounds.maxX
topView.frame = CGRectMake(0, bounds.minY, width, height)
topView.userInteractionEnabled = false
topView.backgroundColor = color
centerView.frame = CGRectMake(0, bounds.midY - round(height / 2), width, height)
centerView.userInteractionEnabled = false
centerView.backgroundColor = color
bottomView.frame = CGRectMake(0, bounds.maxY - height, width, height)
bottomView.userInteractionEnabled = false
bottomView.backgroundColor = color
addSubview(topView)
addSubview(centerView)
addSubview(bottomView)
}
}
| apache-2.0 | dad8a23b25908615e08f713b5d6c408d | 29.811881 | 111 | 0.6009 | 5.118421 | false | false | false | false |
JohnEstropia/CoreStore | Demo/Sources/Demos/Classic/ColorsDemo/Classic.ColorsDemo.Palette.swift | 1 | 2465 | //
// Demo
// Copyright © 2020 John Rommel Estropia, Inc. All rights reserved.
import CoreData
import UIKit
// MARK: - Classic.ColorsDemo.Palette
@objc(Classic_ColorsDemo_Palette)
final class Classic_ColorsDemo_Palette: NSManagedObject {
// MARK: Internal
@NSManaged
dynamic var hue: Float
@NSManaged
dynamic var saturation: Float
@NSManaged
dynamic var brightness: Float
@objc
dynamic var colorGroup: String! {
let key = #keyPath(colorGroup)
if case let value as String = self.getValue(forKvcKey: key) {
return value
}
let newValue: String
switch self.hue * 359 {
case 0 ..< 20: newValue = "Lower Reds"
case 20 ..< 57: newValue = "Oranges and Browns"
case 57 ..< 90: newValue = "Yellow-Greens"
case 90 ..< 159: newValue = "Greens"
case 159 ..< 197: newValue = "Blue-Greens"
case 197 ..< 241: newValue = "Blues"
case 241 ..< 297: newValue = "Violets"
case 297 ..< 331: newValue = "Magentas"
default: newValue = "Upper Reds"
}
self.setPrimitiveValue(newValue, forKey: key)
return newValue
}
var color: UIColor {
let newValue = UIColor(
hue: CGFloat(self.hue),
saturation: CGFloat(self.saturation),
brightness: CGFloat(self.brightness),
alpha: 1.0
)
return newValue
}
var colorText: String {
let newValue: String = "H: \(self.hue * 359)˚, S: \(round(self.saturation * 100.0))%, B: \(round(self.brightness * 100.0))%"
return newValue
}
func setRandomHue() {
self.hue = Self.randomHue()
}
// MARK: NSManagedObject
public override func awakeFromInsert() {
super.awakeFromInsert()
self.hue = Self.randomHue()
self.saturation = Self.randomSaturation()
self.brightness = Self.randomBrightness()
}
// MARK: Private
private static func randomHue() -> Float {
return Float.random(in: 0.0 ... 1.0)
}
private static func randomSaturation() -> Float {
return Float.random(in: 0.4 ... 1.0)
}
private static func randomBrightness() -> Float {
return Float.random(in: 0.1 ... 0.9)
}
}
| mit | 0e918f2501099d2f8e2194abcba527f1 | 23.386139 | 132 | 0.545676 | 4.453888 | false | false | false | false |
DikeyKing/WeCenterMobile-iOS | WeCenterMobile/View/Question/QuestionTitleCell.swift | 1 | 1021 | //
// QuestionTitleCell.swift
// WeCenterMobile
//
// Created by Darren Liu on 15/4/2.
// Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import UIKit
class QuestionTitleCell: UITableViewCell {
@IBOutlet weak var questionTitleLabel: UILabel!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var borderA: UIView!
@IBOutlet weak var borderB: UIView!
override func awakeFromNib() {
super.awakeFromNib()
msr_scrollView?.delaysContentTouches = false
let theme = SettingsManager.defaultManager.currentTheme
containerView.backgroundColor = theme.backgroundColorB
questionTitleLabel.textColor = theme.titleTextColor
for v in [borderA, borderB] {
v.backgroundColor = theme.borderColorA
}
}
func update(#question: Question) {
questionTitleLabel.text = question.title ?? "加载中"
setNeedsLayout()
layoutIfNeeded()
}
}
| gpl-2.0 | 8de7b9d7c57203441475d18f968952df | 27.942857 | 99 | 0.677196 | 5.039801 | false | false | false | false |
Swiftodon/Leviathan | Leviathan/Sources/Persistence/Model/PersistedAccount.swift | 1 | 2001 | //
// PersistedAccount.swift
// Leviathan
//
// Created by Thomas Bonk on 17.11.22.
// Copyright 2022 The Swiftodon Team
//
// 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 CoreData
import Foundation
import MastodonSwift
extension PersistedAccount: Identifiable, NamedEntity {
// MARK: - Static Methods
static func create(in context: NSManagedObjectContext, from account: Account) throws -> PersistedAccount {
guard
let accountId = SessionModel.shared.currentSession?.account.id
else {
throw LeviathanError.noUserLoggedOn
}
let persistedAccount: PersistedAccount = context.createEntity()
persistedAccount.loggedOnAccountId = accountId
persistedAccount.accountId = account.id
persistedAccount.username = account.username
persistedAccount.acct = account.acct
persistedAccount.displayName = account.displayName
persistedAccount.note = account.note
persistedAccount.url = account.url
persistedAccount.avatar = account.avatar
persistedAccount.header = account.header
persistedAccount.locked = account.locked
persistedAccount.createdAt = account.createdAt
persistedAccount.followersCount = Int64(account.followersCount)
persistedAccount.followingCount = Int64(account.followingCount)
persistedAccount.statusesCount = Int64(account.statusesCount)
return persistedAccount
}
}
| apache-2.0 | df743b64cdce04dc036b595fcc65f6d1 | 34.732143 | 110 | 0.718141 | 4.71934 | false | false | false | false |
adolfrank/Swift_practise | 11-day/11-day/NavController.swift | 1 | 2064 | //
// NavController.swift
// 11-day
//
// Created by Hongbo Yu on 16/3/24.
// Copyright © 2016年 Frank. All rights reserved.
//
import UIKit
class NavController: UINavigationController {
override func viewDidLoad() {
super.viewDidLoad()
hideNavImage()
// Do any additional setup after loading the view.
}
override func pushViewController(viewController: UIViewController, animated: Bool) {
// 这个方法可以拦截所有通过导航栏进来的push
super.pushViewController(viewController, animated: animated)
}
// MARK: - 找出导航栏地步的黑条
private func hairlineImageViewInNavigationBar(view: UIView) -> UIImageView?
{
if let imageView = view as? UIImageView where imageView.bounds.height <= 1
{
return imageView
}
for subview: UIView in view.subviews
{
if let imageView = hairlineImageViewInNavigationBar(subview)
{
return imageView
}
}
return nil
}
// MARK: - 隐藏导航栏的黑条
func hideNavImage(){
let NavImage: UIImageView = self.hairlineImageViewInNavigationBar(self.navigationBar)!
NavImage.hidden = true
}
}
/* 找出导航栏的黑条
extension UIToolbar
{
func hideHairline()
{
let navigationBarImageView = hairlineImageViewInToolbar(self)?.hidden = true
}
func showHairline()
{
let navigationBarImageView = hairlineImageViewInToolbar(self)?.hidden = false
}
private func hairlineImageViewInToolbar(view: UIView) -> UIImageView?
{
if let imageView = view as? UIImageView where imageView.bounds.height <= 1
{
return imageView
}
for subview: UIView in view.subviews
{
if let imageView = hairlineImageViewInToolbar(subview)
{
return imageView
}
}
return nil
}
}
*/
| mit | 90225db15bf416fa23f4fd27e4f6c2e2 | 22.211765 | 94 | 0.593512 | 4.7657 | false | false | false | false |
RMizin/PigeonMessenger-project | FalconMessenger/Settings/Menu/PrivacyAndSecurity/PrivacyTableViewController.swift | 1 | 2554 | //
// PrivacyTableViewController.swift
// FalconMessenger
//
// Created by Roman Mizin on 8/12/18.
// Copyright © 2018 Roman Mizin. All rights reserved.
//
import UIKit
class PrivacyTableViewController: MenuControlsTableViewController {
var privacyElements = [SwitchObject]()
override func viewDidLoad() {
super.viewDidLoad()
createDataSource()
navigationItem.title = "Privacy"
}
fileprivate func createDataSource() {
let biometricsState = userDefaults.currentBoolObjectState(for: userDefaults.biometricalAuth)
let contactsSyncState = userDefaults.currentBoolObjectState(for: userDefaults.contactsContiniousSync)
let biometricsObject = SwitchObject(Biometrics().title, subtitle: nil, state: biometricsState, defaultsKey: userDefaults.biometricalAuth)
let contactsSyncObject = SwitchObject("Syncronize Contacts", subtitle: nil, state: contactsSyncState, defaultsKey: userDefaults.contactsContiniousSync)
privacyElements.append(biometricsObject)
privacyElements.append(contactsSyncObject)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 2
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 1 { return privacyElements.count }
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
if indexPath.section == 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: controlButtonCellID,
for: indexPath) as? GroupAdminPanelTableViewCell ?? GroupAdminPanelTableViewCell()
cell.button.setTitle("Blacklist", for: .normal)
cell.button.addTarget(self, action: #selector(controlButtonClicked(_:)), for: .touchUpInside)
cell.selectionStyle = .none
return cell
} else {
let cell = tableView.dequeueReusableCell(withIdentifier: switchCellID,
for: indexPath) as? SwitchTableViewCell ?? SwitchTableViewCell()
cell.currentViewController = self
cell.setupCell(object: privacyElements[indexPath.row], index: indexPath.row)
return cell
}
}
@objc fileprivate func controlButtonClicked(_ sender: UIButton) {
guard let superview = sender.superview else { return }
let point = tableView.convert(sender.center, from: superview)
guard let indexPath = tableView.indexPathForRow(at: point), indexPath.section == 0 else { return }
let destination = BlockedUsersTableViewController()
navigationController?.pushViewController(destination, animated: true)
}
}
| gpl-3.0 | c65e4ee90fc2d60c17d2792b134f6e61 | 38.276923 | 155 | 0.754407 | 4.641818 | false | false | false | false |
h-n-y/UICollectionView-TheCompleteGuide | chapter-2/2-time-machine/chapter2-4/AppDelegate.swift | 1 | 2663 | //
// AppDelegate.swift
// chapter2-4
//
// Created by Hans Yelek on 4/25/16.
// Copyright © 2016 Hans Yelek. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
let flowLayout = UICollectionViewFlowLayout()
let viewController = ViewController(collectionViewLayout: flowLayout)
let rootViewController = UINavigationController(rootViewController: viewController)
rootViewController.navigationBar.barStyle = .Black
window = UIWindow(frame: UIScreen.mainScreen().bounds)
window!.backgroundColor = UIColor.whiteColor()
window!.rootViewController = rootViewController
window!.makeKeyAndVisible()
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
| mit | e3359db6d7334c2b049b931d63f0fe0a | 45.701754 | 285 | 0.74305 | 5.824945 | false | false | false | false |
Jamnitzer/MBJ_Mipmapping | MBJ_Mipmapping/MBJ_Mipmapping/MBJRenderer.swift | 1 | 12222 | //
// MBERenderer.m
// Mipmapping
//
// Created by Warren Moore on 11/7/14.
// Copyright (c) 2014 Metal By Example. All rights reserved.
//------------------------------------------------------------------------
// converted to Swift by Jamnitzer (Jim Wrenholt)
//------------------------------------------------------------------------
import UIKit
import Metal
import simd
import QuartzCore
//------------------------------------------------------------------------------
enum MIPMAP_MODE:UInt {
case MBJMipmappingMode_None,
MBJMipmappingMode_BlitGeneratedLinear,
MBJMipmappingMode_VibrantLinear,
MBJMipmappingMode_VibrantNearest }
//------------------------------------------------------------------------------
class MBJRenderer
{
//-------------------------------------------------------------------------
var device:MTLDevice! = nil
var layer:CAMetalLayer! = nil
var cameraDistance:Float! = nil
var mipmappingMode:MIPMAP_MODE = .MBJMipmappingMode_None
let X = float3(1, 0, 0)
let Y = float3(0, 1, 0)
var commandQueue:MTLCommandQueue! = nil
var library:MTLLibrary! = nil
var pipeline:MTLRenderPipelineState? = nil
var uniformBuffer:MTLBuffer! = nil
var depthTexture:MTLTexture! = nil
var checkerTexture:MTLTexture! = nil
var vibrantCheckerTexture:MTLTexture! = nil
var depthState:MTLDepthStencilState? = nil
var notMipSamplerState:MTLSamplerState! = nil
var nearestMipSamplerState:MTLSamplerState! = nil
var linearMipSamplerState:MTLSamplerState! = nil
var cube:MBJMesh! = nil
var angleX:Float = 0.0
var angleY:Float = 0.0
//-------------------------------------------------------------------------
init(layer:CAMetalLayer)
{
self.cameraDistance = 1
self.mipmappingMode = .MBJMipmappingMode_VibrantLinear
buildMetal()
buildPipeline()
buildResources()
self.layer = layer
self.layer.device = self.device
}
//-------------------------------------------------------------------------
func buildMetal()
{
self.device = MTLCreateSystemDefaultDevice()
commandQueue = device!.newCommandQueue()
self.library = self.device!.newDefaultLibrary()
}
//-------------------------------------------------------------------------
func buildPipeline()
{
let vertexDescriptor = MTLVertexDescriptor()
vertexDescriptor.attributes[0].bufferIndex = 0
vertexDescriptor.attributes[0].offset = 0
vertexDescriptor.attributes[0].format = MTLVertexFormat.Float4
vertexDescriptor.attributes[1].offset = sizeof(float4)
vertexDescriptor.attributes[1].format = MTLVertexFormat.Float4
vertexDescriptor.attributes[1].bufferIndex = 0
vertexDescriptor.layouts[0].stepFunction = MTLVertexStepFunction.PerVertex
vertexDescriptor.layouts[0].stepRate = 1
vertexDescriptor.layouts[0].stride = sizeof(MBJVertex)
print("sizeof(MBJVertex) = \(sizeof(MBJVertex)) ")
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.vertexFunction = self.library.newFunctionWithName("vertex_project")
pipelineDescriptor.fragmentFunction = self.library.newFunctionWithName("fragment_texture")
pipelineDescriptor.vertexDescriptor = vertexDescriptor
pipelineDescriptor.colorAttachments[0].pixelFormat = MTLPixelFormat.BGRA8Unorm
pipelineDescriptor.depthAttachmentPixelFormat = MTLPixelFormat.Depth32Float
do {
self.pipeline = try
device.newRenderPipelineStateWithDescriptor(pipelineDescriptor)
}
catch let pipelineError as NSError
{
self.pipeline = nil
print("Error occurred when creating render pipeline state \(pipelineError)")
assert(false)
}
let depthDescriptor = MTLDepthStencilDescriptor()
depthDescriptor.depthCompareFunction = MTLCompareFunction.Less
depthDescriptor.depthWriteEnabled = true
self.depthState = device!.newDepthStencilStateWithDescriptor(depthDescriptor)
let samplerDescriptor = MTLSamplerDescriptor()
samplerDescriptor.minFilter = MTLSamplerMinMagFilter.Linear
samplerDescriptor.magFilter = MTLSamplerMinMagFilter.Linear
samplerDescriptor.sAddressMode = MTLSamplerAddressMode.ClampToEdge
samplerDescriptor.tAddressMode = MTLSamplerAddressMode.ClampToEdge
samplerDescriptor.mipFilter = MTLSamplerMipFilter.NotMipmapped
self.notMipSamplerState = self.device!.newSamplerStateWithDescriptor(samplerDescriptor)
samplerDescriptor.mipFilter = MTLSamplerMipFilter.Nearest
self.nearestMipSamplerState = self.device!.newSamplerStateWithDescriptor(samplerDescriptor)
samplerDescriptor.mipFilter = MTLSamplerMipFilter.Linear
self.linearMipSamplerState = self.device!.newSamplerStateWithDescriptor(samplerDescriptor)
}
//-------------------------------------------------------------------------
func buildResources()
{
self.cube = MBJCubeMesh(device:self.device)
let textureSize:CGSize = CGSizeMake(512.0, 512.0)
let tileCount:Int = 8
MBJTextureGenerator.checkerboardTextureWithSize(textureSize,
tileCount:tileCount,
colorfulMipmaps:false,
device:self.device,
completionBlock: { (texture:MTLTexture) in self.checkerTexture = texture } )
MBJTextureGenerator.checkerboardTextureWithSize(textureSize,
tileCount:tileCount,
colorfulMipmaps:true,
device:self.device,
completionBlock: { (texture:MTLTexture) in self.vibrantCheckerTexture = texture } )
let uniforms_size = sizeof(Float) * (16 + 16 + 12)
self.uniformBuffer = self.device.newBufferWithLength(uniforms_size,
options:.CPUCacheModeDefaultCache)
self.uniformBuffer.label = "uniformBuffer"
}
//-------------------------------------------------------------------------
func buildDepthBuffer()
{
let drawableSize:CGSize = self.layer.drawableSize
let depthTexDesc =
MTLTextureDescriptor.texture2DDescriptorWithPixelFormat( .Depth32Float,
width: Int(drawableSize.width), height: Int(drawableSize.height),
mipmapped: false)
self.depthTexture = self.device.newTextureWithDescriptor(depthTexDesc)
self.depthTexture.label = "depthTexture"
}
//-------------------------------------------------------------------------
func drawSceneWithCommandEncoder(commandEncoder:MTLRenderCommandEncoder)
{
var texture:MTLTexture! = nil
var sampler:MTLSamplerState! = nil
switch (self.mipmappingMode)
{
case .MBJMipmappingMode_None:
texture = self.checkerTexture
sampler = self.notMipSamplerState
case .MBJMipmappingMode_BlitGeneratedLinear:
texture = self.checkerTexture
sampler = self.linearMipSamplerState
case .MBJMipmappingMode_VibrantNearest:
texture = self.vibrantCheckerTexture
sampler = self.nearestMipSamplerState
case .MBJMipmappingMode_VibrantLinear:
texture = self.vibrantCheckerTexture
sampler = self.linearMipSamplerState
}
commandEncoder.setRenderPipelineState(self.pipeline!)
commandEncoder.setDepthStencilState( self.depthState!)
commandEncoder.setFragmentTexture( texture, atIndex: 0)
commandEncoder.setFragmentSamplerState( sampler, atIndex: 0)
commandEncoder.setVertexBuffer( self.cube.vertexBuffer, offset: 0, atIndex: 0)
commandEncoder.setVertexBuffer( self.uniformBuffer, offset: 0, atIndex: 1)
commandEncoder.drawIndexedPrimitives( .Triangle,
indexCount:self.cube.indexBuffer.length / sizeof(MBJIndexType),
indexType:MTLIndexType.UInt16,
indexBuffer:self.cube.indexBuffer,
indexBufferOffset:0)
}
//-------------------------------------------------------------------------
func renderPassForDrawable(drawable:CAMetalDrawable) -> MTLRenderPassDescriptor
{
let renderPass = MTLRenderPassDescriptor()
renderPass.colorAttachments[0].texture = drawable.texture
renderPass.colorAttachments[0].loadAction = MTLLoadAction.Clear
renderPass.colorAttachments[0].storeAction = MTLStoreAction.Store
renderPass.colorAttachments[0].clearColor = MTLClearColorMake(1, 1, 1, 1)
renderPass.depthAttachment.texture = self.depthTexture
renderPass.depthAttachment.loadAction = MTLLoadAction.Clear
renderPass.depthAttachment.storeAction = MTLStoreAction.DontCare
renderPass.depthAttachment.clearDepth = 1
return renderPass
}
//-------------------------------------------------------------------------
func updateUniforms()
{
let size:CGSize = self.layer.bounds.size
let aspectRatio:Float = Float(size.width / size.height)
let verticalFOV:Float = (aspectRatio > 1) ? Float(M_PI / 3) : Float(M_PI / 2)
let near:Float = 0.1
let far:Float = 100.0
let projectionMatrix:float4x4 = matrix_perspective_projection(aspectRatio,
fovy: verticalFOV, near: near, far: far)
let cameraPosition = float4(0.0, 0.0, -self.cameraDistance, 1.0)
let viewMatrix:float4x4 = matrix_translation(cameraPosition)
let cubePosition:float4 = float4(0, 0, 0, 1)
let cube_rotX:float4x4 = matrix_rotation(X, angle:self.angleX)
let cube_rotY:float4x4 = matrix_rotation(Y, angle:self.angleY)
let cube_rotXY:float4x4 = cube_rotX * cube_rotY
let cube_trans:float4x4 = matrix_translation(cubePosition)
let cubeModelMatrix:float4x4 = cube_trans * cube_rotXY
var uniforms = MBJUniforms()
let uniforms_size = sizeof(Float) * (16 + 16 + 12)
uniforms.modelMatrix = cubeModelMatrix
let cubeMM3:float3x3 = matrix_upper_left3x3(cubeModelMatrix)
uniforms.normalMatrix = cubeMM3.inverse
let mv:float4x4 = viewMatrix * cubeModelMatrix
let mvp:float4x4 = projectionMatrix * mv
uniforms.modelViewProjectionMatrix = mvp
memcpy(self.uniformBuffer.contents(), &uniforms, uniforms_size)
self.angleY += 0.01
self.angleX += 0.015
}
//-------------------------------------------------------------------------
func draw()
{
let drawableSize:CGSize = self.layer.drawableSize
if (self.depthTexture == nil )
{
buildDepthBuffer()
}
if (CGFloat(self.depthTexture.width) != drawableSize.width ||
CGFloat(self.depthTexture.height) != drawableSize.height)
{
buildDepthBuffer()
}
let drawable:CAMetalDrawable? = self.layer.nextDrawable()
if (drawable != nil)
{
updateUniforms()
let commandBuffer:MTLCommandBuffer = commandQueue.commandBuffer()
let renderPass:MTLRenderPassDescriptor = renderPassForDrawable(drawable!)
let commandEncoder:MTLRenderCommandEncoder =
commandBuffer.renderCommandEncoderWithDescriptor(renderPass)
commandEncoder.setCullMode( MTLCullMode.Back)
commandEncoder.setFrontFacingWinding(MTLWinding.CounterClockwise)
drawSceneWithCommandEncoder(commandEncoder)
commandEncoder.endEncoding()
commandBuffer.presentDrawable(drawable!)
commandBuffer.commit()
}
}
//-------------------------------------------------------------------------
}
//------------------------------------------------------------------------------
| mit | f9baf98efde75664e483d8f11bec4952 | 40.713311 | 99 | 0.597365 | 5.410359 | false | false | false | false |
ksuayan/JsonClient | JsonClient/APIController.swift | 1 | 1884 | //
// APIController.swift
// JsonClient
//
// Created by Suayan, William on 7/18/14.
// Copyright (c) 2014 Kyo Suayan. All rights reserved.
//
import UIKit
protocol APIControllerProtocol {
func JSONAPIResults(results: NSArray)
}
class APIController: NSObject {
var delegate:APIControllerProtocol?
func GetAPIResultsAsync(urlString:String) {
//The Url that will be called
var url = NSURL.URLWithString(urlString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding))
//Create a request
var request: NSURLRequest = NSURLRequest(URL: url)
println("url >>>> "+url.path)
//Create a queue to hold the call
var queue: NSOperationQueue = NSOperationQueue()
// Sending Asynchronous request using NSURLConnection
NSURLConnection.sendAsynchronousRequest(request, queue: queue,
completionHandler:{
(response:NSURLResponse!, responseData:NSData!, error: NSError!) ->Void in
var error: AutoreleasingUnsafePointer<NSError?> = nil
// Serialize the JSON result into a dictionary
let jsonResult: NSDictionary! = NSJSONSerialization.JSONObjectWithData(responseData,
options:NSJSONReadingOptions.MutableContainers,
error: error) as? NSDictionary
// If there is a result add the data into an array
if jsonResult.count>0 && jsonResult["result"].count>0 {
var results: NSArray = jsonResult["result"] as NSArray
//Use the completion handler to pass the results
self.delegate?.JSONAPIResults(results)
} else {
println(error)
}
})
}
}
| mit | fe5ae47a004858259e9be5421200a6d8 | 31.482759 | 112 | 0.595011 | 5.726444 | false | false | false | false |
mentrena/SyncKit | SyncKit/Classes/QSSynchronizer/TempFileManager.swift | 1 | 1341 | //
// TempFileManager.swift
// Pods-CoreDataExample
//
// Created by Manuel Entrena on 25/04/2019.
//
import Foundation
class TempFileManager {
let identifier: String
init(identifier: String) {
self.identifier = identifier
}
private lazy var assetDirectory: URL = {
let directoryURL = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent("com.mentrena.QSTempFileManager").appendingPathComponent(identifier)
if FileManager.default.fileExists(atPath: directoryURL.path) == false {
try? FileManager.default.createDirectory(at: directoryURL, withIntermediateDirectories: true, attributes: nil)
}
return directoryURL
}()
func store(data: Data) -> URL {
let fileName = ProcessInfo.processInfo.globallyUniqueString
let url = assetDirectory.appendingPathComponent(fileName)
try? data.write(to: url, options: .atomicWrite)
return url
}
func clearTempFiles() {
guard let fileURLs = try? FileManager.default.contentsOfDirectory(at: assetDirectory, includingPropertiesForKeys: nil, options: []) else {
return
}
for fileURL in fileURLs {
try? FileManager.default.removeItem(at: fileURL)
}
}
}
| mit | 02ae7f1b81a88f020988058db6ebc67e | 28.8 | 163 | 0.647278 | 5.157692 | false | false | false | false |
lenglengiOS/BuDeJie | 百思不得姐/Pods/Charts/Charts/Classes/Charts/PieChartView.swift | 17 | 14593 | //
// PieChartView.swift
// Charts
//
// Created by Daniel Cohen Gindi on 4/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import Foundation
import UIKit
/// View that represents a pie chart. Draws cake like slices.
public class PieChartView: PieRadarChartViewBase
{
/// rect object that represents the bounds of the piechart, needed for drawing the circle
private var _circleBox = CGRect()
/// array that holds the width of each pie-slice in degrees
private var _drawAngles = [CGFloat]()
/// array that holds the absolute angle in degrees of each slice
private var _absoluteAngles = [CGFloat]()
public override init(frame: CGRect)
{
super.init(frame: frame)
}
public required init?(coder aDecoder: NSCoder)
{
super.init(coder: aDecoder)
}
internal override func initialize()
{
super.initialize()
renderer = PieChartRenderer(chart: self, animator: _animator, viewPortHandler: _viewPortHandler)
}
public override func drawRect(rect: CGRect)
{
super.drawRect(rect)
if (_dataNotSet)
{
return
}
let optionalContext = UIGraphicsGetCurrentContext()
guard let context = optionalContext else { return }
renderer!.drawData(context: context)
if (valuesToHighlight())
{
renderer!.drawHighlighted(context: context, indices: _indicesToHighlight)
}
renderer!.drawExtras(context: context)
renderer!.drawValues(context: context)
_legendRenderer.renderLegend(context: context)
drawDescription(context: context)
drawMarkers(context: context)
}
internal override func calculateOffsets()
{
super.calculateOffsets()
// prevent nullpointer when no data set
if (_dataNotSet)
{
return
}
let radius = diameter / 2.0
let c = self.centerOffsets
let shift = (data as? PieChartData)?.dataSet?.selectionShift ?? 0.0
// create the circle box that will contain the pie-chart (the bounds of the pie-chart)
_circleBox.origin.x = (c.x - radius) + shift
_circleBox.origin.y = (c.y - radius) + shift
_circleBox.size.width = diameter - shift * 2.0
_circleBox.size.height = diameter - shift * 2.0
}
internal override func calcMinMax()
{
super.calcMinMax()
calcAngles()
}
public override func getMarkerPosition(entry e: ChartDataEntry, highlight: ChartHighlight) -> CGPoint
{
let center = self.centerCircleBox
var r = self.radius
var off = r / 10.0 * 3.6
if self.isDrawHoleEnabled
{
off = (r - (r * self.holeRadiusPercent)) / 2.0
}
r -= off // offset to keep things inside the chart
let rotationAngle = self.rotationAngle
let i = e.xIndex
// offset needed to center the drawn text in the slice
let offset = drawAngles[i] / 2.0
// calculate the text position
let x: CGFloat = (r * cos(((rotationAngle + absoluteAngles[i] - offset) * _animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.x)
let y: CGFloat = (r * sin(((rotationAngle + absoluteAngles[i] - offset) * _animator.phaseY) * ChartUtils.Math.FDEG2RAD) + center.y)
return CGPoint(x: x, y: y)
}
/// calculates the needed angles for the chart slices
private func calcAngles()
{
_drawAngles = [CGFloat]()
_absoluteAngles = [CGFloat]()
_drawAngles.reserveCapacity(_data.yValCount)
_absoluteAngles.reserveCapacity(_data.yValCount)
var dataSets = _data.dataSets
var cnt = 0
for (var i = 0; i < _data.dataSetCount; i++)
{
let set = dataSets[i]
var entries = set.yVals
for (var j = 0; j < entries.count; j++)
{
_drawAngles.append(calcAngle(abs(entries[j].value)))
if (cnt == 0)
{
_absoluteAngles.append(_drawAngles[cnt])
}
else
{
_absoluteAngles.append(_absoluteAngles[cnt - 1] + _drawAngles[cnt])
}
cnt++
}
}
}
/// checks if the given index in the given DataSet is set for highlighting or not
public func needsHighlight(xIndex xIndex: Int, dataSetIndex: Int) -> Bool
{
// no highlight
if (!valuesToHighlight() || dataSetIndex < 0)
{
return false
}
for (var i = 0; i < _indicesToHighlight.count; i++)
{
// check if the xvalue for the given dataset needs highlight
if (_indicesToHighlight[i].xIndex == xIndex
&& _indicesToHighlight[i].dataSetIndex == dataSetIndex)
{
return true
}
}
return false
}
/// calculates the needed angle for a given value
private func calcAngle(value: Double) -> CGFloat
{
return CGFloat(value) / CGFloat(_data.yValueSum) * 360.0
}
public override func indexForAngle(angle: CGFloat) -> Int
{
// take the current angle of the chart into consideration
let a = ChartUtils.normalizedAngleFromAngle(angle - self.rotationAngle)
for (var i = 0; i < _absoluteAngles.count; i++)
{
if (_absoluteAngles[i] > a)
{
return i
}
}
return -1; // return -1 if no index found
}
/// - returns: the index of the DataSet this x-index belongs to.
public func dataSetIndexForIndex(xIndex: Int) -> Int
{
var dataSets = _data.dataSets
for (var i = 0; i < dataSets.count; i++)
{
if (dataSets[i].entryForXIndex(xIndex) !== nil)
{
return i
}
}
return -1
}
/// - returns: an integer array of all the different angles the chart slices
/// have the angles in the returned array determine how much space (of 360°)
/// each slice takes
public var drawAngles: [CGFloat]
{
return _drawAngles
}
/// - returns: the absolute angles of the different chart slices (where the
/// slices end)
public var absoluteAngles: [CGFloat]
{
return _absoluteAngles
}
/// Sets the color for the hole that is drawn in the center of the PieChart (if enabled).
///
/// *Note: Use holeTransparent with holeColor = nil to make the hole transparent.*
public var holeColor: UIColor?
{
get
{
return (renderer as! PieChartRenderer).holeColor!
}
set
{
(renderer as! PieChartRenderer).holeColor = newValue
setNeedsDisplay()
}
}
/// Set the hole in the center of the PieChart transparent
public var holeTransparent: Bool
{
get
{
return (renderer as! PieChartRenderer).holeTransparent
}
set
{
(renderer as! PieChartRenderer).holeTransparent = newValue
setNeedsDisplay()
}
}
/// - returns: true if the hole in the center of the PieChart is transparent, false if not.
public var isHoleTransparent: Bool
{
return (renderer as! PieChartRenderer).holeTransparent
}
/// the alpha of the hole in the center of the piechart, in case holeTransparent == true
///
/// **default**: 0.41
public var holeAlpha: CGFloat
{
get
{
return (renderer as! PieChartRenderer).holeAlpha
}
set
{
(renderer as! PieChartRenderer).holeAlpha = newValue
setNeedsDisplay()
}
}
/// true if the hole in the center of the pie-chart is set to be visible, false if not
public var drawHoleEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawHoleEnabled
}
set
{
(renderer as! PieChartRenderer).drawHoleEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if the hole in the center of the pie-chart is set to be visible, false if not
public var isDrawHoleEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawHoleEnabled
}
}
/// the text that is displayed in the center of the pie-chart
public var centerText: String?
{
get
{
return (renderer as! PieChartRenderer).centerAttributedText?.string
}
set
{
var attrString: NSMutableAttributedString?
if newValue == nil
{
attrString = nil
}
else
{
let paragraphStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = NSLineBreakMode.ByTruncatingTail
paragraphStyle.alignment = .Center
attrString = NSMutableAttributedString(string: newValue!)
attrString?.setAttributes([
NSForegroundColorAttributeName: UIColor.blackColor(),
NSFontAttributeName: UIFont.systemFontOfSize(12.0),
NSParagraphStyleAttributeName: paragraphStyle
], range: NSMakeRange(0, attrString!.length))
}
(renderer as! PieChartRenderer).centerAttributedText = attrString
setNeedsDisplay()
}
}
/// the text that is displayed in the center of the pie-chart
public var centerAttributedText: NSAttributedString?
{
get
{
return (renderer as! PieChartRenderer).centerAttributedText
}
set
{
(renderer as! PieChartRenderer).centerAttributedText = newValue
setNeedsDisplay()
}
}
/// true if drawing the center text is enabled
public var drawCenterTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawCenterTextEnabled
}
set
{
(renderer as! PieChartRenderer).drawCenterTextEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if drawing the center text is enabled
public var isDrawCenterTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawCenterTextEnabled
}
}
internal override var requiredLegendOffset: CGFloat
{
return _legend.font.pointSize * 2.0
}
internal override var requiredBaseOffset: CGFloat
{
return 0.0
}
public override var radius: CGFloat
{
return _circleBox.width / 2.0
}
/// - returns: the circlebox, the boundingbox of the pie-chart slices
public var circleBox: CGRect
{
return _circleBox
}
/// - returns: the center of the circlebox
public var centerCircleBox: CGPoint
{
return CGPoint(x: _circleBox.midX, y: _circleBox.midY)
}
/// the radius of the hole in the center of the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.5 (50%) (half the pie)
public var holeRadiusPercent: CGFloat
{
get
{
return (renderer as! PieChartRenderer).holeRadiusPercent
}
set
{
(renderer as! PieChartRenderer).holeRadiusPercent = newValue
setNeedsDisplay()
}
}
/// the radius of the transparent circle that is drawn next to the hole in the piechart in percent of the maximum radius (max = the radius of the whole chart)
///
/// **default**: 0.55 (55%) -> means 5% larger than the center-hole by default
public var transparentCircleRadiusPercent: CGFloat
{
get
{
return (renderer as! PieChartRenderer).transparentCircleRadiusPercent
}
set
{
(renderer as! PieChartRenderer).transparentCircleRadiusPercent = newValue
setNeedsDisplay()
}
}
/// set this to true to draw the x-value text into the pie slices
public var drawSliceTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawXLabelsEnabled
}
set
{
(renderer as! PieChartRenderer).drawXLabelsEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if drawing x-values is enabled, false if not
public var isDrawSliceTextEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).drawXLabelsEnabled
}
}
/// If this is enabled, values inside the PieChart are drawn in percent and not with their original value. Values provided for the ValueFormatter to format are then provided in percent.
public var usePercentValuesEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).usePercentValuesEnabled
}
set
{
(renderer as! PieChartRenderer).usePercentValuesEnabled = newValue
setNeedsDisplay()
}
}
/// - returns: true if drawing x-values is enabled, false if not
public var isUsePercentValuesEnabled: Bool
{
get
{
return (renderer as! PieChartRenderer).usePercentValuesEnabled
}
}
/// the rectangular radius of the bounding box for the center text, as a percentage of the pie hole
public var centerTextRadiusPercent: CGFloat
{
get
{
return (renderer as! PieChartRenderer).centerTextRadiusPercent
}
set
{
(renderer as! PieChartRenderer).centerTextRadiusPercent = newValue
setNeedsDisplay()
}
}
} | apache-2.0 | 9f67fd6224386269e46696abeb819811 | 27.839921 | 189 | 0.566269 | 5.21329 | false | false | false | false |
PD-Jell/Swift_study | SwiftStudy/RxSwift/Rxswift-sketchbook/RxSwiftSketchbookViewController.swift | 1 | 2298 | //
// RxSwiftSketchbookViewController.swift
// SwiftStudy
//
// Created by YooHG on 9/9/20.
// Copyright © 2020 Jell PD. All rights reserved.
//
import RxSwift
import RxCocoa
class RxSwiftSketchbookViewController: UIViewController {
@IBOutlet var countLabel: UILabel!
let vm = RxSwiftSketchbookViewModel()
// let publish: PublishSubject<Int> = PublishSubject()
let behavior: BehaviorSubject<Int> = BehaviorSubject(value: 0)
let json: BehaviorSubject<[RxTodo]> = BehaviorSubject<[RxTodo]>(value: [])
let bag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
let z = 1
let a = Observable.from(optional: z)
a.subscribe(onNext: {
print("onNext: \($0)")
}, onError: {error in
print("onError: \(error)")
}, onCompleted: {
print("onCompleted")
}, onDisposed: {
print("onDisposed")
}).disposed(by: bag)
behavior.subscribe(onNext: {[weak self] in
print("behavior: \($0)")
self?.countLabel.text = "\($0)"
}).disposed(by: bag)
behavior.onNext(100)
// vm.down(url: "https://jsonplaceholder.typicode.com/todos")
// .subscribe(onNext: {
// print($0)
// }).disposed(by: bag)
json.asObserver().subscribe(onNext: {[weak self] todo in
print(todo)
print("json is complete!")
if (try! self?.behavior.value())! > 130 {
self?.behavior.onNext(0)
}
}).disposed(by: bag)
}
@IBAction func increaseBtnClicked(_ sender: Any) {
behavior.onNext(try! behavior.value() + 1)
vm.down(url: "https://jsonplaceholder.typicode.com/todos") // 데이터형을 뽑아야 함.
.bind(to: json)
.disposed(by: bag)
behavior.onNext(try! behavior.value() + 1)
vm.down(url: "https://jsonplaceholder.typicode.com/todos")
.bind(to: json)
.disposed(by: bag)
behavior.onNext(try! behavior.value() + 1)
vm.down(url: "https://jsonplaceholder.typicode.com/todos")
.bind(to: json)
.disposed(by: bag)
}
}
| mit | 97ecd5cd6e967fbebc5c9d6d442ad8da | 28.986842 | 82 | 0.545415 | 4.173993 | false | false | false | false |
whereuat/whereuat-ios | whereuat-ios/Views/ContactView/ContactViewCell.swift | 1 | 1849 | //
// ContactViewCell.swift
// whereuat-ios
//
// Created by Raymond Jacobson on 3/23/16.
// Copyright © 2016 whereu@. All rights reserved.
//
import UIKit
class ContactViewCell: UICollectionViewCell {
var delegate: ContactsViewController!
var contactView: ContactView!
var contactData: Contact!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
/*
* addContactView loads the contact data into the contact view and constrains it
*/
func addContactView() {
self.contactView.delegate = self.delegate
self.contentView.addSubview(self.contactView)
self.contactView.translatesAutoresizingMaskIntoConstraints = false
let leftSideConstraint = NSLayoutConstraint(item: self.contactView, attribute: .Left, relatedBy: .Equal, toItem: self, attribute: .Left, multiplier: 1.0, constant: 0.0)
let bottomConstraint = NSLayoutConstraint(item: self.contactView, attribute: .Bottom, relatedBy: .Equal, toItem: self, attribute: .Bottom, multiplier: 1.0, constant: 0.0)
let widthConstraint = NSLayoutConstraint(item: self.contactView, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1.0, constant: 0.0)
let heightConstraint = NSLayoutConstraint(item: self.contactView, attribute: .Height, relatedBy: .Equal, toItem: self, attribute: .Height, multiplier: 1.0, constant: 0.0)
self.addConstraints([leftSideConstraint, bottomConstraint, widthConstraint, heightConstraint])
}
/*
* prepareForReuse is called when the cell leaves the screen.
* The contact view is removed from the superview to prevent duplicate drawing
*/
override func prepareForReuse() {
super.prepareForReuse()
self.contactView.removeFromSuperview()
}
}
| apache-2.0 | 97adb5598a15538da8ca13fc034859e7 | 40.066667 | 178 | 0.704545 | 4.529412 | false | false | false | false |
xwu/swift | stdlib/private/SwiftPrivateLibcExtras/Subprocess.swift | 1 | 16010 | //===--- Subprocess.swift -------------------------------------------------===//
//
// 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 SwiftPrivate
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import CRT
import WinSDK
#endif
#if !os(WASI)
// No signals support on WASI yet, see https://github.com/WebAssembly/WASI/issues/166.
internal func _signalToString(_ signal: Int) -> String {
switch CInt(signal) {
case SIGILL: return "SIGILL"
case SIGABRT: return "SIGABRT"
case SIGFPE: return "SIGFPE"
case SIGSEGV: return "SIGSEGV"
#if !os(Windows)
case SIGTRAP: return "SIGTRAP"
case SIGBUS: return "SIGBUS"
case SIGSYS: return "SIGSYS"
#endif
default: return "SIG???? (\(signal))"
}
}
#endif
public enum ProcessTerminationStatus : CustomStringConvertible {
case exit(Int)
case signal(Int)
public var description: String {
switch self {
case .exit(let status):
return "Exit(\(status))"
case .signal(let signal):
#if os(WASI)
// No signals support on WASI yet, see https://github.com/WebAssembly/WASI/issues/166.
fatalError("Signals are not supported on WebAssembly/WASI")
#else
return "Signal(\(_signalToString(signal)))"
#endif
}
}
}
#if !SWIFT_STDLIB_HAS_COMMANDLINE
@_silgen_name("_swift_stdlib_getUnsafeArgvArgc")
internal func _swift_stdlib_getUnsafeArgvArgc(_: UnsafeMutablePointer<Int32>) -> UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>
public enum CommandLine {
public static var arguments: [String] = {
var argc: Int32 = 0
var unsafeArgv = _swift_stdlib_getUnsafeArgvArgc(&argc)
return (0 ..< Int(argc)).map { String(cString: unsafeArgv[$0]!) }
}()
}
#endif // !SWIFT_STDLIB_HAS_COMMANDLINE
#if os(Windows)
public func spawnChild(_ args: [String])
-> (process: HANDLE, stdin: HANDLE, stdout: HANDLE, stderr: HANDLE) {
var _stdin: (read: HANDLE?, write: HANDLE?)
var _stdout: (read: HANDLE?, write: HANDLE?)
var _stderr: (read: HANDLE?, write: HANDLE?)
var saAttributes: SECURITY_ATTRIBUTES = SECURITY_ATTRIBUTES()
saAttributes.nLength = DWORD(MemoryLayout<SECURITY_ATTRIBUTES>.size)
saAttributes.bInheritHandle = true
saAttributes.lpSecurityDescriptor = nil
if !CreatePipe(&_stdin.read, &_stdin.write, &saAttributes, 0) {
fatalError("CreatePipe() failed")
}
if !SetHandleInformation(_stdin.write, HANDLE_FLAG_INHERIT, 0) {
fatalError("SetHandleInformation() failed")
}
if !CreatePipe(&_stdout.read, &_stdout.write, &saAttributes, 0) {
fatalError("CreatePipe() failed")
}
if !SetHandleInformation(_stdout.read, HANDLE_FLAG_INHERIT, 0) {
fatalError("SetHandleInformation() failed")
}
if !CreatePipe(&_stderr.read, &_stderr.write, &saAttributes, 0) {
fatalError("CreatePipe() failed")
}
if !SetHandleInformation(_stderr.read, HANDLE_FLAG_INHERIT, 0) {
fatalError("SetHandleInformation() failed")
}
var siStartupInfo: STARTUPINFOW = STARTUPINFOW()
siStartupInfo.cb = DWORD(MemoryLayout<STARTUPINFOW>.size)
siStartupInfo.hStdError = _stderr.write
siStartupInfo.hStdOutput = _stdout.write
siStartupInfo.hStdInput = _stdin.read
siStartupInfo.dwFlags |= STARTF_USESTDHANDLES
var piProcessInfo: PROCESS_INFORMATION = PROCESS_INFORMATION()
// TODO(compnerd): properly quote the command line being invoked here. See
// https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/
// for more details on how to properly quote the command line for Windows.
let command: String =
([CommandLine.arguments[0]] + args).joined(separator: " ")
command.withCString(encodedAs: UTF16.self) { cString in
if !CreateProcessW(nil, UnsafeMutablePointer<WCHAR>(mutating: cString),
nil, nil, true, 0, nil, nil,
&siStartupInfo, &piProcessInfo) {
let dwError: DWORD = GetLastError()
fatalError("CreateProcessW() failed \(dwError)")
}
}
if !CloseHandle(_stdin.read) {
fatalError("CloseHandle() failed")
}
if !CloseHandle(_stdout.write) {
fatalError("CloseHandle() failed")
}
if !CloseHandle(_stderr.write) {
fatalError("CloseHandle() failed")
}
// CloseHandle(piProcessInfo.hProcess)
CloseHandle(piProcessInfo.hThread)
return (piProcessInfo.hProcess,
_stdin.write ?? INVALID_HANDLE_VALUE,
_stdout.read ?? INVALID_HANDLE_VALUE,
_stderr.read ?? INVALID_HANDLE_VALUE)
}
public func waitProcess(_ process: HANDLE) -> ProcessTerminationStatus {
let result = WaitForSingleObject(process, INFINITE)
if result != WAIT_OBJECT_0 {
fatalError("WaitForSingleObject() failed")
}
var status: DWORD = 0
if !GetExitCodeProcess(process, &status) {
fatalError("GetExitCodeProcess() failed")
}
if status & DWORD(0x80000000) == DWORD(0x80000000) {
return .signal(Int(status))
}
return .exit(Int(status))
}
#elseif os(WASI)
// WASI doesn't support child processes
public func spawnChild(_ args: [String])
-> (pid: pid_t, stdinFD: CInt, stdoutFD: CInt, stderrFD: CInt) {
fatalError("\(#function) is not supported on WebAssembly/WASI")
}
public func posixWaitpid(_ pid: pid_t) -> ProcessTerminationStatus {
fatalError("\(#function) is not supported on WebAssembly/WASI")
}
#else
// posix_spawn is not available on Android.
// posix_spawn is not available on Haiku.
#if !os(Android) && !os(Haiku)
// posix_spawn isn't available in the public watchOS SDK, we sneak by the
// unavailable attribute declaration here of the APIs that we need.
// FIXME: Come up with a better way to deal with APIs that are pointers on some
// platforms but not others.
#if os(Linux)
typealias _stdlib_posix_spawn_file_actions_t = posix_spawn_file_actions_t
#else
typealias _stdlib_posix_spawn_file_actions_t = posix_spawn_file_actions_t?
#endif
@_silgen_name("_stdlib_posix_spawn_file_actions_init")
internal func _stdlib_posix_spawn_file_actions_init(
_ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>
) -> CInt
@_silgen_name("_stdlib_posix_spawn_file_actions_destroy")
internal func _stdlib_posix_spawn_file_actions_destroy(
_ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>
) -> CInt
@_silgen_name("_stdlib_posix_spawn_file_actions_addclose")
internal func _stdlib_posix_spawn_file_actions_addclose(
_ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>,
_ filedes: CInt) -> CInt
@_silgen_name("_stdlib_posix_spawn_file_actions_adddup2")
internal func _stdlib_posix_spawn_file_actions_adddup2(
_ file_actions: UnsafeMutablePointer<_stdlib_posix_spawn_file_actions_t>,
_ filedes: CInt,
_ newfiledes: CInt) -> CInt
@_silgen_name("_stdlib_posix_spawn")
internal func _stdlib_posix_spawn(
_ pid: UnsafeMutablePointer<pid_t>?,
_ file: UnsafePointer<Int8>,
_ file_actions: UnsafePointer<_stdlib_posix_spawn_file_actions_t>?,
_ attrp: UnsafePointer<posix_spawnattr_t>?,
_ argv: UnsafePointer<UnsafeMutablePointer<Int8>?>,
_ envp: UnsafePointer<UnsafeMutablePointer<Int8>?>?) -> CInt
#endif
/// Calls POSIX `pipe()`.
func posixPipe() -> (readFD: CInt, writeFD: CInt) {
var fds: [CInt] = [ -1, -1 ]
if pipe(&fds) != 0 {
preconditionFailure("pipe() failed")
}
return (fds[0], fds[1])
}
#if !SWIFT_STDLIB_HAS_ENVIRON
@_silgen_name("_NSGetEnviron")
func _NSGetEnviron() -> UnsafeMutablePointer<UnsafeMutablePointer<UnsafeMutablePointer<CChar>?>>
var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> {
#if os(macOS)
return _NSGetEnviron().pointee
#elseif os(Windows)
return __p_environ().pointee
#elseif os(Linux)
return __environ
#else
#error("unsupported platform")
#endif
}
#endif
/// Start the same executable as a child process, redirecting its stdout and
/// stderr.
public func spawnChild(_ args: [String])
-> (pid: pid_t, stdinFD: CInt, stdoutFD: CInt, stderrFD: CInt) {
// The stdout, stdin, and stderr from the child process will be redirected
// to these pipes.
let childStdout = posixPipe()
let childStdin = posixPipe()
let childStderr = posixPipe()
#if os(Android) || os(Haiku)
// posix_spawn isn't available on Android. Instead, we fork and exec.
// To correctly communicate the exit status of the child process to this
// (parent) process, we'll use this pipe.
let childToParentPipe = posixPipe()
let pid = fork()
precondition(pid >= 0, "fork() failed")
if pid == 0 {
// pid of 0 means we are now in the child process.
// Capture the output before executing the program.
close(childStdout.readFD)
close(childStdin.writeFD)
close(childStderr.readFD)
close(childToParentPipe.readFD)
dup2(childStdout.writeFD, STDOUT_FILENO)
dup2(childStdin.readFD, STDIN_FILENO)
dup2(childStderr.writeFD, STDERR_FILENO)
// Set the "close on exec" flag on the parent write pipe. This will
// close the pipe if the execve() below successfully executes a child
// process.
let closeResult = fcntl(childToParentPipe.writeFD, F_SETFD, FD_CLOEXEC)
let closeErrno = errno
precondition(
closeResult == 0,
"Could not set the close behavior of the child-to-parent pipe; " +
"errno: \(closeErrno)")
// Start the executable. If execve() does not encounter an error, the
// code after this block will never be executed, and the parent write pipe
// will be closed.
withArrayOfCStrings([CommandLine.arguments[0]] + args) {
execve(CommandLine.arguments[0], $0, environ)
}
// If execve() encountered an error, we write the errno encountered to the
// parent write pipe.
let errnoSize = MemoryLayout.size(ofValue: errno)
var execveErrno = errno
let writtenBytes = withUnsafePointer(to: &execveErrno) {
write(childToParentPipe.writeFD, UnsafePointer($0), errnoSize)
}
let writeErrno = errno
if writtenBytes > 0 && writtenBytes < errnoSize {
// We were able to write some of our error, but not all of it.
// FIXME: Retry in this case.
preconditionFailure("Unable to write entire error to child-to-parent " +
"pipe.")
} else if writtenBytes == 0 {
preconditionFailure("Unable to write error to child-to-parent pipe.")
} else if writtenBytes < 0 {
preconditionFailure("An error occurred when writing error to " +
"child-to-parent pipe; errno: \(writeErrno)")
}
// Close the pipe when we're done writing the error.
close(childToParentPipe.writeFD)
} else {
close(childToParentPipe.writeFD)
// Figure out if the child’s call to execve was successful or not.
var readfds = _stdlib_fd_set()
readfds.set(childToParentPipe.readFD)
var writefds = _stdlib_fd_set()
var errorfds = _stdlib_fd_set()
errorfds.set(childToParentPipe.readFD)
var ret: CInt
repeat {
ret = _stdlib_select(&readfds, &writefds, &errorfds, nil)
} while ret == -1 && errno == EINTR
if ret <= 0 {
fatalError("select() returned an error: \(errno)")
}
if readfds.isset(childToParentPipe.readFD) || errorfds.isset(childToParentPipe.readFD) {
var childErrno: CInt = 0
let readResult: ssize_t = withUnsafeMutablePointer(to: &childErrno) {
return read(childToParentPipe.readFD, $0, MemoryLayout.size(ofValue: $0.pointee))
}
if readResult == 0 {
// We read an EOF indicating that the child's call to execve was successful.
} else if readResult < 0 {
fatalError("read() returned error: \(errno)")
} else {
// We read an error from the child.
print(String(cString: strerror(childErrno)))
preconditionFailure("execve() failed")
}
}
close(childToParentPipe.readFD)
}
#else
var fileActions = _make_posix_spawn_file_actions_t()
if _stdlib_posix_spawn_file_actions_init(&fileActions) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_init() failed")
}
// Close the write end of the pipe on the child side.
if _stdlib_posix_spawn_file_actions_addclose(
&fileActions, childStdin.writeFD) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stdin.
if _stdlib_posix_spawn_file_actions_adddup2(
&fileActions, childStdin.readFD, STDIN_FILENO) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_adddup2() failed")
}
// Close the read end of the pipe on the child side.
if _stdlib_posix_spawn_file_actions_addclose(
&fileActions, childStdout.readFD) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stdout.
if _stdlib_posix_spawn_file_actions_adddup2(
&fileActions, childStdout.writeFD, STDOUT_FILENO) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_adddup2() failed")
}
// Close the read end of the pipe on the child side.
if _stdlib_posix_spawn_file_actions_addclose(
&fileActions, childStderr.readFD) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_addclose() failed")
}
// Remap child's stderr.
if _stdlib_posix_spawn_file_actions_adddup2(
&fileActions, childStderr.writeFD, STDERR_FILENO) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_adddup2() failed")
}
var pid: pid_t = -1
var childArgs = args
childArgs.insert(CommandLine.arguments[0], at: 0)
let interpreter = getenv("SWIFT_INTERPRETER")
if interpreter != nil {
if let invocation = String(validatingUTF8: interpreter!) {
childArgs.insert(invocation, at: 0)
}
}
let spawnResult = withArrayOfCStrings(childArgs) {
_stdlib_posix_spawn(
&pid, childArgs[0], &fileActions, nil, $0, environ)
}
if spawnResult != 0 {
print(String(cString: strerror(spawnResult)))
preconditionFailure("_stdlib_posix_spawn() failed")
}
if _stdlib_posix_spawn_file_actions_destroy(&fileActions) != 0 {
preconditionFailure("_stdlib_posix_spawn_file_actions_destroy() failed")
}
#endif
// Close the read end of the pipe on the parent side.
if close(childStdin.readFD) != 0 {
preconditionFailure("close() failed")
}
// Close the write end of the pipe on the parent side.
if close(childStdout.writeFD) != 0 {
preconditionFailure("close() failed")
}
// Close the write end of the pipe on the parent side.
if close(childStderr.writeFD) != 0 {
preconditionFailure("close() failed")
}
return (pid, childStdin.writeFD, childStdout.readFD, childStderr.readFD)
}
#if !os(Android) && !os(Haiku)
#if os(Linux)
internal func _make_posix_spawn_file_actions_t()
-> _stdlib_posix_spawn_file_actions_t {
return posix_spawn_file_actions_t()
}
#else
internal func _make_posix_spawn_file_actions_t()
-> _stdlib_posix_spawn_file_actions_t {
return nil
}
#endif
#endif
public func posixWaitpid(_ pid: pid_t) -> ProcessTerminationStatus {
var status: CInt = 0
#if os(Cygwin)
withUnsafeMutablePointer(to: &status) {
statusPtr in
let statusPtrWrapper = __wait_status_ptr_t(__int_ptr: statusPtr)
while waitpid(pid, statusPtrWrapper, 0) < 0 {
if errno != EINTR {
preconditionFailure("waitpid() failed")
}
}
}
#else
while waitpid(pid, &status, 0) < 0 {
if errno != EINTR {
preconditionFailure("waitpid() failed")
}
}
#endif
if WIFEXITED(status) {
return .exit(Int(WEXITSTATUS(status)))
}
if WIFSIGNALED(status) {
return .signal(Int(WTERMSIG(status)))
}
preconditionFailure("did not understand what happened to child process")
}
// !os(Windows)
#endif
| apache-2.0 | 4042a2ee41e748743e7c38674b596976 | 32.559748 | 131 | 0.687344 | 3.841613 | false | false | false | false |
prebid/prebid-mobile-ios | Example/PrebidDemo/PrebidDemoSwift/Examples/In-App/InAppDisplayInterstitialViewController.swift | 1 | 2011 | /* Copyright 2019-2022 Prebid.org, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import PrebidMobile
fileprivate let storedResponseDisplayInterstitial = "response-prebid-display-interstitial-320-480"
fileprivate let storedImpDisplayInterstitial = "imp-prebid-display-interstitial-320-480"
class InAppDisplayInterstitialViewController: UIViewController, InterstitialAdUnitDelegate {
// Prebid
private var renderingInterstitial: InterstitialRenderingAdUnit!
override func loadView() {
super.loadView()
Prebid.shared.storedAuctionResponse = storedResponseDisplayInterstitial
createAd()
}
func createAd() {
// 1. Create a InterstitialRenderingAdUnit
renderingInterstitial = InterstitialRenderingAdUnit(configID: storedImpDisplayInterstitial)
// 2. Configure the InterstitialRenderingAdUnit
renderingInterstitial.adFormats = [.display]
renderingInterstitial.delegate = self
// 3. Load the interstitial ad
renderingInterstitial.loadAd()
}
// MARK: - InterstitialAdUnitDelegate
func interstitialDidReceiveAd(_ interstitial: InterstitialRenderingAdUnit) {
interstitial.show(from: self)
}
func interstitial(_ interstitial: InterstitialRenderingAdUnit, didFailToReceiveAdWithError error: Error?) {
PrebidDemoLogger.shared.error("Interstitial Rendering ad unit did fail to receive ad with error: \(error)")
}
}
| apache-2.0 | 5f774c8c9cf6886af52ef288eb703efc | 35.563636 | 115 | 0.73645 | 5.236979 | false | false | false | false |
wuleijun/Zeus | Zeus/Views/UserCountLabel.swift | 1 | 822 | //
// UserCountLabel.swift
// Zeus
//
// Created by 吴蕾君 on 16/4/15.
// Copyright © 2016年 rayjuneWu. All rights reserved.
//
import UIKit
class UserCountLabel: UILabel {
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(title: String) {
super.init(frame: CGRect(x: 0, y: 0, width: 300, height: 40))
text = title
backgroundColor = UIColor.whiteColor()
textColor = UIColor.darkGrayColor()
font = UIFont.systemFontOfSize(14)
textAlignment = .Center
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| mit | 763897ef997162dacff5f49d7a55f87e | 23.636364 | 78 | 0.629766 | 4.147959 | false | false | false | false |
zhangliangzhi/RollCall | RollCall/INSPersistentContainer/MyColor.swift | 1 | 2580 | //
// MyColor.swift
// xxword
//
// Created by ZhangLiangZhi on 2017/4/23.
// Copyright © 2017年 xigk. All rights reserved.
//
import Foundation
import UIKit
func randomSmallCaseString(length: Int) -> String {
var output = ""
for _ in 0..<length {
let randomNumber = arc4random() % 26 + 97
let randomChar = Character(UnicodeScalar(randomNumber)!)
output.append(randomChar)
}
return output
}
// 背景1
let BG1_COLOR = UIColor(red: 233/255, green: 228/255, blue: 217/255, alpha: 1)
let BG_COLOR = UIColor(red: 246/255, green: 246/255, blue: 250/255, alpha: 1) // 几乎白色
// 背景2
let BG2_COLOR = UIColor(red: 249/255, green: 247/255, blue: 242/255, alpha: 1)
// 淡蓝1
let BG3_COLOR = UIColor(red: 230/255, green: 245/255, blue: 255/255, alpha: 1)
// 淡蓝2
let BG4_COLOR = UIColor(red: 214/255, green: 238/255, blue: 255/255, alpha: 1)
// 蓝, 标题,导航头部
let BLUE_COLOR = UIColor(red: 55/255, green: 124/255, blue: 185/255, alpha: 1)
let BLUE2_COLOR = UIColor(red: 0/255, green: 170/255, blue: 251/255, alpha: 1)
// 金
let GOLD_COLOR = UIColor(red: 222/255, green: 155/255, blue: 1/255, alpha: 1)
let TI_COLOR = UIColor(red: 249/255, green: 247/255, blue: 242/255, alpha: 1)
// 首页文字1 大字
let WZ1_COLOR = UIColor(red: 120/255, green: 105/255, blue: 90/255, alpha: 1)
// 首页文字2 小字
let WZ2_COLOR = UIColor(red: 181/255, green: 172/255, blue: 149/255, alpha: 1)
// 成功颜色
let CG_COLOR = UIColor(red: 102/255, green: 184/255, blue: 77/255, alpha: 1)
let INFO_COLOR = UIColor(red: 99/255, green: 191/255, blue: 225/255, alpha: 1) // 青色
let DEF_COLOR = UIColor(red: 230/255, green: 230/255, blue: 230/255, alpha: 1) //
let WARN_COLOR = UIColor(red: 238/255, green: 174/255, blue: 56/255, alpha: 1) // 橙色
let DANG_COLOR = UIColor(red: 212/255, green: 84/255, blue: 76/255, alpha: 1) // 红色
let PRI_COLOR = UIColor(red: 70/255, green: 138/255, blue: 207/255, alpha: 1) // 蓝色
// 单词颜色
let WZ4_COLOR = UIColor(red: 150/255, green: 154/255, blue: 153/255, alpha: 1)
let SX1_COLOR = UIColor(red: 218/255, green: 213/255, blue: 203/255, alpha: 1) // 深背景
let SX2_COLOR = UIColor(red: 233/255, green: 228/255, blue: 217/255, alpha: 1) // 浅背景
let SX3_COLOR = UIColor(red: 74/255, green: 85/255, blue: 105/255, alpha: 1) // 单词颜色
let SX4_COLOR = UIColor(red: 144/255, green: 144/255, blue: 144/255, alpha: 1) // 音标颜色,灰
let SX5_COLOR = UIColor(red: 181/255, green: 172/255, blue: 150/255, alpha: 1) // 背景边框的颜色
| mit | 879c21e33a57290a68316dbd272746da | 37.650794 | 90 | 0.652977 | 2.563158 | false | false | false | false |
TakuSemba/DribbbleSwiftApp | DribbbleSwiftApp/ShotApi.swift | 1 | 1817 | //
// HttpClient.swift
// DribbbleSwiftApp
//
// Created by TakuSemba on 2016/06/01.
// Copyright © 2016年 TakuSemba. All rights reserved.
//
import RxSwift
import Alamofire
import Foundation
import ObjectMapper
class ShotApi {
static let ACCESS_TOKEN: String = "9a41e101508074ad21b5dee2b64ea32a38d8a9ec9318306dd912edb717a3a739"
static let limit = "24"
static let BASE_URL: String = "https://api.dribbble.com/v1/shots/"
static func getShots(page: Int, category: Category) -> Observable<[Shot]> {
let params: [String: String] = ["access_token": ACCESS_TOKEN, "page": String(page), "list": category.rawValue, "per_page": limit]
return Observable.create { observer -> Disposable in
Alamofire.request(.GET, BASE_URL, parameters: params)
.responseJSON { response in
switch response.result {
case .Success(let result):
var shots: [Shot] = []
for i in 0 ..< result.count {
let shot = Mapper<Shot>().map(result[i])
shots.append(shot!)
}
observer.on(.Next(shots))
observer.on(.Completed)
case .Failure(let error):
observer.on(.Error(error))
}
}
return AnonymousDisposable {}
}
}
enum Category: String {
case ANIMATED = "animated"
case ATTACHMENTS = "attachments"
case DEBUTS = "debuts"
case PLAYOFFS = "playoffs"
case REBOUNDS = "rebounds"
case TEAMS = "teams"
static let allValues = [ANIMATED, ATTACHMENTS, DEBUTS, PLAYOFFS, REBOUNDS, TEAMS]
}
} | apache-2.0 | ab0f6dcc1f92d18ac0bc6614bf38cee2 | 33.903846 | 137 | 0.545204 | 4.208817 | false | false | false | false |
wibosco/ASOS-Consumer | ASOSConsumer/Networking/Media/MediaAPIManager.swift | 1 | 1318 | //
// MediaAPIManager.swift
// ASOSConsumer
//
// Created by William Boles on 03/03/2016.
// Copyright © 2016 Boles. All rights reserved.
//
import UIKit
import CoreData
class MediaAPIManager: APIManager {
//MARK: - Retrieval
class func retrieveMediaAsset(media: Media, completion:((media: Media, mediaImage: UIImage?) -> Void)?) {
let url = NSURL(string: media.remoteURL!)!
let session = NSURLSession.sharedSession()
let callBackQueue = NSOperationQueue.currentQueue()!
let task = session.downloadTaskWithURL(url) { (assetLocalURL: NSURL?, response: NSURLResponse?, error: NSError?) -> Void in
if (error == nil) {
let imageData = NSData(contentsOfURL: assetLocalURL!)
callBackQueue.addOperationWithBlock({ () -> Void in
let mediaImage = UIImage(data: imageData!)
if (completion != nil) {
completion!(media: media, mediaImage: mediaImage)
}
})
} else {
if ((completion) != nil) {
completion!(media: media, mediaImage: nil)
}
}
}
task.resume()
}
}
| mit | 1a90de596c8bc0ea1c383abfad0b028d | 29.627907 | 131 | 0.524677 | 5.185039 | false | false | false | false |
jacobwhite/firefox-ios | UITests/ReadingListTest.swift | 1 | 7101 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import EarlGrey
import WebKit
class ReadingListTests: KIFTestCase, UITextFieldDelegate {
fileprivate var webRoot: String!
override func setUp() {
super.setUp()
// We undo the localhost/127.0.0.1 switch in order to get 'localhost' in accessibility labels.
webRoot = SimplePageServer.start()
.replacingOccurrences(of: "127.0.0.1", with: "localhost")
BrowserUtils.configEarlGrey()
BrowserUtils.dismissFirstRunUI()
}
func enterUrl(url: String) {
EarlGrey.select(elementWithMatcher: grey_accessibilityID("url")).perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityID("address")).perform(grey_replaceText(url))
EarlGrey.select(elementWithMatcher: grey_accessibilityID("address")).perform(grey_typeText("\n"))
}
func waitForReadingList() {
let readingList = GREYCondition(name: "wait until Reading List Add btn appears", block: {
var errorOrNil: NSError?
let matcher = grey_allOf([grey_accessibilityLabel("Add to Reading List"),
grey_sufficientlyVisible()])
EarlGrey.select(elementWithMatcher: matcher)
.assert(grey_notNil(), error: &errorOrNil)
let success = errorOrNil == nil
return success
}).wait(withTimeout: 20)
GREYAssertTrue(readingList, reason: "Can't be added to Reading List")
}
func waitForEmptyReadingList() {
let readable = GREYCondition(name: "Check readable list is empty", block: {
var error: NSError?
let matcher = grey_allOf([grey_accessibilityLabel("Save pages to your Reading List by tapping the book plus icon in the Reader View controls."),
grey_sufficientlyVisible()])
EarlGrey.select(elementWithMatcher: matcher)
.assert(grey_notNil(), error: &error)
return error == nil
}).wait(withTimeout: 10)
GREYAssertTrue(readable, reason: "Read list should not appear")
}
/**
* Tests opening reader mode pages from the urlbar and reading list.
*/
func testReadingList() {
// Load a page
let url1 = "\(webRoot!)/readablePage.html"
enterUrl(url: url1)
tester().waitForWebViewElementWithAccessibilityLabel("Readable Page")
// Add it to the reading list
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Reader View"))
.perform(grey_tap())
waitForReadingList()
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Add to Reading List"))
.perform(grey_tap())
// Open a new page
let url2 = "\(webRoot!)/numberedPage.html?page=1"
enterUrl(url: url2)
tester().waitForWebViewElementWithAccessibilityLabel("Page 1")
// Check that it appears in the reading list home panel
EarlGrey.select(elementWithMatcher: grey_accessibilityID("url"))
.perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Reading list"))
.perform(grey_tap())
// Tap to open it
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("localhost"))
.perform(grey_tap())
tester().waitForWebViewElementWithAccessibilityLabel("Readable page")
// Remove it from the reading list
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Remove from Reading List"))
.perform(grey_tap())
// Check that it no longer appears in the reading list home panel
EarlGrey.select(elementWithMatcher: grey_accessibilityID("url"))
.perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Reading list"))
.perform(grey_tap())
waitForEmptyReadingList()
EarlGrey.select(elementWithMatcher: grey_accessibilityID("goBack")).perform(grey_tap())
}
func testReadingListAutoMarkAsRead() {
// Load a page
let url1 = "\(webRoot!)/readablePage.html"
enterUrl(url: url1)
tester().waitForWebViewElementWithAccessibilityLabel("Readable Page")
// Add it to the reading list
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Reader View"))
.perform(grey_tap())
waitForReadingList()
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Add to Reading List"))
.perform(grey_tap())
// Check that it appears in the reading list home panel and make sure it marked as unread
EarlGrey.select(elementWithMatcher: grey_accessibilityID("url"))
.perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Reading list"))
.perform(grey_tap())
tester().waitForView(withAccessibilityLabel: "Readable page, unread, localhost")
// Select to Read
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("localhost"))
.perform(grey_tap())
tester().waitForWebViewElementWithAccessibilityLabel("Readable page")
// Go back to the reading list panel
EarlGrey.select(elementWithMatcher: grey_accessibilityID("url"))
.perform(grey_tap())
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Reading list"))
.perform(grey_tap())
// Make sure the article is marked as read
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Readable page"))
.inRoot(grey_kindOfClass(NSClassFromString("UITableViewCellContentView")!))
.assert(grey_notNil())
tester().waitForView(withAccessibilityLabel: "Readable page, read, localhost")
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("localhost"))
.assert(grey_notNil())
// Remove the list entry
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Readable page"))
.inRoot(grey_kindOfClass(NSClassFromString("UITableViewCellContentView")!))
.perform(grey_swipeSlowInDirection(GREYDirection.left))
EarlGrey.select(elementWithMatcher: grey_accessibilityLabel("Remove"))
.inRoot(grey_kindOfClass(NSClassFromString("UISwipeActionStandardButton")!))
.perform(grey_tap())
// check the entry no longer exist
waitForEmptyReadingList()
EarlGrey.select(elementWithMatcher: grey_accessibilityID("goBack")).perform(grey_tap())
}
override func tearDown() {
BrowserUtils.resetToAboutHome()
BrowserUtils.clearPrivateData()
super.tearDown()
}
}
| mpl-2.0 | 6f3ecb9b7ccf48a7d3c0af4b98202204 | 44.229299 | 156 | 0.642445 | 5.424752 | false | true | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/Services/ReaderSiteSearchService.swift | 1 | 2231 | import Foundation
import CocoaLumberjack
typealias ReaderSiteSearchSuccessBlock = (_ feeds: [ReaderFeed], _ hasMore: Bool, _ feedCount: Int) -> Void
typealias ReaderSiteSearchFailureBlock = (_ error: Error?) -> Void
/// Allows searching for sites / feeds in the Reader.
///
@objc class ReaderSiteSearchService: LocalCoreDataService {
// The size of a single page of results when performing a search.
static let pageSize = 20
private func apiRequest() -> WordPressComRestApi {
let defaultAccount = try? WPAccount.lookupDefaultWordPressComAccount(in: managedObjectContext)
if let api = defaultAccount?.wordPressComRestApi, api.hasCredentials() {
return api
}
return WordPressComRestApi.defaultApi(oAuthToken: nil, userAgent: WPUserAgent.wordPress())
}
/// Performs a search for sites / feeds matching the specified query.
///
/// - Parameters:
/// - query: The phrase to search for
/// - page: Results are requested in pages. Use this to specify which
/// page of results to return. 0 indexed.
/// - success: Success block called on a successful search. Parameters
/// are a list of ReaderFeeds, a bool for `hasMore` (are there
/// more feeds to fetch), and a total feed count.
/// - failure: Failure block called on a failed search.
///
func performSearch(with query: String,
page: Int,
success: @escaping ReaderSiteSearchSuccessBlock,
failure: @escaping ReaderSiteSearchFailureBlock) {
let remote = ReaderSiteSearchServiceRemote(wordPressComRestApi: apiRequest())
remote.performSearch(query,
offset: page * Constants.pageSize,
count: Constants.pageSize,
success: { (feeds, hasMore, feedCount) in
success(feeds, hasMore, feedCount)
}, failure: { error in
DDLogError("Error while performing Reader site search: \(String(describing: error))")
failure(error)
})
}
private enum Constants {
static let pageSize = 20
}
}
| gpl-2.0 | 6bf96c7ed7d4b1d0d7f746646fcc9e53 | 41.09434 | 107 | 0.622591 | 5.212617 | false | false | false | false |
cldershem/elevenchat | ElevenChat/FriendsViewController.swift | 1 | 6606 | //
// FriendsViewController.swift
// ElevenChat
//
// Created by Cameron Dershem on 9/12/14.
// Copyright (c) 2014 Cameron Dershem. All rights reserved.
//
// add this to your shiznit
// http://pastebin.com/DXQkX70g
import Foundation
class FriendsViewController : PFQueryTableViewController, UISearchBarDelegate {
// get stuff, return count, display stuff
// PFQueryViewController is a subclass of TableViewController from Parse SDK
var searchText = ""
var selectFriendMode = false
override init(style: UITableViewStyle) {
super.init(style: style)
self.parseClassName = Friendship.parseClassName()
}
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)
self.parseClassName = Friendship.parseClassName()
}
override func viewDidLoad() {
super.viewDidLoad()
// fixes annoying UI bug
self.tableView.contentInset = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0)
println("MODE: \(selectFriendMode)")
}
// MARK: tableView
override func queryForTable() -> PFQuery! {
var query : PFQuery!
if searchText.isEmpty {
query = Friendship.query()
query.whereKey("currentUser", equalTo: ChatUser.currentUser())
query.includeKey("theFriend")
} else {
// username search
var userNameSearch = ChatUser.query()
userNameSearch.whereKey("username", containsString: searchText)
// email search
var emailSearch = ChatUser.query()
emailSearch.whereKey("email", equalTo: searchText)
// phone number search
var additionalSearch = ChatUser.query()
additionalSearch.whereKey("additional", equalTo: searchText)
// or them together
query = PFQuery.orQueryWithSubqueries([userNameSearch, emailSearch, additionalSearch])
}
return query
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!, object: PFObject!) -> PFTableViewCell! {
var cellIdentifier = selectFriendMode ? "FriendCell" : "PFTableViewCell"
// println("cellID is \(cellIdentifier)")
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as PFTableViewCell?
if cell == nil {
// println("cell is \(cell)")
cell = PFTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: cellIdentifier)
} else {
// println("cell is not nil and is \(cell)")
}
// println("cell after if nil \(cell)")
if object is Friendship {
// println("Object is Friendship")
var friends = object as Friendship
if cell is FriendCell {
// println("cell is FriendCell")
var friendCell = cell as? FriendCell
friendCell?.setupCell(friends)
} else {
// println("cell is not FriendCell")
cell?.textLabel?.text = friends.theFriend?.username
}
} else if object is ChatUser {
// println("Object is ChatUser")
var user = object as ChatUser
cell?.textLabel?.text = user.username
} else {
// println("object is something?")
}
// println("end of func. cell is \(cell)")
return cell
}
override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if selectFriendMode { return 0 }
return 44
}
override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if selectFriendMode { return nil }
var headerCell = tableView.dequeueReusableCellWithIdentifier("HeaderCell") as UITableViewCell
return headerCell as UIView
}
// http://pastebin.com/NdYvPSsY <-------- does this with erros.
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
// get the object
var selectedObject = self.objectAtIndexPath(indexPath)
if selectedObject is ChatUser {
// probably *should* have a confirmation box...
self.addFriend(selectedObject as ChatUser)
}
self.tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
// MARK: Add friend
func addFriend(friend:ChatUser) {
// var areFriends = PFQuery(className: self.parseClassName)
var areFriends = Friendship.query()
areFriends.whereKey("currentUser", equalTo: ChatUser.currentUser())
areFriends.whereKey("theFriend", equalTo: friend)
areFriends.countObjectsInBackgroundWithBlock { (count, _) -> Void in
if count > 0 {
// already friends
println("Not adding, already friends.")
} else {
// add friend
var bff = Friendship()
bff.currentUser = ChatUser.currentUser()
bff.theFriend = friend
bff.saveInBackground()
println("adding \(bff.currentUser!.username) -> \(bff.theFriend!.username)")
}
}
}
func getTargetFriends() -> [ChatUser]
{
var targetFriends = [ChatUser]()
let friendships = self.objects as? [Friendship]
for friend in friendships! {
if friend.selected {
targetFriends.append(friend.theFriend!)
}
}
return targetFriends
}
// MARK: Search Bar
// delegate in story board
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchBar.showsCancelButton = true
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchBar.showsCancelButton = false
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
// add minimum length of search
searchText = searchBar.text
self.loadObjects()
}
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
// clear out search box
searchBar.text = nil
// clear out search variable
searchText = ""
// reload the table
self.loadObjects()
// hide keyboard
searchBar.resignFirstResponder()
}
}
| mit | 6a41d87f03fe77bc27f45f43d8ae2049 | 30.913043 | 140 | 0.590827 | 5.242857 | false | false | false | false |
apple/swift-nio | Sources/NIOPerformanceTester/Benchmark.swift | 1 | 1513 | //===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftNIO open source project
//
// Copyright (c) 2019 Apple Inc. and the SwiftNIO project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
import Dispatch
protocol Benchmark: AnyObject {
func setUp() throws
func tearDown()
func run() throws -> Int
}
func measureAndPrint<B: Benchmark>(desc: String, benchmark bench: B) throws {
try bench.setUp()
defer {
bench.tearDown()
}
try measureAndPrint(desc: desc) {
return try bench.run()
}
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
protocol AsyncBenchmark: AnyObject, Sendable {
func setUp() async throws
func tearDown()
func run() async throws -> Int
}
@available(macOS 10.15, iOS 13, tvOS 13, watchOS 6, *)
func measureAndPrint<B: AsyncBenchmark>(desc: String, benchmark bench: B) throws {
let group = DispatchGroup()
group.enter()
Task {
do {
try await bench.setUp()
defer {
bench.tearDown()
}
try await measureAndPrint(desc: desc) {
return try await bench.run()
}
}
group.leave()
}
group.wait()
}
| apache-2.0 | f39b4e933b922f293d517ee2b7eaccb6 | 25.086207 | 82 | 0.553206 | 4.570997 | false | false | false | false |
allenlinli/Wildlife-League | Wildlife League/Board+BeedDropper.swift | 1 | 1643 | //
// Board+BeedDropper.swift
// Wildlife League
//
// Created by allenlin on 7/21/14.
// Copyright (c) 2014 Raccoonism. All rights reserved.
//
import Foundation
extension Board {
func fillBeeds() {
var baseRow :Int
for emptyCol in 0..<NumColumns {
for (var emptyRow = NumRows-1; emptyRow>=0 ; emptyRow--){
var emptyBeed = self[emptyCol,emptyRow]!
if (emptyBeed.beedType == BeedType.BeedTypeEmpty){
baseRow = emptyRow+1
if let beedToFill = self._theBeedToFillOnTopAt(col: emptyCol,row: emptyRow) {
var oldRowOfBeedToFill = beedToFill.row
var oldColumnOfBeedToFill = beedToFill.column
beedToFill.row = emptyRow
beedToFill.column = emptyCol
self.insertBeed(beedToFill)
self.insertBeed(Beed(column: oldColumnOfBeedToFill, row: oldRowOfBeedToFill, beedType: BeedType.BeedTypeEmpty))
}
else {
/* Add New Beed Upon */
var newBeed = Beed(column: emptyCol, row: emptyRow, beedType: BeedType.randomType())
self.insertBeed(newBeed)
}
}
}
}
}
func _theBeedToFillOnTopAt(#col :Int , row :Int) -> Beed?{
for (var row2 = row-1; row2>=0 ; row2--){
if self[col,row2]!.beedType != BeedType.BeedTypeEmpty {
return self[col,row2]!
}
}
return nil
}
} | apache-2.0 | a38cffd3da5abc64c9e28ab7f1f43e3c | 34.73913 | 135 | 0.511869 | 3.987864 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPress/Classes/ViewRelated/Reader/ReaderHelpers.swift | 1 | 6619 | import Foundation
import WordPressShared
/// A collection of helper methods used by the Reader.
///
@objc open class ReaderHelpers: NSObject {
// MARK: - Topic Helpers
/// Check if the specified topic is a default topic
///
/// - Parameters:
/// - topic: A ReaderAbstractTopic
///
/// - Returns: True if the topic is a default topic
///
open class func isTopicDefault(_ topic: ReaderAbstractTopic) -> Bool {
return topic.isKind(of: ReaderDefaultTopic.self)
}
/// Check if the specified topic is a list
///
/// - Parameters:
/// - topic: A ReaderAbstractTopic
///
/// - Returns: True if the topic is a list topic
///
open class func isTopicList(_ topic: ReaderAbstractTopic) -> Bool {
return topic.isKind(of: ReaderListTopic.self)
}
/// Check if the specified topic is a site topic
///
/// - Parameters:
/// - topic: A ReaderAbstractTopic
///
/// - Returns: True if the topic is a site topic
///
open class func isTopicSite(_ topic: ReaderAbstractTopic) -> Bool {
return topic.isKind(of: ReaderSiteTopic.self)
}
/// Check if the specified topic is a tag topic
///
/// - Parameters:
/// - topic: A ReaderAbstractTopic
///
/// - Returns: True if the topic is a tag topic
///
open class func isTopicTag(_ topic: ReaderAbstractTopic) -> Bool {
return topic.isKind(of: ReaderTagTopic.self)
}
/// Check if the specified topic is a search topic
///
/// - Parameters:
/// - topic: A ReaderAbstractTopic
///
/// - Returns: True if the topic is a search topic
///
open class func isTopicSearchTopic(_ topic: ReaderAbstractTopic) -> Bool {
return topic.isKind(of: ReaderSearchTopic.self)
}
/// Check if the specified topic is for Freshly Pressed
///
/// - Parameters:
/// - topic: A ReaderAbstractTopic
///
/// - Returns: True if the topic is for Freshly Pressed
///
open class func topicIsFreshlyPressed(_ topic: ReaderAbstractTopic) -> Bool {
return topic.path.hasSuffix("/freshly-pressed")
}
/// Check if the specified topic is for Discover
///
/// - Parameters:
/// - topic: A ReaderAbstractTopic
///
/// - Returns: True if the topic is for Discover
///
open class func topicIsDiscover(_ topic: ReaderAbstractTopic) -> Bool {
return topic.path.contains("/read/sites/53424024/posts")
}
/// Check if the specified topic is for Following
///
/// - Parameters:
/// - topic: A ReaderAbstractTopic
///
/// - Returns: True if the topic is for Following
///
open class func topicIsFollowing(_ topic: ReaderAbstractTopic) -> Bool {
return topic.path.hasSuffix("/read/following")
}
/// Check if the specified topic is for Posts I Like
///
/// - Parameters:
/// - topic: A ReaderAbstractTopic
///
/// - Returns: True if the topic is for Posts I Like
///
open class func topicIsLiked(_ topic: ReaderAbstractTopic) -> Bool {
return topic.path.hasSuffix("/read/liked")
}
// MARK: Analytics Helpers
open class func trackLoadedTopic(_ topic: ReaderAbstractTopic, withProperties properties: [AnyHashable: Any]) {
var stat: WPAnalyticsStat?
if topicIsFreshlyPressed(topic) {
stat = .readerFreshlyPressedLoaded
} else if isTopicDefault(topic) && topicIsDiscover(topic) {
// Tracks Discover only if it was one of the default menu items.
stat = .readerDiscoverViewed
} else if isTopicList(topic) {
stat = .readerListLoaded
} else if isTopicTag(topic) {
stat = .readerTagLoaded
}
if (stat != nil) {
WPAnalytics.track(stat!, withProperties: properties)
}
}
open class func statsPropertiesForPost(_ post: ReaderPost, andValue value: AnyObject?, forKey key: String?) -> [AnyHashable: Any] {
var properties = [AnyHashable: Any]()
properties[WPAppAnalyticsKeyBlogID] = post.siteID
properties[WPAppAnalyticsKeyPostID] = post.postID
properties[WPAppAnalyticsKeyIsJetpack] = post.isJetpack
if let feedID = post.feedID, let feedItemID = post.feedItemID {
properties[WPAppAnalyticsKeyFeedID] = feedID
properties[WPAppAnalyticsKeyFeedItemID] = feedItemID
}
if let value = value, let key = key {
properties[key] = value
}
return properties
}
open class func bumpPageViewForPost(_ post: ReaderPost) {
// Don't bump page views for feeds else the wrong blog/post get's bumped
if post.isExternal && !post.isJetpack {
return
}
guard
let siteID = post.siteID,
let postID = post.postID,
let host = NSURL(string: post.blogURL)?.host else {
return
}
// If the user is an admin on the post's site do not bump the page view unless
// the the post is private.
if !post.isPrivate() && isUserAdminOnSiteWithID(siteID) {
return
}
let pixelStatReferrer = "https://wordpress.com/"
let pixel = "https://pixel.wp.com/g.gif"
let params: NSArray = [
"v=wpcom",
"reader=1",
"ref=\(pixelStatReferrer)",
"host=\(host)",
"blog=\(siteID)",
"post=\(postID)",
NSString(format: "t=%d", arc4random())
]
let userAgent = WPUserAgent.wordPress()
let path = NSString(format: "%@?%@", pixel, params.componentsJoined(by: "&")) as String
let url = URL(string: path)
let request = NSMutableURLRequest(url: url!)
request.setValue(userAgent, forHTTPHeaderField: "User-Agent")
request.addValue(pixelStatReferrer, forHTTPHeaderField: "Referer")
let session = URLSession.shared
let task = session.dataTask(with: request as URLRequest)
task.resume()
}
open class func isUserAdminOnSiteWithID(_ siteID: NSNumber) -> Bool {
let context = ContextManager.sharedInstance().mainContext
let blogService = BlogService(managedObjectContext: context)
if let blog = blogService.blog(byBlogId: siteID) {
return blog.isAdmin
}
return false
}
// MARK: Logged in helper
open class func isLoggedIn() -> Bool {
return AccountHelper.isDotcomAvailable()
}
}
| gpl-2.0 | 949481858023054d1d700bae1043b902 | 28.815315 | 135 | 0.602206 | 4.651441 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPress/Classes/System/3DTouch/WP3DTouchShortcutCreator.swift | 2 | 8688 | import UIKit
public protocol ApplicationShortcutsProvider {
var shortcutItems: [UIApplicationShortcutItem]? { get set }
var is3DTouchAvailable: Bool { get }
}
extension UIApplication: ApplicationShortcutsProvider {
public var is3DTouchAvailable: Bool {
return keyWindow?.traitCollection.forceTouchCapability == .available
}
}
open class WP3DTouchShortcutCreator: NSObject {
enum LoggedIn3DTouchShortcutIndex: Int {
case notifications = 0,
stats,
newPhotoPost,
newPost
}
var shortcutsProvider: ApplicationShortcutsProvider
let mainContext = ContextManager.sharedInstance().mainContext
let blogService: BlogService
fileprivate let logInShortcutIconImageName = "icon-shortcut-signin"
fileprivate let notificationsShortcutIconImageName = "icon-shortcut-notifications"
fileprivate let statsShortcutIconImageName = "icon-shortcut-stats"
fileprivate let newPhotoPostShortcutIconImageName = "icon-shortcut-new-photo"
fileprivate let newPostShortcutIconImageName = "icon-shortcut-new-post"
public init(shortcutsProvider: ApplicationShortcutsProvider) {
self.shortcutsProvider = shortcutsProvider
blogService = BlogService(managedObjectContext: mainContext)
super.init()
registerForNotifications()
}
deinit {
NotificationCenter.default.removeObserver(self)
}
public convenience override init() {
self.init(shortcutsProvider: UIApplication.shared)
}
open func createShortcutsIf3DTouchAvailable(_ loggedIn: Bool) {
guard shortcutsProvider.is3DTouchAvailable else {
return
}
if loggedIn {
if hasBlog() {
createLoggedInShortcuts()
} else {
clearShortcuts()
}
} else {
createLoggedOutShortcuts()
}
}
fileprivate func registerForNotifications() {
let notificationCenter = NotificationCenter.default
notificationCenter.addObserver(self, selector: #selector(WP3DTouchShortcutCreator.createLoggedInShortcuts), name: NSNotification.Name(rawValue: SigninHelpers.WPSigninDidFinishNotification), object: nil)
notificationCenter.addObserver(self, selector: #selector(WP3DTouchShortcutCreator.createLoggedInShortcuts), name: NSNotification.Name(rawValue: RecentSitesService.RecentSitesChanged), object: nil)
notificationCenter.addObserver(self, selector: #selector(WP3DTouchShortcutCreator.createLoggedInShortcuts), name: NSNotification.Name.WPBlogUpdated, object: nil)
notificationCenter.addObserver(self, selector: #selector(WP3DTouchShortcutCreator.createLoggedInShortcuts), name: NSNotification.Name.WPAccountDefaultWordPressComAccountChanged, object: nil)
}
fileprivate func loggedOutShortcutArray() -> [UIApplicationShortcutItem] {
let logInShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.LogIn.type,
localizedTitle: NSLocalizedString("Log In", comment: "Log In 3D Touch Shortcut"),
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: logInShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.LogIn.rawValue])
return [logInShortcut]
}
fileprivate func loggedInShortcutArray() -> [UIApplicationShortcutItem] {
var defaultBlogName: String?
if blogService.blogCountForAllAccounts() > 1 {
defaultBlogName = blogService.lastUsedOrFirstBlog()?.settings?.name
}
let notificationsShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.Notifications.type,
localizedTitle: NSLocalizedString("Notifications", comment: "Notifications 3D Touch Shortcut"),
localizedSubtitle: nil,
icon: UIApplicationShortcutIcon(templateImageName: notificationsShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.Notifications.rawValue])
let statsShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.Stats.type,
localizedTitle: NSLocalizedString("Stats", comment: "Stats 3D Touch Shortcut"),
localizedSubtitle: defaultBlogName,
icon: UIApplicationShortcutIcon(templateImageName: statsShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.Stats.rawValue])
let newPhotoPostShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPhotoPost.type,
localizedTitle: NSLocalizedString("New Photo Post", comment: "New Photo Post 3D Touch Shortcut"),
localizedSubtitle: defaultBlogName,
icon: UIApplicationShortcutIcon(templateImageName: newPhotoPostShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPhotoPost.rawValue])
let newPostShortcut = UIMutableApplicationShortcutItem(type: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPost.type,
localizedTitle: NSLocalizedString("New Post", comment: "New Post 3D Touch Shortcut"),
localizedSubtitle: defaultBlogName,
icon: UIApplicationShortcutIcon(templateImageName: newPostShortcutIconImageName),
userInfo: [WP3DTouchShortcutHandler.applicationShortcutUserInfoIconKey: WP3DTouchShortcutHandler.ShortcutIdentifier.NewPost.rawValue])
return [notificationsShortcut, statsShortcut, newPhotoPostShortcut, newPostShortcut]
}
@objc fileprivate func createLoggedInShortcuts() {
DispatchQueue.main.async {[weak self]() in
guard let strongSelf = self else {
return
}
var entireShortcutArray = strongSelf.loggedInShortcutArray()
var visibleShortcutArray = [UIApplicationShortcutItem]()
if strongSelf.hasWordPressComAccount() {
visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.notifications.rawValue])
}
if strongSelf.doesCurrentBlogSupportStats() {
visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.stats.rawValue])
}
visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.newPhotoPost.rawValue])
visibleShortcutArray.append(entireShortcutArray[LoggedIn3DTouchShortcutIndex.newPost.rawValue])
strongSelf.shortcutsProvider.shortcutItems = visibleShortcutArray
}
}
fileprivate func clearShortcuts() {
shortcutsProvider.shortcutItems = nil
}
fileprivate func createLoggedOutShortcuts() {
shortcutsProvider.shortcutItems = loggedOutShortcutArray()
}
fileprivate func is3DTouchAvailable() -> Bool {
let window = UIApplication.shared.keyWindow
return window?.traitCollection.forceTouchCapability == .available
}
fileprivate func hasWordPressComAccount() -> Bool {
return AccountHelper.isDotcomAvailable()
}
fileprivate func doesCurrentBlogSupportStats() -> Bool {
guard let currentBlog = blogService.lastUsedOrFirstBlog() else {
return false
}
return hasWordPressComAccount() && currentBlog.supports(BlogFeature.stats)
}
fileprivate func hasBlog() -> Bool {
return blogService.blogCountForAllAccounts() > 0
}
}
| gpl-2.0 | 63f9f231c49601ddbed212e17f2c9810 | 51.337349 | 210 | 0.659645 | 6.895238 | false | false | false | false |
ScoutHarris/WordPress-iOS | WordPress/Classes/Utility/ImmuTable.swift | 1 | 11897 | /**
ImmuTable represents the view model for a static UITableView.
ImmuTable consists of zero or more sections, each one containing zero or more rows,
and an optional header and footer text.
Each row contains the model necessary to configure a specific type of UITableViewCell.
To use ImmuTable, first you need to create some custom rows. An example row for a cell
that acts as a button which performs a destructive action could look like this:
struct DestructiveButtonRow: ImmuTableRow {
static let cell = ImmuTableCell.Class(UITableViewCell.self)
let title: String
let action: ImmuTableAction?
func configureCell(cell: UITableViewCell) {
cell.textLabel?.text = title
cell.textLabel?.textAlignment = .Center
cell.textLabel?.textColor = UIColor.redColor()
}
}
The easiest way to use ImmuTable is through ImmuTableViewHandler, which takes a
UITableViewController as an argument, and acts as the table view delegate and data
source. You would then assign an ImmuTable object to the handler's `viewModel`
property.
- attention: before using any ImmuTableRow type, you need to call `registerRows(_:tableView:)`
passing the row type. This is needed so ImmuTable can register the class or nib with the table view.
If you fail to do this, UIKit will raise an exception when it tries to load the row.
*/
public struct ImmuTable {
/// An array of the sections to be represented in the table view
public let sections: [ImmuTableSection]
/// Initializes an ImmuTable object with the given sections
public init(sections: [ImmuTableSection]) {
self.sections = sections
}
/// Returns the row model for a specific index path.
///
/// - Precondition: `indexPath` should represent a valid section and row, otherwise this method
/// will raise an exception.
///
public func rowAtIndexPath(_ indexPath: IndexPath) -> ImmuTableRow {
return sections[indexPath.section].rows[indexPath.row]
}
/// Registers the row custom class or nib with the table view so it can later be
/// dequeued with `dequeueReusableCellWithIdentifier(_:forIndexPath:)`
///
public static func registerRows(_ rows: [ImmuTableRow.Type], tableView: UITableView) {
registerRows(rows, registrator: tableView)
}
/// This function exists for testing purposes
/// - seealso: registerRows(_:tableView:)
internal static func registerRows(_ rows: [ImmuTableRow.Type], registrator: CellRegistrator) {
let registrables = rows.reduce([:]) {
(classes, row) -> [String: ImmuTableCell] in
var classes = classes
classes[row.cell.reusableIdentifier] = row.cell
return classes
}
for (identifier, registrable) in registrables {
registrator.register(registrable, cellReuseIdentifier: identifier)
}
}
}
extension ImmuTable {
/// Alias for an ImmuTable with no sections
static var Empty: ImmuTable {
return ImmuTable(sections: [])
}
}
// MARK: -
/// ImmuTableSection represents the view model for a table view section.
///
/// A section has an optional header and footer text, and zero or more rows.
/// - seealso: ImmuTableRow
///
public struct ImmuTableSection {
let headerText: String?
let rows: [ImmuTableRow]
let footerText: String?
/// Initializes a ImmuTableSection with the given rows and optionally header and footer text
public init(headerText: String? = nil, rows: [ImmuTableRow], footerText: String? = nil) {
self.headerText = headerText
self.rows = rows
self.footerText = footerText
}
}
// MARK: - ImmuTableRow
/// ImmuTableRow represents the minimum common elements of a row model.
///
/// You should implement your own types that conform to ImmuTableRow to define your custom rows.
///
public protocol ImmuTableRow {
/**
The closure to call when the row is tapped. The row is passed as an argument to the closure.
To improve readability, we recommend that you implement the action logic in one of
your view controller methods, instead of including the closure inline.
Also, be mindful of retain cycles. If your closure needs to reference `self` in
any way, make sure to use `[unowned self]` in the parameter list.
An example row with its action could look like this:
class ViewController: UITableViewController {
func buildViewModel() {
let item1Row = NavigationItemRow(title: "Item 1", action: navigationAction())
...
}
func navigationAction() -> ImmuTableRow -> Void {
return { [unowned self] row in
let controller = self.controllerForRow(row)
self.navigationController?.pushViewController(controller, animated: true)
}
}
...
}
*/
var action: ImmuTableAction? { get }
/// This method is called when an associated cell needs to be configured.
///
/// - Precondition: You can assume that the passed cell is of the type defined
/// by cell.cellClass and force downcast accordingly.
///
func configureCell(_ cell: UITableViewCell)
/// An ImmuTableCell value defining the associated cell type.
///
/// - Seealso: See ImmuTableCell for possible options.
///
static var cell: ImmuTableCell { get }
/// The desired row height (Optional)
///
/// If not defined or nil, the default height will be used.
///
static var customHeight: Float? { get }
}
extension ImmuTableRow {
public var reusableIdentifier: String {
return type(of: self).cell.reusableIdentifier
}
public var cellClass: UITableViewCell.Type {
return type(of: self).cell.cellClass
}
public static var customHeight: Float? {
return nil
}
}
// MARK: - ImmuTableCell
/// ImmuTableCell describes cell types so they can be registered with a table view.
///
/// It supports two options:
/// - Nib for Interface Builder defined cells.
/// - Class for cells defined in code.
/// Both cases presume a custom UITableViewCell subclass. If you aren't subclassing,
/// you can also use UITableViewCell as the type.
///
/// - Note: If you need to use any cell style other than .Default we recommend you
/// subclass UITableViewCell and override init(style:reuseIdentifier:).
///
public enum ImmuTableCell {
/// A cell using a UINib. Values are the UINib object and the custom cell class.
case nib(UINib, UITableViewCell.Type)
/// A cell using a custom class. The associated value is the custom cell class.
case `class`(UITableViewCell.Type)
/// A String that uniquely identifies the cell type
public var reusableIdentifier: String {
switch self {
case .class(let cellClass):
return NSStringFromClass(cellClass)
case .nib(_, let cellClass):
return NSStringFromClass(cellClass)
}
}
/// The class of the custom cell
public var cellClass: UITableViewCell.Type {
switch self {
case .class(let cellClass):
return cellClass
case .nib(_, let cellClass):
return cellClass
}
}
}
// MARK: -
/// ImmuTableViewHandler is a helper to facilitate integration of ImmuTable in your
/// table view controllers.
///
/// It acts as the table view data source and delegate, and signals the table view to
/// reload its data when the underlying model changes.
///
/// - Note: As it keeps a weak reference to its target, you should keep a strong
/// reference to the handler from your view controller.
///
open class ImmuTableViewHandler: NSObject, UITableViewDataSource, UITableViewDelegate {
unowned let target: UITableViewController
/// Initializes the handler with a target table view controller.
/// - postcondition: After initialization, it becomse the data source and
/// delegate for the the target's table view.
public init(takeOver target: UITableViewController) {
self.target = target
super.init()
self.target.tableView.dataSource = self
self.target.tableView.delegate = self
}
/// An ImmuTable object representing the table structure.
open var viewModel = ImmuTable.Empty {
didSet {
if target.isViewLoaded {
target.tableView.reloadData()
}
}
}
// MARK: Table View Data Source
open func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.sections.count
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.sections[section].rows.count
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = viewModel.rowAtIndexPath(indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: row.reusableIdentifier, for: indexPath)
row.configureCell(cell)
return cell
}
open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return viewModel.sections[section].headerText
}
open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return viewModel.sections[section].footerText
}
// MARK: Table View Delegate
open func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if target.responds(to: #selector(UITableViewDelegate.tableView(_:willSelectRowAt:))) {
return target.tableView(tableView, willSelectRowAt: indexPath)
} else {
return indexPath
}
}
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if target.responds(to: #selector(UITableViewDelegate.tableView(_:didSelectRowAt:))) {
target.tableView(tableView, didSelectRowAt: indexPath)
} else {
let row = viewModel.rowAtIndexPath(indexPath)
row.action?(row)
}
}
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let row = viewModel.rowAtIndexPath(indexPath)
if let customHeight = type(of: row).customHeight {
return CGFloat(customHeight)
}
return tableView.rowHeight
}
open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if target.responds(to: #selector(UITableViewDelegate.tableView(_:heightForFooterInSection:))) {
return target.tableView(tableView, heightForFooterInSection: section)
}
return UITableViewAutomaticDimension
}
open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if target.responds(to: #selector(UITableViewDelegate.tableView(_:viewForFooterInSection:))) {
return target.tableView(tableView, viewForFooterInSection: section)
}
return nil
}
}
// MARK: - Type aliases
public typealias ImmuTableAction = (ImmuTableRow) -> Void
// MARK: - Internal testing helpers
protocol CellRegistrator {
func register(_ cell: ImmuTableCell, cellReuseIdentifier: String)
}
extension UITableView: CellRegistrator {
public func register(_ cell: ImmuTableCell, cellReuseIdentifier: String) {
switch cell {
case .nib(let nib, _):
self.register(nib, forCellReuseIdentifier: cell.reusableIdentifier)
case .class(let cellClass):
self.register(cellClass, forCellReuseIdentifier: cell.reusableIdentifier)
}
}
}
| gpl-2.0 | 0b22ed9d5071543a64787e1d84f40f9d | 32.894587 | 105 | 0.672691 | 5.103818 | false | false | false | false |
Dormmate/DORMLibrary | DORM/Classes/DeviceResize.swift | 1 | 2376 | //
// BaseView.swift
// DORM
//
// Created by Dormmate on 2017. 5. 4..
// Copyright © 2017 Dormmate. All rights reserved.
//
import UIKit
/*
아이폰의 화면 비율에 맞게 위치와 높이, 너비를 조정해주는 클래스이다.
It is a class that adjusts the position, height and width according to the aspect ratio of the iPhone.
*/
struct ScreenSize
{
static let SCREEN_WIDTH = UIScreen.main.bounds.size.width
static let SCREEN_HEIGHT = UIScreen.main.bounds.size.height
}
struct DeviceType
{
static let IPHONE_4 = (width:Float(320.0), height:Float(480.0))
static let IPHONE_5 = (width:Float(320.0), height:Float(568.0))
static let IPHONE_SE = (width:Float(320.0), height:Float(568.0))
static let IPHONE_6 = (width: Float(375.0), height:Float(667.0))
static let IPHONE_6_P = (width: Float(414.0), height:Float(736.0))
static let IPHONE_7 = (width: Float(375.0), height:Float(667.0))
static let IPHONE_7_P = (width: Float(414.0), height:Float(736.0))
}
class DeviceResize {
var testDevice : (width: Float, height: Float) = (width: 0,height: 0)
var userDevice : (width: Float, height: Float) = (width: 0,height: 0)
init(testDeviceModel: (width: Float, height: Float),userDeviceModel: (width: Float, height: Float)){
testDevice = modelName(model :testDeviceModel)!
userDevice = modelName(model :userDeviceModel)!
}
func modelName(model :(width: Float,height:Float)) -> (width: Float, height: Float)?{
let modelNameList : [(width: Float, height: Float)] = [
DeviceType.IPHONE_4,
DeviceType.IPHONE_5,
DeviceType.IPHONE_SE,
DeviceType.IPHONE_6,
DeviceType.IPHONE_6_P,
DeviceType.IPHONE_7,
DeviceType.IPHONE_7_P,
]
for modelName in modelNameList {
if modelName.height == model.height{
return modelName
}
}
return nil
}
func userDeviceHeight() -> CGFloat{
let heightRatio = CGFloat(self.userDevice.height / self.testDevice.height)
return heightRatio
}
func userDeviceWidth() -> CGFloat{
let widthRatio = CGFloat(self.userDevice.width / self.testDevice.width)
return widthRatio
}
}
| mit | be59d0942b6f4d5ee443366ff644ab3e | 26.583333 | 104 | 0.611135 | 3.592248 | false | true | false | false |
Athlee/ATHKit | Source/ATHImagePickerTabBarController.swift | 2 | 5594 | //
// ATHImagePickerTabBarController.swift
// ATHImagePickerController
//
// Created by mac on 01/01/2017.
// Copyright © 2017 Athlee LLC. All rights reserved.
//
import UIKit
import Material
extension PageTabBarController {
open var isTracking: Bool {
return scrollView?.contentOffset.x != scrollView?.frame.width
}
}
open class ATHImagePickerTabBarController: PageTabBarController, StatusBarUpdatable {
typealias Config = ATHImagePickerStatusBarConfig
// MARK: - Properties
open override var prefersStatusBarHidden: Bool {
return isStatusBarHidden
}
open override var preferredStatusBarUpdateAnimation: UIStatusBarAnimation {
return statusBarAnimation
}
internal weak var commiterDelegate: ATHImagePickerCommiterDelegate? {
didSet {
setupConfig()
}
}
fileprivate let handler = ATHNavigationBarHandler()
fileprivate var config: ATHImagePickerPageConfig! {
didSet {
title = config.title
handler.setupItem(navigationItem, config: config, ignoreRight: false, leftHandler: { [weak self] in
self?.commiterDelegate?.commit(item: ATHImagePickerItem(image: nil))
}) { [weak self] in
guard let image = self?.viewControllers.filter({ $0 is SelectionController}).map({ $0 as! SelectionController }).first?.floatingView.snapshot() else {
return
}
self?.commiterDelegate?.commit(item: ATHImagePickerItem(image: image))
}
}
}
fileprivate var isStatusBarHidden: Bool = false {
didSet {
updateStatusBar(with: config.statusBarConfig)
}
}
fileprivate var statusBarAnimation: UIStatusBarAnimation = .none {
didSet {
updateStatusBar(with: config.statusBarConfig)
}
}
fileprivate var changed = false
fileprivate var oldIndex: Int = 0
fileprivate var currentIndex: Int = 0 {
didSet {
oldIndex = oldValue
}
}
fileprivate var countOfPages: Int {
return viewControllers.count
}
// MARK: - Life cycle
override open func viewDidLoad() {
super.viewDidLoad()
}
override open func prepare() {
super.prepare()
delegate = self
preparePageTabBar()
}
open override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
// MARK: - Setup utils
fileprivate func setupConfig(for sourceType: ATHImagePickerSourceType = []) {
guard let config = commiterDelegate?.commit(configFor: sourceType) else {
return
}
self.config = config
title = config.title
pageTabBarItem.title = config.title
pageTabBarItem.titleColor = config.titleColor
pageTabBarItem.titleLabel?.font = UIFont.systemFont(ofSize: 17, weight: UIFontWeightMedium)
isStatusBarHidden = config.statusBarConfig.isStatusBarHidden
statusBarAnimation = config.statusBarConfig.statusBarAnimation
}
}
// MARK: - UIPageViewController management
extension ATHImagePickerTabBarController {
public func presentationIndex(for pageViewController: UIPageViewController) -> Int {
return currentIndex
}
}
// MARK: - UIScrollViewDelegate
extension ATHImagePickerTabBarController {
open override func scrollViewDidScroll(_ scrollView: UIScrollView) {
super.scrollViewDidScroll(scrollView)
var pageValue = Int((scrollView.contentOffset.x - scrollView.bounds.width) / scrollView.bounds.width)
if pageValue != 0 {
changed = true
if pageValue == -1 {
pageValue = 0
}
}
if changed {
currentIndex = pageValue
changed = false
}
keepInBounds(scrollView: scrollView)
}
public func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
keepInBounds(scrollView: scrollView)
updateCurrentViewController()
}
public func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
keepInBounds(scrollView: scrollView)
}
}
// MAKR: - Utils
extension ATHImagePickerTabBarController {
fileprivate func preparePageTabBar() {
pageTabBar.lineColor = .clear
}
fileprivate func keepInBounds(scrollView: UIScrollView) {
let minOffset = scrollView.bounds.width - CGFloat(currentIndex) * scrollView.bounds.width
let maxOffset = CGFloat(countOfPages - currentIndex) * scrollView.bounds.width
let bounds = scrollView.bounds
if scrollView.contentOffset.x <= minOffset {
scrollView.contentOffset.x = minOffset
} else if scrollView.contentOffset.x >= maxOffset {
scrollView.contentOffset.x = maxOffset
}
scrollView.bounds = bounds
changed = false
}
fileprivate func updateCurrentViewController() {
let direction: UIPageViewControllerNavigationDirection = oldIndex > currentIndex ? .reverse : .forward
pageViewController?.setViewControllers([viewControllers[currentIndex]], direction: direction, animated: false, completion: nil)
}
}
// MARK: - PageTabBarControllerDelegate
extension ATHImagePickerTabBarController: PageTabBarControllerDelegate {
public func pageTabBarController(pageTabBarController: PageTabBarController, didTransitionTo viewController: UIViewController) {
switch viewController {
case is ATHImagePickerSelectionViewController:
setupConfig(for: .library)
navigationItem.rightBarButtonItem?.isEnabled = true
case is ATHImagePickerCaptureViewController:
setupConfig(for: .camera)
navigationItem.rightBarButtonItem?.isEnabled = false
default:
()
}
}
}
| mit | 21315adb207fbc9a50c125f687866c67 | 26.825871 | 158 | 0.713928 | 5.075318 | false | true | false | false |
jkolb/Asheron | Sources/Asheron/Palette.swift | 1 | 1925 | /*
The MIT License (MIT)
Copyright (c) 2020 Justin Kolb
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
public final class Palette : Identifiable {
/*
list[1] = LF_MEMBER, protected, type = T_ULONG(0022), offset = 56 member name = 'num_colors'
list[2] = LF_MEMBER, protected, type = T_REAL32(0040), offset = 60 member name = 'min_lighting'
list[3] = LF_MEMBER, protected, type = T_32PULONG(0422), offset = 64 member name = 'ARGB'
*/
public var id: Identifier
public var argb: [ARGB8888]
public subscript (index: Int) -> ARGB8888 {
return argb[index]
}
public init(from dataStream: DataStream, id: Identifier) {
let diskId = Identifier(from: dataStream)
precondition(diskId == id)
self.id = id
self.argb = [ARGB8888](from: dataStream)
}
@inlinable public func encode(to dataStream: DataStream) {
fatalError("Not implemented")
}
}
| mit | 1067e9ecf4be3b2cfe0b693f693def80 | 39.104167 | 100 | 0.720519 | 4.230769 | false | false | false | false |
cottonBuddha/Qsic | Qsic/QSNaviTitleWidget.swift | 1 | 1358 | //
// QSNaviTitleWidget.swift
// Qsic
//
// Created by 江齐松 on 2017/7/21.
// Copyright © 2017年 cottonBuddha. All rights reserved.
//
import Foundation
class QSNaviTitleWidget: QSWidget {
var titleStack: [String] = []
var currentSong: String?
override init(startX: Int, startY: Int, width: Int, height: Int) {
super.init(startX: startX, startY: startY, width: width, height: 2)
}
public func push(title:String) {
self.titleStack.append(title)
self.refreshNaviTitle()
}
public func pop() {
self.titleStack.removeLast()
self.refreshNaviTitle()
}
public func refreshNaviTitle() {
drawWidget()
}
override func drawWidget() {
super.drawWidget()
var naviStr : String = ""
self.titleStack.forEach {
if $0.lengthInCurses() > 20 {
naviStr.append("↴" + "\n" + " " + $0)
} else {
naviStr.append("-" + $0)
}
}
if self.titleStack.count < 1 {
return
}
var subStr = naviStr.removeFirstCharacter()
if currentSong != nil {
subStr = subStr + "[\(currentSong!)]"
}
self.eraseSelf()
mvwaddstr(self.window, 0, 0, subStr)
wrefresh(self.window)
}
}
| mit | f68789aca5e7ed946fe13d273e90291e | 23.490909 | 75 | 0.536006 | 3.826705 | false | false | false | false |
ucotta/BrilliantTemplate | Sources/BrilliantTemplate/processors/TagProcessor.swift | 1 | 4635 | //
// Created by Ubaldo Cotta on 4/1/17.
//
import Foundation
import BrilliantHTML5Parser
extension BrilliantTemplate {
func processTids(doc: ParserHTML5, data: [String: Any?]) {
while let node: HTMLNode = doc.root.getNextTid() {
processTids(node: node, data: data)
node["tid"] = nil
}
}
func processTids(node: HTMLNode, data: [String: Any?] ) {
if let tid = node["tid"] {
if (tid.isEmpty) {
node.addNode(node: TextHTML(text: "/* Empty tid cannot be used */"))
} else {
let escaped = tid.replacingOccurrences(of: "\\:", with: "$DDOTESC$")
var parts = escaped.components(separatedBy: ":")
if var variable = untieVar(name: parts[0], data: data) {
variable = toInteger(value: variable)
switch variable {
case let v as String:
let r = filterString(value: v, filters: parts)
switch r.result {
case .replace:
node.removeNodes()
node.addNode(node: TextHTML(text: r.value))
case .removeNode:
node.removeNodes()
node.parentNode = nil
default: break
}
case let v as Date:
let r = filterDate(value: v, filters: parts)
switch r.result {
case .replace:
node.removeNodes()
node.addNode(node: TextHTML(text: r.value))
case .removeNode:
node.removeNodes()
node.parentNode = nil
default: break
}
case let v as Bool:
if filterBoolTID(value: v, filters: parts).result == .removeNode {
node.removeNodes()
node.parentNode = nil
}
case let v as [[String: Any?]]:
// Array of dictionaries
// Bool dont populate arrays, just show or remove a tag.
if parts.contains("empty") {
if v.count > 0 {
node.removeNodes()
node.parentNode = nil
}
} else if parts.contains("noempty") {
if v.count == 0 {
node.removeNodes()
node.parentNode = nil
}
} else {
processArray(node: node, values: v)
}
node["tid"] = nil
case let v as [HTMLNode]:
node.removeNodes()
node.content = v
default:
if variable is UInt {
variable = NSNumber(value: variable as! UInt)
} else if variable is Int {
variable = NSNumber(value: variable as! Int)
}
if let v = variable as? NSNumber {
let r = filterNumber(value: v, filters: parts)
switch r.result {
case .replace:
node.removeNodes()
node.addNode(node: TextHTML(text: r.value))
case .removeNode:
node.removeNodes()
node.parentNode = nil
default: break
}
} else if String(describing: variable) == "nil" {
// Strings with "nil" text value was procesed in case let v as String. This is a real nil value...
if parts.contains("notnil") {
node.removeNodes()
node.parentNode = nil
}
} else {
print("\(parts[0]) not supported")
}
}
} else {
node.removeNodes()
node.addNode(node: TextHTML(text: "/* \"\(tid)\" not found! */"))
}
}
}
node["tid"] = nil
}
}
| apache-2.0 | ff989d5c78b3bedce3e2df25fb65fdec | 36.991803 | 105 | 0.385761 | 5.631835 | false | false | false | false |
legendecas/Rocket.Chat.iOS | Rocket.Chat.SDK/Controllers/SupportDepartmentViewController.swift | 1 | 2286 | //
// SupportDepartmentViewController.swift
// Rocket.Chat
//
// Created by Lucas Woo on 7/17/17.
// Copyright © 2017 Rocket.Chat. All rights reserved.
//
import UIKit
public protocol SupportDepartmentViewControllerDelegate: class {
func didSelect(department: Department)
}
class SupportDepartmentViewController: UITableViewController, LivechatManagerInjected {
weak var delegate: SupportDepartmentViewControllerDelegate?
var selectedIndexPath = IndexPath(row: 0, section: 0)
override func viewDidLoad() {
super.viewDidLoad()
tableView.selectRow(at: selectedIndexPath, animated: false, scrollPosition: .middle)
tableView.cellForRow(at: selectedIndexPath)?.accessoryType = .checkmark
}
func dismissSelf() {
if let navigationController = navigationController {
navigationController.popViewController(animated: true)
} else {
dismiss(animated: true, completion: nil)
}
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return livechatManager.departments.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "DepartmentCell", for: indexPath)
cell.accessoryType = .none
if let label = cell.contentView.viewWithTag(1) as? UILabel {
label.text = livechatManager.departments[indexPath.row].name
}
if let label = cell.contentView.viewWithTag(2) as? UILabel {
label.text = livechatManager.departments[indexPath.row].description
}
return cell
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
tableView.cellForRow(at: selectedIndexPath)?.accessoryType = .none
selectedIndexPath = indexPath
tableView.cellForRow(at: indexPath)?.accessoryType = .checkmark
delegate?.didSelect(department: livechatManager.departments[indexPath.row])
}
}
| mit | 4fe9731f07f3de9f6c0c0aef164602f9 | 33.104478 | 109 | 0.701532 | 5.123318 | false | false | false | false |
cherrythia/FYP | FYP Table/SpringViewController_Table.swift | 1 | 8337 | //
// ViewController.swift
// FYP Table
//
// Created by Chia Wei Zheng Terry on 18/1/15.
// Copyright (c) 2015 Chia Wei Zheng Terry. All rights reserved.
import UIKit
import CoreData
class SpringViewController_Table : UITableViewController {
@IBOutlet weak var addButton: UIBarButtonItem!
var springVar : Array <AnyObject> = []
var forceArray : [Float] = []
var stiffness : [Float] = []
// MARK: UITableViewDataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override var canBecomeFirstResponder : Bool {
return true
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return springVar.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cellIdentifier = "Cell"
var cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier)
cell = UITableViewCell(style: UITableViewCellStyle.subtitle, reuseIdentifier: "cell")
var data : NSManagedObject = springVar[indexPath.row] as! NSManagedObject
cell!.textLabel!.text = "Spring \(indexPath.row + 1)"
cell!.textLabel!.font = UIFont.boldSystemFont(ofSize: 17)
var force : Float = data.value(forKey: "force") as! Float
var stiffness : Float = data.value(forKey: "stiffness") as! Float
cell!.detailTextLabel!.text = "Force = \(force)N \t\t Stiffness = \(stiffness)N/m"
cell!.detailTextLabel!.textColor = UIColor .darkGray
cell!.accessoryType = UITableViewCellAccessoryType.disclosureIndicator
return cell!
}
// Negative of [Summation of forces] for calculation later
func forceAtWall() {
forceArray.append(0)
//arrange force to array
for index in 0..<springVar.count {
let selectedItem : NSManagedObject = springVar[index] as! NSManagedObject //first index is 1 not zero
let tempForce : Float = selectedItem.value(forKey: "force") as! Float
forceArray.append(tempForce)
}
for index in 0...(springVar.count){
forceArray[0] += forceArray[index]
}
forceArray[0] = -(forceArray[0])
}
func arrayOfStiff() {
for index in 0..<springVar.count
{
let selectedItem : NSManagedObject = springVar[index] as! NSManagedObject
let tempStiffness : Float = selectedItem.value(forKey: "stiffness") as! Float
stiffness.append(tempStiffness)
}
}
override func viewDidLoad() {
super.viewDidLoad()
title = "Springs' Variables "
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
}
override func viewDidAppear(_ animated: Bool) {
let appDel : AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context : NSManagedObjectContext = appDel.managedObjectContext!
let freq = NSFetchRequest<NSFetchRequestResult>(entityName: "SpringVariables")
do {
try springVar = context.fetch(freq)
} catch {
}
//springVar = context.executeFetchRequest(freq)!
if(isCheckedGlobal == true){
addButton.isEnabled = false
}
tableView.reloadData()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func Add(_ sender: AnyObject) {
self.performSegue(withIdentifier: "addSpring", sender: sender)
}
@IBAction func solve_Pressed(_ sender: AnyObject) {
self.forceAtWall()
self.arrayOfStiff()
self.performSegue(withIdentifier: "Solve", sender: sender)
}
//Shake to reset
override func motionEnded(_ motion: UIEventSubtype, with event: UIEvent?) {
if(event?.subtype == UIEventSubtype.motionShake){
let appDel : AppDelegate = UIApplication.shared.delegate as! AppDelegate
let context : NSManagedObjectContext = appDel.managedObjectContext!
var error : NSError?
for object in springVar as! [NSManagedObject] {
context.delete(object)
}
do {
try context.save()
} catch {
print("save failed : \(error)")
}
springVar.removeAll(keepingCapacity: true)
isCheckedGlobal = false
addButton.isEnabled = true
self.tableView.reloadData()
self.viewDidLoad()
}
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
return true
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let footerHeight : CGFloat = (tableView.frame.size.height - (CGFloat(springVar.count) * 45.0) - 45.0 - 64.0)
let oneCell = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.size.width, height: footerHeight))
/************************************** View of UIView ************************************************/
return oneCell
}
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let footerHeight : CGFloat = (tableView.frame.size.height - (CGFloat(springVar.count) * 45.0) - 45.0 - 64.0)
return footerHeight
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
self.performSegue(withIdentifier: "detail", sender:self)
}
override func prepare ( for segue: UIStoryboardSegue, sender: Any!) {
//solve button
if (segue.identifier == "Solve") {
let svcViewController_Results = segue.destination as! SpringViewController_Results
svcViewController_Results.forceView2 = self.forceArray
svcViewController_Results.stiffView2 = self.stiffness
svcViewController_Results.springCount = springVar.count
}
//detail display onto next view
if (segue.identifier == "detail") {
let selectedItem : NSManagedObject = springVar[self.tableView.indexPathForSelectedRow!.row] as! NSManagedObject
let insertSpringVar : SpringInsertVariables = segue.destination as! SpringInsertVariables
let tempForce : Float = selectedItem.value(forKey: "force") as! Float
let tempStiff : Float = selectedItem.value(forKey: "stiffness") as! Float
let globalChecked : Bool = selectedItem.value(forKey: "globalChecked") as! Bool
let arrowChecked : Bool = selectedItem.value(forKey: "arrowChecked") as! Bool
insertSpringVar.tempForce = tempForce
insertSpringVar.tempStiffness = tempStiff
insertSpringVar.tempMangObj = selectedItem
insertSpringVar.tempChcekedGlobal = globalChecked
insertSpringVar.tempCount = self.tableView.indexPathForSelectedRow!.row
insertSpringVar.tempArrow = arrowChecked
if(self.tableView.indexPathForSelectedRow!.row != (springVar.count-1)){
let tempCanCheckCheckedBox : Bool = false
insertSpringVar.tempCanCheckCheckedBox = tempCanCheckCheckedBox
}
else{
let tempCanCheckCheckedBox : Bool = true
insertSpringVar.tempCanCheckCheckedBox = tempCanCheckCheckedBox
}
}
//add button
if(segue.identifier == "addSpring"){
let insertSpringVar : SpringInsertVariables = segue.destination as! SpringInsertVariables
insertSpringVar.tempCount = springVar.count
}
}
}
| mit | 4f4ddf3f4328986967117077408a284d | 34.326271 | 123 | 0.596498 | 5.406615 | false | false | false | false |
keyeMyria/DeckRocket | Source/iOS/ViewController.swift | 1 | 5908 | //
// ViewController.swift
// DeckRocket
//
// Created by JP Simard on 6/13/14.
// Copyright (c) 2014 JP Simard. All rights reserved.
//
import UIKit
import MultipeerConnectivity
import Cartography
final class ViewController: UICollectionViewController, UIScrollViewDelegate {
// MARK: Properties
var slides: [Slide]? {
didSet {
dispatch_async(dispatch_get_main_queue()) {
self.infoLabel.hidden = self.slides != nil
self.collectionView?.contentOffset.x = 0
self.collectionView?.reloadData()
// Trigger state change block
self.multipeerClient.onStateChange??(state: self.multipeerClient.state, peerID: MCPeerID())
}
}
}
private let multipeerClient = MultipeerClient()
private let infoLabel = UILabel()
// MARK: View Lifecycle
init() {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .Horizontal
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
super.init(collectionViewLayout: layout)
}
convenience required init(coder aDecoder: NSCoder) {
self.init()
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
setupConnectivityObserver()
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString
if let slidesData = NSData(contentsOfFile: documentsPath.stringByAppendingPathComponent("slides")) {
slides = flatMap(Slide.slidesfromData(slidesData)) { compact($0) }
}
}
// MARK: Connectivity Updates
private func setupConnectivityObserver() {
multipeerClient.onStateChange = { state, peerID in
let client = self.multipeerClient
let borderColor: CGColorRef
switch state {
case .NotConnected:
borderColor = UIColor.redColor().CGColor
if client.session?.connectedPeers.count == 0 {
client.browser?.invitePeer(peerID, toSession: client.session, withContext: nil, timeout: 30)
}
case .Connecting:
borderColor = UIColor.orangeColor().CGColor
case .Connected:
borderColor = UIColor.greenColor().CGColor
}
dispatch_async(dispatch_get_main_queue()) {
collectionView?.layer.borderColor = borderColor
}
}
}
// MARK: UI
private func setupUI() {
setupCollectionView()
setupInfoLabel()
}
private func setupCollectionView() {
collectionView?.registerClass(Cell.self, forCellWithReuseIdentifier: "cell")
collectionView?.pagingEnabled = true
collectionView?.showsHorizontalScrollIndicator = false
collectionView?.layer.borderColor = UIColor.redColor().CGColor
collectionView?.layer.borderWidth = 2
setCollectionViewItemSize(view.bounds.size)
}
private func setupInfoLabel() {
infoLabel.userInteractionEnabled = false
infoLabel.numberOfLines = 0
infoLabel.text = "Thanks for installing DeckRocket!\n\n" +
"To get started, follow these simple steps:\n\n" +
"1. Open a presentation in Deckset on your Mac.\n" +
"2. Launch DeckRocket on your Mac.\n" +
"3. Click the DeckRocket menu bar icon and select \"Send Slides\".\n\n" +
"From there, swipe on your phone to control your Deckset slides, " +
"tap the screen to toggle between current slide and notes view, and finally: " +
"keep an eye on the color of the border! Red means the connection was lost. Green means everything should work!"
infoLabel.textColor = UIColor.whiteColor()
view.addSubview(infoLabel)
layout(infoLabel, view) {
$0.left == $1.left + 20
$0.right == $1.right - 20
$0.top == $1.top
$0.bottom == $1.bottom
}
}
// MARK: Collection View
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return slides?.count ?? 0
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! Cell
cell.imageView.image = slides?[indexPath.item].image
cell.notesView.text = slides?[indexPath.item].notes
cell.nextSlideView.image = indexPath.item + 1 < slides?.count ? slides?[indexPath.item + 1].image : nil
return cell
}
// MARK: UIScrollViewDelegate
private func currentSlide() -> UInt {
return map(collectionView) { cv in
let cvLayout = cv.collectionViewLayout as! UICollectionViewFlowLayout
return UInt(round(cv.contentOffset.x / cvLayout.itemSize.width))
} ?? 0
}
override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
multipeerClient.sendString("\(currentSlide())")
}
// MARK: Rotation
private func setCollectionViewItemSize(size: CGSize) {
let cvLayout = collectionView?.collectionViewLayout as? UICollectionViewFlowLayout
cvLayout?.itemSize = size
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
let current = currentSlide()
UIView.animateWithDuration(coordinator.transitionDuration()) {
self.collectionView?.contentOffset.x = CGFloat(current) * size.width
}
setCollectionViewItemSize(size)
}
}
| mit | 475da2a14408a18ca638b6ad4766be63 | 36.157233 | 139 | 0.645735 | 5.284436 | false | false | false | false |
tensorflow/examples | lite/examples/bert_qa/ios/ViewInUIKit/Controllers/OptionTableViewController.swift | 1 | 1727 | // Copyright 2020 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import UIKit
class OptionTableViewController: UITableViewController {
// MARK: Storyboard Connections
@IBOutlet weak var threadCountLabel: UILabel!
@IBOutlet weak var threadCountStepper: UIStepper!
// MARK: - View handling methods
override func viewDidLoad() {
// Initialize UI properties with user default value.
let threadCount = UserDefaults.standard.integer(forKey: InterpreterOptions.threadCount.id)
threadCountLabel.text = threadCount.description
threadCountStepper.value = Double(threadCount)
// Set thread count limits.
threadCountStepper.maximumValue = Double(InterpreterOptions.threadCount.maximumValue)
threadCountStepper.minimumValue = Double(InterpreterOptions.threadCount.minimumValue)
}
// MARK: Button Actions
@IBAction func didChangeThreadCount(_ sender: UIStepper) {
threadCountLabel.text = Int(sender.value).description
}
@IBAction func didResetOptions() {
threadCountLabel.text = InterpreterOptions.threadCount.defaultValue.description
threadCountStepper.value = Double(InterpreterOptions.threadCount.defaultValue)
}
}
| apache-2.0 | 340ab2a0b8840feb543fdcb8c2286988 | 39.162791 | 94 | 0.771859 | 4.824022 | false | false | false | false |
Antondomashnev/Sourcery | SourceryTests/Stub/Performance-Code/Kiosk/Sale Artwork Details/SaleArtworkDetailsViewController.swift | 2 | 19019 | import UIKit
import ORStackView
import Artsy_UILabels
import Artsy_UIFonts
import RxSwift
import Artsy_UIButtons
import SDWebImage
import Action
class SaleArtworkDetailsViewController: UIViewController {
var allowAnimations = true
var auctionID = AppSetup.sharedState.auctionID
var saleArtwork: SaleArtwork!
var provider: Networking!
var showBuyersPremiumCommand = { () -> CocoaAction in
appDelegate().showBuyersPremiumCommand()
}
class func instantiateFromStoryboard(_ storyboard: UIStoryboard) -> SaleArtworkDetailsViewController {
return storyboard.viewController(withID: .SaleArtworkDetail) as! SaleArtworkDetailsViewController
}
lazy var artistInfo: Observable<Any> = {
let artistInfo = self.provider.request(.artwork(id: self.saleArtwork.artwork.id)).filterSuccessfulStatusCodes().mapJSON()
return artistInfo.shareReplay(1)
}()
@IBOutlet weak var metadataStackView: ORTagBasedAutoStackView!
@IBOutlet weak var additionalDetailScrollView: ORStackScrollView!
var buyersPremium: () -> (BuyersPremium?) = { appDelegate().sale.buyersPremium }
let layoutSubviews = PublishSubject<Void>()
let viewWillAppear = PublishSubject<Void>()
override func viewDidLoad() {
super.viewDidLoad()
setupMetadataView()
setupAdditionalDetailStackView()
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// OK, so this is pretty weird, eh? So basically we need to be notified of layout changes _just after_ the layout
// is actually done. For whatever reason, the UIKit hack to get the labels to adhere to their proper width only
// works if we defer recalculating their geometry to the next runloop.
// This wasn't an issue with RAC's rac_signalForSelector because that invoked the signal _after_ this method completed.
// So that's what I've done here.
DispatchQueue.main.async {
self.layoutSubviews.onNext()
}
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
viewWillAppear.onCompleted()
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue == .ZoomIntoArtwork {
let nextViewController = segue.destination as! SaleArtworkZoomViewController
nextViewController.saleArtwork = saleArtwork
}
}
enum MetadataStackViewTag: Int {
case lotNumberLabel = 1
case artistNameLabel
case artworkNameLabel
case artworkMediumLabel
case artworkDimensionsLabel
case imageRightsLabel
case estimateTopBorder
case estimateLabel
case estimateBottomBorder
case currentBidLabel
case currentBidValueLabel
case numberOfBidsPlacedLabel
case bidButton
case buyersPremium
}
@IBAction func backWasPressed(_ sender: AnyObject) {
_ = navigationController?.popViewController(animated: true)
}
fileprivate func setupMetadataView() {
enum LabelType {
case serif
case sansSerif
case italicsSerif
case bold
}
func label(_ type: LabelType, tag: MetadataStackViewTag, fontSize: CGFloat = 16.0) -> UILabel {
let label: UILabel = { () -> UILabel in
switch type {
case .serif:
return ARSerifLabel()
case .sansSerif:
return ARSansSerifLabel()
case .italicsSerif:
return ARItalicsSerifLabel()
case .bold:
let label = ARSerifLabel()
label.font = UIFont.sansSerifFont(withSize: label.font.pointSize)
return label
}
}()
label.lineBreakMode = .byWordWrapping
label.font = label.font.withSize(fontSize)
label.tag = tag.rawValue
label.preferredMaxLayoutWidth = 276
return label
}
let hasLotNumber = (saleArtwork.lotNumber != nil)
if let _ = saleArtwork.lotNumber {
let lotNumberLabel = label(.sansSerif, tag: .lotNumberLabel)
lotNumberLabel.font = lotNumberLabel.font.withSize(12)
metadataStackView.addSubview(lotNumberLabel, withTopMargin: "0", sideMargin: "0")
saleArtwork
.viewModel
.lotNumber()
.filterNil()
.mapToOptional()
.bindTo(lotNumberLabel.rx.text)
.addDisposableTo(rx_disposeBag)
}
if let artist = artist() {
let artistNameLabel = label(.sansSerif, tag: .artistNameLabel)
artistNameLabel.text = artist.name
metadataStackView.addSubview(artistNameLabel, withTopMargin: hasLotNumber ? "10" : "0", sideMargin: "0")
}
let artworkNameLabel = label(.italicsSerif, tag: .artworkNameLabel)
artworkNameLabel.text = "\(saleArtwork.artwork.title), \(saleArtwork.artwork.date)"
metadataStackView.addSubview(artworkNameLabel, withTopMargin: "10", sideMargin: "0")
if let medium = saleArtwork.artwork.medium {
if medium.isNotEmpty {
let mediumLabel = label(.serif, tag: .artworkMediumLabel)
mediumLabel.text = medium
metadataStackView.addSubview(mediumLabel, withTopMargin: "22", sideMargin: "0")
}
}
if saleArtwork.artwork.dimensions.count > 0 {
let dimensionsLabel = label(.serif, tag: .artworkDimensionsLabel)
dimensionsLabel.text = (saleArtwork.artwork.dimensions as NSArray).componentsJoined(by: "\n")
metadataStackView.addSubview(dimensionsLabel, withTopMargin: "5", sideMargin: "0")
}
retrieveImageRights()
.filter { imageRights -> Bool in
return imageRights.isNotEmpty
}.subscribe(onNext: { [weak self] imageRights in
let rightsLabel = label(.serif, tag: .imageRightsLabel)
rightsLabel.text = imageRights
self?.metadataStackView.addSubview(rightsLabel, withTopMargin: "22", sideMargin: "0")
})
.addDisposableTo(rx_disposeBag)
let estimateTopBorder = UIView()
estimateTopBorder.constrainHeight("1")
estimateTopBorder.tag = MetadataStackViewTag.estimateTopBorder.rawValue
metadataStackView.addSubview(estimateTopBorder, withTopMargin: "22", sideMargin: "0")
var estimateBottomBorder: UIView?
let estimateString = saleArtwork.viewModel.estimateString
if estimateString.isNotEmpty {
let estimateLabel = label(.serif, tag: .estimateLabel)
estimateLabel.text = estimateString
metadataStackView.addSubview(estimateLabel, withTopMargin: "15", sideMargin: "0")
estimateBottomBorder = UIView()
_ = estimateBottomBorder?.constrainHeight("1")
estimateBottomBorder?.tag = MetadataStackViewTag.estimateBottomBorder.rawValue
metadataStackView.addSubview(estimateBottomBorder, withTopMargin: "10", sideMargin: "0")
}
viewWillAppear
.subscribe(onCompleted: { [weak estimateTopBorder, weak estimateBottomBorder] in
estimateTopBorder?.drawDottedBorders()
estimateBottomBorder?.drawDottedBorders()
})
.addDisposableTo(rx_disposeBag)
let hasBids = saleArtwork
.rx.observe(NSNumber.self, "highestBidCents")
.map { observeredCents -> Bool in
guard let cents = observeredCents else { return false }
return (cents as Int) > 0
}
let currentBidLabel = label(.serif, tag: .currentBidLabel)
hasBids
.flatMap { hasBids -> Observable<String> in
if hasBids {
return .just("Current Bid:")
} else {
return .just("Starting Bid:")
}
}
.mapToOptional()
.bindTo(currentBidLabel.rx.text)
.addDisposableTo(rx_disposeBag)
metadataStackView.addSubview(currentBidLabel, withTopMargin: "22", sideMargin: "0")
let currentBidValueLabel = label(.bold, tag: .currentBidValueLabel, fontSize: 27)
saleArtwork
.viewModel
.currentBid()
.mapToOptional()
.bindTo(currentBidValueLabel.rx.text)
.addDisposableTo(rx_disposeBag)
metadataStackView.addSubview(currentBidValueLabel, withTopMargin: "10", sideMargin: "0")
let numberOfBidsPlacedLabel = label(.serif, tag: .numberOfBidsPlacedLabel)
saleArtwork
.viewModel
.numberOfBidsWithReserve
.mapToOptional()
.bindTo(numberOfBidsPlacedLabel.rx.text)
.addDisposableTo(rx_disposeBag)
metadataStackView.addSubview(numberOfBidsPlacedLabel, withTopMargin: "10", sideMargin: "0")
let bidButton = ActionButton()
bidButton
.rx.tap
.asObservable()
.subscribe(onNext: { [weak self] _ in
guard let me = self else { return }
me.bid(auctionID: me.auctionID, saleArtwork: me.saleArtwork, allowAnimations: me.allowAnimations, provider: me.provider)
})
.addDisposableTo(rx_disposeBag)
saleArtwork
.viewModel
.forSale()
.subscribe(onNext: { [weak bidButton] forSale in
let forSale = forSale
let title = forSale ? "BID" : "SOLD"
bidButton?.setTitle(title, for: .normal)
})
.addDisposableTo(rx_disposeBag)
saleArtwork
.viewModel
.forSale()
.bindTo(bidButton.rx.isEnabled)
.addDisposableTo(rx_disposeBag)
bidButton.tag = MetadataStackViewTag.bidButton.rawValue
metadataStackView.addSubview(bidButton, withTopMargin: "40", sideMargin: "0")
if let _ = buyersPremium() {
let buyersPremiumView = UIView()
buyersPremiumView.tag = MetadataStackViewTag.buyersPremium.rawValue
let buyersPremiumLabel = ARSerifLabel()
buyersPremiumLabel.font = buyersPremiumLabel.font.withSize(16)
buyersPremiumLabel.text = "This work has a "
buyersPremiumLabel.textColor = .artsyGrayBold()
var buyersPremiumButton = ARButton()
let title = "buyers premium"
let attributes: [String: AnyObject] = [ NSUnderlineStyleAttributeName: NSUnderlineStyle.styleSingle.rawValue as AnyObject, NSFontAttributeName: buyersPremiumLabel.font ]
let attributedTitle = NSAttributedString(string: title, attributes: attributes)
buyersPremiumButton.setTitle(title, for: .normal)
buyersPremiumButton.titleLabel?.attributedText = attributedTitle
buyersPremiumButton.setTitleColor(.artsyGrayBold(), for: .normal)
buyersPremiumButton.rx.action = showBuyersPremiumCommand()
buyersPremiumView.addSubview(buyersPremiumLabel)
buyersPremiumView.addSubview(buyersPremiumButton)
buyersPremiumLabel.alignTop("0", leading: "0", bottom: "0", trailing: nil, to: buyersPremiumView)
buyersPremiumLabel.alignBaseline(with: buyersPremiumButton, predicate: nil)
buyersPremiumButton.alignAttribute(.left, to: .right, of: buyersPremiumLabel, predicate: "0")
metadataStackView.addSubview(buyersPremiumView, withTopMargin: "30", sideMargin: "0")
}
metadataStackView.bottomMarginHeight = CGFloat(NSNotFound)
}
fileprivate func setupImageView(_ imageView: UIImageView) {
if let image = saleArtwork.artwork.defaultImage {
// We'll try to retrieve the thumbnail image from the cache. If we don't have it, we'll set the background colour to grey to indicate that we're downloading it.
let key = SDWebImageManager.shared().cacheKey(for: image.thumbnailURL() as URL!)
let thumbnailImage = SDImageCache.shared().imageFromDiskCache(forKey: key)
if thumbnailImage == nil {
imageView.backgroundColor = .artsyGrayLight()
}
imageView.sd_setImage(with: image.fullsizeURL(), placeholderImage: thumbnailImage, options: [], completed: { (image, _, _, _) in
// If the image was successfully downloaded, make sure we aren't still displaying grey.
if image != nil {
imageView.backgroundColor = .clear
}
})
let heightConstraintNumber = { () -> CGFloat in
if let aspectRatio = image.aspectRatio {
if aspectRatio != 0 {
return min(400, CGFloat(538) / aspectRatio)
}
}
return 400
}()
imageView.constrainHeight( "\(heightConstraintNumber)" )
imageView.contentMode = .scaleAspectFit
imageView.isUserInteractionEnabled = true
let recognizer = UITapGestureRecognizer()
imageView.addGestureRecognizer(recognizer)
recognizer
.rx.event
.asObservable()
.subscribe(onNext: { [weak self] _ in
self?.performSegue(.ZoomIntoArtwork)
})
.addDisposableTo(rx_disposeBag)
}
}
fileprivate func setupAdditionalDetailStackView() {
enum LabelType {
case header
case body
}
func label(_ type: LabelType, layout: Observable<Void>? = nil) -> UILabel {
let (label, fontSize) = { () -> (UILabel, CGFloat) in
switch type {
case .header:
return (ARSansSerifLabel(), 14)
case .body:
return (ARSerifLabel(), 16)
}
}()
label.font = label.font.withSize(fontSize)
label.lineBreakMode = .byWordWrapping
layout?
.take(1)
.subscribe(onNext: { [weak label] (_) in
if let label = label {
label.preferredMaxLayoutWidth = label.frame.width
}
})
.addDisposableTo(rx_disposeBag)
return label
}
additionalDetailScrollView.stackView.bottomMarginHeight = 40
let imageView = UIImageView()
additionalDetailScrollView.stackView.addSubview(imageView, withTopMargin: "0", sideMargin: "40")
setupImageView(imageView)
let additionalInfoHeaderLabel = label(.header)
additionalInfoHeaderLabel.text = "Additional Information"
additionalDetailScrollView.stackView.addSubview(additionalInfoHeaderLabel, withTopMargin: "20", sideMargin: "40")
if let blurb = saleArtwork.artwork.blurb {
let blurbLabel = label(.body, layout: layoutSubviews)
blurbLabel.attributedText = MarkdownParser().attributedString( fromMarkdownString: blurb )
additionalDetailScrollView.stackView.addSubview(blurbLabel, withTopMargin: "22", sideMargin: "40")
}
let additionalInfoLabel = label(.body, layout: layoutSubviews)
additionalInfoLabel.attributedText = MarkdownParser().attributedString( fromMarkdownString: saleArtwork.artwork.additionalInfo )
additionalDetailScrollView.stackView.addSubview(additionalInfoLabel, withTopMargin: "22", sideMargin: "40")
retrieveAdditionalInfo()
.filter { info in
return info.isNotEmpty
}.subscribe(onNext: { [weak self] info in
additionalInfoLabel.attributedText = MarkdownParser().attributedString(fromMarkdownString: info)
self?.view.setNeedsLayout()
self?.view.layoutIfNeeded()
})
.addDisposableTo(rx_disposeBag)
if let artist = artist() {
retrieveArtistBlurb()
.filter { blurb in
return blurb.isNotEmpty
}
.subscribe(onNext: { [weak self] blurb in
guard let me = self else { return }
let aboutArtistHeaderLabel = label(.header)
aboutArtistHeaderLabel.text = "About \(artist.name)"
me.additionalDetailScrollView.stackView.addSubview(aboutArtistHeaderLabel, withTopMargin: "22", sideMargin: "40")
let aboutAristLabel = label(.body, layout: me.layoutSubviews)
aboutAristLabel.attributedText = MarkdownParser().attributedString(fromMarkdownString: blurb)
me.additionalDetailScrollView.stackView.addSubview(aboutAristLabel, withTopMargin: "22", sideMargin: "40")
})
.addDisposableTo(rx_disposeBag)
}
}
fileprivate func artist() -> Artist? {
return saleArtwork.artwork.artists?.first
}
fileprivate func retrieveImageRights() -> Observable<String> {
let artwork = saleArtwork.artwork
if let imageRights = artwork.imageRights {
return .just(imageRights)
} else {
return artistInfo.map { json in
return (json as AnyObject)["image_rights"] as? String
}
.filterNil()
.doOnNext { imageRights in
artwork.imageRights = imageRights
}
}
}
fileprivate func retrieveAdditionalInfo() -> Observable<String> {
let artwork = saleArtwork.artwork
if let additionalInfo = artwork.additionalInfo {
return .just(additionalInfo)
} else {
return artistInfo.map { json in
return (json as AnyObject)["additional_information"] as? String
}
.filterNil()
.doOnNext { info in
artwork.additionalInfo = info
}
}
}
fileprivate func retrieveArtistBlurb() -> Observable<String> {
guard let artist = artist() else {
return .empty()
}
if let blurb = artist.blurb {
return .just(blurb)
} else {
let retrieveArtist = provider.request(.artist(id: artist.id))
.filterSuccessfulStatusCodes()
.mapJSON()
return retrieveArtist.map { json in
return (json as AnyObject)["blurb"] as? String
}
.filterNil()
.doOnNext { blurb in
artist.blurb = blurb
}
}
}
}
| mit | dd317944292234f92f7b922bb27ec09d | 38.376812 | 181 | 0.604921 | 5.791413 | false | false | false | false |
revealapp/Revert | Shared/Sources/DynamicColourViewController.swift | 1 | 3462 | // Copyright © 2020 Itty Bitty Apps. All rights reserved.
import Foundation
final class DynamicColourViewController: RevertViewController {
private let collection: [ColourSection] = RevertItems.coloursData
@IBOutlet var segmentedControl: UISegmentedControl!
@IBOutlet var accessibilityTextLabel: UILabel!
@IBOutlet var tableView: UITableView!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setToolbarHidden(false, animated: true)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.setToolbarHidden(true, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
self.setToolbarItems([UIBarButtonItem(customView: segmentedControl)], animated: true)
accessibilityDidChange()
addAccessibilityObserver()
}
deinit {
[UIAccessibility.invertColorsStatusDidChangeNotification, UIAccessibility.darkerSystemColorsStatusDidChangeNotification].forEach {
NotificationCenter.default.removeObserver(
self,
name: $0,
object: nil
)
}
}
private func addAccessibilityObserver() {
[UIAccessibility.invertColorsStatusDidChangeNotification, UIAccessibility.darkerSystemColorsStatusDidChangeNotification].forEach {
NotificationCenter.default.addObserver(
self,
selector: #selector(accessibilityDidChange),
name: $0,
object: nil
)
}
}
@objc func accessibilityDidChange() {
var labelText: String = "Accessibility: "
switch (UIAccessibility.isInvertColorsEnabled, UIAccessibility.isDarkerSystemColorsEnabled) {
case (true, true):
labelText += "Invert colors, Increase contrast"
case (true, false):
labelText += "Invert colors"
case (false, true):
labelText += "Increase contrast"
case (false, false):
labelText += "None"
}
accessibilityTextLabel.text = labelText
}
@available(iOS 13, *)
@IBAction func onSegmentValueChanged(_ sender: UISegmentedControl) {
switch sender.selectedSegmentIndex {
case 0:
overrideUserInterfaceStyle = .unspecified
case 1:
overrideUserInterfaceStyle = .light
case 2:
overrideUserInterfaceStyle = .dark
default:
break
}
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 13, *), traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
tableView.reloadData()
}
}
}
extension DynamicColourViewController: UITableViewDataSource, UITableViewDelegate {
func numberOfSections(in tableView: UITableView) -> Int {
collection.count
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
collection[section].rows.count
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
collection[section].title
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewControllerCell") as? DynamicColourCell else {
fatalError("Unknown cellIdentifier or cell")
}
cell.setupCell(with: collection[indexPath.section].rows[indexPath.row])
return cell
}
}
| bsd-3-clause | b76c7d5b79d3d56c5a6972702d39caa6 | 28.330508 | 134 | 0.72898 | 5.283969 | false | false | false | false |
richardpiazza/LCARSDisplayKit | Sources/LCARSDisplayKitViews/DirectionGroupingView02.swift | 1 | 5529 | #if canImport(LCARSDisplayKit)
import LCARSDisplayKit
#endif
#if canImport(LCARSDisplayKitUI)
import LCARSDisplayKitUI
#endif
#if (os(iOS) || os(tvOS))
import UIKit
import GraphPoint
/// An expansion on `DirectionGroupingView01` that adds Outer Ring controls to
/// the bottom half, and an additional row of controls to the top.
@IBDesignable open class DirectionGroupingView02: DirectionGroupingView01 {
open lazy var outerRing01: CrescentButton = {
let innerArc = Arc(radius: secondRingInteriorRadius, startDegree: DPad.arc01.start, endDegree: DPad.arc04.end)
let outerArc = Arc(radius: secondRingExteriorRadius, startDegree: DPad.arc01.start, endDegree: DPad.arc04.end)
let crescent = Crescent(innerArc: innerArc, outerArc: outerArc)
let button = CrescentButton(with: crescent, inBounds: bounds, offset: offset)
button.setTitle("OR01", for: UIControl.State())
button.titleEdgeInsets = UIEdgeInsets(top: 50, left: 50, bottom: 0, right: 0)
button.color = Configuration.theme.primaryDark
self.addSubview(button)
return button
}()
open lazy var outerRing05: CrescentButton = {
let innerArc = Arc(radius: secondRingInteriorRadius, startDegree: DPad.arc05.start, endDegree: DPad.arc05.end)
let outerArc = Arc(radius: secondRingExteriorRadius, startDegree: DPad.arc05.start, endDegree: DPad.arc05.end)
let crescent = Crescent(innerArc: innerArc, outerArc: outerArc)
let button = CrescentButton(with: crescent, inBounds: bounds, offset: offset)
button.setTitle("OR05", for: UIControl.State())
button.color = Configuration.theme.primaryDark
self.addSubview(button)
return button
}()
open lazy var top01: RoundedRectangleButton = {
let e13Points = edge13.edgedCrescent.additionalPoints
let e13Origin = edge13.frame.origin
let width = e13Points[1].x - e13Points[0].x
let height = RoundedRectangleButton.defaultSize.height * scaleRatio
let x = e13Origin.x
let y = e13Origin.y - height - Configuration.theme.defaultSpacing
let button = RoundedRectangleButton(frame: CGRect(x: x, y: y, width: width, height: height))
button.setTitle("CALIBRATE", for: UIControl.State())
button.color = Configuration.theme.tertiaryLight
self.addSubview(button)
return button
}()
open var calibrate: RoundedRectangleButton {
return top01
}
open lazy var top02: RoundedRectangleButton = {
var frame = top03.frame
frame.size.width = (RoundedRectangleButton.defaultSize.width * scaleRatio) * 0.55
frame.origin.x = frame.origin.x - frame.size.width - Configuration.theme.defaultSpacing
let button = RoundedRectangleButton(frame: frame)
button.setTitle("T02", for: UIControl.State())
button.color = Configuration.theme.primaryLight
button.roundLeft = true
self.addSubview(button)
return button
}()
open lazy var top03: RoundedRectangleButton = {
let e15Points = edge15.edgedCrescent.additionalPoints
let e15Origin = edge15.frame.origin
let width = e15Points[1].x - e15Points[0].x
let height = RoundedRectangleButton.defaultSize.height * scaleRatio
let x = e15Origin.x
let y = e15Origin.y - height - Configuration.theme.defaultSpacing
let button = RoundedRectangleButton(frame: CGRect(x: x, y: y, width: width, height: height))
button.setTitle("T03", for: UIControl.State())
button.color = Configuration.theme.tertiaryDark
self.addSubview(button)
return button
}()
open lazy var top04: RoundedRectangleButton = {
var frame = top03.frame
let top03Width = frame.size.width
frame.size.width = (RoundedRectangleButton.defaultSize.width * scaleRatio) * 0.55
frame.origin.x = frame.origin.x + top03Width + Configuration.theme.defaultSpacing
let button = RoundedRectangleButton(frame: frame)
button.setTitle("T04", for: UIControl.State())
button.color = Configuration.theme.primaryDark
button.roundRight = true
self.addSubview(button)
return button
}()
open lazy var top05: RoundedRectangleButton = {
var frame = top00.frame
frame.origin.y = frame.origin.y - frame.size.height - Configuration.theme.defaultSpacing
let button = RoundedRectangleButton(frame: frame)
button.setTitle("T05", for: UIControl.State())
button.color = Configuration.theme.primaryDark
button.roundLeft = true
button.roundRight = true
self.addSubview(button)
return button
}()
open override var intrinsicContentSize: CGSize {
return CGSize(width: 760, height: 755)
}
// {0.0, 52.0}
open override var offset: GraphOriginOffset {
return GraphOriginOffset(x: 0.0, y: (scaledContentSize.height * 0.068))
}
open override var firstRingEdgeExteriorRadius: CGFloat {
return secondRingExteriorRadius
}
open override func layoutSubviews() {
super.layoutSubviews()
outerRing01.layoutIfNeeded()
outerRing05.layoutIfNeeded()
top01.layoutIfNeeded()
top02.layoutIfNeeded()
top03.layoutIfNeeded()
top04.layoutIfNeeded()
top05.layoutIfNeeded()
}
}
#endif
| mit | 33f204797ae3442db1b9fb80e8b99ac7 | 39.654412 | 118 | 0.667933 | 4.309431 | false | true | false | false |
mleiv/MEGameTracker | MEGameTracker/Models/CoreData/Data Rows/DataMapLocationable.swift | 1 | 6089 | //
// DataMapLocationable.swift
// MEGameTracker
//
// Created by Emily Ivie on 9/26/15.
// Copyright © 2015 Emily Ivie. All rights reserved.
//
import UIKit
/// Defines common characterstics to all objects available for display on a map.
public protocol DataMapLocationable {
// MARK: Required
var id: String { get }
var name: String { get }
var description: String? { get }
var gameVersion: GameVersion { get }
var mapLocationType: MapLocationType { get }
var mapLocationPoint: MapLocationPoint? { get set }
var inMapId: String? { get set }
var inMissionId: String? { get set }
var sortIndex: Int { get set }
var annotationNote: String? { get set }
var unavailabilityMessages: [String] { get set }
var isHidden: Bool { get set }
var isAvailable: Bool { get set }
// MARK: Optional
var searchableName: String { get set }
var linkToMapId: String? { get set }
var shownInMapId: String? { get set }
var isShowInParentMap: Bool { get set }
var isShowInList: Bool { get set }
var isShowPin: Bool { get set }
var isOpensDetail: Bool { get set }
}
extension DataMapLocationable {
public var searchableName: String { get { return name } set {} }
public var linkToMapId: String? { get { return nil } set {} }
public var shownInMapId: String? { get { return nil } set {} }
public var isShowInParentMap: Bool { get { return false } set {} }
public var isShowInList: Bool { get { return true } set {} }
public var isShowPin: Bool { get { return false } set {} }
public var isOpensDetail: Bool { get { return false } set {} }
public func isEqual(_ mapLocation: DataMapLocationable) -> Bool {
return id == mapLocation.id
&& gameVersion == mapLocation.gameVersion
&& mapLocationType == mapLocation.mapLocationType
}
}
// MARK: Serializable Utilities
//extension DataMapLocationable {
// /// Fetch MapLocationable values from a remote dictionary.
// public mutating func unserializeMapLocationableData(_ data: [String: Any?]) {
// createdDate = data["createdDate"] as? Date ?? createdDate
// modifiedDate = data["modifiedDate"] as? Date ?? modifiedDate
// }
//}
extension DataMapLocationable where Self: Codable {
/// Fetch MapLocationable values from a Codable dictionary.
public mutating func unserializeMapLocationableData(decoder: Decoder) throws {
let container = try decoder.container(keyedBy: DataMapLocationableCodingKeys.self)
mapLocationPoint = try? container.decodeIfPresent(MapLocationPoint.self, forKey: .mapLocationPoint)
inMapId = try container.decodeIfPresent(String.self, forKey: .inMapId)
inMissionId = try container.decodeIfPresent(String.self, forKey: .inMissionId)
sortIndex = try container.decodeIfPresent(Int.self, forKey: .sortIndex) ?? sortIndex
annotationNote = try container.decodeIfPresent(String.self, forKey: .annotationNote)
unavailabilityMessages = try container.decodeIfPresent(
[String].self,
forKey: .unavailabilityMessages
) ?? unavailabilityMessages
isHidden = try container.decodeIfPresent(Bool.self, forKey: .isHidden) ?? isHidden
isAvailable = try container.decodeIfPresent(Bool.self, forKey: .isAvailable) ?? isAvailable
searchableName = try container.decodeIfPresent(String.self, forKey: .searchableName) ?? searchableName
linkToMapId = try container.decodeIfPresent(String.self, forKey: .linkToMapId)
shownInMapId = try container.decodeIfPresent(String.self, forKey: .shownInMapId)
isShowInParentMap = (try container.decodeIfPresent(Bool.self, forKey: .isShowInParentMap)) ?? isShowInParentMap
isShowInList = try container.decodeIfPresent(Bool.self, forKey: .isShowInList) ?? isShowInList
isShowPin = try container.decodeIfPresent(Bool.self, forKey: .isShowPin) ?? isShowPin
isOpensDetail = try container.decodeIfPresent(Bool.self, forKey: .isOpensDetail) ?? isOpensDetail
}
/// Store MapLocationable values to a Codable dictionary.
public func serializeMapLocationableData(encoder: Encoder) throws {
var container = encoder.container(keyedBy: DataMapLocationableCodingKeys.self)
try container.encode(mapLocationPoint, forKey: .mapLocationPoint)
try container.encode(inMapId, forKey: .inMapId)
try container.encode(inMissionId, forKey: .inMissionId)
try container.encode(sortIndex, forKey: .sortIndex)
try container.encode(annotationNote, forKey: .annotationNote)
try container.encode(unavailabilityMessages, forKey: .unavailabilityMessages)
try container.encode(isHidden, forKey: .isHidden)
try container.encode(isAvailable, forKey: .isAvailable)
try container.encode(searchableName, forKey: .searchableName)
try container.encode(linkToMapId, forKey: .linkToMapId)
try container.encode(shownInMapId, forKey: .shownInMapId)
try container.encode(isShowInParentMap, forKey: .isShowInParentMap)
try container.encode(isShowInList, forKey: .isShowInList)
try container.encode(isShowPin, forKey: .isShowPin)
try container.encode(isOpensDetail, forKey: .isOpensDetail)
}
}
//extension DataMapLocationable where Self: CodableCoreDataStorable {
// /// Save DateModifiable values to Core Data
// public func setMapLocationableColumnsOnSave(coreItem: EntityType) {
// coreItem.setValue(createdDate, forKey: "createdDate")
// coreItem.setValue(modifiedDate, forKey: "modifiedDate")
// }
//}
/// Codable keys for objects adhering to DateModifiable
public enum DataMapLocationableCodingKeys: String, CodingKey {
case mapLocationPoint
case inMapId
case inMissionId
case sortIndex
case annotationNote
case unavailabilityMessages
case isHidden
case isAvailable
case searchableName
case linkToMapId
case shownInMapId
case isShowInParentMap
case isShowInList
case isShowPin
case isOpensDetail
}
| mit | 4706269841fb6e8a831b9ef82e11c7dc | 43.437956 | 119 | 0.710907 | 4.466618 | false | false | false | false |
howardhsien/EasyTaipei-iOS | EasyTaipei/EasyTaipei/view/MenuCell.swift | 2 | 2514 | //
// MenuCell.swift
// EasyTaipei
//
// Created by howard hsien on 2016/7/7.
// Copyright © 2016年 AppWorks School Hsien. All rights reserved.
//
import UIKit
class MenuCell: BaseCell {
let tabButton: UIButton = {
let button = UIButton()
button.backgroundColor = UIColor.esyDuskBlueColor()
return button
}()
let tabButtonView = TabButtonView.viewFromNib()
var cellDelegate:CellDelegate?
override var highlighted: Bool {
didSet {
tabButton.backgroundColor = highlighted ? UIColor.esyBluegreenColor() : UIColor.esyDuskBlueColor()
}
}
override var selected: Bool {
didSet {
tabButton.backgroundColor = selected ? UIColor.esyBluegreenColor() : UIColor.esyDuskBlueColor()
}
}
// setting button tag makes collectionView easier to dothing to cell
// for cell has no property like indexPath
func setButtonTag(tag: Int){
tabButton.tag = tag
}
// delegate to collectionview to set selected index
func setSelected() {
cellDelegate?.selectIndex(tabButton.tag)
}
func setTabButtonView(text:String,image:UIImage?) {
tabButtonView.setLabelText(text)
if let image = image{
tabButtonView.setImage(image)
}
}
override func setupViews() {
super.setupViews()
clipsToBounds = false
addSubview(tabButton)
let widthConstraint = NSLayoutConstraint(item: tabButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 78)
self.addConstraint(widthConstraint)
let heightConstraint = NSLayoutConstraint(item: tabButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 78)
tabButton.addConstraint(widthConstraint)
tabButton.addConstraint(heightConstraint)
tabButton.layer.cornerRadius = 78/2
tabButton.autoConstrainAttribute( .Bottom, toAttribute: .Bottom, ofView: self)
tabButton.autoAlignAxisToSuperviewAxis(.Vertical)
tabButton.addTarget(self, action: #selector(setSelected), forControlEvents: .TouchUpInside)
tabButton.addSubview(tabButtonView)
tabButtonView.autoPinEdgesToSuperviewEdges()
}
}
| mit | c6a454447bd463ed4039c5dfb853dec2 | 31.192308 | 225 | 0.667065 | 5.022 | false | false | false | false |
ello/ello-ios | Sources/Model/ArtistInvite.swift | 1 | 6878 | ////
/// ArtistInvite.swift
//
import SwiftyJSON
@objc(ArtistInvite)
final class ArtistInvite: Model {
// Version 1: initial
static let Version = 1
struct Guide {
let title: String
let html: String
}
struct Stream {
let endpoint: ElloAPI
let label: String
let submissionsStatus: ArtistInviteSubmission.Status
init?(link: [String: Any], submissionsStatus: ArtistInviteSubmission.Status) {
guard
let url = (link["href"] as? String).flatMap({ URL(string: $0) }),
let label = link["label"] as? String
else { return nil }
self.endpoint = .custom(url: url, mimics: .artistInviteSubmissions)
self.label = label
self.submissionsStatus = submissionsStatus
}
}
enum Status: String {
case preview
case upcoming
case open
case selecting
case closed
}
let id: String
let slug: String
let title: String
let shortDescription: String
let submissionBody: String
let longDescription: String
let inviteType: String
let status: Status
let openedAt: Date?
let closedAt: Date?
var headerImage: Asset?
var logoImage: Asset?
var redirectURL: URL?
var guide: [Guide] = []
var approvedSubmissionsStream: Stream?
var selectedSubmissionsStream: Stream?
var unapprovedSubmissionsStream: Stream?
var declinedSubmissionsStream: Stream?
override var description: String { return longDescription }
var shareLink: String {
return "\(ElloURI.baseURL)/creative-briefs/\(slug)"
}
var hasAdminLinks: Bool {
return approvedSubmissionsStream != nil && unapprovedSubmissionsStream != nil
}
init(
id: String,
slug: String,
title: String,
shortDescription: String,
submissionBody: String,
longDescription: String,
inviteType: String,
status: Status,
openedAt: Date?,
closedAt: Date?
) {
self.id = id
self.slug = slug
self.title = title
self.shortDescription = shortDescription
self.submissionBody = submissionBody
self.longDescription = longDescription
self.inviteType = inviteType
self.status = status
self.openedAt = openedAt
self.closedAt = closedAt
super.init(version: ArtistInvite.Version)
}
required init(coder: NSCoder) {
let decoder = Coder(coder)
id = decoder.decodeKey("id")
slug = decoder.decodeKey("slug")
title = decoder.decodeKey("title")
shortDescription = decoder.decodeKey("shortDescription")
submissionBody = decoder.decodeKey("submissionBody")
longDescription = decoder.decodeKey("longDescription")
inviteType = decoder.decodeKey("inviteType")
status = Status(rawValue: decoder.decodeKey("status")) ?? .closed
openedAt = decoder.decodeOptionalKey("openedAt")
closedAt = decoder.decodeOptionalKey("closedAt")
redirectURL = decoder.decodeOptionalKey("redirectURL")
super.init(coder: coder)
}
override func encode(with coder: NSCoder) {
let encoder = Coder(coder)
encoder.encodeObject(id, forKey: "id")
encoder.encodeObject(slug, forKey: "slug")
encoder.encodeObject(title, forKey: "title")
encoder.encodeObject(shortDescription, forKey: "shortDescription")
encoder.encodeObject(submissionBody, forKey: "submissionBody")
encoder.encodeObject(longDescription, forKey: "longDescription")
encoder.encodeObject(inviteType, forKey: "inviteType")
encoder.encodeObject(status.rawValue, forKey: "status")
encoder.encodeObject(openedAt, forKey: "openedAt")
encoder.encodeObject(closedAt, forKey: "closedAt")
encoder.encodeObject(redirectURL, forKey: "redirectURL")
super.encode(with: coder)
}
class func fromJSON(_ data: [String: Any]) -> ArtistInvite {
let json = JSON(data)
let id = json["id"].idValue
let artistInvite = ArtistInvite(
id: id,
slug: json["slug"].stringValue,
title: json["title"].stringValue,
shortDescription: json["short_description"].stringValue,
submissionBody: json["submission_body_block"].stringValue,
longDescription: json["description"].stringValue,
inviteType: json["invite_type"].stringValue,
status: Status(rawValue: json["status"].stringValue) ?? .closed,
openedAt: json["opened_at"].string?.toDate(),
closedAt: json["closed_at"].string?.toDate()
)
artistInvite.headerImage = Asset.parseAsset(
"artist_invite_header_\(id)",
node: data["header_image"] as? [String: Any]
)
artistInvite.logoImage = Asset.parseAsset(
"artist_invite_logo_\(id)",
node: data["logo_image"] as? [String: Any]
)
artistInvite.redirectURL = json["redirect_url"].url
if let approvedSubmissionsLink = json["links"]["approved_submissions"].object
as? [String: Any],
let stream = Stream(link: approvedSubmissionsLink, submissionsStatus: .approved)
{
artistInvite.approvedSubmissionsStream = stream
}
if let selectedSubmissionsLink = json["links"]["selected_submissions"].object
as? [String: Any],
let stream = Stream(link: selectedSubmissionsLink, submissionsStatus: .selected)
{
artistInvite.selectedSubmissionsStream = stream
}
if let unapprovedSubmissionsLink = json["links"]["unapproved_submissions"].object
as? [String: Any],
let stream = Stream(link: unapprovedSubmissionsLink, submissionsStatus: .unapproved)
{
artistInvite.unapprovedSubmissionsStream = stream
}
if let declinedSubmissionsLink = json["links"]["declined_submissions"].object
as? [String: Any],
let stream = Stream(link: declinedSubmissionsLink, submissionsStatus: .declined)
{
artistInvite.declinedSubmissionsStream = stream
}
if let guide = json["guide"].array?.compactMap({ $0.object as? [String: String] }) {
artistInvite.guide = guide.compactMap { g -> Guide? in
guard let title = g["title"], let html = g["rendered_body"] else { return nil }
return Guide(title: title, html: html)
}
}
artistInvite.mergeLinks(data["links"] as? [String: Any])
return artistInvite
}
}
extension ArtistInvite: JSONSaveable {
var uniqueId: String? { return "ArtistInvite-\(id)" }
var tableId: String? { return id }
}
| mit | 9f51b7262495a3a5dbd3035ad315db4e | 33.913706 | 96 | 0.621983 | 4.75657 | false | false | false | false |
CatchChat/Yep | Yep/Views/SayHi/BottomButtonView.swift | 1 | 2848 | //
// SayHiView.swift
// Yep
//
// Created by NIX on 15/5/29.
// Copyright (c) 2015年 Catch Inc. All rights reserved.
//
import UIKit
@IBDesignable
final class BottomButtonView: UIView {
@IBInspectable var topLineColor: UIColor = UIColor.yepBorderColor()
@IBInspectable var topLineWidth: CGFloat = 1 / UIScreen.mainScreen().scale
@IBInspectable var title: String = NSLocalizedString("Say Hi", comment: "") {
didSet {
actionButton.setTitle(title, forState: .Normal)
}
}
lazy var actionButton: UIButton = {
let button = UIButton()
button.titleLabel?.font = UIFont.systemFontOfSize(14)
button.setTitle(self.title, forState: .Normal)
button.backgroundColor = UIColor.yepTintColor()
button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
button.layer.cornerRadius = 5
button.addTarget(self, action: #selector(BottomButtonView.tryTap), forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
var tapAction: (() -> Void)?
override func didMoveToSuperview() {
super.didMoveToSuperview()
backgroundColor = UIColor.whiteColor()
// Add actionButton
self.addSubview(actionButton)
actionButton.translatesAutoresizingMaskIntoConstraints = false
let actionButtonCenterXConstraint = NSLayoutConstraint(item: actionButton, attribute: .CenterX, relatedBy: .Equal, toItem: self, attribute: .CenterX, multiplier: 1.0, constant: 0)
let actionButtonCenterYConstraint = NSLayoutConstraint(item: actionButton, attribute: .CenterY, relatedBy: .Equal, toItem: self, attribute: .CenterY, multiplier: 1.0, constant: 0)
let actionButtonWidthConstraint = NSLayoutConstraint(item: actionButton, attribute: .Width, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 185)
let actionButtonHeightConstraint = NSLayoutConstraint(item: actionButton, attribute: .Height, relatedBy: .Equal, toItem: nil, attribute: .NotAnAttribute, multiplier: 1.0, constant: 30)
let constraints: [NSLayoutConstraint] = [
actionButtonCenterXConstraint,
actionButtonCenterYConstraint,
actionButtonWidthConstraint,
actionButtonHeightConstraint,
]
NSLayoutConstraint.activateConstraints(constraints)
}
// MARK: Actions
func tryTap() {
tapAction?()
}
// MARK: Draw
override func drawRect(rect: CGRect) {
super.drawRect(rect)
topLineColor.setStroke()
let context = UIGraphicsGetCurrentContext()
CGContextSetLineWidth(context, topLineWidth)
CGContextMoveToPoint(context, 0, 0)
CGContextAddLineToPoint(context, CGRectGetWidth(rect), 0)
CGContextStrokePath(context)
}
}
| mit | 3803f48d19887fb96c33b5b4f633588d | 32.880952 | 192 | 0.687983 | 5.091234 | false | false | false | false |
SheffieldKevin/SwiftSVG | SwiftSVG Demo/Document.swift | 1 | 1535 | //
// Document.swift
// SwiftSVGTestNT
//
// Created by Jonathan Wight on 2/25/15.
// Copyright (c) 2015 No. All rights reserved.
//
import Cocoa
import SwiftSVG
class Document: NSDocument {
dynamic var source: String? = nil
override init() {
super.init()
}
override func windowControllerDidLoadNib(aController: NSWindowController) {
super.windowControllerDidLoadNib(aController)
if let controller = aController.contentViewController as? ViewController {
controller.document = self
}
}
// override class func autosavesInPlace() -> Bool {
// return false
// }
override func makeWindowControllers() {
let storyboard = NSStoryboard(name: "Main", bundle: nil)
let windowController = storyboard.instantiateControllerWithIdentifier("Document Window Controller") as! NSWindowController
if let controller = windowController.contentViewController as? ViewController {
controller.document = self
}
self.addWindowController(windowController)
}
override func readFromURL(url: NSURL, ofType typeName: String) throws {
var encoding = NSStringEncoding()
source = try String(contentsOfURL: url, usedEncoding: &encoding)
}
override func dataOfType(typeName: String) throws -> NSData {
guard let data = source?.dataUsingEncoding(NSUTF8StringEncoding) else {
throw NSError(domain: "TODO", code: -1, userInfo: nil)
}
return data
}
}
| bsd-2-clause | f55f131f6e36310cfe1d4529efd3ff69 | 26.909091 | 130 | 0.669055 | 4.904153 | false | false | false | false |
zslzhappy/JNPlayer2GitHub | JNPlayerKit/Example/ViewController.swift | 1 | 5809 | //
// ViewController.swift
// Example
//
// Created by mac on 16/10/12.
// Copyright © 2016年 Magugi. All rights reserved.
//
import UIKit
import JNPlayerKit
class ViewController: UIViewController {
let topPlayerView:JNPlayerView = JNPlayerView()
override func viewDidLoad() {
super.viewDidLoad()
self.topPlayerView.autoPlay = false
self.setUpTopPlayer()
self.topPlayerView.delegate = self
//self.topPlayerView.play("http://od7vwyosd.bkt.clouddn.com/o_1asev3gvokag1bqb1ohqg6h1ko29.mp4", title: "TopPlayerView")
self.topPlayerView.play(items:[("http://baobab.wdjcdn.com/1457162012752491010143.mp4", "firstAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"), ("http://baobab.wdjcdn.com/14571455324031.mp4", "second"), ("http://gslb.miaopai.com/stream/kPzSuadRd2ipEo82jk9~sA__.mp4", "third")])
self.topPlayerView.backAction = {
self.navigationController?.popViewController(animated: true)
}
self.navigationController?.setNavigationBarHidden(true, animated: true)
//self.bottomPlayerView.play(NSURL(string: "http://gslb.miaopai.com/stream/kPzSuadRd2ipEo82jk9~sA__.mp4")!, title: "BottomPlayerView")
}
var bottomConstraint:NSLayoutConstraint?
var heightConstraint:NSLayoutConstraint?
func setUpTopPlayer(){
self.view.addSubview(self.topPlayerView)
self.view.addConstraints({
let left = NSLayoutConstraint(item: self.topPlayerView, attribute: .left, relatedBy: .equal, toItem: self.view, attribute: .left, multiplier: 1, constant: 0)
let top = NSLayoutConstraint(item: self.topPlayerView, attribute: .top, relatedBy: .equal, toItem: self.view, attribute: .top, multiplier: 1, constant: 0)
let right = NSLayoutConstraint(item: self.topPlayerView, attribute: .right, relatedBy: .equal, toItem: self.view, attribute: .right, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: self.topPlayerView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 0)
self.bottomConstraint = bottom
return [left, top, right, bottom]}()
)
self.topPlayerView.addConstraint({
let height = NSLayoutConstraint(item: self.topPlayerView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 200)
self.heightConstraint = height
return height
}())
let isPartrait = self.view.frame.width < self.view.frame.height
self.bottomConstraint?.isActive = !isPartrait
self.heightConstraint?.isActive = isPartrait
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
self.topPlayerView.play(url:nil)
}
var shouldPlay:Bool = false
@IBAction func exchangeStatusAction(_ sender: UIButton) {
self.shouldPlay = !self.shouldPlay
}
@IBAction func tapToPlay(_ sender: UIButton) {
self.topPlayerView.play()
}
@IBAction func tapToPause(_ sender: UIButton) {
self.topPlayerView.pause()
}
}
extension ViewController: JNPlayerViewDelegate{
// 当前正在播放的视频, 该方法会在加载视频时执行
func playerView(player:JNPlayerView, playingItem:JNPlayerItem, index:Int){
print("playingItem:\(playingItem) index:\(index)")
}
// 播放完成的视频, 该方法会在视频播放完成时执行
func playerView(player:JNPlayerView, playEndItem:JNPlayerItem){
print("playedItme:\(playEndItem)")
}
// 返回按钮点击回调
func playerViewBackAction(player:JNPlayerView){
print("backAction")
}
// 播放失败
func playerView(player:JNPlayerView, playingItem:JNPlayerItem, error:NSError){
print("playerItemError:\(playingItem)")
}
func playerViewWillPlayItem(player:JNPlayerView, willPlayItem:JNPlayerItem) -> Bool{
return self.shouldPlay
}
}
extension ViewController{
override var shouldAutorotate: Bool{
get{
return true
}
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask{
get{
return [.portrait, .landscapeLeft, .landscapeRight]
}
}
override var preferredInterfaceOrientationForPresentation: UIInterfaceOrientation{
get{
return .portrait
}
}
override var prefersStatusBarHidden: Bool{
get{
if self.view.frame.width > self.view.frame.height{
return true
}else{
return false
}
}
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
coordinator.animate(alongsideTransition: { (context) in
if size.width > size.height{
self.bottomConstraint?.isActive = true
self.heightConstraint?.isActive = false
self.view.layoutIfNeeded()
}else{
self.bottomConstraint?.isActive = false
self.heightConstraint?.isActive = true
self.view.layoutIfNeeded()
}
}, completion: {content in
})
}
}
| apache-2.0 | 406103e3e929dc0abf93edb5d21f687b | 31.936416 | 328 | 0.630221 | 4.595161 | false | false | false | false |
coderwhy/DouYuZB | DYZB/DYZB/Classes/Main/Controller/BaseAnchorViewController.swift | 1 | 4897 | //
// BaseAnchorViewController.swift
// DYZB
//
// Created by 1 on 16/10/10.
// Copyright © 2016年 小码哥. All rights reserved.
//
import UIKit
private let kItemMargin : CGFloat = 10
private let kHeaderViewH : CGFloat = 50
private let kNormalCellID = "kNormalCellID"
private let kHeaderViewID = "kHeaderViewID"
let kPrettyCellID = "kPrettyCellID"
let kNormalItemW = (kScreenW - 3 * kItemMargin) / 2
let kNormalItemH = kNormalItemW * 3 / 4
let kPrettyItemH = kNormalItemW * 4 / 3
class BaseAnchorViewController: BaseViewController {
// MARK: 定义属性
var baseVM : BaseViewModel!
lazy var collectionView : UICollectionView = {[unowned self] in
// 1.创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kNormalItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
// 2.创建UICollectionView
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: kNormalCellID)
collectionView.register(UINib(nibName: "CollectionPrettyCell", bundle: nil), forCellWithReuseIdentifier: kPrettyCellID)
collectionView.register(UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
// MARK: 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
loadData()
}
}
// MARK:- 设置UI界面
extension BaseAnchorViewController {
override func setupUI() {
// 1.给父类中内容View的引用进行赋值
contentView = collectionView
// 2.添加collectionView
view.addSubview(collectionView)
// 3.调用super.setupUI()
super.setupUI()
}
}
// MARK:- 请求数据
extension BaseAnchorViewController {
func loadData() {
}
}
// MARK:- 遵守UICollectionView的数据源
extension BaseAnchorViewController : UICollectionViewDataSource {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return baseVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return baseVM.anchorGroups[section].anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.取出Cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
// 2.给cell设置数据
cell.anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1.取出HeaderView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
// 2.给HeaderView设置数据
headerView.group = baseVM.anchorGroups[indexPath.section]
return headerView
}
}
// MARK:- 遵守UICollectionView的代理协议
extension BaseAnchorViewController : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 1.取出对应的主播信息
let anchor = baseVM.anchorGroups[indexPath.section].anchors[indexPath.item]
// 2.判断是秀场房间&普通房间
anchor.isVertical == 0 ? pushNormalRoomVc() : presentShowRoomVc()
}
private func presentShowRoomVc() {
// 1.创建ShowRoomVc
let showRoomVc = RoomShowViewController()
// 2.以Modal方式弹出
present(showRoomVc, animated: true, completion: nil)
}
private func pushNormalRoomVc() {
// 1.创建NormalRoomVc
let normalRoomVc = RoomNormalViewController()
// 2.以Push方式弹出
navigationController?.pushViewController(normalRoomVc, animated: true)
}
}
| mit | 31367f0ae7b41fba2f62e3c89923ba69 | 31.783217 | 186 | 0.68942 | 5.703163 | false | false | false | false |
MaartenBrijker/project | project/External/AudioKit-master/AudioKit/iOS/AudioKit/AudioKit.playground/Pages/Newtons Cradle.xcplaygroundpage/Contents.swift | 2 | 10170 | import UIKit
import XCPlayground
import AudioKit
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("click", ofType: "wav")
var tink = AKAudioPlayer(file!)
var reverb = AKCostelloReverb(tink)
let gravity = 0.166
reverb.feedback = 0.2 / gravity
reverb.cutoffFrequency = 20000 * gravity
AudioKit.output = AKMixer(tink, reverb)
AudioKit.start()
/*:
## Newton's Cradle and UIKit Dynamics
This playground uses **UIKit Dynamics** to create a [Newton's Cradle](https://en.wikipedia.org/wiki/Newton%27s_cradle). Commonly seen on desks around the world, Newton's Cradle is a device that illustrates conservation of momentum and energy.
Let's create an instance of our UIKit Dynamics based Newton's Cradle. Try adding more colors to the array to increase the number of balls in the device.
*/
let newtonsCradle = NewtonsCradle(colors: [[#Color(colorLiteralRed: 0.8779790997505188, green: 0.3812967836856842, blue: 0.5770481824874878, alpha: 1)#], [#Color(colorLiteralRed: 0.2202886641025543, green: 0.7022308707237244, blue: 0.9593387842178345, alpha: 1)#], [#Color(colorLiteralRed: 0.9166661500930786, green: 0.4121252298355103, blue: 0.2839399874210358, alpha: 1)#], [#Color(colorLiteralRed: 0.521954357624054, green: 0.7994346618652344, blue: 0.3460423350334167, alpha: 1)#]])
/*:
### Size and spacing
Try changing the size and spacing of the balls and see how that changes the device. What happens if you make `ballPadding` a negative number?
*/
newtonsCradle.ballSize = CGSize(width: 60, height: 60)
newtonsCradle.ballPadding = 2.0
/*:
### Behavior
Adjust `elasticity` and `resistance` to change how the balls react to eachother.
*/
newtonsCradle.itemBehavior.elasticity = 1.0
newtonsCradle.itemBehavior.resistance = 0.2
/*:
### Shape and rotation
How does Newton's Cradle look if we use squares instead of circles and allow them to rotate?
*/
newtonsCradle.useSquaresInsteadOfBalls = false
newtonsCradle.itemBehavior.allowsRotation = false
/*:
### Gravity
Change the `angle` and/or `magnitude` of gravity to see what Newton's Device might look like in another world.
*/
newtonsCradle.gravityBehavior.angle = CGFloat(M_PI_2)
newtonsCradle.gravityBehavior.magnitude = CGFloat(gravity)
/*:
### Attachment
What happens if you change `length` of the attachment behaviors to different values?
*/
for attachmentBehavior in newtonsCradle.attachmentBehaviors {
attachmentBehavior.length = 100
}
XCPlaygroundPage.currentPage.liveView = newtonsCradle
public class NewtonsCradle: UIView, UICollisionBehaviorDelegate {
private let colors: [UIColor]
private var balls: [UIView] = []
private var animator: UIDynamicAnimator?
private var ballsToAttachmentBehaviors: [UIView:UIAttachmentBehavior] = [:]
private var snapBehavior: UISnapBehavior?
public let collisionBehavior: UICollisionBehavior
public let gravityBehavior: UIGravityBehavior
public let itemBehavior: UIDynamicItemBehavior
public init(colors: [UIColor]) {
self.colors = colors
collisionBehavior = UICollisionBehavior(items: [])
gravityBehavior = UIGravityBehavior(items: [])
itemBehavior = UIDynamicItemBehavior(items: [])
super.init(frame: CGRect(x: 0, y: 0, width: 480, height: 320))
backgroundColor = UIColor.whiteColor()
animator = UIDynamicAnimator(referenceView: self)
animator?.addBehavior(collisionBehavior)
animator?.addBehavior(gravityBehavior)
animator?.addBehavior(itemBehavior)
createBallViews()
collisionBehavior.collisionDelegate = self
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
for ball in balls {
ball.removeObserver(self, forKeyPath: "center")
}
}
// MARK: Collision
public func collisionBehavior(behavior: UICollisionBehavior, beganContactForItem item1: UIDynamicItem, withItem item2: UIDynamicItem, atPoint point: CGPoint) {
tink.stop()
tink.play()
}
// MARK: Ball Views
func createBallViews() {
for color in colors {
let ball = UIView(frame: CGRect.zero)
// Observe the center point of the ball view to draw the attachment behavior.
ball.addObserver(self, forKeyPath: "center", options: NSKeyValueObservingOptions.init(rawValue: 0), context: nil)
// Make the ball view round and set the background
ball.backgroundColor = color
// Add the balls as a subview before we add it to any UIDynamicBehaviors.
addSubview(ball)
balls.append(ball)
// Layout the balls based on the ballSize and ballPadding.
layoutBalls()
}
}
// MARK: Properties
public var attachmentBehaviors: [UIAttachmentBehavior] {
get {
var attachmentBehaviors: [UIAttachmentBehavior] = []
for ball in balls {
guard let attachmentBehavior = ballsToAttachmentBehaviors[ball] else { fatalError("Can't find attachment behavior for \(ball)") }
attachmentBehaviors.append(attachmentBehavior)
}
return attachmentBehaviors
}
}
public var useSquaresInsteadOfBalls: Bool = false {
didSet {
for ball in balls {
if useSquaresInsteadOfBalls {
ball.layer.cornerRadius = 0
} else {
ball.layer.cornerRadius = ball.bounds.width / 2.0
}
}
}
}
public var ballSize: CGSize = CGSize(width: 50, height: 50) {
didSet {
layoutBalls()
}
}
public var ballPadding: Double = 0.0 {
didSet {
layoutBalls()
}
}
// MARK: Ball Layout
private func layoutBalls() {
let requiredWidth = CGFloat(balls.count) * (ballSize.width + CGFloat(ballPadding))
for (index, ball) in balls.enumerate() {
// Remove any attachment behavior that already exists.
if let attachmentBehavior = ballsToAttachmentBehaviors[ball] {
animator?.removeBehavior(attachmentBehavior)
}
// Remove the ball from the appropriate behaviors before update its frame.
collisionBehavior.removeItem(ball)
gravityBehavior.removeItem(ball)
itemBehavior.removeItem(ball)
// Determine the horizontal position of the ball based on the number of balls.
let ballXOrigin = ((bounds.width - requiredWidth) / 2.0) + (CGFloat(index) * (ballSize.width + CGFloat(ballPadding)))
ball.frame = CGRect(x: ballXOrigin, y: bounds.midY, width: ballSize.width, height: ballSize.height)
// Create the attachment behavior.
let attachmentBehavior = UIAttachmentBehavior(item: ball, attachedToAnchor: CGPoint(x: ball.frame.midX, y: bounds.midY - 50))
ballsToAttachmentBehaviors[ball] = attachmentBehavior
animator?.addBehavior(attachmentBehavior)
// Add the collision, gravity and item behaviors.
collisionBehavior.addItem(ball)
gravityBehavior.addItem(ball)
itemBehavior.addItem(ball)
}
}
// MARK: Touch Handling
override public func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let touchLocation = touch.locationInView(superview)
for ball in balls {
if CGRectContainsPoint(ball.frame, touchLocation) {
snapBehavior = UISnapBehavior(item: ball, snapToPoint: touchLocation)
animator?.addBehavior(snapBehavior!)
}
}
}
}
override public func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let touch = touches.first {
let touchLocation = touch.locationInView(superview)
if let snapBehavior = snapBehavior {
snapBehavior.snapPoint = touchLocation
}
}
}
public override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
if let snapBehavior = snapBehavior {
animator?.removeBehavior(snapBehavior)
}
snapBehavior = nil
}
// MARK: KVO
public override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
if keyPath == "center" {
setNeedsDisplay()
}
}
// MARK: Drawing
public override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
CGContextSaveGState(context)
for ball in balls {
guard let attachmentBehavior = ballsToAttachmentBehaviors[ball] else { fatalError("Can't find attachment behavior for \(ball)") }
let anchorPoint = attachmentBehavior.anchorPoint
CGContextMoveToPoint(context, anchorPoint.x, anchorPoint.y)
CGContextAddLineToPoint(context, ball.center.x, ball.center.y)
CGContextSetStrokeColorWithColor(context, UIColor.darkGrayColor().CGColor)
CGContextSetLineWidth(context, 4.0)
CGContextStrokePath(context)
let attachmentDotWidth: CGFloat = 10.0
let attachmentDotOrigin = CGPoint(x: anchorPoint.x - (attachmentDotWidth / 2), y: anchorPoint.y - (attachmentDotWidth / 2))
let attachmentDotRect = CGRect(x: attachmentDotOrigin.x, y: attachmentDotOrigin.y, width: attachmentDotWidth, height: attachmentDotWidth)
CGContextSetFillColorWithColor(context, UIColor.darkGrayColor().CGColor)
CGContextFillEllipseInRect(context, attachmentDotRect)
}
CGContextRestoreGState(context)
}
}
| apache-2.0 | 68970491dee88448d2a84eafbeba1a1c | 37.816794 | 486 | 0.651426 | 4.79717 | false | false | false | false |
AsyncNinja/AsyncNinja | Tests/AsyncNinja/EventSource_TransformTests.swift | 1 | 10028 | //
// Copyright (c) 2016-2017 Anton Mironov
//
// 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 XCTest
import Dispatch
@testable import AsyncNinja
#if os(Linux)
import Glibc
#endif
class EventSource_TransformTests: XCTestCase {
static let allTests = [
("testDebounce", testDebounce),
("testDistinctInts", testDistinctInts),
("testDistinctOptionalInts", testDistinctOptionalInts),
("testDistinctArrays", testDistinctArrays),
("testDistinctNSObjects", testDistinctNSObjects),
("testDistinctArrayNSObjects", testDistinctArrayNSObjects),
("testSkip", testSkip),
("testTake", testTake)
]
func testDebounce() {
let initalProducer = Producer<Int, String>()
let derivedProducer = initalProducer.debounce(interval: 0.5)
let expectation = self.expectation(description: "completion of derived producer")
derivedProducer.extractAll().onSuccess {
let (numbers, stringOrError) = $0
XCTAssertEqual([1, 6, 9, 12], numbers)
XCTAssertEqual("Finished!", stringOrError.maybeSuccess)
expectation.fulfill()
}
DispatchQueue.global().async {
mysleep(0.1)
initalProducer.update(1)
initalProducer.update(2)
initalProducer.update(3)
mysleep(0.25)
initalProducer.update(4)
initalProducer.update(5)
initalProducer.update(6)
mysleep(0.25)
initalProducer.update(7)
initalProducer.update(8)
initalProducer.update(9)
mysleep(1.0)
initalProducer.update(10)
initalProducer.update(11)
initalProducer.update(12)
mysleep(0.2)
initalProducer.succeed("Finished!")
}
self.waitForExpectations(timeout: 5.0)
}
func testTrottle() {
let initalProducer = Producer<Int, String>()
let derivedProducer = initalProducer.throttle(interval: 0.5) // sendLast as default
let derivedProducer2 = initalProducer.throttle(interval: 0.5, after: .sendFirst)
let derivedProducer3 = initalProducer.throttle(interval: 0.5, after: .none)
let expectation1 = self.expectation(description: "completion of derived producer")
let expectation2 = self.expectation(description: "completion of derived producer")
let expectation3 = self.expectation(description: "completion of derived producer")
derivedProducer.extractAll().onSuccess {
let (numbers, stringOrError) = $0
XCTAssertEqual([1, 3, 4, 6], numbers)
XCTAssertEqual("Finished!", stringOrError.maybeSuccess)
expectation1.fulfill()
}
derivedProducer2.extractAll().onSuccess {
let (numbers, stringOrError) = $0
XCTAssertEqual([1, 2, 4, 5], numbers)
XCTAssertEqual("Finished!", stringOrError.maybeSuccess)
expectation2.fulfill()
}
derivedProducer3.extractAll().onSuccess {
let (numbers, stringOrError) = $0
XCTAssertEqual([1, 4], numbers)
XCTAssertEqual("Finished!", stringOrError.maybeSuccess)
expectation3.fulfill()
}
DispatchQueue.global().async {
mysleep(0.01)
initalProducer.update(1)
mysleep(0.01)
initalProducer.update(2)
mysleep(0.01)
initalProducer.update(3)
mysleep(1)
initalProducer.update(4)
mysleep(0.01)
initalProducer.update(5)
mysleep(0.01)
initalProducer.update(6)
mysleep(0.01)
initalProducer.succeed("Finished!")
}
self.waitForExpectations(timeout: 2.0)
}
func testDistinctInts() {
let updatable = Producer<Int, String>()
let expectation = self.expectation(description: "completion of producer")
updatable.distinct().extractAll().onSuccess {
let (updates, completion) = $0
XCTAssertEqual(updates, [1, 2, 3, 4, 5, 6, 7])
XCTAssertEqual(completion.maybeSuccess, "done")
expectation.fulfill()
}
let fixture = [1, 2, 2, 3, 3, 3, 4, 5, 6, 6, 7]
DispatchQueue.global().async {
updatable.update(fixture)
updatable.succeed("done")
}
self.waitForExpectations(timeout: 1.0)
}
func testDistinctOptionalInts() {
let updatable = Producer<Int?, String>()
let expectation = self.expectation(description: "completion of producer")
updatable.distinct().extractAll().onSuccess {
let (updates, completion) = $0
let assumedResults: [Int?] = [nil, 1, nil, 2, 3, nil, 3, 4, 5, 6, 7]
XCTAssertEqual(updates.count, assumedResults.count)
for (update, result) in zip(updates, assumedResults) {
XCTAssertEqual(update, result)
}
XCTAssertEqual(completion.maybeSuccess, "done")
expectation.fulfill()
}
let fixture: [Int?] = [nil, 1, nil, nil, 2, 2, 3, nil, 3, 3, 4, 5, 6, 6, 7]
DispatchQueue.global().async {
updatable.update(fixture)
updatable.succeed("done")
}
self.waitForExpectations(timeout: 1.0)
}
func testDistinctArrays() {
let updatable = Producer<[Int], String>()
let expectation = self.expectation(description: "completion of producer")
updatable.distinct().extractAll().onSuccess {
let (updates, completion) = $0
let assumedResults: [[Int]] = [[1], [1, 2], [1, 2, 3], [1]]
XCTAssertEqual(updates.count, assumedResults.count)
for (update, result) in zip(updates, assumedResults) {
XCTAssert(update == result)
}
XCTAssertEqual(completion.maybeSuccess, "done")
expectation.fulfill()
}
let fixture: [[Int]] = [[1], [1], [1, 2], [1, 2, 3], [1, 2, 3], [1]]
DispatchQueue.global().async {
updatable.update(fixture)
updatable.succeed("done")
}
self.waitForExpectations(timeout: 1.0)
}
func testDistinctNSObjects() {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let updatable = Producer<NSString, String>()
let expectation = self.expectation(description: "completion of producer")
updatable.distinctNSObjects().extractAll().onSuccess {
let (updates, completion) = $0
let assumedResults: [NSString] = ["objectA", "objectB", "objectC", "objectA"]
XCTAssertEqual(updates.count, assumedResults.count)
for (update, result) in zip(updates, assumedResults) {
XCTAssert(update == result)
}
XCTAssertEqual(completion.maybeSuccess, "done")
expectation.fulfill()
}
let fixture: [NSString] = ["objectA", "objectA", "objectB", "objectC", "objectC", "objectA"]
DispatchQueue.global().async {
updatable.update(fixture)
updatable.succeed("done")
}
self.waitForExpectations(timeout: 1.0)
#endif
}
func testDistinctArrayNSObjects() {
#if os(macOS) || os(iOS) || os(tvOS) || os(watchOS)
let updatable = Producer<[NSString], String>()
let expectation = self.expectation(description: "completion of producer")
let objectA: NSString = "objectA"
let objectB: NSString = "objectB"
let objectC: NSString = "objectC"
updatable.distinctCollectionOfNSObjects().extractAll().onSuccess {
let (updates, completion) = $0
let assumedResults: [[NSString]] = [[objectA], [objectA, objectB], [objectA, objectB, objectC], [objectA]]
XCTAssertEqual(updates.count, assumedResults.count)
for (update, result) in zip(updates, assumedResults) {
XCTAssert(update == result)
}
XCTAssertEqual(completion.maybeSuccess, "done")
expectation.fulfill()
}
let fixture: [[NSString]] = [
[objectA],
[objectA],
[objectA, objectB],
[objectA, objectB, objectC],
[objectA, objectB, objectC],
[objectA]
]
DispatchQueue.global().async {
updatable.update(fixture)
updatable.succeed("done")
}
self.waitForExpectations(timeout: 1.0)
#endif
}
func testSkip() {
multiTest {
let source = Producer<Int, String>()
let sema = DispatchSemaphore(value: 0)
source.skip(first: 2, last: 3).extractAll()
.onSuccess {
let (updates, completion) = $0
XCTAssertEqual([2, 3, 4, 5, 6], updates)
XCTAssertEqual("Done", completion.maybeSuccess)
sema.signal()
}
source.update(0..<10)
source.succeed("Done")
sema.wait()
}
}
func testTake() {
multiTest {
let source = Producer<Int, String>()
let sema = DispatchSemaphore(value: 0)
source.take(first: 2, last: 3).extractAll()
.onSuccess {
let (updates, completion) = $0
XCTAssertEqual([0, 1, 7, 8, 9], updates)
XCTAssertEqual("Done", completion.maybeSuccess)
sema.signal()
}
source.update(0..<10)
source.succeed("Done")
sema.wait()
}
let result = (channel(updates: [1, 2, 3, 4], success: "Success") as Channel<Int, String>)
.take(2, completion: "bla", cancellationToken: nil, bufferSize: .specific(2))
.waitForAll()
XCTAssert(result.updates == [1, 2])
XCTAssert(result.completion.maybeSuccess == "bla")
}
}
| mit | 40bf06813df8ddc14bca338c16007a09 | 31.986842 | 114 | 0.651376 | 4.028927 | false | true | false | false |
mcxiaoke/learning-ios | swift-language-guide/07_Closures.playground/Contents.swift | 1 | 3684 | //: Playground - noun: a place where people can play
// https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Closures.html#//apple_ref/doc/uid/TP40014097-CH11-ID94
// http://wiki.jikexueyuan.com/project/swift/chapter2/07_Closures.html
import UIKit
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
func backwards(s1:String, s2:String) -> Bool {
return s1 > s2
}
var reversed = names.sort(backwards)
reversed = names.sort({ (s1:String, s2:String) -> Bool in
return s1 > s2
})
reversed = names.sort({ (s1:String, s2:String) -> Bool in return s1 > s2 })
reversed = names.sort( { s1, s2 in return s1 > s2 } ) // type inferring
reversed = names.sort({ s1, s2 in s1 > s2 })
reversed = names.sort( { $0 > $1 } )
reversed = names.sort(>)
func someFunctionThatTakesAClosure(closure: () -> Void) {
// function body
print("function!")
}
someFunctionThatTakesAClosure({
// closure body
print("closure!")
})
someFunctionThatTakesAClosure() {
// closure body
print("closure!")
}
someFunctionThatTakesAClosure {
// closure body
print("closure!")
}
reversed = names.sort() { $0 > $1 }
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 strings = numbers.map {
(var number) -> String in
var output = ""
while number > 0 {
output = digitNames[number % 10]! + output
number /= 10
}
return output
}
print(strings)
func makeIncrementor(forIncrement amount: Int) -> () -> Int {
var runningTotal = 0
func incrementor() -> Int {
runningTotal += amount
return runningTotal
}
return incrementor
}
let incrementByTen = makeIncrementor(forIncrement: 10)
incrementByTen()
incrementByTen()
incrementByTen()
let alsoIncrementByTen = incrementByTen
alsoIncrementByTen()
makeIncrementor.dynamicType
incrementByTen.dynamicType
func someFunctionWithNoescapeClosure(@noescape closure: () -> Void) {
closure()
}
var completionHandlers: [() -> Void] = []
func someFunctionWithEscapingClosure(completionHandler: ()->Void) {
completionHandlers.append(completionHandler)
}
class SomeClass {
var x = 10
func doSomething(){
someFunctionWithEscapingClosure { self.x = 100 }
someFunctionWithNoescapeClosure { x = 200 }
}
}
let instance = SomeClass()
instance.doSomething()
print(instance.x)
completionHandlers.first?()
print(instance.x)
var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
print(customersInLine.count)
let customerProvider = {customersInLine.removeAtIndex(0)}
print(customersInLine.count)
customerProvider.dynamicType
print("Now serving \(customerProvider())!")
print(customersInLine.count)
func serveCustomer(customerProvider:() -> String) {
print("Now serving \(customerProvider())!")
}
serveCustomer( { customersInLine.removeAtIndex(0) } )
func serveCustomer(@autoclosure customerProvider:()->String){
print("Now serving \(customerProvider())!")
}
serveCustomer(customersInLine.removeAtIndex(0))
// customersInLine is ["Barry", "Daniella"]
var customerProviders: [() -> String] = []
func collectCustomerProviders(@autoclosure(escaping) customerProvider: () -> String) {
customerProviders.append(customerProvider)
}
collectCustomerProviders(customersInLine.removeAtIndex(0))
collectCustomerProviders(customersInLine.removeAtIndex(0))
print("Collected \(customerProviders.count) closures.")
// prints "Collected 2 closures."
for customerProvider in customerProviders {
print("Now serving \(customerProvider())!")
}
// prints "Now serving Barry!"
// prints "Now serving Daniella!"
| apache-2.0 | 80fb9f92064c150be7581531dc86b616 | 19.581006 | 155 | 0.70684 | 3.676647 | false | false | false | false |
danthorpe/Examples | Operations/Permissions/Permissions/PhotosViewController.swift | 1 | 2162 | //
// PhotosViewController.swift
// Permissions
//
// Created by Daniel Thorpe on 14/04/2016.
// Copyright © 2016 Daniel Thorpe. All rights reserved.
//
import Foundation
import Photos
import Operations
class PhotosViewController: PermissionViewController {
override func viewDidLoad() {
super.viewDidLoad()
title = NSLocalizedString("Photos", comment: "Address Book")
permissionNotDetermined.informationLabel.text = "We haven't yet asked permission to access your Photo Library."
permissionGranted.instructionLabel.text = "Perform an operation with the Photos Library"
permissionGranted.button.setTitle("Do something with the library", forState: .Normal)
operationResults.informationLabel.text = "These are the results of our Photos Operation"
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
determineAuthorizationStatus()
}
override func conditionsForState(state: State, silent: Bool) -> [Condition] {
return configureConditionsForState(state, silent: silent)(AuthorizedFor(Capability.Photos()))
}
func photosEnabled(enabled: Bool, withAuthorization status: PHAuthorizationStatus) {
switch (enabled, status) {
case (false, _):
print("Photos Library are not enabled")
case (true, .Authorized):
self.state = .Authorized
case (true, .Restricted), (true, .Denied):
self.state = .Denied
default:
self.state = .Unknown
}
}
func determineAuthorizationStatus() {
let status = GetAuthorizationStatus(Capability.Photos(), completion: photosEnabled)
queue.addOperation(status)
}
override func requestPermission() {
let authorize = Authorize(Capability.Photos(), completion: photosEnabled)
queue.addOperation(authorize)
}
override func performOperation() {
let block = BlockOperation { (continueWithError: BlockOperation.ContinuationBlockType) in
print("It's now safe to use the Photos Library.")
}
queue.addOperation(block)
}
}
| mit | 8f1483ff1346fcb78077deac5acf699f | 31.253731 | 119 | 0.67839 | 5.145238 | false | false | false | false |
EasySwift/EasySwift | Carthage/Checkouts/Kingfisher/Tests/KingfisherTests/ImageProcessorTests.swift | 2 | 7748 | //
// ImageProcessorTests.swift
// Kingfisher
//
// Created by Wei Wang on 2016/08/30.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import XCTest
import Kingfisher
class ImageProcessorTests: XCTestCase {
let imageNames = ["kingfisher.jpg", "onevcat.jpg", "unicorn.png"]
var nonPNGIamgeNames: [String] {
return imageNames.filter { !$0.contains(".png") }
}
func imageData(_ noAlpha: Bool = false) -> [Data] {
return noAlpha ? nonPNGIamgeNames.map { Data(fileName: $0) } : imageNames.map { Data(fileName: $0) }
}
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testRenderEqual() {
let image1 = Image(data: testImageData! as Data)!
let image2 = Image(data: testImagePNGData)!
XCTAssertTrue(image1.renderEqual(to: image2))
}
func testRoundCornerProcessor() {
let p = RoundCornerImageProcessor(cornerRadius: 40)
XCTAssertEqual(p.identifier, "com.onevcat.Kingfisher.RoundCornerImageProcessor(40.0)")
checkProcessor(p, with: "round-corner-40")
}
func testRoundCornerWithResizingProcessor() {
let p = RoundCornerImageProcessor(cornerRadius: 60, targetSize: CGSize(width: 100, height: 100))
XCTAssertEqual(p.identifier, "com.onevcat.Kingfisher.RoundCornerImageProcessor(60.0_(100.0, 100.0))")
checkProcessor(p, with: "round-corner-60-resize-100")
}
func testResizingProcessor() {
let p = ResizingImageProcessor(targetSize: CGSize(width: 120, height: 120))
XCTAssertEqual(p.identifier, "com.onevcat.Kingfisher.ResizingImageProcessor((120.0, 120.0))")
checkProcessor(p, with: "resize-120")
}
func testBlurProcessor() {
let p = BlurImageProcessor(blurRadius: 10)
XCTAssertEqual(p.identifier, "com.onevcat.Kingfisher.BlurImageProcessor(10.0)")
// Alpha convolving would vary due to context. So we do not test blur for PNGs.
// See results in Resource folder.
checkProcessor(p, with: "blur-10", noAlpha: true)
}
func testOverlayProcessor() {
let p1 = OverlayImageProcessor(overlay: .red)
XCTAssertEqual(p1.identifier, "com.onevcat.Kingfisher.OverlayImageProcessor(#ff0000ff_0.5)")
checkProcessor(p1, with: "overlay-red")
let p2 = OverlayImageProcessor(overlay: .red, fraction: 0.7)
XCTAssertEqual(p2.identifier, "com.onevcat.Kingfisher.OverlayImageProcessor(#ff0000ff_0.7)")
checkProcessor(p2, with: "overlay-red-07")
}
func testTintProcessor() {
let color = Color.yellow.withAlphaComponent(0.2)
let p = TintImageProcessor(tint: color)
XCTAssertEqual(p.identifier, "com.onevcat.Kingfisher.TintImageProcessor(#ffff0033)")
checkProcessor(p, with: "tint-yellow-02")
}
func testColorControlProcessor() {
let p = ColorControlsProcessor(brightness: 0, contrast: 1.1, saturation: 1.2, inputEV: 0.7)
XCTAssertEqual(p.identifier, "com.onevcat.Kingfisher.ColorControlsProcessor(0.0_1.1_1.2_0.7)")
checkProcessor(p, with: "color-control-b00-c11-s12-ev07")
}
func testBlackWhiteProcessor() {
let p = BlackWhiteProcessor()
XCTAssertEqual(p.identifier, "com.onevcat.Kingfisher.BlackWhiteProcessor")
checkProcessor(p, with: "b&w")
}
func testCompositionProcessor() {
let p = BlurImageProcessor(blurRadius: 4) >> RoundCornerImageProcessor(cornerRadius: 60)
XCTAssertEqual(p.identifier, "com.onevcat.Kingfisher.BlurImageProcessor(4.0)|>com.onevcat.Kingfisher.RoundCornerImageProcessor(60.0)")
// Alpha convolving would vary due to context. So we do not test blur for PNGs.
// See results in Resource folder.
checkProcessor(p, with: "blur-4-round-corner-60", noAlpha: true)
}
func testCIImageProcessor() {
let p = TestCIImageProcessor(filter: .tint(Color.yellow.withAlphaComponent(0.2)))
checkProcessor(p, with: "tint-yellow-02")
}
}
struct TestCIImageProcessor: CIImageProcessor {
let identifier = "com.onevcat.kingfishertest.tint"
let filter: Filter
}
extension ImageProcessorTests {
func checkProcessor(_ p: ImageProcessor, with suffix: String, noAlpha: Bool = false) {
let specifiedSuffix = getSuffix(with: suffix)
let filteredImageNames = noAlpha ? nonPNGIamgeNames : imageNames
let targetImages = filteredImageNames
.map { $0.replacingOccurrences(of: ".", with: "-\(specifiedSuffix).") }
.map { Image(fileName: $0) }
let resultImages = imageData(noAlpha: noAlpha).flatMap { p.process(item: .data($0), options: []) }
checkImagesEqual(targetImages: targetImages, resultImages: resultImages, for: specifiedSuffix)
}
func checkImagesEqual(_ targetImages: [Image], resultImages: [Image], for suffix: String) {
XCTAssertEqual(targetImages.count, resultImages.count)
for (i, (resultImage, targetImage)) in zip(resultImages, targetImages).enumerated() {
guard resultImage.renderEqual(to: targetImage) else {
let originalName = imageNames[i]
let excutingName = originalName.replacingOccurrences(of: ".", with: "-\(suffix).")
XCTFail("Result image is not the same to target. Failed at: \(excutingName)) for \(originalName)")
let t = targetImage.write("target-\(excutingName)")
let r = resultImage.write("result-\(excutingName)")
print("Expected: \(t)")
print("But Got: \(r)")
continue
}
}
}
func getSuffix(with ori: String) -> String {
#if os(macOS)
return "\(ori)-mac"
#else
return ori
#endif
}
}
extension ImageProcessorTests {
//Helper Writer
func _testWrite() {
let p = BlurImageProcessor(blurRadius: 4) >> RoundCornerImageProcessor(cornerRadius: 60)
let suffix = "blur-4-round-corner-60-mac"
let resultImages = imageData().flatMap { p.process(item: .data($0), options: []) }
for i in 0..<resultImages.count {
resultImages[i].write(imageNames[i].replacingOccurrences(of: ".", with: "-\(suffix)."))
}
}
}
| apache-2.0 | 6c842d9e8120306218bf9181e4ff1562 | 40.433155 | 142 | 0.659009 | 4.206298 | false | true | false | false |
catloafsoft/AudioKit | AudioKit/Common/Nodes/Effects/Filters/High Pass Butterworth Filter/AKHighPassButterworthFilter.swift | 1 | 3416 | //
// AKHighPassButterworthFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// These filters are Butterworth second-order IIR filters. They offer an almost
/// flat passband and very good precision and stopband attenuation.
///
/// - parameter input: Input node to process
/// - parameter cutoffFrequency: Cutoff frequency. (in Hertz)
///
public class AKHighPassButterworthFilter: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKHighPassButterworthFilterAudioUnit?
internal var token: AUParameterObserverToken?
private var cutoffFrequencyParameter: AUParameter?
/// Cutoff frequency. (in Hertz)
public var cutoffFrequency: Double = 500 {
willSet(newValue) {
if cutoffFrequency != newValue {
cutoffFrequencyParameter?.setValue(Float(newValue), originator: token!)
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this filter node
///
/// - parameter input: Input node to process
/// - parameter cutoffFrequency: Cutoff frequency. (in Hertz)
///
public init(
_ input: AKNode,
cutoffFrequency: Double = 500) {
self.cutoffFrequency = cutoffFrequency
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = 0x62746870 /*'bthp'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKHighPassButterworthFilterAudioUnit.self,
asComponentDescription: description,
name: "Local AKHighPassButterworthFilter",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKHighPassButterworthFilterAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
guard let tree = internalAU?.parameterTree else { return }
cutoffFrequencyParameter = tree.valueForKey("cutoffFrequency") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.cutoffFrequencyParameter!.address {
self.cutoffFrequency = Double(value)
}
}
}
cutoffFrequencyParameter?.setValue(Float(cutoffFrequency), originator: token!)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
| mit | 6a9af41651de164ee1e27f2bb42c08cd | 30.925234 | 100 | 0.651932 | 5.456869 | false | false | false | false |
srn214/Floral | Floral/Pods/CleanJSON/CleanJSON/Classes/DecodingError+CleanJSON.swift | 1 | 4368 | //
// DecodingError+CleanJSON.swift
// CleanJSON
//
// Created by Pircate([email protected]) on 2018/10/11
// Copyright © 2018 Pircate. All rights reserved.
//
import Foundation
extension DecodingError {
/// Returns a `.typeMismatch` error describing the expected type.
///
/// - parameter path: The path of `CodingKey`s taken to decode a value of this type.
/// - parameter expectation: The type expected to be encountered.
/// - parameter reality: The value that was encountered instead of the expected type.
/// - returns: A `DecodingError` with the appropriate path and debug description.
static func _typeMismatch(at path: [CodingKey], expectation: Any.Type, reality: Any) -> DecodingError {
let description = "Expected to decode \(expectation) but found \(_typeDescription(of: reality)) instead."
return .typeMismatch(expectation, Context(codingPath: path, debugDescription: description))
}
/// Returns a description of the type of `value` appropriate for an error message.
///
/// - parameter value: The value whose type to describe.
/// - returns: A string describing `value`.
/// - precondition: `value` is one of the types below.
fileprivate static func _typeDescription(of value: Any) -> String {
if value is NSNull {
return "a null value"
} else if value is NSNumber /* FIXME: If swift-corelibs-foundation isn't updated to use NSNumber, this check will be necessary: || value is Int || value is Double */ {
return "a number"
} else if value is String {
return "a string/data"
} else if value is [Any] {
return "an array"
} else if value is [String : Any] {
return "a dictionary"
} else {
return "\(type(of: value))"
}
}
}
extension DecodingError {
struct Keyed {
static func keyNotFound<Key: CodingKey>(_ key: Key, codingPath: [CodingKey]) -> DecodingError {
return .keyNotFound(
key,
DecodingError.Context(
codingPath: codingPath,
debugDescription: "No value associated with key \("\(key) (\"\(key.stringValue)\")")."))
}
static func valueNotFound(_ type: Any.Type, codingPath: [CodingKey]) -> DecodingError {
return DecodingError.valueNotFound(
type,
DecodingError.Context(
codingPath: codingPath,
debugDescription: "Expected \(type) value but found null instead."))
}
}
}
extension DecodingError {
struct Unkeyed {
static func valueNotFound(
_ type: Any.Type,
codingPath: [CodingKey],
currentIndex: Int,
isAtEnd: Bool = false) -> DecodingError {
let debugDescription = isAtEnd
? "Unkeyed container is at end."
: "Expected \(type) but found null instead."
return DecodingError.valueNotFound(
type,
DecodingError.Context(
codingPath: codingPath + [CleanJSONKey(index: currentIndex)],
debugDescription: debugDescription))
}
}
}
extension DecodingError {
struct Nested {
static func keyNotFound<Key: CodingKey>(_ key: Key, codingPath: [CodingKey], isUnkeyed: Bool = false) -> DecodingError {
let debugDescription = isUnkeyed
? "Cannot get UnkeyedDecodingContainer -- no value found for key \("\(key) (\"\(key.stringValue)\")")"
: "Cannot get \(KeyedDecodingContainer<Key>.self) -- no value found for key \("\(key) (\"\(key.stringValue)\")")"
return DecodingError.keyNotFound(
key,
DecodingError.Context(
codingPath: codingPath,
debugDescription: debugDescription))
}
static func valueNotFound(_ type: Any.Type, codingPath: [CodingKey], debugDescription: String) -> DecodingError {
return DecodingError.valueNotFound(
type,
DecodingError.Context(
codingPath: codingPath,
debugDescription: debugDescription))
}
}
}
| mit | 3d33475f6542b9424bfa43c8941f8f56 | 38.342342 | 175 | 0.583696 | 5.280532 | false | false | false | false |
Mazy-ma/DemoBySwift | EmotionKeyboard/EmotionKeyboard/InputToolView.swift | 1 | 4048 | //
// InputToolView.swift
// EmotionKeyboard
//
// Created by Mazy on 2017/9/1.
// Copyright © 2017年 Mazy. All rights reserved.
//
import UIKit
class InputToolView: UIView, NibLoadable {
@IBOutlet weak var textField: UITextField!
@IBOutlet weak var sendButton: UIButton!
var emotionButtonClickClosure: ((UIButton)->Void)?
fileprivate var flowLayout: CollectionViewHorizontalFlowLayout = CollectionViewHorizontalFlowLayout(rows: 3, cols: 7)
fileprivate lazy var emotionButton = UIButton(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
fileprivate var emotionView: EmotionView!
fileprivate lazy var emotionsArray: [[String]] = [[String]]()
override func awakeFromNib() {
super.awakeFromNib()
emotionButton.setImage(UIImage(named: "chat_btn_emoji"), for: .normal)
emotionButton.setImage(UIImage(named: "chat_btn_keyboard"), for: .selected)
emotionButton.addTarget(self, action: #selector(emotionButtonClick), for: .touchUpInside)
textField.rightView = emotionButton
textField.rightViewMode = .always
flowLayout = CollectionViewHorizontalFlowLayout(rows: 3, cols: 7)
flowLayout.minimumLineSpacing = 10
flowLayout.minimumInteritemSpacing = 10
flowLayout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
flowLayout.scrollDirection = .horizontal
let property = TitleViewProperty()
property.isInTop = true
emotionView = EmotionView(frame: CGRect(x: 0, y: 100, width: UIScreen.main.bounds.width, height: 260), titles: ["普通","会员专属"] ,layout: flowLayout, property: property)
emotionView.dataSource = self
emotionView.delegate = self
emotionView.register(nib: UINib(nibName: "NormalEmotionCell", bundle: nil), forCellWithReuseIdentifier: normalEmotionCellID)
loadEmotionData()
}
func loadEmotionData() {
guard let normalPath = Bundle.main.path(forResource: "QHNormalEmotionSort.plist", ofType: nil) else { return }
let normalEmotions: [String] = NSArray(contentsOfFile: normalPath) as! [String]
emotionsArray.append(normalEmotions)
guard let giftPath = Bundle.main.path(forResource: "QHSohuGifSort.plist", ofType: nil) else { return }
let giftEmotions: [String] = NSArray(contentsOfFile: giftPath) as! [String]
emotionsArray.append(giftEmotions)
}
@objc fileprivate func emotionButtonClick(button: UIButton) {
button.isSelected = !button.isSelected
let range = textField.selectedTextRange
textField.resignFirstResponder()
textField.inputView = textField.inputView == nil ? emotionView : nil
textField.becomeFirstResponder()
textField.selectedTextRange = range
}
}
extension InputToolView: EmotionViewDataSource {
func numberOfSections(in emotionView: EmotionView) -> Int {
return emotionsArray.count
}
func numberOfItemsInSection(emotionView: EmotionView, section: Int) -> Int {
return emotionsArray[section].count
}
func collectionView(emotionView: EmotionView, collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell: NormalEmotionCell = collectionView.dequeueReusableCell(withReuseIdentifier: normalEmotionCellID, for: indexPath) as! NormalEmotionCell
cell.emotionName = emotionsArray[indexPath.section][indexPath.row]
return cell
}
}
extension InputToolView: EmotionViewDelegate {
func collectionView(collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let emotionString = emotionsArray[indexPath.section][indexPath.row]
print(emotionString)
if emotionString == "delete-n" {
self.textField.deleteBackward()
return
}
self.textField.insertText(emotionString)
}
}
| apache-2.0 | a2697dcf2f7d52c3b26b594eb93a4bea | 36.342593 | 173 | 0.681379 | 4.942402 | false | false | false | false |
galv/reddift | reddiftSample/AccountViewController.swift | 1 | 3214 | //
// AccountViewController.swift
// reddift
//
// Created by sonson on 2015/04/13.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import reddift
class AccountViewController: UITableViewController {
var names:[String] = []
@IBAction func addAccount(sender:AnyObject) {
OAuth2Authorizer.sharedInstance.challengeWithAllScopes()
}
func reload() {
names.removeAll(keepCapacity: false)
names += OAuth2TokenRepository.savedNamesInKeychain()
tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "didSaveToken:", name: OAuth2TokenRepositoryDidSaveToken, object: nil)
reload()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
if names.indices ~= indexPath.row {
let name:String = names[indexPath.row]
cell.textLabel?.text = name
}
return cell
}
func didSaveToken(notification:NSNotification) {
reload()
}
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return true
}
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
if names.indices ~= indexPath.row {
let name:String = names[indexPath.row]
OAuth2TokenRepository.removeFromKeychainTokenWithName(name)
names.removeAtIndex(indexPath.row)
tableView.beginUpdates()
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
tableView.endUpdates()
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "ToUserViewController" {
if let con = segue.destinationViewController as? UserViewController {
if let selectedIndexPath = tableView.indexPathForSelectedRow {
if names.indices ~= selectedIndexPath.row {
let name:String = names[selectedIndexPath.row]
let result = OAuth2TokenRepository.restoreFromKeychainWithName(name)
switch result {
case .Failure(let error):
print(error.description)
case .Success(let token):
con.session = Session(token: token)
}
}
}
}
}
}
}
| mit | 7bfbe5caf4b4f8aef7eef48f076308ea | 34.296703 | 157 | 0.629826 | 5.715302 | false | false | false | false |
LeoFangQ/CMSwiftUIKit | Source/CMCycleScrollView/PageControl/CMAnimatedDotView.swift | 1 | 1818 | //
// CMAnimatedDotView.swift
// YFStore
//
// Created by Fang on 2016/12/20.
// Copyright © 2016年 yfdyf. All rights reserved.
//
import UIKit
class CMAnimatedDotView: CMAbstractDotView {
let kAnimateDuration = 1
var dotColor: UIColor? {
didSet {
self.layer.borderColor = dotColor?.cgColor
}
}
override init() {
super.init()
initialization()
}
override init(frame: CGRect) {
super.init(frame: frame)
initialization()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func initialization() {
self.dotColor = .white
self.backgroundColor = .clear
self.layer.cornerRadius = self.frame.size.width / 2
self.layer.borderColor = UIColor.white.cgColor
self.layer.borderWidth = 2
}
override func changeActivityState(active: Bool) {
if active{
self.animateToActiveState()
}else{
self.animateToDeactiveState()
}
}
func animateToActiveState() {
UIView.animate(withDuration: TimeInterval(kAnimateDuration), delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: -20, options: .curveLinear, animations: {
self.backgroundColor = self.dotColor
self.transform = CGAffineTransform(scaleX: 1.4, y: 1.4)
}, completion: nil)
}
func animateToDeactiveState() {
UIView.animate(withDuration: TimeInterval(kAnimateDuration), delay: 0, usingSpringWithDamping: 10, initialSpringVelocity: 0, options: .curveLinear, animations: {
self.backgroundColor = .clear
self.transform = CGAffineTransform.identity
}, completion: nil)
}
}
| mit | fb324c2de218010d464da093eeae14ca | 26.5 | 173 | 0.616529 | 4.571788 | false | false | false | false |
honghaoz/UW-Quest-iOS | UW Quest/Network/QuestClient.swift | 1 | 13149 | //
// QuestClient.swift
// UW Quest
//
// Created by Honghao on 12/30/14.
// Copyright (c) 2014 Honghao. All rights reserved.
//
import Foundation
let kQuestLoginURL = "https://quest.pecs.uwaterloo.ca/psp/SS/?cmd=login&languageCd=ENG"
let kQuestLogoutURL = "https://quest.pecs.uwaterloo.ca/psp/SS/ACADEMIC/SA/?cmd=logout"
let kStudentCenterURL_SA = "https://quest.pecs.uwaterloo.ca/psc/SS/ACADEMIC/SA/c/SA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL"
let kStudentCenterURL_HRMS = "https://quest.pecs.uwaterloo.ca/psc/SS/ACADEMIC/HRMS/c/SA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL"
private let _sharedClient = QuestClient(baseURL: NSURL(string: ""))
class QuestClient: AFHTTPSessionManager {
var icsid: String = ""
var currentStateNum: Int = 0
var currentURLString: String!
var isUndergraduate: Bool = true
var isLogin: Bool = false
enum PostPage {
case None
case PersonalInformation
case Enroll
case MyClassScheduleTerm
case Finance
// ...
}
var currentPostPage: PostPage = .None
var basicPostData: Dictionary<String, String> {
return [
"ICAJAX": "1",
"ICNAVTYPEDROPDOWN":"0",
"ICType":"Panel",
"ICElementNum":"0",
"ICStateNum": String(currentStateNum),
"ICAction":"", // Need to change
"ICXPos":"0",
"ICYPos":"0",
"ResponsetoDiffFrame":"-1",
"TargetFrameName":"None",
"FacetPath":"None",
"ICFocus":"",
"ICSaveWarningFilter":"0",
"ICChanged":"-1",
"ICResubmit":"0",
"ICSID": icsid, // Need to change
"ICActionPrompt":"false",
"ICFind":"",
"ICAddCount":"",
"ICAPPCLSDATA":"",
]
}
init(baseURL url: NSURL!) {
super.init(baseURL: url, sessionConfiguration: nil)
setup()
}
override init(baseURL url: NSURL!, sessionConfiguration configuration: NSURLSessionConfiguration!) {
super.init(baseURL: url, sessionConfiguration: configuration)
setup()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
func setup() {
logInfo("Service inited")
self.responseSerializer = AFHTTPResponseSerializer() as AFHTTPResponseSerializer
self.requestSerializer = AFHTTPRequestSerializer()
self.reachabilityManager.setReachabilityStatusChangeBlock { (status) -> Void in
switch status {
case .ReachableViaWWAN, AFNetworkReachabilityStatus.ReachableViaWiFi:
logInfo(".Reachable")
self.operationQueue.suspended = false
case .NotReachable:
logInfo(".NotReachable")
self.operationQueue.suspended = true
case .Unknown:
logInfo(".Unknown")
default:
break
}
}
self.reachabilityManager.startMonitoring()
}
class var sharedClient: QuestClient {
return _sharedClient
}
}
// MARK: Helper methods
extension QuestClient {
func getHtmlContentFromResponse(response: AnyObject) -> NSString? {
let htmlNSString = NSString(data: response as! NSData, encoding: NSUTF8StringEncoding)
return htmlNSString
}
func getICSID(response: AnyObject) -> String? {
logVerbose()
let html = getHtmlContentFromResponse(response)
if html == nil {
return nil
}
let element = html!.peekAtSearchWithXPathQuery("//*[@id=\"ICSID\"]")
if element != nil {
return element!.objectForKey("value")
}
return nil
}
func pageIsValid(response: AnyObject) -> Bool {
logVerbose()
let icsid = getICSID(response)
if icsid == nil {
return false
} else {
return true
}
}
func getStateNum(response: AnyObject) -> Int? {
logVerbose()
let html = getHtmlContentFromResponse(response)
if html == nil {
return nil
}
let element = html!.peekAtSearchWithXPathQuery("//*[@id=\"ICStateNum\"]")
if element != nil {
return element!.objectForKey("value").toInt()
}
return nil
}
func updateState(response: AnyObject) -> Bool {
logVerbose()
return updateICSID(response) && updateStateNum(response)
}
func updateICSID(response: AnyObject) -> Bool{
logVerbose()
let icsidString = getICSID(response)
if icsidString == nil { return false }
self.icsid = icsidString!
return true
}
func updateStateNum(response: AnyObject) -> Bool {
logVerbose()
let newNum = getStateNum(response)
if newNum == nil { return false }
self.currentStateNum = newNum!
return true
}
func isCookieExpired() -> Bool {
logVerbose()
let cookie = NSHTTPCookieStorage.cookieForKey("PS_TOKENEXPIRE", urlString: currentURLString)
let lastUpdateDateString: String = cookie!.value!
let formatter = NSDateFormatter()
formatter.dateFormat = "dd_MMM_y_HH:mm:ss_z"
let lastUpdateDate = formatter.dateFromString(lastUpdateDateString)!
let currentDate = NSDate()
let interval = currentDate.timeIntervalSinceDate(lastUpdateDate)
if interval >= 20 * 60 {
logInfo("Cookies is expired")
return true
} else {
logInfo("Cookies is not expired")
return false
}
}
func isOnLoginPage(response: AnyObject) -> Bool {
logVerbose()
let html = getHtmlContentFromResponse(response)
if html != nil {
let element = html!.peekAtSearchWithXPathQuery("//*[@id='login']//*[@type='submit']")
if element != nil {
if element!.objectForKey("value") == "Sign in" {
return true
}
}
}
return false
}
func usernamePasswordInvalid(response: AnyObject) -> Bool {
logVerbose()
let html = getHtmlContentFromResponse(response)
if html != nil {
let element = html!.peekAtSearchWithXPathQuery("//*[@id='login']//*[@class='PSERRORTEXT']")
if element != nil {
if element!.text() == "Your User ID and/or Password are invalid." {
return true
}
}
}
return false
}
func checkIsUndergraduate(response: AnyObject) -> Bool? {
logVerbose()
//*/table[@id="ACE_DERIVED_SSS_SCL_SS_ACAD_INFO_LINK"]//*/table[@id="ACE_$ICField280"]//tr//a
let html = getHtmlContentFromResponse(response)
if html != nil {
var elements = html!.searchWithXPathQuery("//*/table[@id='ACE_DERIVED_SSS_SCL_SS_ACAD_INFO_LINK']//*/table[@id='ACE_$ICField280']//tr//a")
var containUndergrad = elements.filter({
$0.text().containsSubString("Undergrad")
})
if containUndergrad.count > 0 {
self.isUndergraduate = true
return true
} else {
self.isUndergraduate = false
return false
}
}
return nil
}
func getBasicParameters() -> Dictionary<String, String> {
var newDict = self.basicPostData
newDict["ICStateNum"] = String(self.currentStateNum)
newDict["ICSID"] = self.icsid
return newDict
}
}
// MARK: Basic operations
extension QuestClient {
func loginWithUsename(username: String, password: String,
success: ((response: AnyObject?, json: JSON?) -> ())? = nil,
failure: ((errorMessage: String, error: NSError) -> ())? = nil)
{
logVerbose("username: \(username), password: \(password)")
let parameters: Dictionary = [
"userid": username,
"pwd": password,
"timezoneOffset": "0",
"httpPort": ""
]
currentURLString = kQuestLogoutURL
self.POST(kQuestLoginURL, parameters: parameters, success: { (task, response) -> Void in
logVerbose("success")
self.getStudentCenter(success: success, failure: failure)
}, failure: { (task, error) -> Void in
logVerbose("failed: \(error.localizedDescription)")
failure?(errorMessage: "Login Failed", error: error)
})
}
func logout(success: ((response: AnyObject?, json: JSON?) -> ())? = nil,
failure: ((errorMessgae: String, error: NSError) -> ())? = nil) {
currentURLString = kQuestLogoutURL
self.GET(kQuestLogoutURL, parameters: nil, success: { (task, response) -> Void in
logInfo("Success")
self.isLogin = false
success?(response: response, json: nil)
}, failure: { (task, error) -> Void in
logError("Failed: \(error.localizedDescription)")
failure?(errorMessgae: "Logout Failed", error: error)
})
}
func getStudentCenter(success: ((response: AnyObject?, json: JSON?) -> ())? = nil, failure: ((errorMessage: String, error: NSError) -> ())? = nil) {
logVerbose()
// https://quest.pecs.uwaterloo.ca/psc/SS/ACADEMIC/SA/c/SA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL?PORTALPARAM_PTCNAV=HC_SSS_STUDENT_CENTER&EOPP.SCNode=SA&EOPP.SCPortal=ACADEMIC&EOPP.SCName=CO_EMPLOYEE_SELF_SERVICE&EOPP.SCLabel=Self%20Service&EOPP.SCPTfname=CO_EMPLOYEE_SELF_SERVICE&FolderPath=PORTAL_ROOT_OBJECT.CO_EMPLOYEE_SELF_SERVICE.HC_SSS_STUDENT_CENTER&IsFolder=false&PortalActualURL=https%3a%2f%2fquest.pecs.uwaterloo.ca%2fpsc%2fSS%2fACADEMIC%2fSA%2fc%2fSA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL&PortalRegistryName=ACADEMIC&PortalServletURI=https%3a%2f%2fquest.pecs.uwaterloo.ca%2fpsp%2fSS%2f&PortalURI=https%3a%2f%2fquest.pecs.uwaterloo.ca%2fpsc%2fSS%2f&PortalHostNode=SA&NoCrumbs=yes&PortalKeyStruct=yes
let parameters: Dictionary = [
"PORTALPARAM_PTCNAV": "HC_SSS_STUDENT_CENTER",
"EOPP.SCNode": "SA",
"EOPP.SCPortal": "ACADEMIC",
"EOPP.SCName": "CO_EMPLOYEE_SELF_SERVICE",
"EOPP.SCLabel": "Self Service",
"EOPP.SCPTfname": "CO_EMPLOYEE_SELF_SERVICE",
"FolderPath": "PORTAL_ROOT_OBJECT.CO_EMPLOYEE_SELF_SERVICE.HC_SSS_STUDENT_CENTER",
"IsFolder": "false",
"PortalActualURL": "https://quest.pecs.uwaterloo.ca/psc/SS/ACADEMIC/SA/c/SA_LEARNER_SERVICES.SSS_STUDENT_CENTER.GBL",
"PortalRegistryName": "ACADEMIC",
"PortalServletURI": "https://quest.pecs.uwaterloo.ca/psp/SS/",
"PortalURI": "https://quest.pecs.uwaterloo.ca/psc/SS/",
"PortalHostNode": "SA",
"NoCrumbs": "yes",
"PortalKeyStruct": "yes"
]
currentURLString = kStudentCenterURL_SA
self.GET(kStudentCenterURL_SA, parameters: parameters, success: { (task, response) -> Void in
logVerbose("Success")
if !self.isOnLoginPage(response) {
if self.pageIsValid(response) {
logInfo("isUndergrad: \(self.checkIsUndergraduate(response))")
logInfo("ICSID: \(self.getICSID(response))")
logInfo("StateNum: \(self.getStateNum(response))")
if self.updateState(response) {
success?(response: response, json: nil)
} else {
failure?(errorMessage: "Update State Failed", error: NSError(domain: "StudentCenter", code: 1003, userInfo: nil))
}
} else {
failure?(errorMessage: "Page invalid", error: NSError(domain: "StudentCenter", code: 1002, userInfo: nil))
}
} else {
if self.usernamePasswordInvalid(response) {
failure?(errorMessage: "Username/Password invalid", error: NSError(domain: "Login", code: 1000, userInfo: nil))
} else {
failure?(errorMessage: "Unknown", error: NSError(domain: "Login", code: 1001, userInfo: nil))
}
}
}, failure: { (task, error) -> Void in
logError("Failed: \(error.localizedDescription)")
failure?(errorMessage: "Go to StudentCenter Failed", error: error)
})
}
}
// MARK: Helpers
extension QuestClient {
func transform2dTo1d(twoDArray: [[String]]) -> [String] {
var oneDArray = [String]()
let rowsCount = twoDArray.count
for row in 1 ..< rowsCount {
var stringToAppend = ""
for col in twoDArray[row] {
if col.length > 0 {
stringToAppend = col
}
}
// if stringToAppend.isEmpty {
// stringToAppend = "-"
// }
oneDArray.append(stringToAppend)
}
return oneDArray
}
} | apache-2.0 | 42b0fa4a5a83f17d92941c5d16c0d902 | 36.679083 | 722 | 0.578751 | 4.158444 | false | false | false | false |
stormpath/stormpath-sdk-swift | Stormpath/Core/Stormpath.swift | 1 | 8043 | //
// Stormpath.swift
// Stormpath
//
// Created by Adis on 16/11/15.
// Copyright © 2015 Stormpath. All rights reserved.
//
import Foundation
/// Callback for Stormpath API responses that respond with a success/fail.
public typealias StormpathSuccessCallback = (Bool, NSError?) -> Void
/// Callback for Stormpath API responses that respond with an account object.
public typealias StormpathAccountCallback = (Account?, NSError?) -> Void
/**
Stormpath represents the state of the application's connection to the Stormpath
Framework server. It allows you to connect to the Stormpath Framework
Integration API, register, login, and stores the current account's access and
refresh tokens securely. All callbacks to the application are handled on the
main thread.
*/
public final class Stormpath: NSObject {
/// Singleton representing the primary Stormpath instance using the default configuration.
public static let sharedSession = Stormpath(identifier: "default")
/// Configuration parameter for the Stormpath object. Can be changed.
public var configuration = StormpathConfiguration.defaultConfiguration
/// Reference to the API Service.
var apiService: APIService!
/// Reference to the Social Login Service.
var socialLoginService: SocialLoginService!
/// Reference to the Keychain Service.
var keychain: KeychainService!
/**
Initializes the Stormpath object with a default configuration. The
identifier is used to namespace the current state of the object, so that on
future loads we can find the saved credentials from the right location. The
default identifier is "default".
*/
public init(identifier: String) {
super.init()
apiService = APIService(withStormpath: self)
keychain = KeychainService(withIdentifier: identifier)
socialLoginService = SocialLoginService(withStormpath: self)
}
/**
This method registers an account from the data provided.
- parameters:
- account: A Registration Model object with the account data you want to
register.
- completionHandler: The completion block to be invoked after the API
request is finished. It returns an account object.
*/
public func register(_ account: RegistrationModel, completionHandler: StormpathAccountCallback? = nil) {
apiService.register(newAccount: account, completionHandler: completionHandler)
}
/**
Logs in an account and assumes that the login path is behind the /login
relative path. This method also stores the account session tokens for later
use.
- parameters:
- username: Account's email or username.
- password: Account password.
- completionHandler: The completion block to be invoked after the API
request is finished. If the method fails, the error will be passed in
the completion.
*/
public func login(_ username: String, password: String, completionHandler: StormpathSuccessCallback? = nil) {
apiService.login(username, password: password, completionHandler: completionHandler)
}
/**
Begins a login flow with a social provider, presenting or opening up Safari
(iOS8) to handle login. This WILL NOT call back if the user clicks "cancel"
on the login screen, as they never began the login process in the first
place.
- parameters:
- socialProvider: the provider (Facebook, Google, etc) from which you
have an access token
- completionHandler: Callback on success or failure
*/
public func login(socialProvider provider: StormpathSocialProvider, completionHandler: StormpathSuccessCallback? = nil) {
socialLoginService.beginLoginFlow(provider, completionHandler: completionHandler)
}
/**
Logs in an account if you have an access token from a social provider.
- parameters:
- socialProvider: the provider (Facebook, Google, etc) from which you
have an access token
- accessToken: String containing the access token
- completionHandler: A block of code that is called back on success or
failure.
*/
public func login(socialProvider provider: StormpathSocialProvider, accessToken: String, completionHandler: StormpathSuccessCallback? = nil) {
apiService.login(socialProvider: provider, accessToken: accessToken, completionHandler: completionHandler)
}
/**
Logs in an account if you have an authorization code from a social provider.
- parameters:
- socialProvider: the provider (Facebook, Google, etc) from which you have
an access token
- authorizationCode: String containing the authorization code
- completionHandler: A block of code that is called back on success or
failure.
*/
// Making this internal for now, since we don't support auth codes for FB /
// Google
func login(socialProvider provider: StormpathSocialProvider, authorizationCode: String, completionHandler: StormpathSuccessCallback? = nil) {
apiService.login(socialProvider: provider, authorizationCode: authorizationCode, completionHandler: completionHandler)
}
/**
Fetches the account data, and returns it in the form of a dictionary.
- parameters:
- completionHandler: Completion block invoked
*/
public func me(_ completionHandler: StormpathAccountCallback? = nil) {
apiService.me(completionHandler)
}
/**
Logs out the account and clears the sessions tokens.
*/
public func logout() {
apiService.logout()
}
// MARK: Account password reset
/**
Generates an account password reset token and sends an email to the user,
if such email exists.
- parameters:
- email: Account email. Usually from an input.
- completionHandler: The completion block to be invoked after the API
request is finished. This will always succeed if the API call is
successful.
*/
public func resetPassword(_ email: String, completionHandler: StormpathSuccessCallback? = nil) {
apiService.resetPassword(email, completionHandler: completionHandler)
}
/// Deep link handler (iOS9)
public func application(_ app: UIApplication, openURL url: URL, options: [UIApplicationOpenURLOptionsKey: Any]) -> Bool {
return socialLoginService.handleCallbackURL(url)
}
/// Deep link handler (<iOS9)
public func application(_ application: UIApplication, openURL url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return self.application(application, openURL: url, options: [UIApplicationOpenURLOptionsKey: Any]())
}
/**
Provides the last access token fetched by either login or
refreshAccessToken functions. The validity of the token is not verified
upon fetching!
- returns: Access token for your API calls.
*/
internal(set) public var accessToken: String? {
get {
return keychain.accessToken
}
set {
keychain.accessToken = newValue
}
}
/// Refresh token for the current account.
internal(set) public var refreshToken: String? {
get {
return keychain.refreshToken
}
set {
keychain.refreshToken = newValue
}
}
/**
Refreshes the access token and stores it to be available via accessToken
var. Call this function if your token expires.
- parameters:
- completionHandler: Block invoked on function completion. It will have
either a new access token passed as a string, or an error if one
occurred.
*/
public func refreshAccessToken(_ completionHandler: StormpathSuccessCallback? = nil) {
apiService.refreshAccessToken(completionHandler)
}
}
| apache-2.0 | 2147c497d1efa760e3757c7faf670bc4 | 37.113744 | 146 | 0.684656 | 5.332891 | false | false | false | false |
ianyh/Highball | Highball/NSAttributedString+Trim.swift | 1 | 728 | //
// NSAttributedString+Trim.swift
// Highball
//
// Created by Ian Ynda-Hummel on 4/4/16.
// Copyright © 2016 ianynda. All rights reserved.
//
import Foundation
public extension NSAttributedString {
public func attributedStringByTrimmingNewlines() -> NSAttributedString {
var attributedString = self
while attributedString.string.characters.first == "\n" {
attributedString = attributedString.attributedSubstringFromRange(NSMakeRange(1, attributedString.string.characters.count - 1))
}
while attributedString.string.characters.last == "\n" {
attributedString = attributedString.attributedSubstringFromRange(NSMakeRange(0, attributedString.string.characters.count - 1))
}
return attributedString
}
}
| mit | 85b1b841b256428733299411569207a1 | 32.045455 | 129 | 0.771664 | 4.226744 | false | false | false | false |
alblue/swift | test/SILGen/keypath_application.swift | 1 | 6045 |
// RUN: %target-swift-emit-silgen -enable-sil-ownership %s | %FileCheck %s
class A {}
class B {}
protocol P {}
protocol Q {}
// CHECK-LABEL: sil hidden @{{.*}}loadable
func loadable(readonly: A, writable: inout A,
value: B,
kp: KeyPath<A, B>,
wkp: WritableKeyPath<A, B>,
rkp: ReferenceWritableKeyPath<A, B>) {
// CHECK: [[ROOT_TMP:%.*]] = alloc_stack $A
// CHECK: [[ROOT_COPY:%.*]] = copy_value %0
// CHECK: store [[ROOT_COPY]] to [init] [[ROOT_TMP]]
// CHECK: [[KP_COPY:%.*]] = copy_value %3
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
// CHECK: [[RESULT_TMP:%.*]] = alloc_stack $B
// CHECK: apply [[PROJECT]]<A, B>([[RESULT_TMP]], [[ROOT_TMP]], [[KP_COPY]])
// CHECK: [[RESULT:%.*]] = load [take] [[RESULT_TMP]]
// CHECK: destroy_value [[RESULT]]
_ = readonly[keyPath: kp]
_ = writable[keyPath: kp]
_ = readonly[keyPath: wkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: wkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: rkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: rkp]
// CHECK: function_ref @{{.*}}_projectKeyPathWritable
writable[keyPath: wkp] = value
// CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable
readonly[keyPath: rkp] = value
// CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable
writable[keyPath: rkp] = value
}
// CHECK-LABEL: sil hidden @{{.*}}addressOnly
func addressOnly(readonly: P, writable: inout P,
value: Q,
kp: KeyPath<P, Q>,
wkp: WritableKeyPath<P, Q>,
rkp: ReferenceWritableKeyPath<P, Q>) {
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: kp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: kp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: wkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: wkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: rkp]
// CHECK: function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: rkp]
// CHECK: function_ref @{{.*}}_projectKeyPathWritable
writable[keyPath: wkp] = value
// CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable
readonly[keyPath: rkp] = value
// CHECK: function_ref @{{.*}}_projectKeyPathReferenceWritable
writable[keyPath: rkp] = value
}
// CHECK-LABEL: sil hidden @{{.*}}reabstracted
func reabstracted(readonly: @escaping () -> (),
writable: inout () -> (),
value: @escaping (A) -> B,
kp: KeyPath<() -> (), (A) -> B>,
wkp: WritableKeyPath<() -> (), (A) -> B>,
rkp: ReferenceWritableKeyPath<() -> (), (A) -> B>) {
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: kp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: kp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: wkp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: wkp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = readonly[keyPath: rkp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReadOnly
_ = writable[keyPath: rkp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathWritable
writable[keyPath: wkp] = value
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReferenceWritable
readonly[keyPath: rkp] = value
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}_projectKeyPathReferenceWritable
writable[keyPath: rkp] = value
}
// CHECK-LABEL: sil hidden @{{.*}}partial
func partial<A>(valueA: A,
valueB: Int,
pkpA: PartialKeyPath<A>,
pkpB: PartialKeyPath<Int>,
akp: AnyKeyPath) {
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathAny
// CHECK: apply [[PROJECT]]<A>
_ = valueA[keyPath: akp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathPartial
// CHECK: apply [[PROJECT]]<A>
_ = valueA[keyPath: pkpA]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathAny
// CHECK: apply [[PROJECT]]<Int>
_ = valueB[keyPath: akp]
// CHECK: [[PROJECT:%.*]] = function_ref @{{.*}}projectKeyPathPartial
// CHECK: apply [[PROJECT]]<Int>
_ = valueB[keyPath: pkpB]
}
extension Int {
var b: Int { get { return 0 } set { } }
var u: Int { get { return 0 } set { } }
var tt: Int { get { return 0 } set { } }
}
// CHECK-LABEL: sil hidden @{{.*}}writebackNesting
func writebackNesting(x: inout Int,
y: WritableKeyPath<Int, Int>,
z: WritableKeyPath<Int, Int>,
w: Int) -> Int {
// -- get 'b'
// CHECK: function_ref @$sSi19keypath_applicationE1bSivg
// -- apply keypath y
// CHECK: [[PROJECT_FN:%.*]] = function_ref @{{.*}}_projectKeyPathWritable
// CHECK: [[PROJECT_RET:%.*]] = apply [[PROJECT_FN]]
// CHECK: ({{%.*}}, [[OWNER_Y:%.*]]) = destructure_tuple [[PROJECT_RET]]
// -- get 'u'
// CHECK: function_ref @$sSi19keypath_applicationE1uSivg
// -- apply keypath z
// CHECK: [[PROJECT_FN:%.*]] = function_ref @{{.*}}_projectKeyPathWritable
// CHECK: [[PROJECT_RET:%.*]] = apply [[PROJECT_FN]]
// CHECK: ({{%.*}}, [[OWNER_Z:%.*]]) = destructure_tuple [[PROJECT_RET]]
// -- set 'tt'
// CHECK: function_ref @$sSi19keypath_applicationE2ttSivs
// -- destroy owner for keypath projection z
// CHECK: destroy_value [[OWNER_Z]]
// -- set 'u'
// CHECK: function_ref @$sSi19keypath_applicationE1uSivs
// -- destroy owner for keypath projection y
// CHECK: destroy_value [[OWNER_Y]]
// -- set 'b'
// CHECK: function_ref @$sSi19keypath_applicationE1bSivs
x.b[keyPath: y].u[keyPath: z].tt = w
}
| apache-2.0 | dfefdb4878b2ac57b810183f1e1ca2f6 | 36.78125 | 82 | 0.587758 | 4.035381 | false | false | false | false |
smaltby/Canary | iOS/Canary/Canary/NativeFunctions.swift | 1 | 1753 | class NativeFunctions: NSObject
{
static func playUri(_ uri: String)
{
print("Attempting to play " + uri)
SPTAudioStreamingController.sharedInstance().playSpotifyURI(uri, startingWith: 0, startingWithPosition: 10)
{
error in if error != nil
{
print("Failed to play: \(error)")
return
}
}
}
static func pause()
{
print("Attempting to pause... ")
SPTAudioStreamingController.sharedInstance().setIsPlaying(false)
{
error in if error != nil
{
print("Failed to play: \(error)")
return
}
}
}
static func resume()
{
print("Attempting to resume... ")
SPTAudioStreamingController.sharedInstance().setIsPlaying(true)
{
error in if error != nil
{
print("Failed to play: \(error)")
return
}
}
}
static func next()
{
print("Attempting to play next song in the queue")
SPTAudioStreamingController.sharedInstance().skipNext(){
error in if error != nil
{
print("Failed to play: \(error)")
return
}
}
}
static func toggleShuffle(_ shuffle: Bool)
{
print("Attempting to toggle shuffle")
SPTAudioStreamingController.sharedInstance().setShuffle(!shuffle){
error in if error != nil
{
print("Failed to toggle shuffle: \(error)")
return
}
}
}
static func toggleRepeat(_ repeat: Bool)
{
}
}
| mit | 2884c12c9475719485256a00556d6f35 | 24.042857 | 115 | 0.486024 | 5.461059 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.