hexsha
stringlengths 40
40
| size
int64 3
1.03M
| content
stringlengths 3
1.03M
| avg_line_length
float64 1.33
100
| max_line_length
int64 2
1k
| alphanum_fraction
float64 0.25
0.99
|
---|---|---|---|---|---|
917e1753ac43c981a0bab506116c48dc56b03e96
| 8,816 |
//
// FLLTest5ViewController.swift
// TangramKit
//
// Created by apple on 16/7/18.
// Copyright © 2016年 youngsoft. All rights reserved.
//
import UIKit
class FLLTest5ViewController: UIViewController {
override func loadView() {
/*
这个例子主要是用来展示数量约束流式布局对分页滚动能力的支持。
*/
let scrollView = UIScrollView()
scrollView.delaysContentTouches = false //因为里面也有滚动视图,优先处理子滚动视图的事件。
self.view = scrollView
let rootLayout = TGFlowLayout(.vert, arrangedCount:1)
rootLayout.backgroundColor = .white
rootLayout.tg_width.equal(.fill)
rootLayout.tg_height.equal(.wrap)
rootLayout.tg_gravity = TGGravity.horz.fill //里面的所有子视图和布局视图宽度一致。
scrollView.addSubview(rootLayout)
//创建一个水平数量流式布局分页从左到右滚动
self.createHorzPagingFlowLayout1(rootLayout)
//创建一个水平数量流式布局分页从上到下滚动的流式布局。
self.createHorzPagingFlowLayout2(rootLayout)
//创建一个垂直数量流式布局分页从上到下滚动
self.createVertPagingFlowLayout1(rootLayout)
//创建一个垂直数量流式布局分页从左到右滚动
self.createVertPagingFlowLayout2(rootLayout)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
extension FLLTest5ViewController {
//添加所有测试子条目视图。
func addAllItemSubviews(_ flowLayout:TGFlowLayout)
{
for i in 0 ..< 40
{
let label = UILabel()
label.textAlignment = .center
label.backgroundColor = CFTool.color(Int(arc4random()) % 14 + 1)
label.text = "\(i)"
flowLayout.addSubview(label)
}
}
/**
* 创建一个水平分页从左向右滚动的流式布局
*/
func createHorzPagingFlowLayout1(_ rootLayout: UIView)
{
let titleLabel = UILabel()
titleLabel.text = "水平流式布局分页从左往右滚动:➡︎"
titleLabel.sizeToFit()
titleLabel.tg_top.equal(20)
rootLayout.addSubview(titleLabel)
//要开启分页功能,必须要将流式布局加入到一个滚动视图里面作为子视图!!!
let scrollView = UIScrollView()
scrollView.isPagingEnabled = true //开启分页滚动模式!!您可以注释这句话看看非分页滚动的布局滚动效果。
scrollView.tg_height.equal(200) //设置明确的高度为200,因为宽度已经由父线性布局的gravity属性确定了,所以不需要设置了。
rootLayout.addSubview(scrollView)
//建立一个水平数量约束流式布局:每列展示3个子视图,每页展示9个子视图,整体从左往右滚动。
let flowLayout = TGFlowLayout(.horz, arrangedCount:3)
flowLayout.tg_pagedCount = 9 //tg_pagedCount设置为非0时表示开始分页展示的功能,这里表示每页展示9个子视图,这个数量必须是tg_arrangedCount的倍数。
flowLayout.tg_width.equal(.wrap) //设置布局视图的宽度由子视图包裹,当水平流式布局的这个属性设置为YES,并和pagedCount搭配使用会产生分页从左到右滚动的效果。
flowLayout.tg_height.equal(scrollView) //因为是分页从左到右滚动,因此布局视图的高度必须设置为和父滚动视图相等。
/*
上面是实现一个水平流式布局分页且从左往右滚动的标准属性设置方法。
*/
flowLayout.tg_hspace = 10
flowLayout.tg_vspace = 10 //设置子视图的水平和垂直间距。
flowLayout.tg_padding = UIEdgeInsetsMake(5, 5, 5, 5) //布局视图的内边距设置!您可以注释掉这句话看看效果!如果设置内边距且也有分页时请将这个值设置和子视图间距相等。
scrollView.addSubview(flowLayout)
flowLayout.backgroundColor = CFTool.color(0)
self.addAllItemSubviews(flowLayout)
//获取流式布局的横屏size classes,并且设置当设备处于横屏时每页的数量由9个变为了18个。您可以注释掉这段代码,然后横竖屏切换看看效果。
let flowLayoutSC = flowLayout.tg_fetchSizeClass(with:.landscape, from:.default) as! TGFlowLayoutViewSizeClass
flowLayoutSC.tg_pagedCount = 18
}
/**
* 创建一个水平分页从上向下滚动的流式布局
*/
func createHorzPagingFlowLayout2(_ rootLayout: UIView)
{
let titleLabel = UILabel()
titleLabel.text = "水平流式布局分页从上往下滚动:⬇︎"
titleLabel.sizeToFit()
titleLabel.tg_top.equal(20)
rootLayout.addSubview(titleLabel)
//要开启分页功能,必须要将流式布局加入到一个滚动视图里面作为子视图!!!
let scrollView = UIScrollView()
scrollView.isPagingEnabled = true //开启分页滚动模式!!您可以注释这句话看看非分页滚动的布局滚动效果。
scrollView.tg_height.equal(250) //设置明确的高度为200,因为宽度已经由父线性布局的gravity属性确定了,所以不需要设置了。
rootLayout.addSubview(scrollView)
//建立一个水平数量约束流式布局:每列展示3个子视图,每页展示9个子视图,整体从上往下滚动。
let flowLayout = TGFlowLayout(.horz, arrangedCount:3)
flowLayout.tg_pagedCount = 9; //pagedCount设置为非0时表示开始分页展示的功能,这里表示每页展示9个子视图,这个数量必须是arrangedCount的倍数。
flowLayout.tg_height.equal(.wrap) //设置布局视图的高度由子视图包裹,当水平流式布局的高度设置为.wrap,并和pagedCount搭配使用会产生分页从上到下滚动的效果。
flowLayout.tg_width.equal(scrollView) //因为是分页从左到右滚动,因此布局视图的宽度必须设置为和父滚动视图相等。
/*
上面是实现一个水平流式布局分页且从上往下滚动的标准属性设置方法。
*/
flowLayout.tg_hspace = 10
flowLayout.tg_vspace = 10 //设置子视图的水平和垂直间距。
flowLayout.tg_padding = UIEdgeInsetsMake(5, 5, 5, 5) //布局视图的内边距设置!您可以注释掉这句话看看效果!如果设置内边距且也有分页时请将这个值设置和子视图间距相等。
scrollView.addSubview(flowLayout)
flowLayout.backgroundColor = CFTool.color(0)
self.addAllItemSubviews(flowLayout)
//获取流式布局的横屏size classes,并且设置当设备处于横屏时每页的数量由9个变为了18个。您可以注释掉这段代码,然后横竖屏切换看看效果。
let flowLayoutSC = flowLayout.tg_fetchSizeClass(with:.landscape, from:.default) as! TGFlowLayoutViewSizeClass
flowLayoutSC.tg_pagedCount = 18
}
/**
* 创建一个垂直分页从上向下滚动的流式布局
*/
func createVertPagingFlowLayout1(_ rootLayout: UIView)
{
let titleLabel = UILabel()
titleLabel.text = "垂直流式布局分页从上往下滚动:⬇︎"
titleLabel.sizeToFit()
titleLabel.tg_top.equal(20)
rootLayout.addSubview(titleLabel)
//要开启分页功能,必须要将流式布局加入到一个滚动视图里面作为子视图!!!
let scrollView = UIScrollView()
scrollView.isPagingEnabled = true //开启分页滚动模式!!您可以注释这句话看看非分页滚动的布局滚动效果。
scrollView.tg_height.equal(250) //设置明确的高度为200,因为宽度已经由父线性布局的gravity属性确定了,所以不需要设置了。
rootLayout.addSubview(scrollView)
//建立一个垂直数量约束流式布局:每列展示3个子视图,每页展示9个子视图,整体从上往下滚动。
let flowLayout = TGFlowLayout(.vert, arrangedCount:3)
flowLayout.tg_pagedCount = 9 //pagedCount设置为非0时表示开始分页展示的功能,这里表示每页展示9个子视图,这个数量必须是arrangedCount的倍数。
flowLayout.tg_height.equal(.wrap) //设置布局视图的高度由子视图包裹,当垂直流式布局高度设置为.wrap,并和pagedCount搭配使用会产生分页从上到下滚动的效果。
flowLayout.tg_width.equal(scrollView)
/*
上面是实现一个垂直流式布局分页且从上往下滚动的标准属性设置方法。
*/
flowLayout.tg_hspace = 10
flowLayout.tg_vspace = 10 //设置子视图的水平和垂直间距。
flowLayout.tg_padding = UIEdgeInsetsMake(5, 5, 5, 5) //布局视图的内边距设置!您可以注释掉这句话看看效果!如果设置内边距且也有分页时请将这个值设置和子视图间距相等。
scrollView.addSubview(flowLayout)
flowLayout.backgroundColor = CFTool.color(0)
self.addAllItemSubviews(flowLayout)
//获取流式布局的横屏size classes,并且设置当设备处于横屏时每页的数量由9个变为了18个。您可以注释掉这段代码,然后横竖屏切换看看效果。
let flowLayoutSC = flowLayout.tg_fetchSizeClass(with:.landscape, from:.default) as! TGFlowLayoutViewSizeClass
flowLayoutSC.tg_arrangedCount = 6
flowLayoutSC.tg_pagedCount = 18
}
/**
* 创建一个垂直分页从左向右滚动的流式布局
*/
func createVertPagingFlowLayout2(_ rootLayout: UIView)
{
let titleLabel = UILabel()
titleLabel.text = "垂直流式布局分页从左往右滚动:➡︎"
titleLabel.sizeToFit()
titleLabel.tg_top.equal(20)
rootLayout.addSubview(titleLabel)
//要开启分页功能,必须要将流式布局加入到一个滚动视图里面作为子视图!!!
let scrollView = UIScrollView()
scrollView.isPagingEnabled = true //开启分页滚动模式!!您可以注释这句话看看非分页滚动的布局滚动效果。
scrollView.tg_height.equal(200) //设置明确的高度为200,因为宽度已经由父线性布局的gravity属性确定了,所以不需要设置了。
rootLayout.addSubview(scrollView)
//建立一个垂直数量约束流式布局:每列展示3个子视图,每页展示9个子视图,整体从左往右滚动。
let flowLayout = TGFlowLayout(.vert, arrangedCount:3)
flowLayout.tg_pagedCount = 9 //pagedCount设置为非0时表示开始分页展示的功能,这里表示每页展示9个子视图,这个数量必须是arrangedCount的倍数。
flowLayout.tg_width.equal(.wrap) //设置布局视图的宽度由子视图包裹,当垂直流式布局的宽度设置为.wrap,并和pagedCount搭配使用会产生分页从左到右滚动的效果。
flowLayout.tg_height.equal(scrollView)
/*
上面是实现一个垂直流式布局分页且从左往右滚动的标准属性设置方法。
*/
flowLayout.tg_hspace = 10
flowLayout.tg_vspace = 10 //设置子视图的水平和垂直间距。
flowLayout.tg_padding = UIEdgeInsetsMake(5, 5, 5, 5) //布局视图的内边距设置!您可以注释掉这句话看看效果!如果设置内边距且也有分页时请将这个值设置和子视图间距相等。
scrollView.addSubview(flowLayout)
flowLayout.backgroundColor = CFTool.color(0)
self.addAllItemSubviews(flowLayout)
//获取流式布局的横屏size classes,并且设置当设备处于横屏时每页的数量由9个变为了18个。您可以注释掉这段代码,然后横竖屏切换看看效果。
let flowLayoutSC = flowLayout.tg_fetchSizeClass(with:.landscape, from:.default) as! TGFlowLayoutViewSizeClass
flowLayoutSC.tg_arrangedCount = 6
flowLayoutSC.tg_pagedCount = 18
}
}
| 34.84585 | 117 | 0.65608 |
9b4c806562068cbe989b5e3adf32790c0f6ac51c
| 5,739 |
//
// ArrayExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/5/16.
// Copyright © 2016 Omar Albeik. All rights reserved.
//
import Foundation
// MARK: - Methods (Integer)
public extension Array where Element: Integer {
/// SwifterSwift: Sum of all elements in array.
/// Returns: sum of the array's elements (Integer).
public func sum() -> Element {
// http://stackoverflow.com/questions/28288148/making-my-function-calculate-average-of-array-swift
return reduce(0, +)
}
}
// MARK: - Methods (FloatingPoint)
public extension Array where Element: FloatingPoint {
/// SwifterSwift: Average of all elements in array.
/// Returns: average of the array's elements (FloatingPoint).
public func average() -> Element {
// http://stackoverflow.com/questions/28288148/making-my-function-calculate-average-of-array-swift
return isEmpty ? 0 : reduce(0, +) / Element(count)
}
/// SwifterSwift: Sum of all elements in array.
/// Returns: sum of the array's elements (FloatingPoint).
public func sum() -> Element {
// http://stackoverflow.com/questions/28288148/making-my-function-calculate-average-of-array-swift
return reduce(0, +)
}
}
// MARK: - Methods
public extension Array {
/// SwifterSwift: Element at the given index if it exists.
///
/// - Parameter index: index of element.
/// - Returns: optional element (if exists).
public func item(at index: Int) -> Element? {
guard startIndex...endIndex ~= index else { return nil }
return self[index]
}
/// SwifterSwift: Remove last element from array and return it.
///
/// - Returns: last element in array (if applicable).
@discardableResult public mutating func pop() -> Element? {
return popLast()
}
/// SwifterSwift: Insert an element at the beginning of array.
///
/// - Parameter newElement: element to insert.
public mutating func prepend(_ newElement: Element) {
insert(newElement, at: 0)
}
/// SwifterSwift: Insert an element to the end of array.
///
/// - Parameter newElement: element to insert.
public mutating func push(_ newElement: Element) {
append(newElement)
}
/// SwifterSwift: Safely Swap values at index positions.
///
/// - Parameters:
/// - index: index of first element.
/// - otherIndex: index of other element.
public mutating func safeSwap(from index: Int, to otherIndex: Int) {
guard index != otherIndex else {
return
}
guard startIndex...endIndex ~= index else {
return
}
guard startIndex...endIndex ~= otherIndex else {
return
}
Swift.swap(&self[index], &self[otherIndex])
}
/// SwifterSwift: Swap values at index positions.
///
/// - Parameters:
/// - from: index of first element.
/// - to: index of other element.
public mutating func swap(from index: Int, to otherIndex: Int) {
Swift.swap(&self[index], &self[otherIndex])
}
}
// MARK: - Methods (Equatable)
public extension Array where Element: Equatable {
/// SwifterSwift: Shuffle array. (Using Fisher-Yates Algorithm)
public mutating func shuffle() {
//http://stackoverflow.com/questions/37843647/shuffle-array-swift-3
guard count > 1 else { return }
for index in startIndex..<endIndex - 1 {
let randomIndex = Int(arc4random_uniform(UInt32(endIndex - index))) + index
if index != randomIndex { Swift.swap(&self[index], &self[randomIndex]) }
}
}
/// SwifterSwift: Shuffled version of array. (Using Fisher-Yates Algorithm)
/// Returns: the array with its elements shuffled.
public func shuffled() -> [Element] {
var array = self
array.shuffle()
return array
}
/// SwifterSwift: Check if array contains an array of elements.
///
/// - Parameter elements: array of elements to check.
/// - Returns: true if array contains all given items.
public func contains(_ elements: [Element]) -> Bool {
guard !elements.isEmpty else { // elements array is empty
return true
}
var found = true
for element in elements {
if !contains(element) {
found = false
}
}
return found
}
/// SwifterSwift: All indexes of specified item.
///
/// - Parameter item: item to check.
/// - Returns: an array with all indexes of the given item.
public func indexes(of item: Element) -> [Int] {
var indexes: [Int] = []
for index in startIndex..<endIndex {
if self[index] == item {
indexes.append(index)
}
}
return indexes
}
/// SwifterSwift: Remove all instances of an item from array.
///
/// - Parameter item: item to remove.
public mutating func removeAll(_ item: Element) {
self = filter { $0 != item }
}
/// SwifterSwift: Remove all duplicate elements from Array.
public mutating func removeDuplicates() {
// Thanks to https://github.com/sairamkotha for improving the method
self = reduce([]){ $0.contains($1) ? $0 : $0 + [$1] }
}
/// SwifterSwift: Return array with all duplicate elements removed.
/// - Returns: An array of unique elements.
public func duplicatesRemoved() -> [Element] {
// Thanks to https://github.com/sairamkotha for improving the property
return reduce([]){ ($0 as [Element]).contains($1) ? $0 : $0 + [$1] }
}
/// SwifterSwift: First index of a given item in an array.
///
/// - Parameter item: item to check.
/// - Returns: first index of item in array (if exists).
public func firstIndex(of item: Element) -> Int? {
for (index, value) in lazy.enumerated() {
if value == item { return index }
}
return nil
}
/// SwifterSwift: Last index of element in array.
///
/// - Parameter item: item to check.
/// - Returns: last index of item in array (if exists).
public func lastIndex(of item: Element) -> Int? {
for (index, value) in lazy.enumerated().reversed() {
if value == item { return index }
}
return nil
}
}
| 28.410891 | 100 | 0.673811 |
fc364ea21da4053a448c02200a622e449f92f394
| 1,580 |
//
// ScoreboardViewController.swift
// Tic Tac Toe
//
// Created by MR.Robot 💀 on 09/11/2018.
// Copyright © 2018 Joselson Dias. All rights reserved.
//
import UIKit
import RealmSwift
class ScoreboardViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var rankPosition = 0
@IBOutlet weak var rankingTable: UITableView!
let realm = try! Realm()
var players: Results<scoreboardDataModel>!
override func viewDidLoad() {
super.viewDidLoad()
loadRankings()
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
//return(scores.count)
return players?.count ?? 1
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "cell")
cell.textLabel?.textAlignment = .center
if let allPlayers = players?[indexPath.row]{
//Obtain row number for scoreboard
let playerRank = indexPath.row + 1
cell.textLabel?.text = "\(playerRank) \(allPlayers.name) \(allPlayers.scores)"
}
return(cell)
}
func loadRankings(){
players = realm.objects(scoreboardDataModel.self).sorted(byKeyPath: "scores", ascending: false)
rankingTable.reloadData()
}
}
| 25.079365 | 132 | 0.600633 |
6185eacbefaf2dc87555c5f58bb44137822cd6a1
| 1,361 |
//
// CGPoint+Extensions.swift
//
// Copyright (c) 2017 Alex Givens (http://alexgivens.com/)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public extension CGPoint {
func distanceTo(_ point: CGPoint) -> CGFloat {
return hypot(self.x - point.x, self.y - point.y)
}
}
| 40.029412 | 81 | 0.730345 |
11235af9e40bbe671c8bc4b7913da71f7ed721f5
| 1,438 |
// RUN: %target-run-simple-swift(-Xfrontend -enable-experimental-concurrency -Xfrontend -disable-availability-checking %import-libdispatch -parse-as-library) | %FileCheck %s --dump-input always
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// rdar://76038845
// UNSUPPORTED: use_os_stdlib
// UNSUPPORTED: back_deployment_runtime
import Dispatch
@available(SwiftStdlib 5.5, *)
func test_taskGroup_cancel_from_inside_child() async {
let one = try! await withTaskGroup(of: Int.self, returning: Int.self) { group in
await group.next()
return 0
}
let two = await withTaskGroup(of: Int.self, returning: Int.self) { group in
0
}
let result = await withTaskGroup(of: Int.self, returning: Int.self) { group in
let firstAdded = group.spawnUnlessCancelled { [group] in // must explicitly capture, as the task executes concurrently
group.cancelAll() // allowed
print("first")
return 1
}
print("firstAdded: \(firstAdded)") // CHECK: firstAdded: true
let one = await group.next()
let secondAdded = group.spawnUnlessCancelled {
print("second")
return 2
}
print("secondAdded: \(secondAdded)") // CHECK: secondAdded: false
return 1
}
print("result: \(result)") // CHECK: result: 1
}
@available(SwiftStdlib 5.5, *)
@main struct Main {
static func main() async {
await test_taskGroup_cancel_from_inside_child()
}
}
| 26.62963 | 193 | 0.696106 |
46f4ecb916f73910dd3698276bf3b57e32c99e73
| 2,105 |
//
// Copyright © 2018 Apparata AB. All rights reserved.
//
import Foundation
import UIKit
class AppNavigationController {
var tabBarController: UITabBarController?
init() {
observeCommands()
}
func observeCommands() {
NotificationCenter.default.addObserver(self, selector: #selector(handleCommandNotification(_:)), name: Notification.Name(rawValue: "appconsole.command"), object: nil)
}
@objc func handleCommandNotification(_ notification: Notification) {
guard let userInfo = notification.userInfo,
let client = userInfo["client"],
let commands = userInfo["commands"] as? [String] else {
return
}
let arguments = userInfo["arguments"] as? [String: Any] ?? [String: Any]()
handleCommand(client: client, commands: commands, arguments: arguments)
}
func handleCommand(client: Any, commands: [String], arguments: [String: Any]) {
switch commands {
case ["selectTab"]:
if let tabIndex = arguments["index"] as? Int {
DispatchQueue.main.async { [tabBarController] in
if tabIndex >= 0 && tabIndex < tabBarController?.viewControllers?.count ?? 0 {
tabBarController?.selectedIndex = tabIndex
}
}
}
case ["shake"]:
DispatchQueue.main.async { [weak self] in
if let view = self?.tabBarController?.view {
self?.shakeHorizontally(layer: view.layer)
}
}
default:
return
}
}
public func shakeHorizontally(layer: CALayer) {
let shake = CAKeyframeAnimation(keyPath: "transform.translation.x")
shake.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.linear)
shake.duration = 0.5
shake.beginTime = CACurrentMediaTime()
shake.values = [-20, 20, -20, 20, -10, 10, -5, 5, 0]
layer.add(shake, forKey: "shake")
}
}
| 32.890625 | 174 | 0.576722 |
203a6611865d6946e16f2996ae9a2e5fd0525eca
| 1,143 |
/*
* Copyright 2016 chaoyang805 [email protected]
*
* 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 ObjectMapper
/// 封装请求豆瓣API的 搜索、正在上映 接口返回的电影结果集合
class DoubanResultsSet: NSObject, Mappable {
var count: Int = 0
var start: Int = 0
var total: Int = 22
var title: String = ""
var subjects: [DoubanMovie] = []
required convenience init?(map: Map) {
self.init()
}
func mapping(map: Map) {
count <- map["count"]
start <- map["start"]
total <- map["total"]
title <- map["title"]
subjects <- map["subjects"]
}
}
| 28.575 | 75 | 0.660542 |
acb98c6443e324dc43d6d9559d9677242663a9ce
| 667 |
//
// MainView.swift
// iDine
//
// Created by Mohammed Elnaggar on 26/07/2021.
// Copyright © 2021 Mohammed Elnaggar. All rights reserved.
//
import SwiftUI
struct MainView: View {
var body: some View {
TabView {
MenuView()
.tabItem {
Label("Menu", systemImage: "list.dash")
}
OrdersView()
.tabItem {
Label("Orders", systemImage: "square.and.pencil")
}
}
}
}
struct MainView_Previews: PreviewProvider {
static var previews: some View {
MainView()
.environmentObject(Order())
}
}
| 20.84375 | 69 | 0.512744 |
912115277b009668f9100be53a30b73457a65b68
| 3,129 |
import Foundation
import azureSwiftRuntime
public protocol InteractionsGet {
var headerParameters: [String: String] { get set }
var resourceGroupName : String { get set }
var hubName : String { get set }
var interactionName : String { get set }
var subscriptionId : String { get set }
var localeCode : String? { get set }
var apiVersion : String { get set }
func execute(client: RuntimeClient,
completionHandler: @escaping (InteractionResourceFormatProtocol?, Error?) -> Void) -> Void ;
}
extension Commands.Interactions {
// Get gets information about the specified interaction.
internal class GetCommand : BaseCommand, InteractionsGet {
public var resourceGroupName : String
public var hubName : String
public var interactionName : String
public var subscriptionId : String
public var localeCode : String?
public var apiVersion = "2017-04-26"
public init(resourceGroupName: String, hubName: String, interactionName: String, subscriptionId: String) {
self.resourceGroupName = resourceGroupName
self.hubName = hubName
self.interactionName = interactionName
self.subscriptionId = subscriptionId
super.init()
self.method = "Get"
self.isLongRunningOperation = false
self.path = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.CustomerInsights/hubs/{hubName}/interactions/{interactionName}"
self.headerParameters = ["Content-Type":"application/json; charset=utf-8"]
}
public override func preCall() {
self.pathParameters["{resourceGroupName}"] = String(describing: self.resourceGroupName)
self.pathParameters["{hubName}"] = String(describing: self.hubName)
self.pathParameters["{interactionName}"] = String(describing: self.interactionName)
self.pathParameters["{subscriptionId}"] = String(describing: self.subscriptionId)
if self.localeCode != nil { queryParameters["locale-code"] = String(describing: self.localeCode!) }
self.queryParameters["api-version"] = String(describing: self.apiVersion)
}
public override func returnFunc(data: Data) throws -> Decodable? {
let contentType = "application/json"
if let mimeType = MimeType.getType(forStr: contentType) {
let decoder = try CoderFactory.decoder(for: mimeType)
let result = try decoder.decode(InteractionResourceFormatData?.self, from: data)
return result;
}
throw DecodeError.unknownMimeType
}
public func execute(client: RuntimeClient,
completionHandler: @escaping (InteractionResourceFormatProtocol?, Error?) -> Void) -> Void {
client.executeAsync(command: self) {
(result: InteractionResourceFormatData?, error: Error?) in
completionHandler(result, error)
}
}
}
}
| 48.138462 | 176 | 0.645254 |
2675b9b52a47c921fafeeecf6941625d98effe0f
| 411 |
// RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
let n1: () {
typealias A : c<T where g<T) { x in 0
}
var e, f, end: a {
}
protocol a {
struct c {
}
f = c<U : A> Any, () -> (self.dynamicType.b {
}
var a)) {
func f: C(n: A {
}))
}
typealias d: d
| 18.681818 | 87 | 0.635036 |
f525dbf05723348071f3ac72554b18cb90a06b34
| 1,468 |
//
// MyXIBSwitchCell.swift
// ReusableDemo
//
// Created by Olivier Halligon on 19/01/2016.
// Copyright © 2016 AliSoftware. All rights reserved.
//
import UIKit
import Reusable
/**
* This view is loaded from a NIB, and is the XIB file's
* root view (and not the File's Owner). => it is `NibLoadable`
*
* It is also reusable and has a `reuseIdentifier` (as it's a TableViewCell
* and it uses the TableView recycling mechanism) => it is `Reusable`
*
* That's why it's annotated with the `NibReusable` protocol,
* Which in fact is just a convenience protocol that combines
* both `NibLoadable` + `Reusable` protocols.
*/
final class MyXIBInfoCell: UITableViewCell, NibReusable {
@IBOutlet private weak var titleLabel: UILabel!
private var info: String = "<Info?>"
private var details: String = "<Details?>"
func fill(title: String, info: String, details: String) {
self.titleLabel.text = title
self.info = info
self.details = details
}
@IBAction func infoAction(sender: UIButton) {
let infoVC = InfoViewController.instantiate()
infoVC.setInfo(self.info)
self.window?.rootViewController?.presentViewController(infoVC, animated: true, completion: nil)
}
@IBAction func detailsAction(sender: UIButton) {
let detailsVC = InfoDetailViewController.instantiate()
detailsVC.setDetails(self.details)
self.window?.rootViewController?.presentViewController(detailsVC, animated: true, completion: nil)
}
}
| 30.583333 | 102 | 0.722071 |
21bd9897c3a10a457ce615eec5bc6c7ddd0c99d6
| 1,144 |
//
// TestEndPoint.swift
// NilNetzwerk_Example
//
// Created by Tanasak.Nge on 11/7/2561 BE.
// Copyright © 2561 CocoaPods. All rights reserved.
//
import Foundation
import NilNetzwerk
struct TestRequestGenerator: RequestGenerator {
func generateRequest(withMethod method: HTTPMethod) -> MutableRequest {
return request(withMethod: method) |> withJsonSupport
}
}
enum TestFetchEndPoint {
case testPost(name: String, job: String)
}
extension TestFetchEndPoint: ServiceEndpoint {
var requestGenerator: RequestGenerator {
return TestRequestGenerator()
}
var parameters: Codable?{
switch self {
case .testPost(let name, let job):
return TestPostModel(name: name, job: job)
}
}
var baseURL: URL {
switch self {
case .testPost:
return URL(string: "https://reqres.in/api")!
}
}
var method: HTTPMethod {
switch self {
case .testPost:
return .POST
}
}
var path: String {
switch self {
case .testPost:
return "/users"
}
}
var queryParameters: [String : String]? {
switch self {
case .testPost:
return nil
}
}
}
| 18.15873 | 73 | 0.65472 |
640bd0b6d7d75f606dafc731cb91681f1119f61c
| 578 |
class RatingDetailItem: RatingItem {
override func cellHeight(tableWidth: CGFloat) -> CGFloat {
return HLHotelDetailsRatingDetailsCell.estimatedHeight(first, last: last)
}
override func cell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: HLHotelDetailsRatingDetailsCell.hl_reuseIdentifier(), for: indexPath) as! HLHotelDetailsRatingDetailsCell
cell.configureForRatingDetails(self)
cell.first = first
cell.last = last
return cell
}
}
| 36.125 | 171 | 0.731834 |
64c4661574f709eef394cf36628671698efcb574
| 1,163 |
// -*- swift -*-
//===----------------------------------------------------------------------===//
// Automatically Generated From validation-test/stdlib/Collection/Inputs/Template.swift.gyb
// Do Not Edit Directly!
//===----------------------------------------------------------------------===//
// RUN: %target-run-simple-swift
// REQUIRES: executable_test
import StdlibUnittest
import StdlibCollectionUnittest
var CollectionTests = TestSuite("Collection")
// Test collections using value types as elements.
do {
var resiliencyChecks = CollectionMisuseResiliencyChecks.all
resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .trap
CollectionTests.addBidirectionalCollectionTests(
makeCollection: { (elements: [OpaqueValue<Int>]) in
return MinimalBidirectionalCollection(elements: elements)
},
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
return MinimalBidirectionalCollection(elements: elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
resiliencyChecks: resiliencyChecks
)
}
runAllTests()
| 29.820513 | 91 | 0.66552 |
5bbf736b3f2bc7bae78c5fca50cb878d47984333
| 1,666 |
//
// Style.swift
// anim
//
// Created by Christopher Zhang on 2017-03-01.
// Copyright (c) 2017 Christopher Zhang. All rights reserved.
import UIKit
struct Color {
static let lightGray = UIColor(red: 219.0/255.0, green: 228.0/255.0, blue: 228.0/255.0, alpha: 1)
static let midGray = UIColor(red: 187.0/255.0, green: 193.0/255.0, blue: 195.0/255.0, alpha: 1)
static let darkGray = UIColor(red: 40.0/255.0, green: 45.0/255.0, blue: 47.0/255.0, alpha: 1)
static let red = UIColor(red: 255.0/255.0, green: 66.0/255.0, blue: 85.0/255.0, alpha: 1)
static let orange = UIColor(red: 232.0/255.0, green: 165.0/255.0, blue: 48.0/255.0, alpha: 1)
static let yellow = UIColor(red: 240.0/255.0, green: 243.0/255.0, blue: 8.0/255.0, alpha: 1)
static let lightGreen = UIColor(red: 207.0/255.0, green: 255.0/255.0, blue: 136.0/255.0, alpha: 1)
static let blue = UIColor(red: 85.0/255.0, green: 48.0/255.0, blue: 232.0/255.0, alpha: 1)
static let green = UIColor(red: 79.0/255.0, green: 173.0/255.0, blue: 167.0/255.0, alpha: 1)
static let all = [red, orange, yellow, lightGreen, blue, green]
}
struct Font {
static let nameBlokk = "BLOKKNeue-Regular"
}
extension String {
var attributedBlock: NSAttributedString {
let attributedString = NSMutableAttributedString(string: self)
let style = NSMutableParagraphStyle()
style.lineSpacing = 12
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: style, range: NSRange(location: 0, length: self.count))
return attributedString
}
}
| 41.65 | 139 | 0.637455 |
fc29c6ff6921c767146401726c94a259838b09f6
| 5,357 |
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
/// Creates a sequence of pairs built out of two underlying sequences.
///
/// In the `Zip2Sequence` instance returned by this function, the elements of
/// the *i*th pair are the *i*th elements of each underlying sequence. The
/// following example uses the `zip(_:_:)` function to iterate over an array
/// of strings and a countable range at the same time:
///
/// let words = ["one", "two", "three", "four"]
/// let numbers = 1...4
///
/// for (word, number) in zip(words, numbers) {
/// print("\(word): \(number)")
/// }
/// // Prints "one: 1"
/// // Prints "two: 2
/// // Prints "three: 3"
/// // Prints "four: 4"
///
/// If the two sequences passed to `zip(_:_:)` are different lengths, the
/// resulting sequence is the same length as the shorter sequence. In this
/// example, the resulting array is the same length as `words`:
///
/// let naturalNumbers = 1...Int.max
/// let zipped = Array(zip(words, naturalNumbers))
/// // zipped == [("one", 1), ("two", 2), ("three", 3), ("four", 4)]
///
/// - Parameters:
/// - sequence1: The first sequence or collection to zip.
/// - sequence2: The second sequence or collection to zip.
/// - Returns: A sequence of tuple pairs, where the elements of each pair are
/// corresponding elements of `sequence1` and `sequence2`.
@inlinable // generic-performance
public func zip<Sequence1, Sequence2>(
_ sequence1: Sequence1, _ sequence2: Sequence2
) -> Zip2Sequence<Sequence1, Sequence2> {
return Zip2Sequence(sequence1, sequence2)
}
/// A sequence of pairs built out of two underlying sequences.
///
/// In a `Zip2Sequence` instance, the elements of the *i*th pair are the *i*th
/// elements of each underlying sequence. To create a `Zip2Sequence` instance,
/// use the `zip(_:_:)` function.
///
/// The following example uses the `zip(_:_:)` function to iterate over an
/// array of strings and a countable range at the same time:
///
/// let words = ["one", "two", "three", "four"]
/// let numbers = 1...4
///
/// for (word, number) in zip(words, numbers) {
/// print("\(word): \(number)")
/// }
/// // Prints "one: 1"
/// // Prints "two: 2
/// // Prints "three: 3"
/// // Prints "four: 4"
@_fixed_layout // generic-performance
public struct Zip2Sequence<Sequence1 : Sequence, Sequence2 : Sequence> {
@usableFromInline // generic-performance
internal let _sequence1: Sequence1
@usableFromInline // generic-performance
internal let _sequence2: Sequence2
/// Creates an instance that makes pairs of elements from `sequence1` and
/// `sequence2`.
@inlinable // generic-performance
internal init(_ sequence1: Sequence1, _ sequence2: Sequence2) {
(_sequence1, _sequence2) = (sequence1, sequence2)
}
}
extension Zip2Sequence {
/// An iterator for `Zip2Sequence`.
@_fixed_layout // generic-performance
public struct Iterator {
@usableFromInline // generic-performance
internal var _baseStream1: Sequence1.Iterator
@usableFromInline // generic-performance
internal var _baseStream2: Sequence2.Iterator
@usableFromInline // generic-performance
internal var _reachedEnd: Bool = false
/// Creates an instance around a pair of underlying iterators.
@inlinable // generic-performance
internal init(
_ iterator1: Sequence1.Iterator,
_ iterator2: Sequence2.Iterator
) {
(_baseStream1, _baseStream2) = (iterator1, iterator2)
}
}
}
extension Zip2Sequence.Iterator: IteratorProtocol {
/// The type of element returned by `next()`.
public typealias Element = (Sequence1.Element, Sequence2.Element)
/// Advances to the next element and returns it, or `nil` if no next element
/// exists.
///
/// Once `nil` has been returned, all subsequent calls return `nil`.
@inlinable // generic-performance
public mutating func next() -> Element? {
// The next() function needs to track if it has reached the end. If we
// didn't, and the first sequence is longer than the second, then when we
// have already exhausted the second sequence, on every subsequent call to
// next() we would consume and discard one additional element from the
// first sequence, even though next() had already returned nil.
if _reachedEnd {
return nil
}
guard let element1 = _baseStream1.next(),
let element2 = _baseStream2.next() else {
_reachedEnd = true
return nil
}
return (element1, element2)
}
}
extension Zip2Sequence: Sequence {
public typealias Element = (Sequence1.Element, Sequence2.Element)
/// Returns an iterator over the elements of this sequence.
@inlinable // generic-performance
public __consuming func makeIterator() -> Iterator {
return Iterator(
_sequence1.makeIterator(),
_sequence2.makeIterator())
}
}
| 36.195946 | 80 | 0.653537 |
71320af7f4d0c711fa7350a3b90b31394981e2d4
| 2,292 |
//
// User.swift
// TwitterClient
//
// Created by Kim Toy (Personal) on 4/15/17.
// Copyright © 2017 Codepath. All rights reserved.
//
import UIKit
class User: NSObject {
var name: String?
var screenname: String?
var handle: String?
var profileUrl: URL?
var tagline: String?
var dictionary: Dictionary<String, Any>?
var followersCount: Int?
var tweetsCount: Int?
var followingCount: Int?
static let userLogoutNotificationKey = "UserDidLogout"
static let userLoginNotificationKey = "UserDidLogin"
init(dictionary: Dictionary<String, Any>) {
self.dictionary = dictionary as Dictionary?
name = dictionary["name"] as? String
screenname = dictionary["screen_name"] as? String
handle = "@\(screenname!)"
let profileUrlString = dictionary["profile_image_url_https"] as? String
if let urlString = profileUrlString {
profileUrl = URL(string: urlString)
}
tagline = dictionary["description"] as? String
followersCount = dictionary["followers_count"] as? Int
tweetsCount = dictionary["statuses_count"] as? Int
followingCount = dictionary["friends_count"] as? Int
}
static var _currentUser: User?
class var currentUser: User? {
get {
if _currentUser == nil {
let defaults = UserDefaults.standard
let userData = defaults.object(forKey: "currentUser") as? Data
if let userData = userData {
let dictionary = try! JSONSerialization.jsonObject(with: userData, options: []) as! Dictionary<String, Any>
_currentUser = User(dictionary: dictionary)
}
}
return _currentUser
}
set(user) {
_currentUser = user
let defaults = UserDefaults.standard
if let user = user {
let data = try! JSONSerialization.data(withJSONObject: user.dictionary!, options: [])
defaults.set(data, forKey: "currentUser")
} else {
defaults.removeObject(forKey: "currentUser")
}
defaults.synchronize()
}
}
}
| 30.56 | 127 | 0.58377 |
d9b9bc5a65e423d1386e239a78ccbab1f397c87a
| 7,142 |
//
// SettingsSection.swift
// CriticalMaps
//
// Created by Malte Bünz on 19.04.19.
// Copyright © 2019 Pokus Labs. All rights reserved.
//
import UIKit
/** TODO: Refactor to a more versataile API like:
Section(title: "NAME", rows: [SwitchRow(title:subTitle:actionClosure:), OptionRow]).....
**/
enum SettingsSection {
typealias AllCases = [SettingsSection]
case preferences(
models: [Model],
sectionTitle: String?
)
case projectLinks(
models: [Model],
[SettingsProjectLinkTableViewCell.CellConfiguration],
sectionTitle: String?
)
case info(
models: [Model],
sectionTitle: String?
)
var numberOfRows: Int {
switch self {
case let .preferences(models: models, _), let .projectLinks(models: models, _, _), let .info(models: models, _):
return models.count
}
}
var models: [Model] {
switch self {
case let .preferences(models: models, _), let .projectLinks(models: models, _, _), let .info(models: models, _):
return models
}
}
var title: String? {
switch self {
case let .preferences(_, title), let .projectLinks(_, _, title), let .info(_, title):
return title
}
}
func cellClass(action: Action) -> IBConstructable.Type {
switch (self, action) {
case (_, .switch(_)):
return SettingsSwitchTableViewCell.self
case (_, .check(_)):
return SettingsCheckTableViewCell.self
case (.projectLinks, _):
return SettingsProjectLinkTableViewCell.self
default:
return SettingsInfoTableViewCell.self
}
}
}
extension SettingsSection {
struct Model {
let title: String?
let subtitle: String?
let action: Action
let accessibilityIdentifier: String
init(
title: String? = nil,
subtitle: String? = nil,
action: Action,
accessibilityIdentifier: String
) {
self.title = title
self.subtitle = subtitle
self.action = action
self.accessibilityIdentifier = accessibilityIdentifier
}
}
enum Action {
case navigate(toViewController: UIViewController.Type)
case open(url: URL)
case `switch`(_ switchtable: Toggleable.Type)
case check(_ checkable: Toggleable.Type)
}
}
extension SettingsSection {
static let cellClasses: [IBConstructable.Type] = {
[
SettingsInfoTableViewCell.self,
SettingsSwitchTableViewCell.self,
SettingsCheckTableViewCell.self,
SettingsProjectLinkTableViewCell.self,
]
}()
}
extension SettingsSection {
static let eventSettings: [SettingsSection] = [
.preferences(
models: [
Model(
title: L10n.Settings.eventSettingsEnable,
subtitle: nil,
action: .switch(RideEventSettings.self),
accessibilityIdentifier: L10n.Settings.eventSettingsEnable
)
],
sectionTitle: nil
),
.info(
models: Ride.RideType.allCases.map {
Model(
title: $0.title,
action: .check(RideEventSettings.RideEventTypeSetting.self),
accessibilityIdentifier: $0.title
)
},
sectionTitle: L10n.Settings.eventTypes
),
.info(
models: Ride.eventRadii.map {
let description = L10n.Settings.eventSearchRadiusDistance($0)
return Model(
title: description,
action: .check(RideEventSettings.RideEventRadius.self),
accessibilityIdentifier: description
)
},
sectionTitle: L10n.Settings.eventSearchRadius
)
]
static let appSettings: [SettingsSection] = {
var themeTitle: String {
if #available(iOS 13.0, *) {
return L10n.Settings.Theme.appearance
} else {
return L10n.Settings.theme
}
}
var themeAction: Action {
if #available(iOS 13.0, *) {
return .navigate(toViewController: ThemeSelectionViewController.self)
} else {
return .switch(ThemeController.self)
}
}
var preferencesModels = [
Model(
title: themeTitle,
action: themeAction,
accessibilityIdentifier: "Theme"
),
Model(
title: L10n.Settings.Observationmode.title,
subtitle: L10n.Settings.Observationmode.detail,
action: .switch(ObservationModePreferenceStore.self),
accessibilityIdentifier: L10n.Settings.Observationmode.title
),
Model(
title: L10n.Settings.appIcon,
action: .navigate(toViewController: AppIconSelectViewController.self),
accessibilityIdentifier: L10n.Settings.appIcon
)
]
if Feature.events.isActive {
let eventSettings = Model(
title: L10n.Settings.eventSettings,
action: .navigate(toViewController: EventSettingsViewController.self),
accessibilityIdentifier: L10n.Settings.eventSettings
)
preferencesModels.insert(eventSettings, at: 0)
}
if Feature.friends.isActive {
let friendsModel = Model(
title: L10n.Settings.friends,
subtitle: nil,
action: .navigate(toViewController: ManageFriendsViewController.self),
accessibilityIdentifier: L10n.Settings.friends
)
preferencesModels.insert(friendsModel, at: 0)
}
return [
.preferences(models: preferencesModels, sectionTitle: nil),
.projectLinks(
models: [
Model(action: .open(url: Constants.criticalMapsiOSGitHubEndpoint), accessibilityIdentifier: "GitHub"),
Model(action: .open(url: Constants.criticalMassDotInURL), accessibilityIdentifier: "CriticalMass.in")
],
[.github, .criticalMassDotIn],
sectionTitle: nil
),
.info(
models: [
Model(title: L10n.Settings.website, action: .open(url: Constants.criticalMapsWebsite), accessibilityIdentifier: "Website"),
Model(title: L10n.Settings.twitter, action: .open(url: Constants.criticalMapsTwitterPage), accessibilityIdentifier: "Twitter"),
Model(title: L10n.Settings.facebook, action: .open(url: Constants.criticalMapsFacebookPage), accessibilityIdentifier: "Facebook")
],
sectionTitle: L10n.Settings.Section.info
)
]
}()
}
| 33.688679 | 149 | 0.561887 |
f9adc818fedb7cc310178d537a35ad2349b6e257
| 4,019 |
/*
Copyright (c) 2017-2018 Kevin McGill <[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 UIKit
import XCTest
@testable import McPicker
// swiftlint:disable nesting
// swiftlint:disable force_cast
class McPickerBarButtonItemTests: XCTestCase {
let mcPicker = McPicker(data: [["Bob", "Bill"]])
func testInitDone_noTitleDefaultStyle() {
let item = McPickerBarButtonItem.done(mcPicker: mcPicker)
XCTAssertNil(item.title)
XCTAssertTrue(item.style == .done)
XCTAssertTrue(item.target as! McPicker == mcPicker)
XCTAssertTrue(item.action == #selector(McPicker.done))
}
func testInitDone_noTitleCustomStyle() {
let item = McPickerBarButtonItem.done(mcPicker: mcPicker, barButtonSystemItem: UIBarButtonSystemItem.save)
XCTAssertNil(item.title)
XCTAssertTrue(item.style == .plain)
XCTAssertTrue(item.target as! McPicker == mcPicker)
XCTAssertTrue(item.action == #selector(McPicker.done))
}
func testInitDone_withTitle() {
let title = "My Custom Title"
let item = McPickerBarButtonItem.done(mcPicker: mcPicker, title: title)
XCTAssertTrue(item.title == title)
XCTAssertTrue(item.style == .plain)
XCTAssertTrue(item.target as! McPicker == mcPicker)
XCTAssertTrue(item.action == #selector(McPicker.done))
}
func testInitCancel_noTitle() {
let item = McPickerBarButtonItem.cancel(mcPicker: mcPicker)
XCTAssertNil(item.title)
XCTAssertTrue(item.style == .plain)
XCTAssertTrue(item.target as! McPicker == mcPicker)
XCTAssertTrue(item.action == #selector(McPicker.cancel))
}
func testInitCancel_noTitleCustomStyle() {
let item = McPickerBarButtonItem.cancel(mcPicker: mcPicker, barButtonSystemItem: UIBarButtonSystemItem.save)
XCTAssertNil(item.title)
XCTAssertTrue(item.style == .plain)
XCTAssertTrue(item.target as! McPicker == mcPicker)
XCTAssertTrue(item.action == #selector(McPicker.cancel))
}
func testInitCancel_withTitle() {
let title = "My Custom Title"
let item = McPickerBarButtonItem.cancel(mcPicker: mcPicker, title: title)
XCTAssertTrue(item.title == title)
XCTAssertTrue(item.style == .plain)
XCTAssertTrue(item.target as! McPicker == mcPicker)
XCTAssertTrue(item.action == #selector(McPicker.cancel))
}
func testInitFlexibleSpace() {
let item = McPickerBarButtonItem.flexibleSpace()
XCTAssertTrue(item.style == .plain)
XCTAssertNil(item.target)
XCTAssertNil(item.action)
}
func testInitFixedSpace() {
let expectedWidth: CGFloat = 2.0
let item = McPickerBarButtonItem.fixedSpace(width: expectedWidth)
XCTAssertTrue(item.width == expectedWidth)
XCTAssertTrue(item.style == .plain)
XCTAssertNil(item.title)
XCTAssertNil(item.target)
XCTAssertNil(item.action)
}
}
| 37.212963 | 116 | 0.708883 |
2278d7a1d3ac395df2c42bb970d21cb7f9c0ce59
| 3,783 |
/*
See LICENSE folder for this sample’s licensing information.
Abstract:
DateIntervalFormatterView.swift
*/
import SwiftUI
struct DateIntervalFormatterView: View {
private let startDate = sampleDate
private let endDate = ISO8601DateFormatter().date(from: "2020-06-26T18:00:00-07:00")!
@State private var formatterState = FormatterState()
var body: some View {
VStack {
HStack {
Text("अंतराल", comment: "Interval")
.font(.subheadline)
.textCase(.uppercase)
.foregroundColor(.gray)
.padding(.top, 10)
.padding(.leading, 10)
Spacer()
}
VStack {
let localizedDateInterval = formatterState.string(from: startDate, to: endDate)
Text(localizedDateInterval)
.font(.title2)
.padding(.top, 10)
.padding(.bottom, 10)
HStack {
Text("तारीख़", comment: "Date")
.font(.subheadline)
.textCase(.uppercase)
.foregroundColor(.gray)
Spacer()
Picker("", selection: $formatterState.dateStyle) {
Text(verbatim: "∅").tag(DateIntervalFormatter.Style.none)
Text(verbatim: "•").tag(DateIntervalFormatter.Style.short)
Text(verbatim: "••").tag(DateIntervalFormatter.Style.medium)
Text(verbatim: "•••").tag(DateIntervalFormatter.Style.long)
Text(verbatim: "••••").tag(DateIntervalFormatter.Style.full)
}
.pickerStyle(SegmentedPickerStyle())
}
HStack {
Text("समय", comment: "Time")
.font(.subheadline)
.textCase(.uppercase)
.foregroundColor(.gray)
Spacer()
Picker("", selection: $formatterState.timeStyle) {
Text(verbatim: "∅").tag(DateIntervalFormatter.Style.none)
Text(verbatim: "•").tag(DateIntervalFormatter.Style.short)
Text(verbatim: "••").tag(DateIntervalFormatter.Style.medium)
Text(verbatim: "•••").tag(DateIntervalFormatter.Style.long)
Text(verbatim: "••••").tag(DateIntervalFormatter.Style.full)
}
.pickerStyle(SegmentedPickerStyle())
.padding(.bottom, 5)
}
}
.background(RoundedRectangle(cornerRadius: 10.0, style: .continuous)
.foregroundColor(.init(.sRGB, red: 0, green: 0, blue: 0, opacity: 0.05))
.padding(-10)
)
.padding(20)
}
}
private struct FormatterState {
private var formatter = DateIntervalFormatter()
var dateStyle = DateIntervalFormatter.Style.medium { didSet { updateFormatter() } }
var timeStyle = DateIntervalFormatter.Style.none { didSet { updateFormatter() } }
init() {
updateFormatter()
}
func string(from fromDate: Date, to toDate: Date) -> String {
formatter.string(from: fromDate, to: toDate)
}
private func updateFormatter() {
formatter.dateStyle = dateStyle
formatter.timeStyle = timeStyle
}
}
}
struct DateIntervalFormatterView_Previews: PreviewProvider {
static var previews: some View {
DateIntervalFormatterView()
}
}
| 38.212121 | 100 | 0.505155 |
096fc0caa636bd47077964d7a09442042b092bef
| 2,407 |
//
// UIColorExtensions.swift
// PhotoZnapp
//
// Created by Behran Kankul on 31.08.2018.
// Copyright © 2018 Be Mobile. All rights reserved.
//
import UIKit
extension UIColor {
open class var navBarBg : UIColor {
return UIColor(red:0.98, green:0.98, blue:0.98, alpha:1.0)
}
open class var followBg : UIColor {
return UIColor(red:0.95, green:0.88, blue:0.09, alpha:1.0)
}
open class var followedBg : UIColor {
return UIColor(red:0.80, green:0.84, blue:0.85, alpha:1.0)
//TagColors.Purple.toUIColor()
}
open class var textFieldBorder:UIColor {
return UIColor(red:0.80, green:0.84, blue:0.85, alpha:1.0)
}
open class var textFieldBorderSelected:UIColor {
return UIColor(red:0.31, green:0.02, blue:0.96, alpha:1.0)
}
open class var btnSelectedBackground:UIColor {
return UIColor(red:0.18, green:0.62, blue:0.75, alpha:1.0)
}
var hexString: String? {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha: CGFloat = 0
let multiplier = CGFloat(255.999999)
guard self.getRed(&red, green: &green, blue: &blue, alpha: &alpha) else {
return nil
}
if alpha == 1.0 {
return String(
format: "#%02lX%02lX%02lX",
Int(red * multiplier),
Int(green * multiplier),
Int(blue * multiplier)
)
}
else {
return String(
format: "#%02lX%02lX%02lX%02lX",
Int(red * multiplier),
Int(green * multiplier),
Int(blue * multiplier),
Int(alpha * multiplier)
)
}
}
public convenience init?(hexString: String, alpha: CGFloat = 1.0) {
var formatted = hexString.replacingOccurrences(of: "0x", with: "")
formatted = formatted.replacingOccurrences(of: "#", with: "")
if let hex = Int(formatted, radix: 16) {
let red = CGFloat(CGFloat((hex & 0xFF0000) >> 16)/255.0)
let green = CGFloat(CGFloat((hex & 0x00FF00) >> 8)/255.0)
let blue = CGFloat(CGFloat((hex & 0x0000FF) >> 0)/255.0)
self.init(red: red, green: green, blue: blue, alpha: alpha)
} else {
return nil
}
}
}
| 32.093333 | 81 | 0.53926 |
b9086a431c6a3820ddc00ca47f50e2275d3517a9
| 5,905 |
//
// Predefine.swift
// SwiftTemplate
//
// Created by RuanMei on 2019/10/14.
// Copyright © 2019 RuanMei. All rights reserved.
//
import UIKit
/// 设备类型
var IS_IPAD: Bool {
return QMUIHelper.isIPad();
}
var IS_IPOD: Bool {
return QMUIHelper.isIPod();
}
var IS_IPHONE: Bool {
return QMUIHelper.isIPhone();
}
var IS_SIMULATOR: Bool {
return QMUIHelper.isSimulator();
}
/// 操作系统版本号,只获取第二级的版本号,例如 10.3.1 只会得到 10.3
var IOS_VERSION: Double {
return Double(UIDevice.current.systemVersion)!;
}
/// 数字形式的操作系统版本号,可直接用于大小比较;如 110205 代表 11.2.5 版本;根据 iOS 规范,版本号最多可能有3位
var IOS_VERSION_NUMBER: Int {
return QMUIHelper.numbericOSVersion();
}
/// 是否横竖屏
/// 用户界面横屏了才会返回YES
var IS_LANDSCAPE: Bool {
if #available(iOS 13.0, *) {
let windowScene:UIWindowScene! = UIApplication.shared.windows.first?.windowScene
return windowScene.interfaceOrientation.isLandscape
} else {
return UIApplication.shared.statusBarOrientation.isLandscape
}
}
/// 无论支不支持横屏,只要设备横屏了,就会返回YES
var IS_DEVICE_LANDSCAPE: Bool {
return UIDevice.current.orientation.isLandscape;
}
/// 屏幕宽度,会根据横竖屏的变化而变化
var SCREEN_WIDTH: CGFloat {
return UIScreen.main.bounds.size.width
}
/// 屏幕高度,会根据横竖屏的变化而变化
var SCREEN_HEIGHT: CGFloat {
return UIScreen.main.bounds.size.height
}
/// 设备宽度,跟横竖屏无关
var DEVICE_WIDTH: CGFloat {
return min(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height)
}
/// 设备高度,跟横竖屏无关
var DEVICE_HEIGHT: CGFloat {
return max(UIScreen.main.bounds.size.width, UIScreen.main.bounds.size.height)
}
/// 在 iPad 分屏模式下等于 app 实际运行宽度,否则等同于 SCREEN_WIDTH
var APPLICATION_WIDTH: CGFloat {
return QMUIHelper.applicationSize().width
}
/// 在 iPad 分屏模式下等于 app 实际运行高度,否则等同于 DEVICE_HEIGHT
var APPLICATION_HEIGHT: CGFloat {
return QMUIHelper.applicationSize().height
}
/// 是否全面屏设备
var IS_NOTCHED_SCREEN: Bool {
return QMUIHelper.isNotchedScreen()
}
/// iPhone XS Max
var IS_65INCH_SCREEN: Bool {
return QMUIHelper.is65InchScreen()
}
/// iPhone XR
var IS_61INCH_SCREEN: Bool {
return QMUIHelper.is61InchScreen()
}
/// iPhone X/XS
var IS_58INCH_SCREEN: Bool {
return QMUIHelper.is58InchScreen()
}
/// iPhone 6/7/8 Plus
var IS_55INCH_SCREEN: Bool {
return QMUIHelper.is55InchScreen()
}
/// iPhone 6/7/8
var IS_47INCH_SCREEN: Bool {
return QMUIHelper.is47InchScreen()
}
/// iPhone 5/5S/SE
var IS_40INCH_SCREEN: Bool {
return QMUIHelper.is40InchScreen()
}
/// iPhone 4/4S
var IS_35INCH_SCREEN: Bool {
return QMUIHelper.is35InchScreen()
}
/// iPhone 4/4S/5/5S/SE
var IS_320WIDTH_SCREEN: Bool {
return (IS_35INCH_SCREEN || IS_40INCH_SCREEN)
}
/// 是否Retina
var IS_RETINASCREEN: Bool {
return UIScreen.main.scale >= 2.0
}
/// 是否放大模式(iPhone 6及以上的设备支持放大模式,iPhone X 除外)
var IS_ZOOMEDMODE: Bool {
return QMUIHelper.isZoomedMode()
}
/// 获取一个像素
var PixelOne: CGFloat {
return QMUIHelper.pixelOne()
}
/// bounds && nativeBounds / scale && nativeScale
var ScreenBoundsSize: CGSize {
return UIScreen.main.bounds.size
}
var ScreenNativeBoundsSize: CGSize {
return UIScreen.main.nativeBounds.size
}
var ScreenScale: CGFloat {
return UIScreen.main.scale
}
var ScreenNativeScale: CGFloat {
return UIScreen.main.nativeScale
}
/// toolBar相关frame
var ToolBarHeight: CGFloat {
return (IS_IPAD ? (IS_NOTCHED_SCREEN ? 70 : (IOS_VERSION >= 12.0 ? 50 : 44)) : (IS_LANDSCAPE ? PreferredValueForVisualDevice(regular: 44, compact: 32) : 44) + SafeAreaInsetsConstantForDeviceWithNotch.bottom)
}
/// tabBar相关frame
var TabBarHeight: CGFloat {
return (IS_IPAD ? (IS_NOTCHED_SCREEN ? 65 : (IOS_VERSION >= 12.0 ? 50 : 49)) : (IS_LANDSCAPE ? PreferredValueForVisualDevice(regular: 49, compact: 32) : 49) + SafeAreaInsetsConstantForDeviceWithNotch.bottom)
}
/// 状态栏高度(来电等情况下,状态栏高度会发生变化,所以应该实时计算,iOS 13 起,来电等情况下状态栏高度不会改变)
var StatusBarHeight: CGFloat {
if #available(iOS 13.0, *) {
let statusBarManager:UIStatusBarManager! = UIApplication.shared.windows.first?.windowScene?.statusBarManager
return statusBarManager.isStatusBarHidden ? 0 : statusBarManager.statusBarFrame.size.height;
} else {
return UIApplication.shared.isStatusBarHidden ? 0 : UIApplication.shared.statusBarFrame.size.height
}
}
/// 状态栏高度(如果状态栏不可见,也会返回一个普通状态下可见的高度)
var StatusBarHeightConstant: CGFloat {
if #available(iOS 13.0, *) {
let statusBarManager:UIStatusBarManager! = UIApplication.shared.windows.first?.windowScene?.statusBarManager
return statusBarManager.isStatusBarHidden ? 0 : statusBarManager.statusBarFrame.size.height;
} else {
return UIApplication.shared.isStatusBarHidden ? (IS_IPAD ? (IS_NOTCHED_SCREEN ? 24 : 20) : PreferredValueForNotchedDevice(notchedDevice: IS_LANDSCAPE ? 0 : 44, otherDevice: 20)) : UIApplication.shared.statusBarFrame.size.height
}
}
/// navigationBar 的静态高度
var NavigationBarHeight: CGFloat {
return (IS_IPAD ? (IOS_VERSION >= 12.0 ? 50 : 44) : (IS_LANDSCAPE ? PreferredValueForVisualDevice(regular: 44, compact: 32) : 44))
}
/// 代表(导航栏+状态栏),这里用于获取其高度
/// @warn 如果是用于 viewController,请使用 UIViewController(QMUI) qmui_navigationBarMaxYInViewCoordinator 代替
var NavigationContentTop: CGFloat {
return StatusBarHeight + NavigationBarHeight
}
/// 同上,这里用于获取它的静态常量值
var NavigationContentTopConstant: CGFloat {
return StatusBarHeightConstant + NavigationBarHeight
}
/// iPhoneX 系列全面屏手机的安全区域的静态值
var SafeAreaInsetsConstantForDeviceWithNotch: UIEdgeInsets {
return QMUIHelper.safeAreaInsetsForDeviceWithNotch();
}
// MARK: 方法
/// 区分全面屏(iPhone X 系列)和非全面屏
func PreferredValueForNotchedDevice(notchedDevice: CGFloat, otherDevice: CGFloat) -> CGFloat {
return QMUIHelper.isNotchedScreen() ? notchedDevice : otherDevice
}
/// 将所有屏幕按照宽松/紧凑分类,其中 iPad、iPhone XS Max/XR/Plus 均为宽松屏幕,但开启了放大模式的设备均会视为紧凑屏幕
func PreferredValueForVisualDevice(regular: CGFloat, compact: CGFloat) -> CGFloat {
return QMUIHelper.isRegularScreen() ? regular : compact
}
| 32.26776 | 235 | 0.745639 |
6717b513e616e70ca88f1bfbabb771558875b6e9
| 1,148 |
import Foundation
func plistValues(_ bundle: Bundle) -> (clientId: String, network: Network)? {
guard
let path = bundle.path(forResource: "OpenLogin", ofType: "plist"),
let values = NSDictionary(contentsOfFile: path) as? [String: Any]
else {
print("Missing OpenLogin.plist file in your bundle!")
return nil
}
guard
let clientId = values["ClientId"] as? String,
let networkValue = values["Network"] as? String,
let network = Network(rawValue: networkValue)
else {
print("OpenLogin.plist file at \(path) is missing or having incorrect 'ClientId' and/or 'Network' entries!")
print("File currently has the following entries: \(values)")
return nil
}
return (clientId: clientId, network: network)
}
func decodedBase64(_ base64URLSafe: String) -> Data? {
var base64 = base64URLSafe
.replacingOccurrences(of: "-", with: "+")
.replacingOccurrences(of: "_", with: "/")
if base64.count % 4 != 0 {
base64.append(String(repeating: "=", count: 4 - base64.count % 4))
}
return Data(base64Encoded: base64)
}
| 34.787879 | 116 | 0.629791 |
ef261fae530c7094d7828362c7675142bfc70360
| 203 |
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct A : A.b {
let b = [ [Void{
| 29 | 87 | 0.729064 |
fc088845405b467e847ab0ed41f7c3eec7198184
| 1,439 |
//
// TopBar.swift
// Gordian Seed Tool
//
// Created by Wolf McNally on 12/16/20.
//
import SwiftUI
struct TopBar<L, T>: ViewModifier where L: View, T: View {
let leading: L
let trailing: T
func body(content: Content) -> some View {
VStack {
HStack {
leading
Spacer()
trailing
}
.frame(maxWidth: .infinity)
.padding()
// KLUDGE: For some reason under Big Sur, Catalyst Buttons are very hard
// to hit if they don't have a visible background.
.background(Application.isCatalyst ? Color.secondary.opacity(0.01) : Color.clear)
content
.frame(maxHeight: .infinity)
}
}
}
extension View {
func topBar<L, T>(leading: L, trailing: T) -> some View where L : View, T : View {
modifier(TopBar(leading: leading, trailing: trailing))
}
func topBar<L>(leading: L) -> some View where L : View {
modifier(TopBar(leading: leading, trailing: EmptyView()))
}
func topBar<T>(trailing: T) -> some View where T : View {
modifier(TopBar(leading: EmptyView(), trailing: trailing))
}
}
#if DEBUG
struct TopBar_Previews: PreviewProvider {
static var previews: some View {
Text("Hello")
.topBar(leading: Text("Leading"), trailing: Text("Trailing"))
.padding()
}
}
#endif
| 24.810345 | 93 | 0.567755 |
918a5ead61854e0c50043c1b55673895ecb989ba
| 858 |
//
// GLBaseTableView.swift
// SmartHeater
//
// Created by GrayLand on 2020/3/31.
// Copyright © 2020 GrayLand119. All rights reserved.
//
import UIKit
open class GLBaseTableView: UITableView {
public override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
self.separatorStyle = .none
if #available(iOS 11.0, *) {
self.contentInsetAdjustmentBehavior = .never
}
self.backgroundColor = UIColor.white
}
public required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Life Cycle
// MARK: - Override
// MARK: - Public
// MARK: - Private
// MARK: - OnEvent
// MARK: - Custom Delegate
// MARK: - Setter
// MARK: - Getter
}
| 20.428571 | 67 | 0.579254 |
4652d431a5003aff791412a4848c1c235fb85f07
| 4,087 |
//
// Conversions.swift
// RbSwift
//
// Created by draveness on 19/03/2017.
// Copyright © 2017 draveness. All rights reserved.
//
import Foundation
import Quick
import Nimble
import RbSwift
class StringConversionsSpec: BaseSpec {
var locale = Locale(identifier: "en_US_POSIX")
override func spec() {
describe(".to_i") {
it("returns an integer under different circumstances") {
expect("0a".to_i(16)).to(equal(10))
expect("0xa".to_i(16)).to(equal(0))
expect("12".to_i).to(equal(12))
expect("-1100101".to_i(2)).to(equal(-101))
expect("1100101".to_i(2)).to(equal(101))
expect("1100101".to_i(8)).to(equal(294977))
expect("1100101".to_i(10)).to(equal(1100101))
expect("1100101".to_i(16)).to(equal(17826049))
}
it("returns zero if base is not in 2...36") {
expect("".to_i).to(equal(0))
expect(" ".to_i).to(equal(0))
expect("0a".to_i(1)).to(equal(0))
expect("0a".to_i(37)).to(equal(0))
}
it("returns zero if format is invalid") {
expect("-".to_i).to(equal(0))
expect("d-1".to_i).to(equal(0))
expect("0a".to_i).to(equal(0))
expect("hello".to_i).to(equal(0))
}
}
describe(".oct") {
it("returns a oct integer from str") {
expect("123".oct).to(equal(83))
expect("-377".oct).to(equal(-255))
expect("377bad".oct).to(equal(255))
expect("bad".oct).to(equal(0))
}
}
describe(".ord") {
it("Return the Integer ordinal of a one-character string") {
expect("a".ord).to(equal(97))
expect("ab".ord).to(equal(97))
expect("b".ord).to(equal(98))
}
}
describe(".hex") {
it("returns a hex integer from str") {
expect("-".hex).to(equal(0))
expect("0xa".hex).to(equal(10))
expect("-0xa".hex).to(equal(-10))
expect("a".hex).to(equal(10))
}
}
describe(".to_double") {
it("returns an float under different circumstances") {
expect("0a".to_double).to(equal(0))
expect("1100101.11".to_double).to(equal(1100101.11))
expect("123.456".to_double).to(equal(123.456))
expect("123.456ddddd".to_double).to(equal(123.456))
expect(".456ddddd".to_double).to(equal(0.456))
}
it("returns zero if format is invalid") {
expect("-".to_double).to(equal(0))
expect("d-1".to_double).to(equal(0))
expect("0a".to_double).to(equal(0))
expect("..12".to_double).to(equal(0))
expect("hello".to_double).to(equal(0))
}
}
describe(".to_datetime") {
it("returns a Date with RFC2822 form") {
let date = "Sun Mar 19 01:04:21 2017".to_datetime(locale: self.locale)!
expect(date.year).to(equal(2017))
expect(date.month).to(equal(3))
expect(date.day).to(equal(19))
expect(date.hour).to(equal(1))
expect(date.minute).to(equal(4))
expect(date.second).to(equal(21))
}
it("returns a Date with custom form") {
let date = "2017-03-19 00:35:36 +0800".to_datetime(locale: self.locale)!
expect(date.year).to(equal(2017))
expect(date.month).to(equal(3))
expect(date.day).to(equal(19))
expect(date.hour).to(equal(0))
expect(date.minute).to(equal(35))
expect(date.second).to(equal(36))
}
}
}
}
| 36.491071 | 88 | 0.472963 |
d9cc0979ae90a4c184f507ec77dd3fa9096af622
| 11,204 |
/*
The MIT License (MIT)
Copyright (c) 2015-present Badoo Trading Limited.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
import UIKit
import Chatto
public protocol ViewModelBuilderProtocol {
associatedtype ModelT: MessageModelProtocol
associatedtype ViewModelT: MessageViewModelProtocol
func canCreateViewModel(fromModel model: Any) -> Bool
func createViewModel(_ model: ModelT) -> ViewModelT
}
public protocol BaseMessageInteractionHandlerProtocol {
associatedtype MessageType
associatedtype ViewModelType
func userDidTapOnFailIcon(message: MessageType, viewModel: ViewModelType, failIconView: UIView)
func userDidTapOnAvatar(message: MessageType, viewModel: ViewModelType)
func userDidTapOnBubble(message: MessageType, viewModel: ViewModelType)
func userDidDoubleTapOnBubble(message: MessageType, viewModel: ViewModelType)
func userDidBeginLongPressOnBubble(message: MessageType, viewModel: ViewModelType)
func userDidEndLongPressOnBubble(message: MessageType, viewModel: ViewModelType)
func userDidSelectMessage(message: MessageType, viewModel: ViewModelType)
func userDidDeselectMessage(message: MessageType, viewModel: ViewModelType)
}
open class BaseMessagePresenter<BubbleViewT, ViewModelBuilderT, InteractionHandlerT>: BaseChatItemPresenter<BaseMessageCollectionViewCell<BubbleViewT>> where
ViewModelBuilderT: ViewModelBuilderProtocol,
InteractionHandlerT: BaseMessageInteractionHandlerProtocol,
InteractionHandlerT.MessageType == ViewModelBuilderT.ModelT,
InteractionHandlerT.ViewModelType == ViewModelBuilderT.ViewModelT,
BubbleViewT: UIView,
BubbleViewT: MaximumLayoutWidthSpecificable,
BubbleViewT: BackgroundSizingQueryable {
public typealias CellT = BaseMessageCollectionViewCell<BubbleViewT>
public typealias ModelT = ViewModelBuilderT.ModelT
public typealias ViewModelT = ViewModelBuilderT.ViewModelT
public init (
messageModel: ModelT,
viewModelBuilder: ViewModelBuilderT,
interactionHandler: InteractionHandlerT?,
sizingCell: BaseMessageCollectionViewCell<BubbleViewT>,
cellStyle: BaseMessageCollectionViewCellStyleProtocol) {
self.messageModel = messageModel
self.sizingCell = sizingCell
self.viewModelBuilder = viewModelBuilder
self.cellStyle = cellStyle
self.interactionHandler = interactionHandler
}
public internal(set) var messageModel: ModelT {
didSet { self.messageViewModel = self.createViewModel() }
}
open override var isItemUpdateSupported: Bool {
/*
By default, item updates are not supported.
But this behaviour could be changed by the descendants.
In this case, an update method checks item type, sets a new value for a message model and creates a new message view model.
*/
return false
}
open override func update(with chatItem: ChatItemProtocol) {
assert(self.isItemUpdateSupported, "Updated is called on presenter which doesn't support updates: \(type(of: chatItem)).")
guard let newMessageModel = chatItem as? ModelT else { assertionFailure("Unexpected type of the message: \(type(of: chatItem))."); return }
self.messageModel = newMessageModel
}
public let sizingCell: BaseMessageCollectionViewCell<BubbleViewT>
public let viewModelBuilder: ViewModelBuilderT
public let interactionHandler: InteractionHandlerT?
public let cellStyle: BaseMessageCollectionViewCellStyleProtocol
public private(set) final lazy var messageViewModel: ViewModelT = self.createViewModel()
open func createViewModel() -> ViewModelT {
let viewModel = self.viewModelBuilder.createViewModel(self.messageModel)
return viewModel
}
public final override func configureCell(_ cell: UICollectionViewCell, decorationAttributes: ChatItemDecorationAttributesProtocol?) {
guard let cell = cell as? CellT else {
assert(false, "Invalid cell given to presenter")
return
}
guard let decorationAttributes = decorationAttributes as? ChatItemDecorationAttributes else {
assert(false, "Expecting decoration attributes")
return
}
self.decorationAttributes = decorationAttributes
self.configureCell(cell, decorationAttributes: decorationAttributes, animated: false, additionalConfiguration: nil)
}
public var decorationAttributes: ChatItemDecorationAttributes!
open func configureCell(_ cell: CellT, decorationAttributes: ChatItemDecorationAttributes, animated: Bool, additionalConfiguration: (() -> Void)?) {
cell.performBatchUpdates({ () -> Void in
self.messageViewModel.decorationAttributes = decorationAttributes.messageDecorationAttributes
// just in case something went wrong while showing UIMenuController
self.messageViewModel.isUserInteractionEnabled = true
cell.baseStyle = self.cellStyle
cell.messageViewModel = self.messageViewModel
cell.allowRevealing = !decorationAttributes.messageDecorationAttributes.isShowingSelectionIndicator
cell.onBubbleTapped = { [weak self] (cell) in
guard let sSelf = self else { return }
sSelf.onCellBubbleTapped()
}
cell.onBubbleDoubleTapped = { [weak self] (cell) in
guard let sSelf = self else { return }
sSelf.onCellBubbleDoubleTapped()
}
cell.onBubbleLongPressBegan = { [weak self] (cell) in
guard let sSelf = self else { return }
sSelf.onCellBubbleLongPressBegan()
}
cell.onBubbleLongPressEnded = { [weak self] (cell) in
guard let sSelf = self else { return }
sSelf.onCellBubbleLongPressEnded()
}
cell.onAvatarTapped = { [weak self] (cell) in
guard let sSelf = self else { return }
sSelf.onCellAvatarTapped()
}
cell.onFailedButtonTapped = { [weak self] (cell) in
guard let sSelf = self else { return }
sSelf.onCellFailedButtonTapped(cell.failedButton)
}
cell.onSelection = { [weak self] (cell) in
guard let sSelf = self else { return }
sSelf.onCellSelection()
}
additionalConfiguration?()
}, animated: animated, completion: nil)
}
open override func heightForCell(maximumWidth width: CGFloat, decorationAttributes: ChatItemDecorationAttributesProtocol?) -> CGFloat {
guard let decorationAttributes = decorationAttributes as? ChatItemDecorationAttributes else {
assert(false, "Expecting decoration attributes")
return 0
}
self.configureCell(self.sizingCell, decorationAttributes: decorationAttributes, animated: false, additionalConfiguration: nil)
return self.sizingCell.sizeThatFits(CGSize(width: width, height: .greatestFiniteMagnitude)).height
}
open override var canCalculateHeightInBackground: Bool {
return self.sizingCell.canCalculateSizeInBackground
}
open override func cellWillBeShown() {
self.messageViewModel.willBeShown()
}
open override func cellWasHidden() {
self.messageViewModel.wasHidden()
}
open override func shouldShowMenu() -> Bool {
guard self.canShowMenu() else { return false }
guard let cell = self.cell else {
assert(false, "Investigate -> Fix or remove assert")
return false
}
cell.bubbleView.isUserInteractionEnabled = false // This is a hack for UITextView, shouldn't harm to all bubbles
NotificationCenter.default.addObserver(self, selector: #selector(BaseMessagePresenter.willShowMenu(_:)), name: UIMenuController.willShowMenuNotification, object: nil)
return true
}
@objc
func willShowMenu(_ notification: Notification) {
NotificationCenter.default.removeObserver(self, name: UIMenuController.willShowMenuNotification, object: nil)
guard let cell = self.cell, let menuController = notification.object as? UIMenuController else {
assert(false, "Investigate -> Fix or remove assert")
return
}
cell.bubbleView.isUserInteractionEnabled = true
menuController.setMenuVisible(false, animated: false)
menuController.setTargetRect(cell.bubbleView.bounds, in: cell.bubbleView)
menuController.setMenuVisible(true, animated: true)
}
open func canShowMenu() -> Bool {
// Override in subclass
return false
}
open func onCellBubbleTapped() {
self.interactionHandler?.userDidTapOnBubble(message: self.messageModel, viewModel: self.messageViewModel)
}
open func onCellBubbleDoubleTapped() {
self.interactionHandler?.userDidDoubleTapOnBubble(message: self.messageModel, viewModel: self.messageViewModel)
}
open func onCellBubbleLongPressBegan() {
self.interactionHandler?.userDidBeginLongPressOnBubble(message: self.messageModel, viewModel: self.messageViewModel)
}
open func onCellBubbleLongPressEnded() {
self.interactionHandler?.userDidEndLongPressOnBubble(message: self.messageModel, viewModel: self.messageViewModel)
}
open func onCellAvatarTapped() {
self.interactionHandler?.userDidTapOnAvatar(message: self.messageModel, viewModel: self.messageViewModel)
}
open func onCellFailedButtonTapped(_ failedButtonView: UIView) {
self.interactionHandler?.userDidTapOnFailIcon(message: self.messageModel, viewModel: self.messageViewModel, failIconView: failedButtonView)
}
open func onCellSelection() {
if self.messageViewModel.decorationAttributes.isSelected {
self.interactionHandler?.userDidDeselectMessage(message: self.messageModel, viewModel: self.messageViewModel)
} else {
self.interactionHandler?.userDidSelectMessage(message: self.messageModel, viewModel: self.messageViewModel)
}
}
}
| 45.730612 | 174 | 0.71769 |
75dec5c85b2b84a571f8a7b82f373400b768cbc6
| 1,414 |
//
// FlickrResponseDecodableTests.swift
// FlickrTrackrTests
//
// Created by Tom Kraina on 20/09/2018.
// Copyright © 2018 Tom Kraina. All rights reserved.
//
import XCTest
@testable import FlickrTrackr
class FlickrResponseDecodableTests: XCTestCase {
func testDecodeFlickrPhotoSearchResponseSuccess() throws {
let response: FlickrPhotoSearchResponse = try JSON(named: "flickr.photos.search-success")
XCTAssertGreaterThan(response.searchResult?.photos.count ?? 0, 0)
}
func testDecodeFlickrPhotoSearchResponseError() throws {
let response: FlickrPhotoSearchResponse = try JSON(named: "flickr.photos.search-error")
XCTAssertNil(response.searchResult)
}
func testDecodeSearchResultWherePagesIsInt() throws {
let json = """
{ "page": 1, "pages": 2, "perpage": 100, "total": "1170344", "photo": [] }
""".data(using: .utf8)!
let searchResult = try JSONDecoder().decode(FlickrSearchResult.self, from: json)
XCTAssertEqual(searchResult.pages, 2)
}
func testDecodeSearchResultWherePagesIsString() throws {
let json = """
{ "page": 1, "pages": "2", "perpage": 100, "total": "1170344", "photo": [] }
""".data(using: .utf8)!
let searchResult = try JSONDecoder().decode(FlickrSearchResult.self, from: json)
XCTAssertEqual(searchResult.pages, 2)
}
}
| 34.487805 | 97 | 0.661952 |
7516ec4a6b78556d01aac773c96ea69aa61d8199
| 1,318 |
//
// UserData.swift
// Instagram_Codepath
//
// Created by user on 3/5/16.
// Copyright © 2016 Jean. All rights reserved.
//
import UIKit
import Parse
class UserData: NSObject {
var image: UIImage?
var author: PFUser?
var createdAt: String?
var caption: String?
var cell: PhotoTableViewCell?
class func postUserImage(image: UIImage?, withCaption caption: String?, withCompletion completion: PFBooleanResultBlock){
// Create Parse object PFObject
let media = PFObject(className: "UserData")
// Add relevant fields to the object
media["media"] = getPFFileFromImage(image) // PFFile column type
media["addedBy"] = PFUser.currentUser() // Pointer column type that points to PFUser
media["date"] = media.dataAvailable
media["caption"] = caption
media.saveInBackgroundWithBlock(completion)
print("posted succesfully")
}
class func getPFFileFromImage(image: UIImage?) -> PFFile? {
// check if image is not nil
if let image = image {
// get image data and check if that is not nil
if let imageData = UIImagePNGRepresentation(image) {
return PFFile(name: "image.png", data: imageData)
}
}
return nil
}
}
| 24.407407 | 125 | 0.628225 |
20e90b6dee60d488b1b21c281317762bc0ee355a
| 2,899 |
//
// XLWeiboCell.swift
// WeiboDemo
//
// Created by Jennifer on 29/11/15.
// Copyright © 2015 Snowgan. All rights reserved.
//
import UIKit
class XLWeiboCell: UITableViewCell {
var originalView: XLWeiboCellOriginalView!
var retweetView: XLWeiboCellRetweetView?
var actionView: XLWeiboCellActionView!
var picsView: XLWeiboPicsView?
var layout: XLWeiboCellLayout! {
didSet {
originalView.origViewLayout = layout.origViewLayout
if let retweetV = retweetView {
retweetV.frame.origin.y = layout.origViewLayout.origHeight
retweetV.retwViewLayout = layout.retwViewLayout
}
if let picsV = picsView {
picsV.frame.origin.y = layout.origViewLayout.origHeight
picsV.picsLayout = layout.picsViewLayout
if picsV.status.isRetweet {
picsV.frame.origin.y += retweetView!.retwViewLayout.retweetHeight
}
}
actionView.frame.origin.y = layout.height + 1.0
}
}
var status: XLStatus! {
didSet {
originalView.status = status.original
if let retweet = status.retweet {
if retweetView == nil {
let retwV = XLWeiboCellRetweetView()
contentView.addSubview(retwV)
retweetView = retwV
}
retweetView!.status = retweet
} else if retweetView != nil {
retweetView!.removeFromSuperview()
retweetView = nil
}
// if picsView != nil {
// picsView!.removeFromSuperview()
// picsView = nil
// }
if let pictures = status.pictures {
if picsView == nil {
let picsV = XLWeiboPicsView()
contentView.addSubview(picsV)
picsView = picsV
}
picsView!.status = pictures
} else if picsView != nil {
picsView!.removeFromSuperview()
picsView = nil
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.backgroundColor = bgColor
let origV = XLWeiboCellOriginalView()
self.contentView.addSubview(origV)
self.originalView = origV
let actV = XLWeiboCellActionView(frame: CGRect(x: 0.0, y: 0.0, width: windowFrame.width, height: 30.0))
self.contentView.addSubview(actV)
self.actionView = actV
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
| 30.197917 | 111 | 0.533632 |
bb65ae6f6554305f8e88e166fc6de6bdde23230f
| 14,537 |
//===----------------------------------------------------------------------===//
//
// This source file is part of the Soto for AWS open source project
//
// Copyright (c) 2017-2021 the Soto project authors
// Licensed under Apache License v2.0
//
// See LICENSE.txt for license information
// See CONTRIBUTORS.txt for the list of Soto project authors
//
// SPDX-License-Identifier: Apache-2.0
//
//===----------------------------------------------------------------------===//
// THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT.
import SotoCore
// MARK: Paginators
extension FMS {
/// Returns an array of AppsListDataSummary objects.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used for logging output
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listAppsListsPaginator<Result>(
_ input: ListAppsListsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListAppsListsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listAppsLists,
inputKey: \ListAppsListsRequest.nextToken,
outputKey: \ListAppsListsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used for logging output
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listAppsListsPaginator(
_ input: ListAppsListsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListAppsListsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listAppsLists,
inputKey: \ListAppsListsRequest.nextToken,
outputKey: \ListAppsListsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns an array of PolicyComplianceStatus objects. Use PolicyComplianceStatus to get a summary of which member accounts are protected by the specified policy.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used for logging output
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listComplianceStatusPaginator<Result>(
_ input: ListComplianceStatusRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListComplianceStatusResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listComplianceStatus,
inputKey: \ListComplianceStatusRequest.nextToken,
outputKey: \ListComplianceStatusResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used for logging output
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listComplianceStatusPaginator(
_ input: ListComplianceStatusRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListComplianceStatusResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listComplianceStatus,
inputKey: \ListComplianceStatusRequest.nextToken,
outputKey: \ListComplianceStatusResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns a MemberAccounts object that lists the member accounts in the administrator's Amazon Web Services organization. The ListMemberAccounts must be submitted by the account that is set as the Firewall Manager administrator.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used for logging output
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listMemberAccountsPaginator<Result>(
_ input: ListMemberAccountsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListMemberAccountsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listMemberAccounts,
inputKey: \ListMemberAccountsRequest.nextToken,
outputKey: \ListMemberAccountsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used for logging output
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listMemberAccountsPaginator(
_ input: ListMemberAccountsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListMemberAccountsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listMemberAccounts,
inputKey: \ListMemberAccountsRequest.nextToken,
outputKey: \ListMemberAccountsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns an array of PolicySummary objects.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used for logging output
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listPoliciesPaginator<Result>(
_ input: ListPoliciesRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListPoliciesResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listPolicies,
inputKey: \ListPoliciesRequest.nextToken,
outputKey: \ListPoliciesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used for logging output
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listPoliciesPaginator(
_ input: ListPoliciesRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListPoliciesResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listPolicies,
inputKey: \ListPoliciesRequest.nextToken,
outputKey: \ListPoliciesResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Returns an array of ProtocolsListDataSummary objects.
///
/// Provide paginated results to closure `onPage` for it to combine them into one result.
/// This works in a similar manner to `Array.reduce<Result>(_:_:) -> Result`.
///
/// Parameters:
/// - input: Input for request
/// - initialValue: The value to use as the initial accumulating value. `initialValue` is passed to `onPage` the first time it is called.
/// - logger: Logger used for logging output
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each paginated response. It combines an accumulating result with the contents of response. This combined result is then returned
/// along with a boolean indicating if the paginate operation should continue.
public func listProtocolsListsPaginator<Result>(
_ input: ListProtocolsListsRequest,
_ initialValue: Result,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (Result, ListProtocolsListsResponse, EventLoop) -> EventLoopFuture<(Bool, Result)>
) -> EventLoopFuture<Result> {
return client.paginate(
input: input,
initialValue: initialValue,
command: listProtocolsLists,
inputKey: \ListProtocolsListsRequest.nextToken,
outputKey: \ListProtocolsListsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
/// Provide paginated results to closure `onPage`.
///
/// - Parameters:
/// - input: Input for request
/// - logger: Logger used for logging output
/// - eventLoop: EventLoop to run this process on
/// - onPage: closure called with each block of entries. Returns boolean indicating whether we should continue.
public func listProtocolsListsPaginator(
_ input: ListProtocolsListsRequest,
logger: Logger = AWSClient.loggingDisabled,
on eventLoop: EventLoop? = nil,
onPage: @escaping (ListProtocolsListsResponse, EventLoop) -> EventLoopFuture<Bool>
) -> EventLoopFuture<Void> {
return client.paginate(
input: input,
command: listProtocolsLists,
inputKey: \ListProtocolsListsRequest.nextToken,
outputKey: \ListProtocolsListsResponse.nextToken,
on: eventLoop,
onPage: onPage
)
}
}
extension FMS.ListAppsListsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FMS.ListAppsListsRequest {
return .init(
defaultLists: self.defaultLists,
maxResults: self.maxResults,
nextToken: token
)
}
}
extension FMS.ListComplianceStatusRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FMS.ListComplianceStatusRequest {
return .init(
maxResults: self.maxResults,
nextToken: token,
policyId: self.policyId
)
}
}
extension FMS.ListMemberAccountsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FMS.ListMemberAccountsRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension FMS.ListPoliciesRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FMS.ListPoliciesRequest {
return .init(
maxResults: self.maxResults,
nextToken: token
)
}
}
extension FMS.ListProtocolsListsRequest: AWSPaginateToken {
public func usingPaginationToken(_ token: String) -> FMS.ListProtocolsListsRequest {
return .init(
defaultLists: self.defaultLists,
maxResults: self.maxResults,
nextToken: token
)
}
}
| 43.39403 | 235 | 0.648139 |
8f9a4e8bde0ee6a392621d8fe3778e9b10e1d9b0
| 2,615 |
//
// CardDetectionSettings.swift
// IDCardCamera
//
// Created by Jakub Dolejs on 11/12/2019.
// Copyright © 2019 Applied Recognition Inc. All rights reserved.
//
import UIKit
/// Card detection session settings
/// - Since: 1.0.0
@objc public class CardDetectionSettings: BaseCardDetectionSettings, TorchSettings {
/// Set the torch level when the user turns the torch on
///
/// Range `0.0` (darkest) – `1` (brightest). Default value is `0.1`.
/// - Since: 1.2.0
@objc public var torchLevel: Float = 0.1
}
/// Base card detection settings
/// - Since: 1.4.0
@objc public class BaseCardDetectionSettings: NSObject {
/// Card orientation
/// - Since: 1.0.0
@objc public enum Orientation: Int {
/// Landscape (height < width)
case landscape
/// Portrait (width < height)
case portrait
}
/// Size of the card to detect
///
/// Only the aspect ratio is considered by the app. The units are inconsequential.
/// - Since: 1.0.0
@objc public var size: CGSize
/// Orientation of the card to be detected
///
/// The orientation is determined by the size. Setting the orientation to the other available value will flip the width and height of the size.
/// - Since: 1.0.0
@objc public var orientation: Orientation {
get {
return size.width > size.height ? .landscape : .portrait
}
set {
if newValue == .landscape && size.width < size.height {
let w = size.width
size.width = size.height
size.height = w
} else if newValue == .portrait && size.height < size.width {
let h = size.height
size.height = size.width
size.width = h
}
}
}
/// Number of image samples the camera should collect
///
/// The samples in the pool are compared for sharpness and the sharpest one is de-warped and returned.
/// - Since: 1.1.0
@objc public var imagePoolSize: Int = 5
/// Initializer
/// - Parameters:
/// - width: Width of the card (units don't matter)
/// - height: Height of the card (units don't matter)
/// - Since: 1.0.0
@objc public init(width: CGFloat, height: CGFloat) {
self.size = CGSize(width: width, height: height)
}
/// Convenience initializer
///
/// Initializes settings with ISO ID-1 dimensions
/// - Since: 1.4.0
@objc public convenience override init() {
self.init(width: 85.6, height: 53.98)
}
}
| 31.130952 | 147 | 0.58891 |
22234940d22999844e65053a1c3851cff9645a03
| 918 |
import Cocoa
// MARK: Protocol definition
/// Make your `NSTableViewCellView` and `NSCollectionViewItem` subclasses
/// conform to this protocol when they are *not* NIB-based but only code-based
/// to be able to dequeue them in a type-safe manner
public protocol Reusable: class {
/// The reuse identifier to use when registering and later dequeuing a reusable cell
static var reuseIdentifier: NSUserInterfaceItemIdentifier { get }
}
/// Make your `NSTableViewCellView` and `NSCollectionViewItem` subclasses
/// conform to this typealias when they *are* NIB-based
/// to be able to dequeue them in a type-safe manner
public typealias NibReusable = Reusable & NibLoadable
// MARK: - Default implementation
public extension Reusable {
/// By default, use the name of the class as String for its reuseIdentifier
static var reuseIdentifier: NSUserInterfaceItemIdentifier {
.init(String(describing: self))
}
}
| 35.307692 | 85 | 0.771242 |
9beae3906da5c1719d4ca630804d25d107e0990f
| 944 |
//
// DirectiveHandleResult.swift
// NuguCore
//
// Created by MinChul Lee on 2020/07/08.
// Copyright (c) 2019 SK Telecom Co., Ltd. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// <#Description#>
public enum DirectiveHandleResult {
case failed(_ description: String)
case canceled
case stopped(directiveCancelPolicy: DirectiveCancelPolicy)
case finished
}
| 31.466667 | 76 | 0.727754 |
e9459a2e8f61088019e1549a166893aa9feb99bd
| 2,458 |
// MIT License
//
// Copyright (c) 2017 Wesley Wickwire
//
// 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
protocol MetadataInfo {
var kind: Kind { get }
var size: Int { get }
var alignment: Int { get }
var stride: Int { get }
init(type: Any.Type)
}
protocol MetadataType: MetadataInfo, TypeInfoConvertible {
associatedtype Layout: MetadataLayoutType
var type: Any.Type { get set }
var metadata: UnsafeMutablePointer<Layout> { get set }
var base: UnsafeMutablePointer<Int> { get set }
init(type: Any.Type, metadata: UnsafeMutablePointer<Layout>, base: UnsafeMutablePointer<Int>)
}
extension MetadataType {
var kind: Kind {
return Kind(flag: base.pointee)
}
var size: Int {
return metadata.pointee.valueWitnessTable.pointee.size
}
var alignment: Int {
return (metadata.pointee.valueWitnessTable.pointee.flags & ValueWitnessFlags.alignmentMask) + 1
}
var stride: Int {
return metadata.pointee.valueWitnessTable.pointee.stride
}
init(type: Any.Type) {
let base = metadataPointer(type: type)
let metadata = base.advanced(by: valueWitnessTableOffset).raw.assumingMemoryBound(to: Layout.self)
self.init(type: type, metadata: metadata, base: base)
}
mutating func toTypeInfo() -> TypeInfo {
return TypeInfo(metadata: self)
}
}
| 34.619718 | 106 | 0.706672 |
750b8a8dca0f726daf1405e9c68d75866e1dfa5c
| 8,740 |
import UIKit
protocol SettingsViewControllerDelegate: class {
func settingsViewController(_ settingsViewController: SettingsViewController,
didChangeSettings settings: SettingsEntity)
}
final class SettingsViewController: UIViewController {
public static func makeModule(settings: SettingsEntity,
delegate: SettingsViewControllerDelegate? = nil) -> UIViewController {
let controller = SettingsViewController(settings: settings)
controller.delegate = delegate
return controller
}
weak var delegate: SettingsViewControllerDelegate?
// MARK: - UI properties
private lazy var tableViewController = TableViewController(style: .grouped)
private lazy var closeBarItem = UIBarButtonItem(image: #imageLiteral(resourceName: "Settings.Close"),
style: .plain,
target: self,
action: #selector(closeBarButtonItemDidPress))
// MARK: - Private properties
private var settings: SettingsEntity {
didSet {
delegate?.settingsViewController(self, didChangeSettings: settings)
}
}
// MARK: - Managing the View
override func loadView() {
view = UIView()
view.setStyles(UIView.Styles.grayBackground)
let tableView: UITableView = tableViewController.tableView
tableView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(tableView)
let constraints: [NSLayoutConstraint]
if #available(iOS 11.0, *) {
constraints = [
tableView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
tableView.leadingAnchor.constraint(equalTo: view.safeAreaLayoutGuide.leadingAnchor),
view.safeAreaLayoutGuide.trailingAnchor.constraint(equalTo: tableView.trailingAnchor),
view.safeAreaLayoutGuide.bottomAnchor.constraint(equalTo: tableView.bottomAnchor),
]
} else {
constraints = [
tableView.top.constraint(equalTo: view.top),
tableView.leading.constraint(equalTo: view.leading),
view.trailing.constraint(equalTo: tableView.trailing),
view.bottom.constraint(equalTo: tableView.bottom),
]
}
NSLayoutConstraint.activate(constraints)
tableViewController.didMove(toParentViewController: self)
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.leftBarButtonItem = closeBarItem
navigationItem.title = Localized.title
navigationItem.backBarButtonItem = UIBarButtonItem(title: "", style: .plain, target: nil, action: nil)
tableViewController.sections = sectionDescriptors
tableViewController.reload()
}
// MARK: - Initialization/Deinitialization
init(settings: SettingsEntity) {
self.settings = settings
super.init(nibName: nil, bundle: nil)
addChildViewController(tableViewController)
}
@available(*, unavailable, message: "Use init(settings:) instead")
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
fatalError("Use init(settings:) instead of init(nibName:, bundle:)")
}
@available(*, unavailable, message: "Use init(settings:) instead")
required init?(coder aDecoder: NSCoder) {
fatalError("Use init(settings:) instead of init?(coder:)")
}
// MARK: - Action handlers
@objc
private func closeBarButtonItemDidPress() {
navigationController?.presentingViewController?.dismiss(animated: true, completion: nil)
}
}
// MARK: - TableView data
extension SettingsViewController {
private var sectionDescriptors: [SectionDescriptor] {
return [
paymentMethodsSection,
uiCustomizationSection,
testModeSection,
]
}
private var paymentMethodsSection: SectionDescriptor {
let yandexMoneyCell = switchCellWith(title: Localized.yandexMoney,
initialValue: { $0.isYandexMoneyEnabled },
settingHandler: { $0.isYandexMoneyEnabled = $1 })
let sberbankCell = switchCellWith(title: Localized.sberbank,
initialValue: { $0.isSberbankEnabled },
settingHandler: { $0.isSberbankEnabled = $1 })
let bankCardCell = switchCellWith(title: Localized.bankCard,
initialValue: { $0.isBankCardEnabled },
settingHandler: { $0.isBankCardEnabled = $1 })
let applePayCell = switchCellWith(title: Localized.applePay,
initialValue: { $0.isApplePayEnabled },
settingHandler: { $0.isApplePayEnabled = $1 })
return SectionDescriptor(headerText: Localized.paymentMethods,
rows: [yandexMoneyCell, sberbankCell, bankCardCell, applePayCell])
}
private var uiCustomizationSection: SectionDescriptor {
let yandexLogoCell = switchCellWith(title: Localized.yandexLogo,
initialValue: { $0.isShowingYandexLogoEnabled },
settingHandler: { $0.isShowingYandexLogoEnabled = $1 })
return SectionDescriptor(rows: [yandexLogoCell])
}
private var testModeSection: SectionDescriptor {
let testMode = CellDescriptor(configuration: { [unowned self] (cell: ContainerTableViewCell<TextValueView>) in
cell.containedView.title = Localized.test_mode
cell.containedView.value = self.settings.testModeSettings.isTestModeEnadled ?
translate(CommonLocalized.on) : translate(CommonLocalized.off)
cell.accessoryType = .disclosureIndicator
}, selection: { [unowned self] (indexPath) in
self.tableViewController.tableView.deselectRow(at: indexPath, animated: true)
let controller = TestSettingsViewController.makeModule(settings: self.settings.testModeSettings,
delegate: self)
let navigation = UINavigationController(rootViewController: controller)
if #available(iOS 11.0, *) {
navigation.navigationBar.prefersLargeTitles = true
}
self.present(navigation, animated: true, completion: nil)
})
return SectionDescriptor(rows: [testMode])
}
private func switchCellWith(title: String,
initialValue: @escaping (SettingsEntity) -> Bool,
settingHandler: @escaping (inout SettingsEntity, Bool) -> Void)
-> CellDescriptor {
return CellDescriptor(configuration: { [unowned self] (cell: ContainerTableViewCell<TitledSwitchView>) in
cell.containedView.title = title
cell.containedView.isOn = initialValue(self.settings)
cell.containedView.valueChangeHandler = {
settingHandler(&self.settings, $0)
}
})
}
}
// MARK: - TestSettingsViewControllerDelegate
extension SettingsViewController: TestSettingsViewControllerDelegate {
func testSettingsViewController(_ testSettingsViewController: TestSettingsViewController,
didChangeSettings settings: TestSettingsEntity) {
self.settings.testModeSettings = settings
tableViewController.reloadTable()
}
}
// MARK: - Localization
extension SettingsViewController {
private enum Localized {
static let title = NSLocalizedString("settings.title", comment: "")
static let paymentMethods = NSLocalizedString("settings.payment_methods.title", comment: "")
static let yandexMoney = NSLocalizedString("settings.payment_methods.yandex_money", comment: "")
static let bankCard = NSLocalizedString("settings.payment_methods.bank_card", comment: "")
static let sberbank = NSLocalizedString("settings.payment_methods.sberbank", comment: "")
static let applePay = NSLocalizedString("settings.payment_methods.apple_pay", comment: "")
static let yandexLogo = NSLocalizedString("settings.ui_customization.yandex_logo", comment: "")
static let test_mode = NSLocalizedString("settings.test_mode.title", comment: "")
}
}
| 39.192825 | 118 | 0.628833 |
fb47dea553689e00b0bf83553a2962a83d348e18
| 393 |
//
// ConfigKeys.swift
// SwiftUI-Demo
//
// Created by Suguru Kishimoto on 2020/08/10.
// Copyright © 2020 su-Tech. All rights reserved.
//
import Foundation
import Lobster
extension ConfigKeys {
static let titleText = ConfigKey<String>("demo_title_text")
static let titleColor = ConfigKey<UIColor>("demo_title_color")
static let person = ConfigKey<Person>("demo_person")
}
| 23.117647 | 66 | 0.722646 |
6afbf9c609f843671c884371388fe2e0c507624e
| 311 |
// RUN: %target-typecheck-verify-swift
func frob(x: inout Int) {}
func foo() {
let x: Int // expected-note* {{}}
x = 0
_ = { frob(x: x) }() // expected-error{{'x' is a 'let'}}
_ = { x = 0 }() // expected-error{{'x' is a 'let'}}
_ = { frob(x: x); x = 0 }() // expected-error 2 {{'x' is a 'let'}}
}
| 22.214286 | 68 | 0.495177 |
29459e7c2951f6df43d126467696e80bdf1cd4a0
| 787 |
// swift-tools-version:4.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
import PackageDescription
let package = Package(
name: "ElementalController",
products: [
.library(
name: "ElementalController",
targets: ["ElementalController"]),
],
dependencies: [
.package(url: "https://github.com/IBM-Swift/BlueSocket.git",.upToNextMajor(from: "1.0.0")),
.package(url: "https://github.com/Bouke/NetService.git",.upToNextMajor(from: "0.5.0"))
],
targets: [
.target(
name: "ElementalController",
dependencies: ["Socket", "NetService"],
path: ".",
sources: ["Sources/ElementalController"]),
]
)
| 30.269231 | 99 | 0.590851 |
1d186f5fef6d26a246e9f4e08c68a840a9ea1cac
| 1,766 |
//
// CreateRequest.swift
// BeaconSDK
//
// Created by Julia Samol on 19.11.20.
// Copyright © 2020 Papers AG. All rights reserved.
//
import Foundation
extension Matrix.RoomService {
struct CreateRequest: Codable {
let visibility: Visibility?
let roomAliasName: String?
let name: String?
let topic: String?
let invite: [String]?
let roomVersion: String?
let preset: Preset?
let isDirect: Bool?
init(
visibility: Visibility? = nil,
roomAliasName: String? = nil,
name: String? = nil,
topic: String? = nil,
invite: [String]? = nil,
roomVersion: String? = nil,
preset: Preset? = nil,
isDirect: Bool? = nil
) {
self.visibility = visibility
self.roomAliasName = roomAliasName
self.name = name
self.topic = topic
self.invite = invite
self.roomVersion = roomVersion
self.preset = preset
self.isDirect = isDirect
}
enum CodingKeys: String, CodingKey {
case visibility
case roomAliasName = "room_alias_name"
case name
case topic
case invite
case roomVersion = "room_version"
case preset
case isDirect = "is_direct"
}
enum Visibility: String, Codable {
case `public`
case `private`
}
enum Preset: String, Codable {
case privateChat = "private_chat"
case publicChat = "public_chat"
case trustedPrivateChat = "trusted_private_chat"
}
}
}
| 26.757576 | 60 | 0.521518 |
2285e4058c8a4c9845d5468268e2a5bc536c37d7
| 1,643 |
//
// Mirror.swift
// NavalWars
//
// Created by Damian Modernell on 21/05/2019.
// Copyright © 2019 Damian Modernell. All rights reserved.
//
import Foundation
public final class Mirror: ReflectableRotatableGameElement {
public var direction: PointingDirection
public init(direction: PointingDirection) {
self.direction = direction
}
}
extension Mirror {
public func reflect(_ laser: Laser) -> [Laser] {
switch laser.direction {
case .down:
if self.direction == .up {
return [Laser(direction: .left)]
} else if self.direction == .right {
return [Laser(direction: .right)]
} else {
return []
}
case .up:
if self.direction == .down {
return [Laser(direction: .right)]
} else if self.direction == .left {
return [Laser(direction: .left)]
} else {
return []
}
case .left:
if self.direction == .right {
return [Laser(direction: .up)]
} else if self.direction == .down {
return [Laser(direction: .down)]
} else {
return []
}
case .right:
if self.direction == .left {
return [Laser(direction: .down)]
} else if self.direction == .up {
return [Laser(direction: .up)]
} else {
return []
}
default:
return []
}
}
}
| 26.5 | 60 | 0.468046 |
399fdb495cb92b9fc4ccaa4a6011a0ff092d5477
| 2,900 |
//
// Language.swift
// NewsRoom
//
// Created by Kunal Shrivastava on 11/23/19.
// Copyright © 2019 Kunal Shrivastava. All rights reserved.
//
import Foundation
enum Language: String {
case english
case martian
}
extension Language {
func translate(text: String) -> String {
guard let languageTranslator = translator() else { return text }
return languageTranslator(text)
}
// TODO: Add tests
/**
- note
The algorithm is as follows:
- Split the string into words and spaces
- Loop over each word and space simultaneosly
- If word is translatable per the rules, replace it with the replacement
- Add the corresponding space
- Repeat until all word-space pair is exhausted
*/
private func translator() -> ((String) -> String)? {
switch self {
case .english:
print("No translator available to convert text to English")
return nil
case .martian:
return { (text) in
var tchSet = CharacterSet()
tchSet.formUnion(.whitespacesAndNewlines)
let words = text.components(separatedBy: tchSet).filter { $0 != "" }
var chSet = CharacterSet()
chSet.formUnion(.alphanumerics)
chSet.formUnion(.punctuationCharacters)
chSet.formUnion(.symbols)
var spaces = text.components(separatedBy: chSet).filter { $0 != "" }
/**
* The number of space based delimiters is equal to number of words minus 1.
* Eg: The New York Times has 4 words and has 3 delimiters.
* zip only works on arrays with equal count and ignores the difference. To accomodate
* for the difference of 1 betwen number of words and spaces, we add a padding of 1.
*/
if spaces.count < words.count {
spaces.append("")
}
var translation = ""
for (word, space) in zip(words, spaces) {
/**
* RegEx to match a word if it has any alphabet in it
*/
// [^a-zA-Z0-9]*$
let canTranlate = word.matches(#"^.*([A-Za-z]+).*$"#) && word.count > 3
let replacementWord = word.isCapitalized() ? "Boinga" : "boinga"
let trailingPunctuation = word.trailingPunctuations() ?? ""
translation += (canTranlate ? replacementWord : word)
translation += (canTranlate ? trailingPunctuation : "")
translation += space
}
return translation
}
}
}
}
| 36.25 | 102 | 0.516552 |
90dbce43ce4a03562ee928a5792a6574036dc174
| 371 |
//
// ApiRelease2.swift
// AFoundationDemo
//
// Created by Ihor Myroniuk on 05.02.2021.
// Copyright © 2021 Ihor Myroniuk. All rights reserved.
//
import AFoundation
extension Api.JsonRpc {
class Release2 {
static let scheme = "https"
static let host = "api.random.org"
static let path = "/json-rpc/2/invoke"
lazy var basic = Basic()
}
}
| 17.666667 | 56 | 0.652291 |
ac5912e9c36954f30e4e7bb0b8ce9cc781782256
| 12,249 |
//
// CarPlayDataSource.swift
// RelistenShared
//
// Created by Jacob Farkas on 7/27/18.
// Copyright © 2018 Alec Gorge. All rights reserved.
//
import Foundation
import MediaPlayer
import Observable
import Siesta
protocol CarPlayDataSourceDelegate : class {
func carPlayDataSourceUpdates(onQueue queue: DispatchQueue, _ updateBlock: @escaping () -> Void)
}
protocol Lockable {
var locked : Bool { get set }
var delegate : CarPlayDataSourceDelegate { get set }
}
class LockableDataItem<T> : Lockable {
private var _backingItem : T
private var _updatedBackingItem : T?
public var item : T {
get { return _backingItem }
set {
queue.async {
if self.locked {
self._updatedBackingItem = newValue
} else {
self.delegate.carPlayDataSourceUpdates(onQueue: self.queue) { [weak self] in
guard let s = self else { return }
s._backingItem = newValue
}
}
}
}
}
private var _locked : Bool = false
public var locked : Bool {
get { return _locked }
set {
dispatchPrecondition(condition: .onQueue(queue))
self._locked = newValue
if !self._locked, let update = self._updatedBackingItem {
self.delegate.carPlayDataSourceUpdates(onQueue: queue) { [weak self] in
guard let s = self else { return }
s._backingItem = update
}
}
}
}
private var queue : DispatchQueue
public unowned var delegate : CarPlayDataSourceDelegate
public init(_ item : T, queue: DispatchQueue, delegate : CarPlayDataSourceDelegate) {
_backingItem = item
self.queue = queue
self.delegate = delegate
}
}
class CarPlayDataSource {
unowned var delegate : CarPlayDataSourceDelegate {
didSet {
for var item in lockableDataItems {
item.delegate = delegate
}
}
}
private var disposal = Disposal()
private let queue = DispatchQueue(label: "net.relisten.CarPlay.DataSource")
public init(delegate: CarPlayDataSourceDelegate) {
_recentlyPlayedShows = LockableDataItem<[CompleteShowInformation]>([], queue: queue, delegate: delegate)
_favoriteShowsByArtist = LockableDataItem<[Artist : [CompleteShowInformation]]>([:], queue: queue, delegate: delegate)
_offlineShowsByArtist = LockableDataItem<[Artist : [CompleteShowInformation]]>([:], queue: queue, delegate: delegate)
_sortedArtistsWithFavorites = LockableDataItem<[ArtistWithCounts]>([], queue: queue, delegate: delegate)
lockableDataItems = [_recentlyPlayedShows, _favoriteShowsByArtist, _offlineShowsByArtist, _sortedArtistsWithFavorites]
self.delegate = delegate
// Realm requires that these observers are set up inside a runloop, so we have to do this on the main queue
DispatchQueue.main.async {
MyLibrary.shared.recent.shows.observeWithValue { [weak self] (recentlyPlayed, changes) in
guard let s = self else { return }
let tracks = recentlyPlayed.asTracks()
s.queue.async {
s.reloadRecentTracks(tracks: tracks)
}
}.dispose(to: &self.disposal)
MyLibrary.shared.offline.sources.observeWithValue { [weak self] (offline, changes) in
guard let s = self else { return }
let shows = offline.asCompleteShows(toIndex: -1)
s.queue.async {
s.reloadOfflineSources(shows: shows)
}
}.dispose(to: &self.disposal)
MyLibrary.shared.favorites.artists.observeWithValue { [weak self] (favArtists, changes) in
guard let s = self else { return }
let ids = Array(favArtists.map({ $0.artist }).filter({ $0 != nil }).map({ $0!.id }))
s.queue.async {
s.reloadFavoriteArtistIds(artistIds: ids)
}
}.dispose(to: &self.disposal)
MyLibrary.shared.favorites.sources.observeWithValue { [weak self] (favoriteShows, changes) in
guard let s = self else { return }
let favs = favoriteShows.asCompleteShows(toIndex: -1)
s.queue.async {
s.reloadFavorites(shows: favs)
}
}.dispose(to: &self.disposal)
self.loadArtists()
}
}
deinit {
DispatchQueue.main.async {
RelistenApi.artists().removeObservers(ownedBy: self)
}
}
private func loadArtists() {
let resource = RelistenApi.artists()
resource.addObserver(owner: self) { [weak self] (resource, _) in
guard let s = self else { return }
if let artistsWithCounts : [ArtistWithCounts] = resource.latestData?.typedContent() {
s.queue.async {
s.reloadArtists(artistsWithCounts: artistsWithCounts)
}
}
}
resource.loadFromCacheThenUpdate()
}
// MARK: Recently Played
public func recentlyPlayedShows() -> [CompleteShowInformation] {
var retval : [CompleteShowInformation]? = nil
queue.sync {
retval = _recentlyPlayedShows.item
}
return retval!
}
// MARK: Downloads
public func artistsWithOfflineShows() -> [Artist] {
var retval : [Artist]? = nil
queue.sync {
retval = _offlineShowsByArtist.item.keys.sorted(by: { $0.name > $1.name })
}
return retval!
}
public func offlineShowsForArtist(_ artist: Artist) -> [CompleteShowInformation]? {
var retval : [CompleteShowInformation]? = nil
queue.sync {
retval = _offlineShowsByArtist.item[artist]
}
return retval!
}
// MARK: Favorite Shows
public func artistsWithFavoritedShows() -> [Artist] {
var retval : [Artist]? = nil
queue.sync {
retval = _favoriteShowsByArtist.item.keys.sorted(by: { $0.name > $1.name })
}
return retval!
}
public func favoriteShowsForArtist(_ artist: Artist) -> [CompleteShowInformation]? {
var retval : [CompleteShowInformation]? = nil
queue.sync {
retval = _favoriteShowsByArtist.item[artist]
}
return retval!
}
// MARK: All Artists
public func allArtists() -> [ArtistWithCounts] {
var retval : [ArtistWithCounts]? = nil
queue.sync {
retval = _sortedArtistsWithFavorites.item
}
return retval!
}
public func years(forArtist artist: ArtistWithCounts) -> [Year]? {
var years : [Year]? = RelistenApi.years(byArtist: artist).latestData?.typedContent()
if let y = years {
years = sortedYears(from: y, for: artist)
}
return years
}
public func shows(forArtist artist : ArtistWithCounts, inYear year : Year) -> [Show]? {
var shows : [Show]? = nil
let yearWithShows : YearWithShows? = RelistenApi.shows(inYear: year, byArtist: artist).latestData?.typedContent()
if let yearWithShows = yearWithShows {
if artist.shouldSortYearsDescending {
shows = yearWithShows.shows.sorted(by: { $0.date.timeIntervalSince($1.date) > 0 })
} else {
shows = yearWithShows.shows
}
}
return shows
}
public func completeShow(forArtist artist : ArtistWithCounts, show : Show) -> CompleteShowInformation? {
var completeShowInfo : CompleteShowInformation? = nil
let showWithSources : ShowWithSources? = RelistenApi.showWithSources(forShow: show, byArtist: artist).latestData?.typedContent()
if let showWithSources = showWithSources {
let source : SourceFull? = showWithSources.sources.first
if let source = source {
completeShowInfo = CompleteShowInformation(source: source, show: show, artist: artist)
}
}
return completeShowInfo
}
// MARK: Sorting Data
private func sortArtistsWithFavorites(_ artists : [ArtistWithCounts]) -> [ArtistWithCounts] {
var favoriteArtists : [ArtistWithCounts] = []
var remainingArtists : [ArtistWithCounts] = []
for artist : ArtistWithCounts in artists {
if _favoriteArtistIds.contains(artist.id) {
favoriteArtists.append(artist)
} else {
remainingArtists.append(artist)
}
}
return favoriteArtists + remainingArtists
}
// MARK: Reloading Data
public func lockData() {
queue.async {
for var item in self.lockableDataItems {
item.locked = true
}
}
}
public func unlockData() {
queue.async {
for var item in self.lockableDataItems {
item.locked = false
}
}
}
private var lockableDataItems : [Lockable]
private var _recentlyPlayedShows: LockableDataItem<[CompleteShowInformation]>
private var _offlineShowsByArtist: LockableDataItem<[Artist : [CompleteShowInformation]]>
private var _favoriteShowsByArtist: LockableDataItem<[Artist : [CompleteShowInformation]]>
private var _sortedArtistsWithFavorites : LockableDataItem<[ArtistWithCounts]>
private var _favoriteArtistIds : [Int] = [] {
didSet {
_sortedArtistsWithFavorites.item = self.sortArtistsWithFavorites(_sortedArtistsWithFavorites.item)
}
}
public func reloadArtists(artistsWithCounts: [ArtistWithCounts]) {
dispatchPrecondition(condition: .onQueue(queue))
let artists = self.sortArtistsWithFavorites(artistsWithCounts)
if !(artists == _sortedArtistsWithFavorites.item) {
_sortedArtistsWithFavorites.item = artists
}
}
private func reloadRecentTracks(tracks: [Track]) {
dispatchPrecondition(condition: .onQueue(queue))
let recentShows : [CompleteShowInformation] = tracks.map { (track : Track) -> CompleteShowInformation in
return track.showInfo
}
if !(recentShows == _recentlyPlayedShows.item) {
_recentlyPlayedShows.item = recentShows
}
}
private func reloadOfflineSources(shows: [CompleteShowInformation]) {
dispatchPrecondition(condition: .onQueue(queue))
var offlineShowsByArtist : [Artist : [CompleteShowInformation]] = [:]
shows.forEach { (show) in
var artistShows = offlineShowsByArtist[show.artist]
if artistShows == nil {
artistShows = []
}
artistShows?.append(show)
offlineShowsByArtist[show.artist] = artistShows
}
if !(offlineShowsByArtist == _offlineShowsByArtist.item) {
_offlineShowsByArtist.item = offlineShowsByArtist
}
}
private func reloadFavoriteArtistIds(artistIds: [Int]) {
dispatchPrecondition(condition: .onQueue(queue))
_favoriteArtistIds = artistIds
}
private func reloadFavorites(shows: [CompleteShowInformation]) {
dispatchPrecondition(condition: .onQueue(queue))
var showsByArtist : [Artist : [CompleteShowInformation]] = [:]
shows.forEach { (show) in
var artistShows = showsByArtist[show.artist]
if artistShows == nil {
artistShows = []
}
artistShows?.append(show)
showsByArtist[show.artist] = artistShows
}
if !(showsByArtist == _favoriteShowsByArtist.item) {
_favoriteShowsByArtist.item = showsByArtist
}
}
}
| 36.239645 | 136 | 0.590171 |
d6d61fd10575913a80ba3b3df5d6b15c7864ee79
| 13,175 |
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_enum.swiftmodule -module-name=resilient_enum -I %t %S/../Inputs/resilient_enum.swift
// RUN: %target-swift-frontend -module-name struct_resilience -I %t -emit-ir -enable-resilience %s | %FileCheck %s
// RUN: %target-swift-frontend -module-name struct_resilience -I %t -emit-ir -enable-resilience -O %s
import resilient_struct
import resilient_enum
// CHECK: %TSi = type <{ [[INT:i32|i64]] }>
// CHECK-LABEL: @"$s17struct_resilience26StructWithResilientStorageVMf" = internal global
// Resilient structs from outside our resilience domain are manipulated via
// value witnesses
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience30functionWithResilientTypesSize_1f010resilient_A00G0VAFn_A2FnXEtF"(%swift.opaque* noalias nocapture sret, %swift.opaque* noalias nocapture, i8*, %swift.opaque*)
public func functionWithResilientTypesSize(_ s: __owned Size, f: (__owned Size) -> Size) -> Size {
// CHECK: entry:
// CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 0)
// CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0
// CHECK: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i8***
// CHECK: [[VWT_ADDR:%.*]] = getelementptr inbounds i8**, i8*** [[METADATA_ADDR]], [[INT]] -1
// CHECK: [[VWT:%.*]] = load i8**, i8*** [[VWT_ADDR]]
// CHECK-NEXT: [[VWT_CAST:%.*]] = bitcast i8** [[VWT]] to %swift.vwtable*
// CHECK-NEXT: [[WITNESS_ADDR:%.*]] = getelementptr inbounds %swift.vwtable, %swift.vwtable* [[VWT_CAST]], i32 0, i32 8
// CHECK: [[WITNESS_FOR_SIZE:%.*]] = load [[INT]], [[INT]]* [[WITNESS_ADDR]]
// CHECK: [[ALLOCA:%.*]] = alloca i8, {{.*}} [[WITNESS_FOR_SIZE]], align 16
// CHECK: [[STRUCT_ADDR:%.*]] = bitcast i8* [[ALLOCA]] to %swift.opaque*
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 2
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[initializeWithCopy:%.*]] = bitcast i8* [[WITNESS]]
// CHECK: [[STRUCT_LOC:%.*]] = call %swift.opaque* [[initializeWithCopy]](%swift.opaque* noalias [[STRUCT_ADDR]], %swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK: [[FN:%.*]] = bitcast i8* %2 to void (%swift.opaque*, %swift.opaque*, %swift.refcounted*)*
// CHECK: [[SELF:%.*]] = bitcast %swift.opaque* %3 to %swift.refcounted*
// CHECK: call swiftcc void [[FN]](%swift.opaque* noalias nocapture sret %0, %swift.opaque* noalias nocapture [[STRUCT_ADDR]], %swift.refcounted* swiftself [[SELF]])
// CHECK: [[WITNESS_PTR:%.*]] = getelementptr inbounds i8*, i8** [[VWT]], i32 1
// CHECK: [[WITNESS:%.*]] = load i8*, i8** [[WITNESS_PTR]]
// CHECK: [[destroy:%.*]] = bitcast i8* [[WITNESS]] to void (%swift.opaque*, %swift.type*)*
// CHECK: call void [[destroy]](%swift.opaque* noalias %1, %swift.type* [[METADATA]])
// CHECK-NEXT: bitcast
// CHECK-NEXT: call
// CHECK-NEXT: ret void
return f(s)
}
// CHECK-LABEL: declare{{( dllimport)?}} swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"
// CHECK-SAME: ([[INT]])
// Rectangle has fixed layout inside its resilience domain, and dynamic
// layout on the outside.
//
// Make sure we use a type metadata accessor function, and load indirect
// field offsets from it.
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience35functionWithResilientTypesRectangleyy010resilient_A00G0VF"(%T16resilient_struct9RectangleV* noalias nocapture)
public func functionWithResilientTypesRectangle(_ r: Rectangle) {
// CHECK: entry:
// CHECK-NEXT: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct9RectangleVMa"([[INT]] 0)
// CHECK-NEXT: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i32*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds i32, i32* [[METADATA_ADDR]], [[INT]] [[IDX:2|4]]
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds i32, i32* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load i32, i32* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %T16resilient_struct9RectangleV* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], i32 [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %TSi*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
_ = r.color
// CHECK-NEXT: ret void
}
// Resilient structs from inside our resilience domain are manipulated
// directly.
public struct MySize {
public let w: Int
public let h: Int
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience32functionWithMyResilientTypesSize_1fAA0eH0VAEn_A2EnXEtF"(%T17struct_resilience6MySizeV* noalias nocapture sret, %T17struct_resilience6MySizeV* noalias nocapture dereferenceable({{8|(16)}}), i8*, %swift.opaque*)
public func functionWithMyResilientTypesSize(_ s: __owned MySize, f: (__owned MySize) -> MySize) -> MySize {
// CHECK: alloca
// CHECK: [[TEMP:%.*]] = alloca %T17struct_resilience6MySizeV
// CHECK: bitcast
// CHECK: llvm.lifetime.start
// CHECK: bitcast
// CHECK: [[COPY:%.*]] = bitcast %T17struct_resilience6MySizeV* %5 to i8*
// CHECK: [[ARG:%.*]] = bitcast %T17struct_resilience6MySizeV* %1 to i8*
// CHECK: call void @llvm.memcpy{{.*}}(i8* align {{4|8}} [[COPY]], i8* align {{4|8}} [[ARG]], {{i32 8|i64 16}}, i1 false)
// CHECK: [[FN:%.*]] = bitcast i8* %2
// CHECK: call swiftcc void [[FN]](%T17struct_resilience6MySizeV* {{.*}} %0, {{.*}} [[TEMP]], %swift.refcounted* swiftself %{{.*}})
// CHECK: ret void
return f(s)
}
// Structs with resilient storage from a different resilience domain require
// runtime metadata instantiation, just like generics.
public struct StructWithResilientStorage {
public let s: Size
public let ss: (Size, Size)
public let n: Int
public let i: ResilientInt
}
// Make sure we call a function to access metadata of structs with
// resilient layout, and go through the field offset vector in the
// metadata when accessing stored properties.
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc {{i32|i64}} @"$s17struct_resilience26StructWithResilientStorageV1nSivg"(%T17struct_resilience26StructWithResilientStorageV* {{.*}})
// CHECK: [[TMP:%.*]] = call swiftcc %swift.metadata_response @"$s17struct_resilience26StructWithResilientStorageVMa"([[INT]] 0)
// CHECK: [[METADATA:%.*]] = extractvalue %swift.metadata_response [[TMP]], 0
// CHECK-NEXT: [[METADATA_ADDR:%.*]] = bitcast %swift.type* [[METADATA]] to i32*
// CHECK-NEXT: [[FIELD_OFFSET_VECTOR:%.*]] = getelementptr inbounds i32, i32* [[METADATA_ADDR]], [[INT]] [[IDX:2|4]]
// CHECK-NEXT: [[FIELD_OFFSET_PTR:%.*]] = getelementptr inbounds i32, i32* [[FIELD_OFFSET_VECTOR]], i32 2
// CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load i32, i32* [[FIELD_OFFSET_PTR]]
// CHECK-NEXT: [[STRUCT_ADDR:%.*]] = bitcast %T17struct_resilience26StructWithResilientStorageV* %0 to i8*
// CHECK-NEXT: [[FIELD_ADDR:%.*]] = getelementptr inbounds i8, i8* [[STRUCT_ADDR]], i32 [[FIELD_OFFSET]]
// CHECK-NEXT: [[FIELD_PTR:%.*]] = bitcast i8* [[FIELD_ADDR]] to %TSi*
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Indirect enums with resilient payloads are still fixed-size.
public struct StructWithIndirectResilientEnum {
public let s: FunnyShape
public let n: Int
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc {{i32|i64}} @"$s17struct_resilience31StructWithIndirectResilientEnumV1nSivg"(%T17struct_resilience31StructWithIndirectResilientEnumV* {{.*}})
// CHECK: [[FIELD_PTR:%.*]] = getelementptr inbounds %T17struct_resilience31StructWithIndirectResilientEnumV, %T17struct_resilience31StructWithIndirectResilientEnumV* %0, i32 0, i32 1
// CHECK-NEXT: [[FIELD_PAYLOAD_PTR:%.*]] = getelementptr inbounds %TSi, %TSi* [[FIELD_PTR]], i32 0, i32 0
// CHECK-NEXT: [[FIELD_PAYLOAD:%.*]] = load [[INT]], [[INT]]* [[FIELD_PAYLOAD_PTR]]
// CHECK-NEXT: ret [[INT]] [[FIELD_PAYLOAD]]
// Partial application of methods on resilient value types
public struct ResilientStructWithMethod {
public func method() {}
}
// Corner case -- type is address-only in SIL, but empty in IRGen
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience29partialApplyOfResilientMethod1ryAA0f10StructWithG0V_tF"(%T17struct_resilience25ResilientStructWithMethodV* noalias nocapture)
public func partialApplyOfResilientMethod(r: ResilientStructWithMethod) {
_ = r.method
}
// Type is address-only in SIL, and resilient in IRGen
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s17struct_resilience29partialApplyOfResilientMethod1sy010resilient_A04SizeV_tF"(%swift.opaque* noalias nocapture)
public func partialApplyOfResilientMethod(s: Size) {
_ = s.method
}
public func wantsAny(_ any: Any) {}
public func resilientAny(s : ResilientWeakRef) {
wantsAny(s)
}
// CHECK-LABEL: define{{.*}} swiftcc void @"$s17struct_resilience12resilientAny1sy0c1_A016ResilientWeakRefV_tF"(%swift.opaque* noalias nocapture)
// CHECK: entry:
// CHECK: [[ANY:%.*]] = alloca %Any
// CHECK: [[META:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct16ResilientWeakRefVMa"([[INT]] 0)
// CHECK: [[META2:%.*]] = extractvalue %swift.metadata_response %3, 0
// CHECK: [[TYADDR:%.*]] = getelementptr inbounds %Any, %Any* %1, i32 0, i32 1
// CHECK: store %swift.type* [[META2]], %swift.type** [[TYADDR]]
// CHECK: call %swift.opaque* @__swift_allocate_boxed_opaque_existential_0(%Any* [[ANY]])
// CHECK: call swiftcc void @"$s17struct_resilience8wantsAnyyyypF"(%Any* noalias nocapture dereferenceable({{(32|16)}}) [[ANY]])
// CHECK: call void @__swift_destroy_boxed_opaque_existential_0(%Any* [[ANY]])
// CHECK: ret void
// Public metadata accessor for our resilient struct
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc %swift.metadata_response @"$s17struct_resilience6MySizeVMa"
// CHECK-SAME: ([[INT]])
// CHECK: ret %swift.metadata_response { %swift.type* bitcast ([[INT]]* getelementptr inbounds {{.*}} @"$s17struct_resilience6MySizeVMf", i32 0, i32 1) to %swift.type*), [[INT]] 0 }
// CHECK-LABEL: define internal swiftcc %swift.metadata_response @"$s17struct_resilience26StructWithResilientStorageVMr"(%swift.type*, i8*, i8**)
// CHECK: [[FIELDS:%.*]] = alloca [4 x i8**]
// CHECK: [[TUPLE_LAYOUT:%.*]] = alloca %swift.full_type_layout,
// CHECK: [[FIELDS_ADDR:%.*]] = getelementptr inbounds [4 x i8**], [4 x i8**]* [[FIELDS]], i32 0, i32 0
// public let s: Size
// CHECK: [[T0:%.*]] = call swiftcc %swift.metadata_response @"$s16resilient_struct4SizeVMa"([[INT]] 319)
// CHECK: [[SIZE_METADATA:%.*]] = extractvalue %swift.metadata_response [[T0]], 0
// CHECK: [[T0:%.*]] = bitcast %swift.type* [[SIZE_METADATA]] to i8***
// CHECK: [[T1:%.*]] = getelementptr inbounds i8**, i8*** [[T0]], [[INT]] -1
// CHECK: [[SIZE_VWT:%.*]] = load i8**, i8*** [[T1]],
// CHECK: [[SIZE_LAYOUT_1:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8
// CHECK: [[FIELD_1:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 0
// CHECK: store i8** [[SIZE_LAYOUT_1:%.*]], i8*** [[FIELD_1]]
// public let ss: (Size, Size)
// CHECK: [[SIZE_LAYOUT_2:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8
// CHECK: [[SIZE_LAYOUT_3:%.*]] = getelementptr inbounds i8*, i8** [[SIZE_VWT]], i32 8
// CHECK: call swiftcc [[INT]] @swift_getTupleTypeLayout2(%swift.full_type_layout* [[TUPLE_LAYOUT]], i8** [[SIZE_LAYOUT_2]], i8** [[SIZE_LAYOUT_3]])
// CHECK: [[T0:%.*]] = bitcast %swift.full_type_layout* [[TUPLE_LAYOUT]] to i8**
// CHECK: [[FIELD_2:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 1
// CHECK: store i8** [[T0]], i8*** [[FIELD_2]]
// Fixed-layout aggregate -- we can reference a static value witness table
// public let n: Int
// CHECK: [[FIELD_3:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 2
// CHECK: store i8** getelementptr inbounds (i8*, i8** @"$sBi{{32|64}}_WV", i32 {{.*}}), i8*** [[FIELD_3]]
// Resilient aggregate with one field -- make sure we don't look inside it
// public let i: ResilientInt
// CHECK: call swiftcc %swift.metadata_response @"$s16resilient_struct12ResilientIntVMa"([[INT]] 319)
// CHECK: [[FIELD_4:%.*]] = getelementptr inbounds i8**, i8*** [[FIELDS_ADDR]], i32 3
// CHECK: store i8** [[SIZE_AND_ALIGNMENT:%.*]], i8*** [[FIELD_4]]
// CHECK: call void @swift_initStructMetadata(%swift.type* {{.*}}, [[INT]] 256, [[INT]] 4, i8*** [[FIELDS_ADDR]], i32* {{.*}})
| 55.357143 | 304 | 0.688501 |
504ad1d207ca2290ee7e78d8136f5b03ce4a8517
| 484 |
//
// DocumentTypesRequest.swift
// zScanner
//
// Created by Jakub Skořepa on 28/07/2019.
// Copyright © 2019 Institut klinické a experimentální medicíny. All rights reserved.
//
import Foundation
struct DocumentTypesRequest: Request {
typealias DataType = [DocumentTypeNetworkModel]
var endpoint: Endpoint = IkemEndpoint.documentTypes
var method: HTTPMethod = .get
var parameters: Parameters? = nil
var headers: HTTPHeaders = [:]
init() {}
}
| 23.047619 | 86 | 0.702479 |
9b57ed8da8da8739b250d828f674a14c0af88534
| 2,457 |
//
// RootRouter.swift
// Presentation
//
// Created by Yuki Okudera on 2022/01/30.
// Copyright © 2022 yuoku. All rights reserved.
//
import Application
import SwiftUI
/// 各タブのトップの画面のRouterプロパティを持つだけなので、RootRouterはRouterプロトコルに準拠しない
public final class RootRouter: ObservableObject {
@ObservedObject private var store: RootStore
let repoListRouter = RepoListRouterImpl(isPresented: .constant(false))
let userListRouter = UserListRouterImpl(isPresented: .constant(false))
public init(store: RootStore = .shared) {
self.store = store
}
func deepLinkValueChanged() async {
defer {
store.deepLink = nil
}
switch store.deepLink {
case .tab(let index):
guard let tab = TabIdentifier(rawValue: index) else {
return
}
// モーダルビューがあれば閉じる
await dismissAllModals()
// タブを選択
store.activeTab = tab
case .repo(let urlString):
// モーダルビューがあれば閉じる
await dismissAllModals()
// Repositoriesタブを選択
store.activeTab = .repositories
// RepositoriesタブのナビゲーションスタックのルートまでPopする
popToRootView(tab: .repositories)
// 遷移アニメーションが見えるようにするためdelayをかける
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(750)) { [weak self] in
self?.repoListRouter.navigateToGeneralWebView(urlString: urlString)
}
case .user(let urlString):
// モーダルビューがあれば閉じる
await dismissAllModals()
// Usersタブを選択
store.activeTab = .users
// UsersタブのナビゲーションスタックのルートまでPopする
popToRootView(tab: .users)
// 遷移アニメーションが見えるようにするためdelayをかける
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(750)) { [weak self] in
self?.userListRouter.navigateToGeneralWebView(urlString: urlString)
}
case .none:
print("Deeplink none.")
}
}
}
extension RootRouter {
private var tabBarController: UITabBarController? {
let rootViewController = UIApplication.shared.windows.filter({ $0.isKeyWindow }).first?.rootViewController
return rootViewController?.children.first as? UITabBarController
}
private func dismissAllModals() async {
await tabBarController?.dismiss(animated: true)
}
private func popToRootView(tab: TabIdentifier) {
guard let navigationController = tabBarController?.viewControllers?[safe: tab.rawValue]?.children.first as? UINavigationController else {
return
}
navigationController.popToRootViewController(animated: true)
}
}
| 29.60241 | 141 | 0.705332 |
012515fb2165eb35e0b6ff03f05d10affd0a790e
| 2,206 |
//
// LRUCache.swift
// AlgorithmPractice
//
// Created by 超杨 on 2020/9/21.
// Copyright © 2020 superYang. All rights reserved.
//
import Foundation
class LRUCache {
private let capacity: Int
private var size: Int = 0
private var cache: [Int: LRUListNode]
private var priority: LRULinkedList = LRULinkedList()
init(_ capacity: Int) {
self.capacity = capacity
self.cache = Dictionary(minimumCapacity: capacity)
}
func get(_ key: Int) -> Int {
guard let node = cache[key] else { return -1 }
priority.moveNodeToHead(node)
return node.value
}
func put(_ key: Int, _ value: Int) {
if let node = cache[key] {
node.value = value
priority.moveNodeToHead(node)
return
}
if cache.count == capacity {
guard let tailNode = priority.removeTailNode() else { return }
cache.removeValue(forKey: tailNode.key)
}
let newNode = LRUListNode(key, value)
cache[key] = newNode
priority.addNodeToHead(newNode)
}
}
private class LRULinkedList {
private let head = LRUListNode()
private let tail = LRUListNode()
init() {
self.head.next = self.tail
self.tail.previous = self.head
}
func addNodeToHead(_ node: LRUListNode) {
node.next = head.next
node.previous = head
head.next?.previous = node
head.next = node
}
func moveNodeToHead(_ node: LRUListNode) {
removeNode(node)
addNodeToHead(node)
}
func removeTailNode() -> LRUListNode? {
guard let node = tail.previous else { return nil }
removeNode(node)
return node
}
private func removeNode(_ node: LRUListNode) {
guard head.next !== tail else { return } // 判空
node.next?.previous = node.previous
node.previous?.next = node.next
}
}
class LRUListNode {
var key: Int = 0
var value: Int = 0
var next: LRUListNode?
weak var previous: LRUListNode?
init(_ key: Int, _ value: Int) {
self.key = key
self.value = value
}
init() {}
}
| 24.241758 | 74 | 0.579782 |
23f09df925539bd1998eef6d64feac80f8d8aa13
| 4,581 |
//
// MyMap.swift
// MapKitWrap
//
// Created by Dmytro Babych on 5/16/17.
// Copyright © 2017 Babych Studio. All rights reserved.
//
import Foundation
import MapKit
public class MyMap : MKMapView, MKMapViewDelegate {
private var mapContainerView : UIView? // MKScrollContainerView - map container that rotates and scales
private var zoom : Float = -1 // saved zoom value
private var rotation : Double = 0 // saved map rotation
private var changesTimer : Timer? // timer to track map changes; nil when changes are not tracked
public var listener : MyMapListener? // map listener to receive rotation changes
override public init(frame: CGRect) {
super.init(frame: frame)
self.mapContainerView = self.findViewOfType("MKScrollContainerView", inView: self)
self.startTrackingChanges()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// *****
// GETTING MAP PROPERTIES
public func getZoom() -> Double {
// function returns current zoom of the map
var angleCamera = self.rotation
if angleCamera > 270 {
angleCamera = 360 - angleCamera
} else if angleCamera > 90 {
angleCamera = fabs(angleCamera - 180)
}
let angleRad = Double.pi * angleCamera / 180 // map rotation in radians
let width = Double(self.frame.size.width)
let height = Double(self.frame.size.height)
let heightOffset : Double = 20 // the offset (status bar height) which is taken by MapKit into consideration to calculate visible area height
// calculating Longitude span corresponding to normal (non-rotated) width
let spanStraight = width * self.region.span.longitudeDelta / (width * cos(angleRad) + (height - heightOffset) * sin(angleRad))
return log2(360 * ((width / 128) / spanStraight))
}
public func getRotation() -> Double? {
// function gets current map rotation based on the transform values of MKScrollContainerView
if self.mapContainerView != nil {
var rotation = fabs(180 * asin(Double(self.mapContainerView!.transform.b)) / .pi)
if self.mapContainerView!.transform.b <= 0 {
if self.mapContainerView!.transform.a >= 0 {
// do nothing
} else {
rotation = 180 - rotation
}
} else {
if self.mapContainerView!.transform.a <= 0 {
rotation = rotation + 180
} else {
rotation = 360 - rotation
}
}
return rotation
} else {
return nil
}
}
// *****
// HANDLING MAP CHANGES
@objc private func trackChanges() {
// function detects map changes and processes it
if let rotation = self.getRotation() {
if rotation != self.rotation {
self.rotation = rotation
self.listener?.mapView?(self, rotationDidChange: rotation)
}
}
}
private func startTrackingChanges() {
// function starts tracking map changes
if self.changesTimer == nil {
self.changesTimer = Timer(timeInterval: 0.1, target: self, selector: #selector(MyMap.trackChanges), userInfo: nil, repeats: true)
RunLoop.current.add(self.changesTimer!, forMode: RunLoop.Mode.common)
}
}
private func stopTrackingChanges() {
// function stops tracking map changes
if self.changesTimer != nil {
self.changesTimer!.invalidate()
self.changesTimer = nil
}
}
// *****
// HELPER FUNCTIONS
private func findViewOfType(_ viewType: String, inView view: UIView) -> UIView? {
// function scans subviews recursively and returns reference to the found one of a type
if view.subviews.count > 0 {
for v in view.subviews {
let valueDescription = v.description
let keywords = viewType
if valueDescription.range(of: keywords) != nil {
return v
}
if let inSubviews = self.findViewOfType(viewType, inView: v) {
return inSubviews
}
}
return nil
} else {
return nil
}
}
}
| 32.260563 | 149 | 0.566252 |
c13ea8dd487afad7584af06ac7965a41aa9022a1
| 1,379 |
import Foundation
internal func identityAsString(value: AnyObject?) -> String {
if value == nil {
return "nil"
}
return NSString(format: "<%p>", unsafeBitCast(value!, Int.self)).description
}
internal func arrayAsString<T>(items: [T], joiner: String = ", ") -> String {
return items.reduce("") { accum, item in
let prefix = (accum.isEmpty ? "" : joiner)
return accum + prefix + "\(stringify(item))"
}
}
@objc internal protocol NMBStringer {
func NMB_stringify() -> String
}
internal func stringify<S: SequenceType>(value: S) -> String {
var generator = value.generate()
var strings = [String]()
var value: S.Generator.Element?
do {
value = generator.next()
if value != nil {
strings.append(stringify(value))
}
} while value != nil
let str = ", ".join(strings)
return "[\(str)]"
}
extension NSArray : NMBStringer {
func NMB_stringify() -> String {
let str = self.componentsJoinedByString(", ")
return "[\(str)]"
}
}
internal func stringify<T>(value: T) -> String {
if let value = value as? Double {
return NSString(format: "%.4f", (value)).description
}
return toString(value)
}
internal func stringify<T>(value: T?) -> String {
if let unboxed = value {
return stringify(unboxed)
}
return "nil"
}
| 24.625 | 80 | 0.598985 |
8a11bc32e8b6879a7f76bfde2833cb688b9ece1e
| 4,381 |
//
// StatusOverlayView.swift
// OBAKit
//
// Created by Aaron Brethorst on 12/8/18.
// Copyright © 2018 OneBusAway. All rights reserved.
//
import UIKit
import OBAKitCore
/// An overlay view placed on top of a map to offer status text to the user, like
/// if they need to zoom in to see stops on the map, or if their search query returned no results.
class StatusOverlayView: UIView {
public override init(frame: CGRect) {
super.init(frame: frame)
layer.cornerRadius = ThemeMetrics.padding
addSubview(statusOverlay)
statusOverlay.pinToSuperview(.edges)
statusOverlay.contentView.addSubview(statusLabel)
statusLabel.pinToSuperview(.layoutMargins)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private lazy var statusOverlay: UIVisualEffectView = {
let blurView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
blurView.backgroundColor = UIColor.white.withAlphaComponent(0.60)
blurView.clipsToBounds = true
blurView.contentView.directionalLayoutMargins = NSDirectionalEdgeInsets(top: ThemeMetrics.compactPadding, leading: ThemeMetrics.padding, bottom: ThemeMetrics.compactPadding, trailing: ThemeMetrics.padding)
return blurView
}()
/// Sets the text that is displayed on the status overlay
public var text: String? {
get {
return statusLabel.text
}
set {
statusLabel.text = newValue
}
}
private lazy var statusLabel: UILabel = {
let label = UILabel.obaLabel(font: .preferredFont(forTextStyle: .headline),
textColor: ThemeColors.shared.lightText)
label.textAlignment = .center
return label
}()
// MARK: - Animations
private var showAnimator: UIViewPropertyAnimator?
private var hideAnimator: UIViewPropertyAnimator?
/// Displays the overlay, by default animating in the display of it.
///
/// - Note: This method and `hideOverlay()` share a lock that prevents simultaneous access while an animation is occurring.
///
/// - Parameters:
/// - message: The text to display on the overlay
/// - animated: Whether or not the display of the overlay should be animated.
public func showOverlay(message: String, animated: Bool = true) {
text = message
// short-circuit the evaluation of this method and show the overlay if `animated` is false.
guard animated else {
statusOverlay.isHidden = false
statusOverlay.alpha = 1.0
return
}
// Bail out if we already have a 'show' animation running.
guard showAnimator == nil else {
return
}
hideAnimator?.stopAnimation(true)
hideAnimator = nil
statusOverlay.alpha = 0.0
statusOverlay.isHidden = false
let animator = UIViewPropertyAnimator(duration: UIView.inheritedAnimationDuration, curve: .easeInOut) { [weak self] in
self?.statusOverlay.alpha = 1.0
}
animator.startAnimation()
showAnimator = animator
}
/// Hides the overlay, by default animating it out.
///
/// - Note: This method and `showOverlay(message:)` share a lock that prevents simultaneous access while an animation is occurring.
///
/// - Parameter animated: Whether or not the display of the overlay should be animated.
public func hideOverlay(animated: Bool = true) {
// short-circuit the evaluation of this method and hide the overlay if `animated` is false.
guard animated else {
statusOverlay.isHidden = true
statusOverlay.alpha = 0.0
return
}
// Bail out if we already have a 'hide' animation running.
guard hideAnimator == nil else {
return
}
showAnimator?.stopAnimation(true)
showAnimator = nil
let animator = UIViewPropertyAnimator(duration: UIView.inheritedAnimationDuration, curve: .easeInOut) { [weak self] in
self?.statusOverlay.alpha = 0.0
}
animator.addCompletion { [unowned self] _ in
self.statusOverlay.isHidden = true
}
animator.startAnimation()
hideAnimator = animator
}
}
| 34.226563 | 213 | 0.647569 |
75c5884395554fd857d1ce3b62eb5fe45be6be72
| 4,069 |
//
// CodeGenerator.swift
// Eject
//
// Created by Brian King on 10/18/16.
// Copyright © 2016 Brian King. All rights reserved.
//
import Foundation
public protocol CodeGenerator {
/// A set of all identifiers that are dependent on this generator.
var dependentIdentifiers: Set<String> { get }
/// Return a line of code, or nil if nothing should be done.
func generateCode(in document: XIBDocument) throws -> String?
}
extension CodeGenerator {
var dependentIdentifiers: Set<String> {
return []
}
}
public enum CodeGeneratorPhase {
case initialization
case isolatedAssignment
case generalAssignment
case subviews
case constraints
var comment: String {
switch self {
case .initialization:
return "// Create Views"
case .isolatedAssignment:
return "" // Assignment without dependencies -- doesn't really warrent a comment.
case .generalAssignment:
return "// Remaining Configuration"
case .subviews:
return "// Assemble View Hierarchy"
case .constraints:
return "// Configure Constraints"
}
}
}
extension XIBDocument {
public func generateCode() throws -> [String] {
var generatedCode: [String] = []
if configuration.includeComments { generatedCode.append(CodeGeneratorPhase.initialization.comment) }
// Cluster the declaration with the configuration that is isolated (ie no external references)
for reference in references {
generatedCode.append(contentsOf: try reference.generateDeclaration(in: self))
}
// Add all of the remaining phases
for phase: CodeGeneratorPhase in [.subviews, .constraints, .generalAssignment] {
generatedCode.append(contentsOf: try generateCode(for: phase))
}
// Trim trailing empty lines
if generatedCode.last == "" {
generatedCode.removeLast()
}
return generatedCode
}
/// Generate code for the specified phase. The code is generated in the reverse order of objects that were
/// added so the top level object configuration is last. This is usually how I like to do things.
func generateCode(for phase: CodeGeneratorPhase) throws -> [String] {
var lines: [String] = []
for reference in references {
lines.append(contentsOf: try reference.generateCode(for: phase, in: self))
}
if lines.count > 0 {
if configuration.includeComments { lines.insert(phase.comment, at: 0) }
lines.append("")
}
return lines
}
}
extension Reference {
/// Generate the declaration of the object, along with any configuration that is isolated from any external dependencies.
func generateDeclaration(in document: XIBDocument) throws -> [String] {
var generatedCode: [String] = []
var lines = try generateCode(for: .initialization, in: document)
lines.append(contentsOf: try generateCode(for: .isolatedAssignment, in: document))
if lines.count > 0 { generatedCode.append(contentsOf: lines) }
if lines.count > 1 { generatedCode.append("") }
return generatedCode
}
/// Generate code for the specified generation phase. The name of the variable to use for this reference can be over-ridden here
/// so the commands can be scoped to a block. The idea is to support `then` style initialization blocks.
func generateCode(for phase: CodeGeneratorPhase, in document: XIBDocument, withName name: String? = nil) throws -> [String] {
let original = document.variableNameOverrides[identifier]
if let name = name {
document.variableNameOverrides[identifier] = { _ in name }
}
let code = try statements
.filter { $0.phase == phase }
.map { try $0.generator.generateCode(in: document) }
.flatMap { $0 }
document.variableNameOverrides[identifier] = original
return code
}
}
| 35.077586 | 132 | 0.651511 |
cce19c0dbad1c6ce3d2a74a7ae8dc5ad5506f013
| 8,445 |
//
// MapBrowser.swift
// TAassets
//
// Created by Logan Jones on 6/4/17.
// Copyright © 2017 Logan Jones. All rights reserved.
//
import Cocoa
import SwiftTA_Core
class MapBrowserViewController: NSViewController, ContentViewController {
var shared = TaassetsSharedState.empty
private var maps: [FileSystem.File] = []
private var tableView: NSTableView!
private var detailViewContainer: NSView!
private var detailViewController = MapDetailViewController()
private var isShowingDetail = false
override func loadView() {
let bounds = NSRect(x: 0, y: 0, width: 480, height: 480)
let mainView = NSView(frame: bounds)
let listWidth: CGFloat = 240
let scrollView = NSScrollView(frame: NSMakeRect(0, 0, listWidth, bounds.size.height))
scrollView.autoresizingMask = [.height]
scrollView.borderType = .noBorder
scrollView.hasVerticalScroller = true
scrollView.hasHorizontalScroller = false
let tableView = NSTableView(frame: NSMakeRect(0, 0, listWidth, bounds.size.height))
let column = NSTableColumn(identifier: NSUserInterfaceItemIdentifier(rawValue: "name"))
column.width = listWidth-2
tableView.addTableColumn(column)
tableView.identifier = NSUserInterfaceItemIdentifier(rawValue: "maps")
tableView.headerView = nil
tableView.rowHeight = 32
scrollView.documentView = tableView
tableView.dataSource = self
tableView.delegate = self
mainView.addSubview(scrollView)
let detail = NSView(frame: NSMakeRect(listWidth, 0, bounds.size.width - listWidth, bounds.size.height))
detail.autoresizingMask = [.width, .height]
mainView.addSubview(detail)
self.view = mainView
self.detailViewContainer = detail
self.tableView = tableView
}
override func viewDidLoad() {
let begin = Date()
let mapsDirectory = shared.filesystem.root[directory: "maps"] ?? FileSystem.Directory()
let maps = mapsDirectory.items
.compactMap { $0.asFile() }
.filter { $0.hasExtension("ota") }
.sorted { FileSystem.sortNames($0.name, $1.name) }
self.maps = maps
let end = Date()
print("Map list load time: \(end.timeIntervalSince(begin)) seconds")
}
}
extension MapBrowserViewController: NSTableViewDataSource {
func numberOfRows(in tableView: NSTableView) -> Int {
return maps.count
}
}
extension MapBrowserViewController: NSTableViewDelegate {
func tableView(_ tableView: NSTableView, viewFor tableColumn: NSTableColumn?, row: Int) -> NSView? {
let cell: MapInfoCell
if let existing = tableView.makeView(withIdentifier: NSUserInterfaceItemIdentifier(rawValue: "MapInfo"), owner: self) as? MapInfoCell {
cell = existing
}
else {
cell = MapInfoCell()
cell.identifier = NSUserInterfaceItemIdentifier(rawValue: "MapInfo")
}
let file = maps[row]
cell.name = file.baseName
return cell
}
func tableViewSelectionDidChange(_ notification: Notification) {
guard let tableView = notification.object as? NSTableView
else { return }
let row = tableView.selectedRow
if row >= 0 {
if !isShowingDetail {
let controller = detailViewController
controller.view.frame = detailViewContainer.bounds
controller.view.autoresizingMask = [.width, .width]
addChild(controller)
detailViewContainer.addSubview(controller.view)
isShowingDetail = true
}
do { try detailViewController.loadMap(in: maps[row], from: shared.filesystem) }
catch { print("!!! Failed to map \(maps[row].name): \(error)") }
}
else if isShowingDetail {
detailViewController.clear()
detailViewController.view.removeFromSuperview()
detailViewController.removeFromParent()
isShowingDetail = false
}
}
}
class MapInfoCell: NSTableCellView {
private var nameField: NSTextField!
override init(frame frameRect: NSRect) {
super.init(frame: frameRect)
nameField = NSTextField(labelWithString: "")
nameField.font = NSFont.systemFont(ofSize: 14)
nameField.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(nameField)
NSLayoutConstraint.activate([
nameField.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8),
nameField.centerYAnchor.constraint(equalTo: self.centerYAnchor),
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var name: String {
get { return nameField?.stringValue ?? "" }
set { nameField.stringValue = newValue }
}
}
class MapDetailViewController: NSViewController {
let mapView = MapViewController()
func loadMap(in otaFile: FileSystem.File, from filesystem: FileSystem) throws {
let name = otaFile.baseName
try mapView.load(name, from: filesystem)
mapTitle = name
}
func clear() {
mapView.clear()
}
var mapTitle: String {
get { return container.titleLabel.stringValue }
set(new) { container.titleLabel.stringValue = new }
}
private var container: ContainerView {
return view as! ContainerView
}
private class ContainerView: NSView {
unowned let titleLabel: NSTextField
let emptyContentView: NSView
weak var contentView: NSView? {
didSet {
guard contentView != oldValue else { return }
oldValue?.removeFromSuperview()
if let contentView = contentView {
addSubview(contentView)
contentView.translatesAutoresizingMaskIntoConstraints = false
addContentViewConstraints(contentView)
}
else {
oldValue?.removeFromSuperview()
addSubview(emptyContentView)
addContentViewConstraints(emptyContentView)
}
}
}
override init(frame frameRect: NSRect) {
let titleLabel = NSTextField(labelWithString: "Title")
titleLabel.font = NSFont.systemFont(ofSize: 18)
titleLabel.textColor = NSColor.labelColor
let contentBox = NSView(frame: NSRect(x: 0, y: 0, width: 32, height: 32))
self.titleLabel = titleLabel
self.emptyContentView = contentBox
super.init(frame: frameRect)
addSubview(contentBox)
addSubview(titleLabel)
contentBox.translatesAutoresizingMaskIntoConstraints = false
titleLabel.translatesAutoresizingMaskIntoConstraints = false
NSLayoutConstraint.activate([
titleLabel.centerXAnchor.constraint(equalTo: self.centerXAnchor),
])
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func addContentViewConstraints(_ contentBox: NSView) {
NSLayoutConstraint.activate([
contentBox.leadingAnchor.constraint(equalTo: self.leadingAnchor, constant: 8),
contentBox.trailingAnchor.constraint(equalTo: self.trailingAnchor, constant: -8),
contentBox.topAnchor.constraint(equalTo: self.topAnchor, constant: 8),
contentBox.heightAnchor.constraint(equalTo: self.heightAnchor, multiplier: 0.61803398875),
titleLabel.topAnchor.constraint(equalTo: contentBox.bottomAnchor, constant: 8),
])
}
}
override func loadView() {
let container = ContainerView(frame: NSRect(x: 0, y: 0, width: 256, height: 256))
self.view = container
addChild(mapView)
container.contentView = mapView.view
}
}
| 34.469388 | 143 | 0.608763 |
38cf64d94ec5b01337934c92556c84d05f9c6104
| 9,342 |
import XCTest
import XcodeProj
@testable import MockingbirdGenerator
class PBXTargetTests: XCTestCase {
// MARK: - productModuleName
func testProductModuleName_handlesNonAlphaNumericCharacters() {
let actual = PBXTarget(name: "a-module.name").resolveProductModuleName(environment: { [:] })
XCTAssertEqual(actual, "a_module_name")
}
func testProductModuleName_handlesFirstCharacterNumeral() {
let actual = PBXTarget(name: "123name").resolveProductModuleName(environment: { [:] })
XCTAssertEqual(actual, "_23name")
}
// MARK: - Build setting resolving
func testResolveBuildSetting_literalValue() {
let actual = try? PBXTarget.resolve(BuildSetting("foobar"), from: [:])
XCTAssertEqual(actual, "foobar")
}
func testResolveBuildSetting_simpleExpression() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO)"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "BAR")
}
func testResolveBuildSetting_simpleExpressionBashStyle() {
let actual = try? PBXTarget.resolve(BuildSetting("${FOO}"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "BAR")
}
func testResolveBuildSetting_simpleExpressionWithLeadingPadding() {
let actual = try? PBXTarget.resolve(BuildSetting("pad$(FOO)"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "padBAR")
}
func testResolveBuildSetting_simpleExpressionWithLeadingPaddingBashStyle() {
let actual = try? PBXTarget.resolve(BuildSetting("pad${FOO}"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "padBAR")
}
func testResolveBuildSetting_simpleExpressionWithTrailingPadding() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO)dap"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "BARdap")
}
func testResolveBuildSetting_simpleExpressionWithTrailingPaddingBashStyle() {
let actual = try? PBXTarget.resolve(BuildSetting("${FOO}dap"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "BARdap")
}
func testResolveBuildSetting_simpleExpressionWithLeadingTrailingPadding() {
let actual = try? PBXTarget.resolve(BuildSetting("pad$(FOO)dap"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "padBARdap")
}
func testResolveBuildSetting_simpleExpressionWithLeadingTrailingPaddingBashStyle() {
let actual = try? PBXTarget.resolve(BuildSetting("pad${FOO}dap"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "padBARdap")
}
func testResolveBuildSetting_multipleConsecutiveExpressions() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO)$(BAR)"),
from: ["FOO": "BAR", "BAR": "BAZ"])
XCTAssertEqual(actual, "BARBAZ")
}
func testResolveBuildSetting_multipleConsecutiveExpressionsBashStyle() {
let actual = try? PBXTarget.resolve(BuildSetting("${FOO}${BAR}"),
from: ["FOO": "BAR", "BAR": "BAZ"])
XCTAssertEqual(actual, "BARBAZ")
}
func testResolveBuildSetting_multipleExpressionsWithPadding() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO)pad$(BAR)"),
from: ["FOO": "BAR", "BAR": "BAZ"])
XCTAssertEqual(actual, "BARpadBAZ")
}
func testResolveBuildSetting_multipleExpressionsWithPaddingBashStyle() {
let actual = try? PBXTarget.resolve(BuildSetting("${FOO}pad${BAR}"),
from: ["FOO": "BAR", "BAR": "BAZ"])
XCTAssertEqual(actual, "BARpadBAZ")
}
// MARK: Chained expressions
func testResolveBuildSetting_simpleChainedExpression() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO)"),
from: ["FOO": "$(BAR)", "BAR": "BAZ"])
XCTAssertEqual(actual, "BAZ")
}
func testResolveBuildSetting_simpleChainedExpressionBashStyle() {
let actual = try? PBXTarget.resolve(BuildSetting("${FOO}"),
from: ["FOO": "${BAR}", "BAR": "BAZ"])
XCTAssertEqual(actual, "BAZ")
}
func testResolveBuildSetting_simpleChainedExpressionMixedStyle() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO)"),
from: ["FOO": "${BAR}", "BAR": "BAZ"])
XCTAssertEqual(actual, "BAZ")
}
// MARK: Default values
func testResolveBuildSetting_nonEmptyExpressionWithDefaultValue() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO:default=a value)"),
from: ["FOO": "BAR"])
XCTAssertEqual(actual, "BAR")
}
func testResolveBuildSetting_missingExpressionWithDefaultValueLiteral() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO:default=a value)"), from: [:])
XCTAssertEqual(actual, "a value")
}
func testResolveBuildSetting_multipleMissingExpressionWithDefaultValueLiteral() {
let actual = try? PBXTarget.resolve(
BuildSetting("$(FOO:default=a value) $(BAR:default=another value)"),
from: [:]
)
XCTAssertEqual(actual, "a value another value")
}
func testResolveBuildSetting_emptyExpressionWithDefaultValueLiteral() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO:default=a value)"),
from: ["FOO": ""])
XCTAssertEqual(actual, "a value")
}
func testResolveBuildSetting_multipleEmptyExpressionWithDefaultValueLiteral() {
let actual = try? PBXTarget.resolve(
BuildSetting("$(FOO:default=a value) $(BAR:default=another value)"),
from: ["FOO": "", "BAR": ""]
)
XCTAssertEqual(actual, "a value another value")
}
func testResolveBuildSetting_missingExpressionWithDefaultValueExpression() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO:default=$(BAR))"),
from: ["BAR": "BAZ"])
XCTAssertEqual(actual, "BAZ")
}
func testResolveBuildSetting_multipleMissingExpressionsWithDefaultValueExpression() {
let actual = try? PBXTarget.resolve(
BuildSetting("$(FOO:default=$(BAR)) $(HELLO:default=$(WORLD))"),
from: ["BAR": "BAZ", "WORLD": "!!"]
)
XCTAssertEqual(actual, "BAZ !!")
}
func testResolveBuildSetting_missingExpressionWithDefaultValuePaddedExpression() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO:default=pad $(BAR) dap)"),
from: ["BAR": "BAZ"])
XCTAssertEqual(actual, "pad BAZ dap")
}
func testResolveBuildSetting_missingExpressionWithNestedDefaultValueLiteral() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO:default=$(BAR:default=a value))"),
from: [:])
XCTAssertEqual(actual, "a value")
}
func testResolveBuildSetting_missingExpressionWithNestedDefaultValueExpression() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO:default=$(BAR:default=$(BAZ)))"),
from: ["BAZ": "BOO"])
XCTAssertEqual(actual, "BOO")
}
// MARK: Circular evaluations
func testResolveBuildSetting_handlesCircularEvaluatedExpressions() {
XCTAssertThrowsError(try PBXTarget.resolve(BuildSetting("$(FOO)"),
from: ["FOO": "$(BAR)",
"BAR": "$(BAZ)",
"BAZ": "$(FOO)"]))
}
func testResolveBuildSetting_handlesCircularEvaluatedExpressionsFromDefaults() {
XCTAssertThrowsError(try PBXTarget.resolve(BuildSetting("$(FOO:default=$(BAR))"),
from: ["BAR": "$(BAZ)",
"BAZ": "$(FOO)"]))
}
// MARK: Unbalanced parentheses
func testResolveBuildSetting_handlesUnbalancedParenthesesClose() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "$(FOO")
}
func testResolveBuildSetting_handlesUnbalancedParenthesesCloseBashStyle() {
let actual = try? PBXTarget.resolve(BuildSetting("${FOO"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "${FOO")
}
func testResolveBuildSetting_handlesUnbalancedParenthesesOpen() {
let actual = try? PBXTarget.resolve(BuildSetting("FOO)"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "FOO)")
}
func testResolveBuildSetting_handlesUnbalancedParenthesesOpenBashStyle() {
let actual = try? PBXTarget.resolve(BuildSetting("FOO}"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "FOO}")
}
func testResolveBuildSetting_handlesUnbalancedMultipleParenthesesClose() {
let actual = try? PBXTarget.resolve(BuildSetting("$((FOO)"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "")
}
func testResolveBuildSetting_handlesUnbalancedMultipleParenthesesCloseBashStyle() {
let actual = try? PBXTarget.resolve(BuildSetting("${{FOO}"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "")
}
func testResolveBuildSetting_handlesUnbalancedMultipleParenthesesOpen() {
let actual = try? PBXTarget.resolve(BuildSetting("$(FOO))"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "BAR)")
}
func testResolveBuildSetting_handlesUnbalancedMultipleParenthesesOpenBashStyle() {
let actual = try? PBXTarget.resolve(BuildSetting("${FOO}}"), from: ["FOO": "BAR"])
XCTAssertEqual(actual, "BAR}")
}
}
| 39.923077 | 96 | 0.643545 |
dee0fbd6c6a09eeed91edc06a58c222b2cb976ef
| 2,111 |
//
// RetailerAnalyticsHomeDTO.swift
// MozoSDK
//
// Created by Hoang Nguyen on 12/14/18.
//
import Foundation
import SwiftyJSON
public class RetailerAnalyticsHomeDTO: ResponseObjectSerializable {
public var diffAirdropAmount: NSNumber?
public var diffCustomerVisited: Int?
public var newAnalyticData: RetailerCustomerAnalyticDTO?
public var oldAnalyticData: RetailerCustomerAnalyticDTO?
public var percentageDiffAirdropAmount: Double?
public var percentageDiffCustomerVisited: Double?
public required init?(json: SwiftyJSON.JSON) {
self.diffAirdropAmount = json["diffAirdropAmount"].number
self.diffCustomerVisited = json["diffCustomerVisited"].int
self.newAnalyticData = RetailerCustomerAnalyticDTO(json: json["newAnalyticData"])
self.oldAnalyticData = RetailerCustomerAnalyticDTO(json: json["oldAnalyticData"])
self.percentageDiffAirdropAmount = json["percentageDiffAirdropAmount"].double
self.percentageDiffCustomerVisited = json["percentageDiffCustomerVisited"].double
}
public required init?(){}
public func toJSON() -> Dictionary<String, Any> {
var json = Dictionary<String, Any>()
if let diffAirdropAmount = self.diffAirdropAmount {
json["diffAirdropAmount"] = diffAirdropAmount
}
if let diffCustomerVisited = self.diffCustomerVisited {
json["diffCustomerVisited"] = diffCustomerVisited
}
if let percentageDiffAirdropAmount = self.percentageDiffAirdropAmount {
json["percentageDiffAirdropAmount"] = percentageDiffAirdropAmount
}
if let percentageDiffCustomerVisited = self.percentageDiffCustomerVisited {
json["percentageDiffCustomerVisited"] = percentageDiffCustomerVisited
}
if let newAnalyticData = self.newAnalyticData {
json["percentageDiffAirdropAmount"] = newAnalyticData.toJSON()
}
if let oldAnalyticData = self.oldAnalyticData {
json["oldAnalyticData"] = oldAnalyticData.toJSON()
}
return json
}
}
| 40.596154 | 89 | 0.710564 |
6adf05cde927a002db665e29af85b4d98e328535
| 44,302 |
// Alamofire.swift
//
// Copyright (c) 2014 Alamofire (http://alamofire.org)
//
// 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 struct Alamofire {
// HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
public enum Method: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case PATCH = "PATCH"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
public enum ParameterEncoding {
case URL
case JSON(options: NSJSONWritingOptions)
case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions)
func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
if !parameters {
return (request, nil)
}
var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
var error: NSError? = nil
switch self {
case .URL:
func query(parameters: [String: AnyObject]) -> String! {
func queryComponents(key: String, value: AnyObject) -> [(String, String)] {
func dictionaryQueryComponents(key: String, dictionary: [String: AnyObject]) -> [(String, String)] {
var components: [(String, String)] = []
for (nestedKey, value) in dictionary {
components += queryComponents("\(key)[\(nestedKey)]", value)
}
return components
}
func arrayQueryComponents(key: String, array: [AnyObject]) -> [(String, String)] {
var components: [(String, String)] = []
for value in array {
components += queryComponents("\(key)[]", value)
}
return components
}
var components: [(String, String)] = []
if let dictionary = value as? [String: AnyObject] {
components += dictionaryQueryComponents(key, dictionary)
} else if let array = value as? [AnyObject] {
components += arrayQueryComponents(key, array)
} else {
components += (key, "\(value)")
}
return components
}
var components: [(String, String)] = []
for key in sorted(Array(parameters.keys), <) {
let value: AnyObject! = parameters[key]
components += queryComponents(key, value)
}
return join("&", components.map{"\($0)=\($1)"} as [String])
}
func encodesParametersInURL(method: Method) -> Bool {
switch method {
case .GET, .HEAD, .DELETE:
return true
default:
return false
}
}
if encodesParametersInURL(Method.fromRaw(request.HTTPMethod)!) {
let URLComponents = NSURLComponents(URL: mutableRequest.URL, resolvingAgainstBaseURL: false)
URLComponents.query = (URLComponents.query ? URLComponents.query + "&" : "") + query(parameters!)
mutableRequest.URL = URLComponents.URL
} else {
if !mutableRequest.valueForHTTPHeaderField("Content-Type") {
mutableRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
}
mutableRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
}
case .JSON(let options):
let data = NSJSONSerialization.dataWithJSONObject(parameters, options: options, error: &error)
if data {
let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
mutableRequest.setValue("application/json; charset=\(charset)", forHTTPHeaderField: "Content-Type")
mutableRequest.HTTPBody = data
}
case .PropertyList(let (format, options)):
let data = NSPropertyListSerialization.dataWithPropertyList(parameters, format: format, options: options, error: &error)
if data {
let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
mutableRequest.setValue("application/x-plist; charset=\(charset)", forHTTPHeaderField: "Content-Type")
mutableRequest.HTTPBody = data
}
}
return (mutableRequest, error)
}
}
// MARK: -
class Manager {
class var sharedInstance: Manager {
struct Singleton {
static let instance = Manager()
}
return Singleton.instance
}
let delegate: SessionDelegate
let session: NSURLSession!
let operationQueue: NSOperationQueue = NSOperationQueue()
var automaticallyStartsRequests: Bool = true
lazy var defaultHeaders: [String: String] = {
// Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"
// Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
let acceptLanguage: String = {
var components: [String] = []
for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as [String]) {
let q = 1.0 - (Double(index) * 0.1)
components += "\(languageCode);q=\(q)"
if q <= 0.5 {
break
}
}
return components.reduce("", {$0 == "" ? $1 : "\($0),\($1)"})
}()
// User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
let userAgent: String = {
if let info = NSBundle.mainBundle().infoDictionary {
let executable: AnyObject? = info[kCFBundleExecutableKey]
let bundle: AnyObject? = info[kCFBundleIdentifierKey]
let version: AnyObject? = info[kCFBundleVersionKey]
let os: AnyObject? = NSProcessInfo.processInfo()?.operatingSystemVersionString
var mutableUserAgent = NSMutableString(string: "\(executable!)/\(bundle!) (\(version!); OS \(os!))") as CFMutableString
let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
return mutableUserAgent as NSString
}
}
return "Alamofire"
}()
return ["Accept-Encoding": acceptEncoding,
"Accept-Language": acceptLanguage,
"User-Agent": userAgent]
}()
required init(configuration: NSURLSessionConfiguration! = nil) {
self.delegate = SessionDelegate()
self.session = NSURLSession(configuration: configuration, delegate: self.delegate, delegateQueue: self.operationQueue)
}
deinit {
self.session.invalidateAndCancel()
}
// MARK: -
func request(request: NSURLRequest) -> Request {
var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
for (field, value) in self.defaultHeaders {
if !mutableRequest.valueForHTTPHeaderField(field){
mutableRequest.setValue(value, forHTTPHeaderField: field)
}
}
var dataTask: NSURLSessionDataTask?
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
dataTask = self.session.dataTaskWithRequest(mutableRequest)
}
let request = Request(session: self.session, task: dataTask!)
self.delegate[request.delegate.task] = request.delegate
request.resume()
return request
}
class SessionDelegate: NSObject, NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate {
private var subdelegates: [Int: Request.TaskDelegate]
private subscript(task: NSURLSessionTask) -> Request.TaskDelegate? {
get {
return self.subdelegates[task.taskIdentifier]
}
set(newValue) {
self.subdelegates[task.taskIdentifier] = newValue
}
}
var sessionDidBecomeInvalidWithError: ((NSURLSession!, NSError!) -> Void)?
var sessionDidFinishEventsForBackgroundURLSession: ((NSURLSession!) -> Void)?
var sessionDidReceiveChallenge: ((NSURLSession!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential!))?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
required init() {
self.subdelegates = Dictionary()
super.init()
}
// MARK: NSURLSessionDelegate
func URLSession(session: NSURLSession!, didBecomeInvalidWithError error: NSError!) {
self.sessionDidBecomeInvalidWithError?(session, error)
}
func URLSession(session: NSURLSession!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if self.sessionDidReceiveChallenge {
completionHandler(self.sessionDidReceiveChallenge!(session, challenge))
} else {
completionHandler(.PerformDefaultHandling, nil)
}
}
func URLSessionDidFinishEventsForBackgroundURLSession(session: NSURLSession!) {
self.sessionDidFinishEventsForBackgroundURLSession?(session)
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if self.taskWillPerformHTTPRedirection {
redirectRequest = self.taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didReceiveChallenge: challenge, completionHandler: completionHandler)
} else {
self.URLSession(session, didReceiveChallenge: challenge, completionHandler: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, needNewBodyStream: completionHandler)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if let delegate = self[task] as? Request.UploadTaskDelegate {
delegate.URLSession(session, task: task, didSendBodyData: bytesSent, totalBytesSent: totalBytesSent, totalBytesExpectedToSend: totalBytesExpectedToSend)
}
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
if let delegate = self[task] {
delegate.URLSession(session, task: task, didCompleteWithError: error)
}
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
if self.dataTaskDidReceiveResponse {
disposition = self.dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
let downloadDelegate = Request.DownloadTaskDelegate(task: downloadTask)
self[downloadTask] = downloadDelegate
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
if let delegate = self[dataTask] as? Request.DataTaskDelegate {
delegate.URLSession(session, dataTask: dataTask, didReceiveData: data)
}
self.dataTaskDidReceiveData?(session, dataTask, data)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if self.dataTaskWillCacheResponse {
cachedResponse = self.dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didFinishDownloadingToURL: location)
}
self.downloadTaskDidFinishDownloadingToURL?(session, downloadTask, location)
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didWriteData: bytesWritten, totalBytesWritten: totalBytesWritten, totalBytesExpectedToWrite: totalBytesExpectedToWrite)
}
self.downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
if let delegate = self[downloadTask] as? Request.DownloadTaskDelegate {
delegate.URLSession(session, downloadTask: downloadTask, didResumeAtOffset: fileOffset, expectedTotalBytes: expectedTotalBytes)
}
self.downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
}
// MARK: NSObject
override func respondsToSelector(selector: Selector) -> Bool {
switch selector {
case "URLSession:didBecomeInvalidWithError:":
return self.sessionDidBecomeInvalidWithError ? true : false
case "URLSession:didReceiveChallenge:completionHandler:":
return self.sessionDidReceiveChallenge ? true : false
case "URLSessionDidFinishEventsForBackgroundURLSession:":
return self.sessionDidFinishEventsForBackgroundURLSession ? true : false
case "URLSession:task:willPerformHTTPRedirection:newRequest:completionHandler:":
return self.taskWillPerformHTTPRedirection ? true : false
case "URLSession:dataTask:didReceiveResponse:completionHandler:":
return self.dataTaskDidReceiveResponse ? true : false
case "URLSession:dataTask:willCacheResponse:completionHandler:":
return self.dataTaskWillCacheResponse ? true : false
default:
return self.dynamicType.instancesRespondToSelector(selector)
}
}
}
}
// MARK: -
class Request {
private let delegate: TaskDelegate
private var session: NSURLSession
private var task: NSURLSessionTask { return self.delegate.task }
var request: NSURLRequest! { return self.task.originalRequest }
var response: NSHTTPURLResponse! { return self.task.response as? NSHTTPURLResponse }
var progress: NSProgress? { return self.delegate.progress }
private init(session: NSURLSession, task: NSURLSessionTask) {
self.session = session
if task is NSURLSessionUploadTask {
self.delegate = UploadTaskDelegate(task: task)
} else if task is NSURLSessionDownloadTask {
self.delegate = DownloadTaskDelegate(task: task)
} else if task is NSURLSessionDataTask {
self.delegate = DataTaskDelegate(task: task)
} else {
self.delegate = TaskDelegate(task: task)
}
}
// MARK: Authentication
func authenticate(HTTPBasic user: String, password: String) -> Self {
let credential = NSURLCredential(user: user, password: password, persistence: .ForSession)
let protectionSpace = NSURLProtectionSpace(host: self.request.URL.host, port: 0, `protocol`: self.request.URL.scheme, realm: nil, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
return authenticate(usingCredential: credential, forProtectionSpace: protectionSpace)
}
func authenticate(usingCredential credential: NSURLCredential, forProtectionSpace protectionSpace: NSURLProtectionSpace) -> Self {
self.session.configuration.URLCredentialStorage.setCredential(credential, forProtectionSpace: protectionSpace)
return self
}
// MARK: Progress
func progress(closure: ((Int64, Int64, Int64) -> Void)? = nil) -> Self {
if let uploadDelegate = self.delegate as? UploadTaskDelegate {
uploadDelegate.uploadProgress = closure
} else if let downloadDelegate = self.delegate as? DownloadTaskDelegate {
downloadDelegate.downloadProgress = closure
}
return self
}
// MARK: Response
func response(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response({ (request, response, data, error) in
return (data, error)
}, completionHandler: completionHandler)
}
func response(priority: Int = DISPATCH_QUEUE_PRIORITY_DEFAULT, queue: dispatch_queue_t? = nil, serializer: (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?), completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
dispatch_async(self.delegate.queue, {
dispatch_async(dispatch_get_global_queue(priority, 0), {
let (responseObject: AnyObject?, error: NSError?) = serializer(self.request, self.response, self.delegate.data, self.delegate.error)
dispatch_async(queue ? queue : dispatch_get_main_queue(), {
completionHandler(self.request, self.response, responseObject, error)
})
})
})
return self
}
func suspend() {
self.task.suspend()
}
func resume() {
self.task.resume()
}
func cancel() {
if let downloadDelegate = self.delegate as? DownloadTaskDelegate {
downloadDelegate.downloadTask.cancelByProducingResumeData { (data) in
downloadDelegate.resumeData = data
}
} else {
self.task.cancel()
}
}
private class TaskDelegate: NSObject, NSURLSessionTaskDelegate {
let task: NSURLSessionTask
let queue: dispatch_queue_t?
let progress: NSProgress
var data: NSData! { return nil }
private(set) var error: NSError?
var taskWillPerformHTTPRedirection: ((NSURLSession!, NSURLSessionTask!, NSHTTPURLResponse!, NSURLRequest!) -> (NSURLRequest!))?
var taskDidReceiveChallenge: ((NSURLSession!, NSURLSessionTask!, NSURLAuthenticationChallenge) -> (NSURLSessionAuthChallengeDisposition, NSURLCredential?))?
var taskDidSendBodyData: ((NSURLSession!, NSURLSessionTask!, Int64, Int64, Int64) -> Void)?
var taskNeedNewBodyStream: ((NSURLSession!, NSURLSessionTask!) -> (NSInputStream!))?
init(task: NSURLSessionTask) {
self.task = task
self.progress = NSProgress(totalUnitCount: 0)
let label: String = "com.alamofire.task-\(task.taskIdentifier)"
let queue = dispatch_queue_create(label.bridgeToObjectiveC().UTF8String, DISPATCH_QUEUE_SERIAL)
dispatch_suspend(queue)
self.queue = queue
}
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, willPerformHTTPRedirection response: NSHTTPURLResponse!, newRequest request: NSURLRequest!, completionHandler: ((NSURLRequest!) -> Void)!) {
var redirectRequest = request
if self.taskWillPerformHTTPRedirection {
redirectRequest = self.taskWillPerformHTTPRedirection!(session, task, response, request)
}
completionHandler(redirectRequest)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didReceiveChallenge challenge: NSURLAuthenticationChallenge!, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential!) -> Void)!) {
var disposition: NSURLSessionAuthChallengeDisposition = .PerformDefaultHandling
var credential: NSURLCredential?
if self.taskDidReceiveChallenge {
(disposition, credential) = self.taskDidReceiveChallenge!(session, task, challenge)
} else {
if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
// TODO: Incorporate Trust Evaluation & TLS Chain Validation
credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust)
disposition = .UseCredential
}
}
completionHandler(disposition, credential)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, needNewBodyStream completionHandler: ((NSInputStream!) -> Void)!) {
var bodyStream: NSInputStream?
if self.taskNeedNewBodyStream {
bodyStream = self.taskNeedNewBodyStream!(session, task)
}
completionHandler(bodyStream)
}
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didCompleteWithError error: NSError!) {
dispatch_resume(self.queue)
}
}
private class DataTaskDelegate: TaskDelegate, NSURLSessionDataDelegate {
var dataTask: NSURLSessionDataTask! { return self.task as NSURLSessionDataTask }
private var mutableData: NSMutableData
override var data: NSData! {
return self.mutableData
}
var dataTaskDidReceiveResponse: ((NSURLSession!, NSURLSessionDataTask!, NSURLResponse!) -> (NSURLSessionResponseDisposition))?
var dataTaskDidBecomeDownloadTask: ((NSURLSession!, NSURLSessionDataTask!) -> Void)?
var dataTaskDidReceiveData: ((NSURLSession!, NSURLSessionDataTask!, NSData!) -> Void)?
var dataTaskWillCacheResponse: ((NSURLSession!, NSURLSessionDataTask!, NSCachedURLResponse!) -> (NSCachedURLResponse))?
init(task: NSURLSessionTask) {
self.mutableData = NSMutableData()
super.init(task: task)
}
// MARK: NSURLSessionDataDelegate
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveResponse response: NSURLResponse!, completionHandler: ((NSURLSessionResponseDisposition) -> Void)!) {
var disposition: NSURLSessionResponseDisposition = .Allow
if self.dataTaskDidReceiveResponse {
disposition = self.dataTaskDidReceiveResponse!(session, dataTask, response)
}
completionHandler(disposition)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didBecomeDownloadTask downloadTask: NSURLSessionDownloadTask!) {
self.dataTaskDidBecomeDownloadTask?(session, dataTask)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, didReceiveData data: NSData!) {
self.dataTaskDidReceiveData?(session, dataTask, data)
self.mutableData.appendData(data)
}
func URLSession(session: NSURLSession!, dataTask: NSURLSessionDataTask!, willCacheResponse proposedResponse: NSCachedURLResponse!, completionHandler: ((NSCachedURLResponse!) -> Void)!) {
var cachedResponse = proposedResponse
if self.dataTaskWillCacheResponse {
cachedResponse = self.dataTaskWillCacheResponse!(session, dataTask, proposedResponse)
}
completionHandler(cachedResponse)
}
}
}
}
// MARK: - Upload
extension Alamofire.Manager {
private enum Uploadable {
case Data(NSURLRequest, NSData)
case File(NSURLRequest, NSURL)
case Stream(NSURLRequest, NSInputStream)
}
private func upload(uploadable: Uploadable) -> Alamofire.Request {
var uploadTask: NSURLSessionUploadTask!
var stream: NSInputStream?
switch uploadable {
case .Data(let request, let data):
uploadTask = self.session.uploadTaskWithRequest(request, fromData: data)
case .File(let request, let fileURL):
uploadTask = self.session.uploadTaskWithRequest(request, fromFile: fileURL)
case .Stream(let request, var stream):
uploadTask = self.session.uploadTaskWithStreamedRequest(request)
}
let request = Alamofire.Request(session: self.session, task: uploadTask)
if stream {
request.delegate.taskNeedNewBodyStream = { _, _ in
return stream
}
}
self.delegate[request.delegate.task] = request.delegate
if self.automaticallyStartsRequests {
request.resume()
}
return request
}
// MARK: File
func upload(request: NSURLRequest, file: NSURL) -> Alamofire.Request {
return upload(.File(request, file))
}
// MARK: Data
func upload(request: NSURLRequest, data: NSData) -> Alamofire.Request {
return upload(.Data(request, data))
}
// MARK: Stream
func upload(request: NSURLRequest, stream: NSInputStream) -> Alamofire.Request {
return upload(.Stream(request, stream))
}
}
extension Alamofire.Request {
private class UploadTaskDelegate: DataTaskDelegate {
var uploadTask: NSURLSessionUploadTask! { return self.task as NSURLSessionUploadTask }
var uploadProgress: ((Int64, Int64, Int64) -> Void)!
// MARK: NSURLSessionTaskDelegate
func URLSession(session: NSURLSession!, task: NSURLSessionTask!, didSendBodyData bytesSent: Int64, totalBytesSent: Int64, totalBytesExpectedToSend: Int64) {
if self.uploadProgress {
self.uploadProgress(bytesSent, totalBytesSent, totalBytesExpectedToSend)
}
self.progress.totalUnitCount = totalBytesExpectedToSend
self.progress.completedUnitCount = totalBytesSent
}
}
}
// MARK: - Download
extension Alamofire.Manager {
private enum Downloadable {
case Request(NSURLRequest)
case ResumeData(NSData)
}
private func download(downloadable: Downloadable, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
var downloadTask: NSURLSessionDownloadTask!
switch downloadable {
case .Request(let request):
downloadTask = self.session.downloadTaskWithRequest(request)
case .ResumeData(let resumeData):
downloadTask = self.session.downloadTaskWithResumeData(resumeData)
}
let request = Alamofire.Request(session: self.session, task: downloadTask)
if let downloadDelegate = request.delegate as? Alamofire.Request.DownloadTaskDelegate {
downloadDelegate.downloadTaskDidFinishDownloadingToURL = { (session, downloadTask, URL) in
return destination(URL, downloadTask.response as NSHTTPURLResponse)
}
}
self.delegate[request.delegate.task] = request.delegate
if self.automaticallyStartsRequests {
request.resume()
}
return request
}
// MARK: Request
func download(request: NSURLRequest, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
return download(.Request(request), destination: destination)
}
// MARK: Resume Data
func download(resumeData: NSData, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
return download(.ResumeData(resumeData), destination: destination)
}
}
extension Alamofire.Request {
class func suggestedDownloadDestination(directory: NSSearchPathDirectory = .DocumentDirectory, domain: NSSearchPathDomainMask = .UserDomainMask) -> (NSURL, NSHTTPURLResponse) -> (NSURL) {
return { (temporaryURL, response) -> (NSURL) in
if let directoryURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] as? NSURL {
return directoryURL.URLByAppendingPathComponent(response.suggestedFilename)
}
return temporaryURL
}
}
private class DownloadTaskDelegate: TaskDelegate, NSURLSessionDownloadDelegate {
var downloadTask: NSURLSessionDownloadTask! { return self.task as NSURLSessionDownloadTask }
var downloadProgress: ((Int64, Int64, Int64) -> Void)?
var resumeData: NSData!
override var data: NSData! { return self.resumeData }
var downloadTaskDidFinishDownloadingToURL: ((NSURLSession!, NSURLSessionDownloadTask!, NSURL) -> (NSURL))?
var downloadTaskDidWriteData: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64, Int64) -> Void)?
var downloadTaskDidResumeAtOffset: ((NSURLSession!, NSURLSessionDownloadTask!, Int64, Int64) -> Void)?
// MARK: NSURLSessionDownloadDelegate
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didFinishDownloadingToURL location: NSURL!) {
if self.downloadTaskDidFinishDownloadingToURL {
let destination = self.downloadTaskDidFinishDownloadingToURL!(session, downloadTask, location)
var fileManagerError: NSError?
NSFileManager.defaultManager().moveItemAtURL(location, toURL: destination, error: &fileManagerError)
// TODO: NSNotification on failure
}
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {
self.downloadTaskDidWriteData?(session, downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
self.downloadProgress?(bytesWritten, totalBytesWritten, totalBytesExpectedToWrite)
self.progress.totalUnitCount = totalBytesExpectedToWrite
self.progress.completedUnitCount = totalBytesWritten
}
func URLSession(session: NSURLSession!, downloadTask: NSURLSessionDownloadTask!, didResumeAtOffset fileOffset: Int64, expectedTotalBytes: Int64) {
self.downloadTaskDidResumeAtOffset?(session, downloadTask, fileOffset, expectedTotalBytes)
self.progress.totalUnitCount = expectedTotalBytes
self.progress.completedUnitCount = fileOffset
}
}
}
// MARK: - Printable
extension Alamofire.Request: Printable {
var description: String {
var description = "\(self.request.HTTPMethod) \(self.request.URL)"
if self.response {
description += " (\(self.response?.statusCode))"
}
return description
}
}
extension Alamofire.Request: DebugPrintable {
func cURLRepresentation() -> String {
var components: [String] = ["$ curl -i"]
let URL = self.request.URL!
if self.request.HTTPMethod != "GET" {
components += "-X \(self.request.HTTPMethod)"
}
if let credentialStorage = self.session.configuration.URLCredentialStorage {
let protectionSpace = NSURLProtectionSpace(host: URL.host, port: URL.port ? URL.port : 0, `protocol`: URL.scheme, realm: URL.host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic)
if let credentials = credentialStorage.credentialsForProtectionSpace(protectionSpace)?.values.array {
if !credentials.isEmpty {
if let credential = credentials[0] as? NSURLCredential {
components += "-u \(credential.user):\(credential.password)"
}
}
}
}
if let cookieStorage = self.session.configuration.HTTPCookieStorage {
if let cookies = cookieStorage.cookiesForURL(URL) as? [NSHTTPCookie] {
if !cookies.isEmpty {
let string = cookies.reduce(""){ $0 + "\($1.name)=\($1.value);" }
components += "-b \"\(string.substringToIndex(string.endIndex.predecessor()))\""
}
}
}
for (field, value) in self.request.allHTTPHeaderFields {
switch field {
case "Cookie":
continue
default:
components += "-H \"\(field): \(value)\""
}
}
if let HTTPBody = self.request.HTTPBody {
components += "-d \"\(NSString(data: HTTPBody, encoding: NSUTF8StringEncoding))\""
}
// TODO: -T arguments for files
components += "\"\(URL.absoluteString)\""
return join(" \\\n\t", components)
}
var debugDescription: String {
return self.cURLRepresentation()
}
}
// MARK: - Response Serializers
// MARK: String
extension Alamofire.Request {
class func stringResponseSerializer(encoding: NSStringEncoding = NSUTF8StringEncoding) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
return { (_, _, data, error) in
let string = NSString(data: data, encoding: encoding)
return (string, error)
}
}
func responseString(completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return responseString(completionHandler: completionHandler)
}
func responseString(encoding: NSStringEncoding = NSUTF8StringEncoding, completionHandler: (NSURLRequest, NSHTTPURLResponse?, String?, NSError?) -> Void) -> Self {
return response(serializer: Alamofire.Request.stringResponseSerializer(encoding: encoding), completionHandler: { request, response, string, error in
completionHandler(request, response, string as? String, error)
})
}
}
// MARK: JSON
extension Alamofire.Request {
class func JSONResponseSerializer(options: NSJSONReadingOptions = .AllowFragments) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
return { (request, response, data, error) in
var serializationError: NSError?
let JSON: AnyObject! = NSJSONSerialization.JSONObjectWithData(data as NSData, options: options, error: &serializationError)
return (JSON, serializationError)
}
}
func responseJSON(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responseJSON(completionHandler: completionHandler)
}
func responseJSON(options: NSJSONReadingOptions = .AllowFragments, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Alamofire.Request.JSONResponseSerializer(options: options), completionHandler: { (request, response, JSON, error) in
completionHandler(request, response, JSON, error)
})
}
}
// MARK: Property List
extension Alamofire.Request {
class func propertyListResponseSerializer(options: NSPropertyListReadOptions = 0) -> (NSURLRequest, NSHTTPURLResponse?, NSData?, NSError?) -> (AnyObject?, NSError?) {
return { (request, response, data, error) in
var propertyListSerializationError: NSError?
let plist: AnyObject! = NSPropertyListSerialization.propertyListWithData(data as NSData, options: options, format: nil, error: &propertyListSerializationError)
return (plist, propertyListSerializationError)
}
}
func responsePropertyList(completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return responsePropertyList(completionHandler: completionHandler)
}
func responsePropertyList(options: NSPropertyListReadOptions = 0, completionHandler: (NSURLRequest, NSHTTPURLResponse?, AnyObject?, NSError?) -> Void) -> Self {
return response(serializer: Alamofire.Request.propertyListResponseSerializer(options: options), completionHandler: { (request, response, plist, error) in
completionHandler(request, response, plist, error)
})
}
}
// MARK: - Convenience
extension Alamofire {
private static func URLRequest(method: Method, _ URL: String) -> NSURLRequest {
let mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: URL))
mutableURLRequest.HTTPMethod = method.toRaw()
return mutableURLRequest
}
// MARK: Request
static func request(URL: String, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
return request(.GET, URL, parameters: parameters, encoding: encoding)
}
static func request(method: Method, _ URL: String, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL) -> Request {
var mutableRequest = NSMutableURLRequest(URL: NSURL(string: URL))
mutableRequest.HTTPMethod = method.toRaw()
return Manager.sharedInstance.request(encoding.encode(URLRequest(method, URL), parameters: parameters).0)
}
// MARK: Upload
static func upload(method: Method, _ URL: String, file: NSURL) -> Alamofire.Request {
return Manager.sharedInstance.upload(URLRequest(method, URL), file: file)
}
static func upload(method: Method, _ URL: String, data: NSData) -> Alamofire.Request {
return Manager.sharedInstance.upload(URLRequest(method, URL), data: data)
}
static func upload(method: Method, _ URL: String, stream: NSInputStream) -> Alamofire.Request {
return Manager.sharedInstance.upload(URLRequest(method, URL), stream: stream)
}
// MARK: Download
static func download(method: Method, _ URL: String, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
return Manager.sharedInstance.download(URLRequest(method, URL), destination: destination)
}
static func download(resumeData data: NSData, destination: (NSURL, NSHTTPURLResponse) -> (NSURL)) -> Alamofire.Request {
return Manager.sharedInstance.download(data, destination: destination)
}
}
typealias AF = Alamofire
| 45.4846 | 290 | 0.633199 |
64ddf31bc2cf41b596f0f68e5b76ea2f13661236
| 849 |
// swift-tools-version:5.0
import PackageDescription
let package = Package(
name: "RxFlow",
platforms: [
.iOS(.v9)
],
products: [
.library(
name: "RxFlow",
targets: ["RxFlow"]
)
],
dependencies: [
.package(url: "https://github.com/ReactiveX/RxSwift.git",
.upToNextMajor(from: "5.0.0")),
// .package(url: "https://github.com/AliSoftware/Reusable.git",
// .upToNextMajor(from: "4.1.0"))
],
targets: [
.target(
name: "RxFlow",
dependencies: ["RxSwift", "RxCocoa"],
path: "RxFlow"
),
// .testTarget(
// name: "RxFlowTests",
// dependencies: ["RxFlow", "RxTest", "RxBlocking", "Reusable"],
// path: "RxFlowTests"
// )
]
)
| 24.970588 | 75 | 0.475854 |
1c548d8bc25959b76ebf3707475b3a1cb45a352d
| 283 |
//
// UIColor+Extenssion.swift
// EventApp
//
// Created by Hemant Gore on 23/05/20.
// Copyright © 2020 Sci-Fi. All rights reserved.
//
import Foundation
import UIKit
extension UIColor {
static let primary = UIColor(red: 0/255, green: 39/255, blue: 255/255, alpha: 0.6)
}
| 18.866667 | 86 | 0.678445 |
fb1ae552220261e9b16d4fff5c59a79c0380d7ce
| 2,820 |
//
// Tez.swift
// TezosSwift
//
// Created by Marek Fořt on 11/30/18.
// Copyright © 2018 Keefer Taylor. All rights reserved.
//
import Foundation
/**
* A model class representing a balance of Tezos.
*/
public struct Tez: TezToken, Codable {
/// Zero amount of Tez
public static let zero: TezToken = Tez(0)
/** The number of decimal places available in Tezos values. */
fileprivate static let decimalDigitCount = 6
let integerAmount: String
let decimalAmount: String
/**
* A human readable representation of the given balance.
*/
public var humanReadableRepresentation: String {
return integerAmount + "." + decimalAmount
}
/**
* A representation of the given balance for use in RPC requests.
*/
public var rpcRepresentation: String {
integerAmount + decimalAmount
}
/**
* Initialize a new balance from a given decimal number.
*
* - Warning: Balances are accurate up to |decimalDigitCount| decimal places. Additional precision
* is dropped.
*/
public init(_ amount: Double) {
let integerValue = Int(amount)
// Convert decimalDigitCount significant digits of decimals into integers to avoid having to
// deal with decimals.
let multiplierDoubleValue = (pow(10, Tez.decimalDigitCount) as NSDecimalNumber).doubleValue
let multiplierIntValue = (pow(10, Tez.decimalDigitCount) as NSDecimalNumber).intValue
let significantDecimalDigitsAsInteger = Int(amount * multiplierDoubleValue)
let significantIntegerDigitsAsInteger = integerValue * multiplierIntValue
let decimalValue = significantDecimalDigitsAsInteger - significantIntegerDigitsAsInteger
self.integerAmount = String(integerValue)
// Decimal values need to be at least decimalDigitCount long. If the decimal value resolved to
// be less than 6 then the number dropped leading zeros. E.G. '0' instead of '000000' or '400'
// rather than 000400.
var paddedDecimalAmount = String(decimalValue)
while paddedDecimalAmount.count < Tez.decimalDigitCount {
paddedDecimalAmount = "0" + paddedDecimalAmount
}
self.decimalAmount = paddedDecimalAmount
}
fileprivate init(integerAmount: String, decimalAmount: String) {
self.integerAmount = integerAmount
self.decimalAmount = decimalAmount
}
}
extension KeyedDecodingContainerProtocol {
public func decode(_ type: Tez.Type, forKey key: Key) throws -> Tez {
let amount = try decodeRPC(Int.self, forKey: key)
return Tez(Double(amount) * 0.000001)
}
}
extension Tez: Equatable {
public static func == (lhs: Tez, rhs: Tez) -> Bool {
return lhs.rpcRepresentation == rhs.rpcRepresentation
}
}
| 33.176471 | 102 | 0.683688 |
086b4597da95c08bbde6cffcbd8db11246eed57d
| 4,218 |
////
// 🦠 Corona-Warn-App
//
import UIKit
import OpenCombine
final class TraceLocationDetailViewModel {
// MARK: - Init
init(_ traceLocation: TraceLocation, eventStore: EventStoringProviding, store: Store) {
self.store = store
self.eventStore = eventStore
self.traceLocation = traceLocation
#if !RELEASE
// save the trace location for dev menu to see every data.
store.recentTraceLocationCheckedInto = DMRecentTraceLocationCheckedInto(
description: traceLocation.description,
id: traceLocation.id,
date: Date()
)
#endif
self.locationType = traceLocation.type.title
self.locationAddress = traceLocation.address
self.locationDescription = traceLocation.description
self.shouldSaveToContactJournal = store.shouldAddCheckinToContactDiaryByDefault
// max duration in the picker is 23:45
let maxDurationInMinutes = (23 * 60) + 45
self.duration = TimeInterval(min(traceLocation.suggestedCheckoutLength, maxDurationInMinutes) * 60)
}
// MARK: - Internal
enum TraceLocationDateStatus {
case notStarted
case inProgress
case ended
}
let locationType: String
let locationDescription: String
let locationAddress: String
var shouldSaveToContactJournal: Bool
@OpenCombine.Published var duration: TimeInterval
var pickerButtonTitle: String {
guard let durationString = durationFormatter.string(from: duration) else {
Log.error("Failed to convert duration to string")
return ""
}
return String(format: AppStrings.Checkins.Details.hoursShortVersion, durationString)
}
var pickerButtonAccessibilityLabel: String {
let components = Calendar.utcCalendar.dateComponents([.hour, .minute], from: Date(timeIntervalSinceReferenceDate: duration))
guard let accessibilityLabel = DateComponentsFormatter.localizedString(from: components, unitsStyle: .spellOut) else {
return ""
}
return accessibilityLabel
}
var traceLocationStatus: TraceLocationDateStatus? {
guard let startDate = traceLocation.startDate,
let endDate = traceLocation.endDate else {
return nil
}
if startDate > Date() {
return .notStarted
} else if endDate < Date() {
return .ended
} else {
return .inProgress
}
}
var formattedStartDateString: String {
guard let date = traceLocation.startDate else {
return ""
}
return DateFormatter.localizedString(from: date, dateStyle: .short, timeStyle: .none)
}
var formattedStartTimeString: String {
guard let date = traceLocation.startDate else {
return ""
}
return DateFormatter.localizedString(from: date, dateStyle: .none, timeStyle: .short)
}
func saveCheckinToDatabase() {
let checkinStartDate = Date()
guard let checkinEndDate = Calendar.current.date(byAdding: .second, value: Int(duration), to: checkinStartDate),
let idHash = traceLocation.idHash else {
Log.warning("checkinEndDate is nill", log: .checkin)
return
}
let checkin: Checkin = Checkin(
id: 0,
traceLocationId: traceLocation.id,
traceLocationIdHash: idHash,
traceLocationVersion: traceLocation.version,
traceLocationType: traceLocation.type,
traceLocationDescription: traceLocation.description,
traceLocationAddress: traceLocation.address,
traceLocationStartDate: traceLocation.startDate,
traceLocationEndDate: traceLocation.endDate,
traceLocationDefaultCheckInLengthInMinutes: traceLocation.defaultCheckInLengthInMinutes,
cryptographicSeed: traceLocation.cryptographicSeed,
cnPublicKey: traceLocation.cnPublicKey,
checkinStartDate: checkinStartDate,
checkinEndDate: checkinEndDate,
checkinCompleted: false,
createJournalEntry: shouldSaveToContactJournal,
checkinSubmitted: false
)
store.shouldAddCheckinToContactDiaryByDefault = shouldSaveToContactJournal
eventStore.createCheckin(checkin)
}
// MARK: - Private
private let traceLocation: TraceLocation
private let eventStore: EventStoringProviding
private let store: Store
private lazy var durationFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
formatter.allowedUnits = [.hour, .minute]
formatter.zeroFormattingBehavior = .default
formatter.zeroFormattingBehavior = .pad
return formatter
}()
}
| 29.914894 | 126 | 0.770744 |
5b8657888ad0dfed973fbb41ea29d36e53d66fe7
| 10,317 |
//
// BottomSheetViewController.swift
// BottomSheetController
//
// Created by Pavan Powani on 13/03/20.
// Copyright © 2020 Pavan Powani. All rights reserved.
//
import UIKit
@available(iOS 11.0, *)
@objc public class BottomSheetViewController: UIViewController {
// MARK: Animation properties
fileprivate var currentState: State = .collapsed
let popupOffset: CGFloat = (UIScreen.main.bounds.height) / 2
lazy var animator: UIViewPropertyAnimator = UIViewPropertyAnimator(duration: 1, timingParameters: UISpringTimingParameters(dampingRatio: 0.5, initialVelocity: .zero))
lazy var panRecognizer: UIPanGestureRecognizer = {
let recognizer = UIPanGestureRecognizer()
recognizer.addTarget(self, action: #selector(handlePan(recognizer:)))
recognizer.delegate = self
return recognizer
}()
// MARK: Content properties
fileprivate lazy var bottomSheetContainerView: UIView = {
let view = UIView()
view.clipsToBounds = true
view.translatesAutoresizingMaskIntoConstraints = false
view.backgroundColor = .white
view.layer.maskedCorners = [.layerMaxXMinYCorner, .layerMinXMinYCorner]
view.layer.shadowColor = UIColor.black.cgColor
view.layer.shadowOpacity = 0.1
view.layer.shadowRadius = 4
view.layer.cornerRadius = 12
return view
}()
fileprivate var contentVC: UIViewController?
fileprivate var didDismiss: ((Bool) -> UIViewController?)?
//MARK: Methods
override public func viewDidLoad() {
super.viewDidLoad()
self.view.addSubview(bottomSheetContainerView)
self.view.bringSubview(toFront: bottomSheetContainerView)
setupConstraints()
embedContent()
self.bottomSheetContainerView.addGestureRecognizer(panRecognizer)
}
override public func viewDidAppear(_ animated: Bool) {
UIView.transition(with: self.view, duration: 0.2, options: .curveLinear, animations: {
self.setupBackground()
self.view.layoutIfNeeded()
}, completion: nil)
}
override public func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
_ = didDismiss?(true)
}
public static func getController(with content: UIViewController) -> BottomSheetViewController {
let controller = BottomSheetViewController()
controller.contentVC = content
controller.modalPresentationStyle = .overFullScreen
return controller
}
}
extension BottomSheetViewController {
fileprivate func setupConstraints() {
let leading = NSLayoutConstraint(item: bottomSheetContainerView, attribute: .leading, relatedBy: .equal, toItem: self.view, attribute: .leading, multiplier: 1, constant: 0)
let trailing = NSLayoutConstraint(item: bottomSheetContainerView, attribute: .trailing, relatedBy: .equal, toItem: self.view, attribute: .trailing, multiplier: 1, constant: 0)
let bottom = NSLayoutConstraint(item: bottomSheetContainerView, attribute: .bottom, relatedBy: .equal, toItem: self.view, attribute: .bottom, multiplier: 1, constant: 0)
let height = NSLayoutConstraint(item: bottomSheetContainerView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.view.frame.height * 0.3)
NSLayoutConstraint.activate([leading, trailing, bottom, height])
}
fileprivate func setupBackground() {
self.view.backgroundColor = UIColor.black.withAlphaComponent(0.3)
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(bgTapped(_:)))
self.view.addGestureRecognizer(tapGesture)
}
@objc fileprivate func bgTapped(_ sender: Any) {
UIView.transition(with: self.view, duration: 0.2, options: .curveLinear, animations: {
self.view.backgroundColor = .white
self.view.layoutIfNeeded()
}, completion: { (_) in
self.currentState = .collapsed
self.dismiss(animated: true, completion: nil)
})
}
fileprivate func embedContent() {
guard let vc = contentVC else { return }
let maxHeight = (self.view.frame.height * 0.8)
vc.willMove(toParentViewController: self)
let heightValue = (vc.view.frame.size.height > maxHeight) ? maxHeight : vc.view.frame.size.height
NSLayoutConstraint.activate([NSLayoutConstraint(item: bottomSheetContainerView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: heightValue)])
vc.view.frame = bottomSheetContainerView.bounds
bottomSheetContainerView.addSubview(vc.view)
self.addChildViewController(vc)
vc.didMove(toParentViewController: self)
self.currentState = .collapsed
}
}
// MARK: PanGesture Handling
@available(iOS 11.0, *)
extension BottomSheetViewController: UIGestureRecognizerDelegate {
fileprivate func toggle(to state: State) {
switch state {
case .collapsed:
collapse(state: state)
case .expanded:
expand(state: state)
case .dismissed:
collapse(state: state)
}
}
@objc func handlePan(recognizer: UIPanGestureRecognizer) {
guard !animator.isRunning else { return }
var animationProgress: CGFloat = 0
switch recognizer.state {
case .began:
let translation = recognizer.translation(in: self.view)
switch currentState {
case .expanded:
if translation.y > 0 {
toggle(to: .collapsed)
}
case .collapsed:
if translation.y > 0.0 {
toggle(to: .dismissed)
} else if translation.y < 0.0 {
toggle(to: .expanded)
}
case .dismissed: break
}
animator.pauseAnimation()
animationProgress = animator.fractionComplete
case .changed:
let translation = recognizer.translation(in: self.view)
var fraction = -translation.y / popupOffset
if currentState == .expanded { fraction *= -1 }
if animator.isReversed { fraction *= -1 }
animator.fractionComplete = fraction + animationProgress
case .ended:
let yVelocity = recognizer.velocity(in: bottomSheetContainerView).y
let shouldClose = yVelocity > 0
if yVelocity == 0 {
animator.continueAnimation(withTimingParameters: nil, durationFactor: 0)
break
}
switch currentState {
case .expanded:
if !shouldClose && !animator.isReversed { animator.isReversed = !animator.isReversed }
if shouldClose && animator.isReversed { animator.isReversed = !animator.isReversed }
case .collapsed:
if shouldClose && !animator.isReversed { animator.isReversed = !animator.isReversed }
if !shouldClose && animator.isReversed { animator.isReversed = !animator.isReversed }
case .dismissed:
if shouldClose && !animator.isReversed { animator.isReversed = !animator.isReversed }
if !shouldClose && animator.isReversed { animator.isReversed = !animator.isReversed }
}
animator.continueAnimation(withTimingParameters: nil, durationFactor: 0)
default: break
}
}
fileprivate func expand(state: State) {
for constraint in self.bottomSheetContainerView.constraints {
if constraint.firstAttribute == .height {
NSLayoutConstraint.deactivate([constraint])
}
}
let height = NSLayoutConstraint(item: bottomSheetContainerView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.view.frame.size.height * 0.8)
NSLayoutConstraint.activate([height])
animator.addAnimations {
self.view.layoutIfNeeded()
}
animator.addCompletion { (position) in
switch position {
case .start:
self.currentState = state.change
case .end:
self.currentState = state
default: break
}
}
animator.startAnimation()
}
fileprivate func collapse(state: State) {
if state == .dismissed {
bgTapped(self)
} else {
for constraint in self.bottomSheetContainerView.constraints {
if constraint.firstAttribute == .height {
NSLayoutConstraint.deactivate([constraint])
}
}
let height = NSLayoutConstraint(item: bottomSheetContainerView, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: self.view.frame.size.height * 0.3)
NSLayoutConstraint.activate([height])
animator.addAnimations {
self.view.layoutIfNeeded()
}
animator.addCompletion { (position) in
switch position {
case .start:
self.currentState = state.change
case .end:
self.currentState = state
default: break
}
}
animator.startAnimation()
}
}
fileprivate func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
return abs((panRecognizer.velocity(in: panRecognizer.view)).y) > abs((panRecognizer.velocity(in: panRecognizer.view)).x)
}
}
fileprivate enum State {
case expanded
case collapsed
case dismissed
var change: State {
switch self {
case .expanded: return .collapsed
case .collapsed: return .expanded
case .dismissed: return .dismissed
}
}
}
| 39.833977 | 215 | 0.6183 |
675e29888a17d4fac2827cb424f65088bc6d426f
| 23,995 |
/*
The MIT License (MIT)
Copyright (c) 2017-2018 Dalton Hinterscher
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
import SnapKit
import MarqueeLabel
public protocol NotificationBannerDelegate: class {
func notificationBannerWillAppear(_ banner: BaseNotificationBanner)
func notificationBannerDidAppear(_ banner: BaseNotificationBanner)
func notificationBannerWillDisappear(_ banner: BaseNotificationBanner)
func notificationBannerDidDisappear(_ banner: BaseNotificationBanner)
}
@objcMembers
open class BaseNotificationBanner: UIView {
/// Notification that will be posted when a notification banner will appear
public static let BannerWillAppear: Notification.Name = Notification.Name(rawValue: "NotificationBannerWillAppear")
/// Notification that will be posted when a notification banner did appear
public static let BannerDidAppear: Notification.Name = Notification.Name(rawValue: "NotificationBannerDidAppear")
/// Notification that will be posted when a notification banner will appear
public static let BannerWillDisappear: Notification.Name = Notification.Name(rawValue: "NotificationBannerWillDisappear")
/// Notification that will be posted when a notification banner did appear
public static let BannerDidDisappear: Notification.Name = Notification.Name(rawValue: "NotificationBannerDidDisappear")
/// Notification banner object key that is included with each Notification
public static let BannerObjectKey: String = "NotificationBannerObjectKey"
/// The delegate of the notification banner
public weak var delegate: NotificationBannerDelegate?
/// The style of the notification banner
public let style: BannerStyle
/// The height of the banner when it is presented
public var bannerHeight: CGFloat {
get {
if let customBannerHeight = customBannerHeight {
return customBannerHeight
} else {
return shouldAdjustForNotchFeaturedIphone() ? 88.0 : 64.0 + heightAdjustment
}
} set {
customBannerHeight = newValue
}
}
/// The topmost label of the notification if a custom view is not desired
public internal(set) var titleLabel: UILabel?
/// The time before the notificaiton is automatically dismissed
public var duration: TimeInterval = 5.0 {
didSet {
updateMarqueeLabelsDurations()
}
}
/// If false, the banner will not be dismissed until the developer programatically dismisses it
public var autoDismiss: Bool = true {
didSet {
if !autoDismiss {
dismissOnTap = false
dismissOnSwipeUp = false
}
}
}
/// The transparency of the background of the notification banner
public var transparency: CGFloat = 1.0 {
didSet {
if let customView = customView {
customView.backgroundColor = customView.backgroundColor?.withAlphaComponent(transparency)
} else {
let color = backgroundColor
self.backgroundColor = color
}
}
}
/// The type of haptic to generate when a banner is displayed
public var haptic: BannerHaptic = .heavy
/// If true, notification will dismissed when tapped
public var dismissOnTap: Bool = true
/// If true, notification will dismissed when swiped up
public var dismissOnSwipeUp: Bool = true
/// Closure that will be executed if the notification banner is tapped
public var onTap: (() -> Void)?
/// Closure that will be executed if the notification banner is swiped up
public var onSwipeUp: (() -> Void)?
/// Responsible for positioning and auto managing notification banners
public var bannerQueue: NotificationBannerQueue = NotificationBannerQueue.default
/// Banner show and dimiss animation duration
public var animationDuration: TimeInterval = 0.5
/// Wether or not the notification banner is currently being displayed
public var isDisplaying: Bool = false
/// The view that the notification layout is presented on. The constraints/frame of this should not be changed
internal var contentView: UIView!
/// A view that helps the spring animation look nice when the banner appears
internal var spacerView: UIView!
// The custom view inside the notification banner
internal var customView: UIView?
/// The default offset for spacerView top or bottom
internal var spacerViewDefaultOffset: CGFloat = 10.0
/// The maximum number of banners simultaneously visible on screen
internal var maximumVisibleBanners: Int = 1
/// The default padding between edges and views
internal var padding: CGFloat = 15.0
/// The view controller to display the banner on. This is useful if you are wanting to display a banner underneath a navigation bar
internal weak var parentViewController: UIViewController?
/// If this is not nil, then this height will be used instead of the auto calculated height
internal var customBannerHeight: CGFloat?
/// Used by the banner queue to determine wether a notification banner was placed in front of it in the queue
var isSuspended: Bool = false
/// The main window of the application which banner views are placed on
private let appWindow: UIWindow? = {
if #available(iOS 13.0, *) {
return UIApplication.shared.connectedScenes
.first { $0.activationState == .foregroundActive }
.map { $0 as? UIWindowScene }
.map { $0?.windows.first } ?? UIApplication.shared.delegate?.window ?? nil
}
return UIApplication.shared.delegate?.window ?? UIApplication.shared.keyWindow
}()
/// The position the notification banner should slide in from
private(set) var bannerPosition: BannerPosition!
/// The notification banner sides edges insets from superview. If presented - spacerView color will be transparent
internal var bannerEdgeInsets: UIEdgeInsets? = nil {
didSet {
if bannerEdgeInsets != nil {
spacerView.backgroundColor = .clear
}
}
}
/// Object that stores the start and end frames for the notification banner based on the provided banner position
internal var bannerPositionFrame: BannerPositionFrame!
/// The user info that gets passed to each notification
private var notificationUserInfo: [String: BaseNotificationBanner] {
return [BaseNotificationBanner.BannerObjectKey: self]
}
open override var backgroundColor: UIColor? {
get {
return contentView.backgroundColor
} set {
guard style != .customView else { return }
let color = newValue?.withAlphaComponent(transparency)
contentView.backgroundColor = color
spacerView.backgroundColor = color
}
}
init(style: BannerStyle, colors: BannerColorsProtocol? = nil) {
self.style = style
super.init(frame: .zero)
spacerView = UIView()
addSubview(spacerView)
contentView = UIView()
addSubview(contentView)
if let colors = colors {
backgroundColor = colors.color(for: style)
} else {
backgroundColor = BannerColors().color(for: style)
}
let swipeUpGesture = UISwipeGestureRecognizer(target: self, action: #selector(onSwipeUpGestureRecognizer))
swipeUpGesture.direction = .up
addGestureRecognizer(swipeUpGesture)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
NotificationCenter.default.removeObserver(self,
name: UIDevice.orientationDidChangeNotification,
object: nil)
}
/**
Creates the proper banner constraints based on the desired banner position
*/
private func createBannerConstraints(for bannerPosition: BannerPosition) {
spacerView.snp.remakeConstraints { (make) in
if bannerPosition == .top {
make.top.equalToSuperview().offset(-spacerViewDefaultOffset)
} else {
make.bottom.equalToSuperview().offset(spacerViewDefaultOffset)
}
make.left.equalToSuperview()
make.right.equalToSuperview()
updateSpacerViewHeight(make: make)
}
contentView.snp.remakeConstraints { (make) in
if bannerPosition == .top {
make.top.equalTo(spacerView.snp.bottom)
make.bottom.equalToSuperview()
} else {
make.top.equalToSuperview()
make.bottom.equalTo(spacerView.snp.top)
}
make.left.equalToSuperview()
make.right.equalToSuperview()
}
}
/**
Updates the spacer view height. Specifically used for orientation changes.
*/
private func updateSpacerViewHeight(make: ConstraintMaker? = nil) {
let finalHeight = spacerViewHeight()
if let make = make {
make.height.equalTo(finalHeight)
} else {
spacerView.snp.updateConstraints({ (make) in
make.height.equalTo(finalHeight)
})
}
}
internal func spacerViewHeight() -> CGFloat {
return NotificationBannerUtilities.isNotchFeaturedIPhone()
&& UIApplication.shared.statusBarOrientation.isPortrait
&& (parentViewController?.navigationController?.isNavigationBarHidden ?? true) ? 40.0 : 10.0
}
private func finishBannerYOffset() -> CGFloat {
let bannerIndex = (bannerQueue.banners.firstIndex(of: self) ?? bannerQueue.banners.filter { $0.isDisplaying }.count)
return bannerQueue.banners.prefix(bannerIndex).reduce(0) { $0
+ $1.bannerHeight
- (bannerPosition == .top ? spacerViewHeight() : 0) // notch spacer height for top position only
+ (bannerPosition == .top ? spacerViewDefaultOffset : -spacerViewDefaultOffset) // to reduct additions in createBannerConstraints (it's needed for proper shadow framing)
+ (bannerPosition == .top ? spacerViewDefaultOffset : -spacerViewDefaultOffset) // default space between banners
// this calculations are made only for banners except first one, for first banner it'll be 0
}
}
internal func updateBannerPositionFrames() {
guard let window = appWindow else { return }
bannerPositionFrame = BannerPositionFrame(bannerPosition: bannerPosition,
bannerWidth: window.frame.width,
bannerHeight: bannerHeight,
maxY: maximumYPosition(),
finishYOffset: finishBannerYOffset(),
edgeInsets: bannerEdgeInsets)
}
internal func animateUpdatedBannerPositionFrames() {
UIView.animate(withDuration: animationDuration,
delay: 0.0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 1,
options: [.curveLinear, .allowUserInteraction],animations: {
self.frame = self.bannerPositionFrame.endFrame
})
}
/**
Places a NotificationBanner on the queue and shows it if its the first one in the queue
- parameter queuePosition: The position to show the notification banner. If the position is .front, the
banner will be displayed immediately
- parameter bannerPosition: The position the notification banner should slide in from
- parameter queue: The queue to display the notification banner on. It is up to the developer
to manage multiple banner queues and prevent any conflicts that may occur.
- parameter viewController: The view controller to display the notifification banner on. If nil, it will
be placed on the main app window
*/
public func show(queuePosition: QueuePosition = .back,
bannerPosition: BannerPosition = .top,
queue: NotificationBannerQueue = NotificationBannerQueue.default,
on viewController: UIViewController? = nil) {
parentViewController = viewController
bannerQueue = queue
show(placeOnQueue: true, queuePosition: queuePosition, bannerPosition: bannerPosition)
}
/**
Places a NotificationBanner on the queue and shows it if its the first one in the queue
- parameter placeOnQueue: If false, banner will not be placed on the queue and will be showed/resumed immediately
- parameter queuePosition: The position to show the notification banner. If the position is .front, the
banner will be displayed immediately
- parameter bannerPosition: The position the notification banner should slide in from
*/
func show(placeOnQueue: Bool,
queuePosition: QueuePosition = .back,
bannerPosition: BannerPosition = .top) {
guard !isDisplaying else {
return
}
self.bannerPosition = bannerPosition
createBannerConstraints(for: bannerPosition)
updateBannerPositionFrames()
NotificationCenter.default.removeObserver(self,
name: UIDevice.orientationDidChangeNotification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(onOrientationChanged),
name: UIDevice.orientationDidChangeNotification,
object: nil)
if placeOnQueue {
bannerQueue.addBanner(self,
bannerPosition: bannerPosition,
queuePosition: queuePosition)
} else {
self.frame = bannerPositionFrame.startFrame
if let parentViewController = parentViewController {
parentViewController.view.addSubview(self)
if statusBarShouldBeShown() {
appWindow?.windowLevel = UIWindow.Level.normal
}
} else {
appWindow?.addSubview(self)
if statusBarShouldBeShown() && !(parentViewController == nil && bannerPosition == .top) {
appWindow?.windowLevel = UIWindow.Level.normal
} else {
appWindow?.windowLevel = UIWindow.Level.statusBar + 1
}
}
NotificationCenter.default.post(name: BaseNotificationBanner.BannerWillAppear, object: self, userInfo: notificationUserInfo)
delegate?.notificationBannerWillAppear(self)
let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(self.onTapGestureRecognizer))
self.addGestureRecognizer(tapGestureRecognizer)
self.isDisplaying = true
let bannerIndex = Double(bannerQueue.banners.firstIndex(of: self) ?? 0) + 1
UIView.animate(withDuration: animationDuration * bannerIndex,
delay: 0.0,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 1,
options: [.curveLinear, .allowUserInteraction],
animations: {
BannerHapticGenerator.generate(self.haptic)
self.frame = self.bannerPositionFrame.endFrame
}) { (completed) in
NotificationCenter.default.post(name: BaseNotificationBanner.BannerDidAppear, object: self, userInfo: self.notificationUserInfo)
self.delegate?.notificationBannerDidAppear(self)
/* We don't want to add the selector if another banner was queued in front of it
before it finished animating or if it is meant to be shown infinitely
*/
if !self.isSuspended && self.autoDismiss {
self.perform(#selector(self.dismiss), with: nil, afterDelay: self.duration)
}
}
}
}
/**
Suspends a notification banner so it will not be dismissed. This happens because a new notification banner was placed in front of it on the queue.
*/
func suspend() {
if autoDismiss {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(dismiss), object: nil)
isSuspended = true
isDisplaying = false
}
}
/**
Resumes a notification banner immediately.
*/
func resume() {
if autoDismiss {
self.perform(#selector(dismiss), with: nil, afterDelay: self.duration)
isSuspended = false
isDisplaying = true
}
}
/**
Resets a notification banner's elapsed duration to zero.
*/
public func resetDuration() {
if autoDismiss {
NSObject.cancelPreviousPerformRequests(withTarget: self, selector: #selector(dismiss), object: nil)
self.perform(#selector(dismiss), with: nil, afterDelay: self.duration)
}
}
/**
The height adjustment needed in order for the banner to look properly displayed.
*/
internal var heightAdjustment: CGFloat {
// iOS 13 does not allow covering the status bar on non-notch iPhones
// The banner needs to be moved further down under the status bar in this case
guard #available(iOS 13.0, *), !NotificationBannerUtilities.isNotchFeaturedIPhone() else {
return 0
}
return UIApplication.shared.statusBarFrame.height
}
/**
Update banner height, it's necessary after banner labels font update
*/
internal func updateBannerHeight() {
onOrientationChanged()
}
/**
Changes the frame of the notification banner when the orientation of the device changes
*/
@objc private dynamic func onOrientationChanged() {
guard let window = appWindow else { return }
updateSpacerViewHeight()
let edgeInsets = bannerEdgeInsets ?? .zero
let newY = (bannerPosition == .top) ? (frame.origin.y) : (window.frame.height - bannerHeight + edgeInsets.top - edgeInsets.bottom)
frame = CGRect(x: frame.origin.x,
y: newY,
width: window.frame.width - edgeInsets.left - edgeInsets.right,
height: bannerHeight)
bannerPositionFrame = BannerPositionFrame(bannerPosition: bannerPosition,
bannerWidth: window.frame.width,
bannerHeight: bannerHeight,
maxY: maximumYPosition(),
finishYOffset: finishBannerYOffset(),
edgeInsets: bannerEdgeInsets)
}
/**
Dismisses the NotificationBanner and shows the next one if there is one to show on the queue
*/
@objc public func dismiss(forced: Bool = false) {
guard isDisplaying else {
return
}
NSObject.cancelPreviousPerformRequests(withTarget: self,
selector: #selector(dismiss),
object: nil)
NotificationCenter.default.post(name: BaseNotificationBanner.BannerWillDisappear, object: self, userInfo: notificationUserInfo)
delegate?.notificationBannerWillDisappear(self)
isDisplaying = false
remove()
UIView.animate(withDuration: forced ? animationDuration / 2 : animationDuration,
animations: {
self.frame = self.bannerPositionFrame.startFrame
}) { (completed) in
self.removeFromSuperview()
NotificationCenter.default.post(name: BaseNotificationBanner.BannerDidDisappear, object: self, userInfo: self.notificationUserInfo)
self.delegate?.notificationBannerDidDisappear(self)
self.bannerQueue.showNext(callback: { (isEmpty) in
if isEmpty || self.statusBarShouldBeShown() {
self.appWindow?.windowLevel = UIWindow.Level.normal
}
})
}
}
/**
Removes the NotificationBanner from the queue if not displaying
*/
public func remove() {
guard !isDisplaying else {
return
}
bannerQueue.removeBanner(self)
}
/**
Called when a notification banner is tapped
*/
@objc private dynamic func onTapGestureRecognizer() {
if dismissOnTap {
dismiss()
}
onTap?()
}
/**
Called when a notification banner is swiped up
*/
@objc private dynamic func onSwipeUpGestureRecognizer() {
if dismissOnSwipeUp {
dismiss()
}
onSwipeUp?()
}
/**
Determines wether or not the status bar should be shown when displaying a banner underneath
the navigation bar
*/
private func statusBarShouldBeShown() -> Bool {
for banner in bannerQueue.banners {
if (banner.parentViewController == nil && banner.bannerPosition == .top) {
return false
}
}
return true
}
/**
Calculates the maximum `y` position that a notification banner can slide in from
*/
private func maximumYPosition() -> CGFloat {
if let parentViewController = parentViewController {
return parentViewController.view.frame.height
} else {
return appWindow?.frame.height ?? 0
}
}
/**
Determines wether or not we should adjust the banner for notch featured iPhone
*/
internal func shouldAdjustForNotchFeaturedIphone() -> Bool {
return NotificationBannerUtilities.isNotchFeaturedIPhone()
&& UIApplication.shared.statusBarOrientation.isPortrait
&& (self.parentViewController?.navigationController?.isNavigationBarHidden ?? true)
}
/**
Updates the scrolling marquee label duration
*/
internal func updateMarqueeLabelsDurations() {
(titleLabel as? MarqueeLabel)?.speed = .duration(CGFloat(duration <= 3 ? 0.5 : duration - 3))
}
}
| 40.058431 | 181 | 0.629214 |
753d4fa74cd185628a172e92b91b13839f4a81b8
| 4,833 |
//
// ValueCoding.swift
// ValueCoding
//
// Created by Daniel Thorpe on 11/10/2015.
//
//
import Foundation
// MARK: - CodingType
/**
A generic protocol for classes which can
encode/decode value types.
*/
public protocol CodingType {
/**
The type of the composed value, ValueType
Bear in mind that there are no constraints on this
type. However, in reality when working with generic
types which require coding, it will be necessary to
constrain your generic clauses like this:
```swift
func foo<T: ValueCoding where T.Coder.ValueType == T>()
```
- see: ValueCoding
*/
typealias ValueType
/// The value type which is being encoded/decoded
var value: ValueType { get }
/// Required initializer receiving the wrapped value type.
init(_: ValueType)
}
// MARK: - ValueCoding
/**
A generic protocol for value types which require
coding.
*/
public protocol ValueCoding {
/**
The Coder which implements CodingType
- see: CodingType
*/
typealias Coder: CodingType
}
// MARK: - Protocol Extensions
extension CodingType where ValueType: ValueCoding, ValueType.Coder == Self {
internal static func decode(object: AnyObject?) -> ValueType? {
return (object as? Self)?.value
}
internal static func decode<S: SequenceType where S.Generator.Element: AnyObject>(objects: S?) -> [ValueType] {
return objects?.flatMap(decode) ?? []
}
internal static func decode<S: SequenceType where S.Generator.Element: SequenceType, S.Generator.Element.Generator.Element: AnyObject>(objects: S?) -> [[ValueType]] {
return objects?.flatMap(decode) ?? []
}
}
extension SequenceType where
Generator.Element: CodingType {
/// Access the values from a sequence of coders.
public var values: [Generator.Element.ValueType] {
return map { $0.value }
}
}
/**
Static methods for decoding `AnyObject` to Self, and returning encoded object
of Self.
*/
extension ValueCoding where Coder: NSCoding, Coder.ValueType == Self {
/**
Decodes the value from a single decoder, if possible.
For example
let foo = Foo.decode(decoder.decodeObjectForKey("foo"))
- parameter object: an optional `AnyObject` which if not nil should
be of `Coder` type.
- returns: an optional `Self`
*/
public static func decode(object: AnyObject?) -> Self? {
return Coder.decode(object)
}
/**
Decodes the values from a sequence of coders, if possible
For example
let foos = Foo.decode(decoder.decodeObjectForKey("foos") as? [AnyObject])
- parameter objects: a `SequenceType` of `AnyObject`.
- returns: the array of values which were able to be unarchived.
*/
public static func decode<S: SequenceType where S.Generator.Element: AnyObject>(objects: S?) -> [Self] {
return Coder.decode(objects)
}
/**
Decodes the values from a sequence of sequence of coders, if possible
- parameter objects: a `SequenceType` of `SequenceType` of `AnyObject`.
- returns: the array of arrays of values which were able to be unarchived.
*/
public static func decode<S: SequenceType where S.Generator.Element: SequenceType, S.Generator.Element.Generator.Element: AnyObject>(objects: S?) -> [[Self]] {
return Coder.decode(objects)
}
/**
Encodes the value type into its Coder.
Typically this would be used inside of
`encodeWithCoder:` when the value is composed inside
another `ValueCoding` or `NSCoding` type. For example:
encoder.encodeObject(foo.encoded, forKey: "foo")
*/
public var encoded: Coder {
return Coder(self)
}
}
extension SequenceType where
Generator.Element: ValueCoding,
Generator.Element.Coder: NSCoding,
Generator.Element.Coder.ValueType == Generator.Element {
/**
Encodes the sequence of value types into an array of coders.
Typically this would be used inside of
`encodeWithCoder:` when a sequence of values is
composed inside another `ValueCoding` or
`NSCoding` type. For example:
encoder.encodeObject(foos.encoded, forKey: "foos")
*/
public var encoded: [Generator.Element.Coder] {
return map { $0.encoded }
}
}
extension SequenceType where
Generator.Element: SequenceType,
Generator.Element.Generator.Element: ValueCoding,
Generator.Element.Generator.Element.Coder: NSCoding,
Generator.Element.Generator.Element.Coder.ValueType == Generator.Element.Generator.Element {
/**
Encodes a sequence of sequences of value types into
an array of arrays of coders.
*/
public var encoded: [[Generator.Element.Generator.Element.Coder]] {
return map { $0.encoded }
}
}
| 26.85 | 170 | 0.672253 |
d960032cbd5917a4d2e8637158f9f363568ae66e
| 1,274 |
//
// KnowYourAnglesUITests.swift
// KnowYourAnglesUITests
//
// Created by Cart 115 Administrator on 7/5/16.
// Copyright © 2016 Iolani School. All rights reserved.
//
import XCTest
class KnowYourAnglesUITests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
// In UI tests it is usually best to stop immediately when a failure occurs.
continueAfterFailure = false
// UI tests must launch the application that they test. Doing this in setup will make sure it happens for each test method.
XCUIApplication().launch()
// In UI tests it’s important to set the initial state - such as interface orientation - required for your tests before they run. The setUp method is a good place to do this.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testExample() {
// Use recording to get started writing UI tests.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
}
| 34.432432 | 182 | 0.669545 |
486d1ce9a08920a6c41db72af0431c47a9f42c94
| 622 |
//
// PNChartLabel.swift
// PNChartSwift
//
// Created by YiChen Zhou on 11/11/16.
// Copyright © 2016 YiChen Zhou. All rights reserved.
//
import UIKit
class PNChartLabel: UILabel {
override init(frame: CGRect) {
super.init(frame: frame)
self.font = UIFont.boldSystemFont(ofSize: 10.0)
self.textColor = MONGrey
self.backgroundColor = UIColor.clear
self.textAlignment = NSTextAlignment.center
self.isUserInteractionEnabled = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder: NSCode) has not been implemented.")
}
}
| 23.923077 | 67 | 0.657556 |
f751da1814b007cb3984b6981f8f095e8a03bb82
| 3,736 |
//
// White_NoiseTests.swift
// White NoiseTests
//
// Created by David Albers on 4/9/17.
// Copyright © 2017 David Albers. All rights reserved.
//
import XCTest
@testable import White_Noise
class White_NoiseTests: XCTestCase {
var viewController: ViewControllerMock!
var presenter: MainPresenter!
class ViewControllerMock : ViewController {
public var playCalled : Bool = false
public var getTimeCalled : Bool = false
public var addTimerCalled : Bool = false
let timerPickerTime : Double = 60.0
public var timerText : String = ""
public var mediaTitle : String = ""
override func play() {
playCalled = true
}
override func getTimerPickerTime() -> Double {
getTimeCalled = true
return timerPickerTime
}
override func addTimer(timerText: String) {
addTimerCalled = true
self.timerText = timerText
}
override func setColor(color: MainPresenter.NoiseColors) {
//mock has nothing to do
}
override func setMediaTitle(title: String) {
mediaTitle = title
}
}
override func setUp() {
super.setUp()
viewController = ViewControllerMock()
presenter = MainPresenter(viewController: viewController)
presenter.volume = 1.0
presenter.resettingVolume = false
}
override func tearDown() {
super.tearDown()
}
func testFade() {
presenter.enableFadeVolume(enabled: true)
XCTAssert(presenter.fadeEnabled)
presenter.tick()
XCTAssert(!isVolumeEqual(volume1: 1.0, volume2: presenter.volume))
XCTAssert(!isVolumeEqual(volume1: 1.0, volume2: presenter.maxVolume))
}
func testWave() {
presenter.enableWavyVolume(enabled: true)
presenter.increasing = false
presenter.tick()
XCTAssert(isVolumeEqual(volume1: 1.0 - presenter.volumeIncrement,
volume2: presenter.volume))
presenter.increasing = true
presenter.tick()
XCTAssert(isVolumeEqual(volume1: 1.0, volume2: presenter.volume))
}
func testFadeAndWave() {
presenter.enableWavyVolume(enabled: true)
presenter.enableFadeVolume(enabled: true)
presenter.increasing = false
presenter.volume = 0.5
presenter.tick()
XCTAssert(isVolumeEqual(volume1: 0.5 - presenter.volumeIncrement,
volume2: presenter.volume))
XCTAssert(!isVolumeEqual(volume1: 0.5, volume2: presenter.maxVolume))
}
func isVolumeEqual(volume1: Float, volume2: Float) -> Bool {
return volume2 < volume1 + 0.00001 && volume2 > volume1 - 0.00001
}
func testChangeColor() {
presenter.changeColor(color: MainPresenter.NoiseColors.Pink);
XCTAssert(presenter.getColor() == MainPresenter.NoiseColors.Pink)
XCTAssertTrue(viewController.mediaTitle == "Pink Noise")
}
func testPlay() {
presenter.isPlaying = false
presenter.playPause()
XCTAssertTrue(viewController.playCalled)
XCTAssert(presenter.isPlaying)
XCTAssertTrue(viewController.mediaTitle == "White Noise")
}
func testAddTimer() {
presenter.addDeleteTimer()
XCTAssert(presenter.timerDisplayed)
XCTAssert(presenter.timerActive)
XCTAssert(viewController.addTimerCalled)
XCTAssert(viewController.getTimeCalled)
print(viewController.timerText)
XCTAssert(viewController.timerText == "01:00")
}
}
| 31.133333 | 77 | 0.618844 |
de29edd3656b73192c3b149fd5c01f899da28fa2
| 2,419 |
import UIKit
import CoreLocation
class CGridMap:CController
{
private(set) weak var modelAlgo:MGridAlgo!
private(set) weak var viewMap:VGridMap!
private(set) var modelMap:MGridMap?
private var locationAsked:Bool
private let kDistanceFilter:CLLocationDistance = 100
private var locationManager:CLLocationManager?
init(modelAlgo:MGridAlgo)
{
self.modelAlgo = modelAlgo
locationAsked = false
super.init()
}
required init?(coder:NSCoder)
{
return nil
}
deinit
{
locationManager = nil
}
override func loadView()
{
let viewMap:VGridMap = VGridMap(controller:self)
self.viewMap = viewMap
view = viewMap
}
override func viewDidAppear(_ animated:Bool)
{
super.viewDidAppear(animated)
parentController.viewParent.panRecognizer.isEnabled = false
if !locationAsked
{
locationAsked = true
askLocation()
}
}
//MARK: private
private func askLocation()
{
let status:CLAuthorizationStatus = CLLocationManager.authorizationStatus()
if status == CLAuthorizationStatus.notDetermined
{
let locationManager:CLLocationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
locationManager.distanceFilter = kDistanceFilter
self.locationManager = locationManager
locationManager.requestWhenInUseAuthorization()
}
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.loadModelMap()
}
}
private func loadModelMap()
{
modelMap = MGridMap(modelAlgo:modelAlgo)
DispatchQueue.main.async
{ [weak self] in
self?.modelMapLoaded()
}
}
private func modelMapLoaded()
{
guard
let annotations:[MGridMapAnnotation] = modelMap?.annotations
else
{
return
}
viewMap.viewRender.addAnnotations(annotations)
}
//MARK: public
func back()
{
parentController.pop(horizontal:CParent.TransitionHorizontal.fromRight)
}
}
| 23.259615 | 82 | 0.58826 |
9ccc1949841ab9fe2e25c5634245f6d3efd56598
| 36,742 |
// swiftlint:disable force_cast inclusive_language
import Foundation
extension String {
func lowercasedFirstLetter() -> String {
prefix(1).lowercased() + dropFirst()
}
mutating func lowercasedFirstLetter() {
self = self.lowercasedFirstLetter()
}
func uppercasedFirstLetter() -> String {
let string = self.replacingOccurrences(of: "`", with: "")
return string.prefix(1).uppercased() + string.dropFirst()
}
mutating func uppercasedFirstLetter() {
self = self.uppercasedFirstLetter()
}
// Make string into a legal swift instance variable name
func parameterName() -> String {
self
.replacingOccurrences(of: "_", with: " ")
.replacingOccurrences(of: "-", with: " ")
.capitalized
.replacingOccurrences(of: " ", with: "")
.replacingOccurrences(of: ".", with: "_")
.lowercasedFirstLetter()
}
}
// swiftlint:disable:next type_body_length
public class Inspector {
struct DefaultType {
let enumName: String
let baseType: String
let characteristic: String
let values: [(String, Int)]
init(_ typeName: String, _ baseType: String, _ characteristic: String, _ values: [(String, Int)]) {
self.enumName = typeName
self.baseType = baseType
self.characteristic = characteristic
self.values = values
}
}
static let defaultTypes: [DefaultType] = [
DefaultType("ContactSensorState", "UInt8", "contact-state", [
("detected", 0),
("notDetected", 1)
]),
DefaultType("PositionState", "UInt8", "position.state", [
("decreasing", 0),
("increasing", 1),
("stopped", 2)
]),
DefaultType("CurrentDoorState", "UInt8", "door-state.current", [
("open", 0),
("closed", 1),
("opening", 2),
("closing", 3),
("stopped", 4)
]),
DefaultType("TargetDoorState", "UInt8", "door-state.target", [
("open", 0),
("closed", 1)
]),
DefaultType("LockCurrentState", "UInt8", "lock-mechanism.current-state", [
("unsecured", 0),
("secured", 1),
("jammed", 2),
("unknown", 3)
]),
DefaultType("LockTargetState", "UInt8", "lock-mechanism.target-state", [
("unsecured", 0),
("secured", 1)
]),
DefaultType("SmokeDetected", "UInt8", "smoke-detected", [
("smokeNotDetected", 0),
("smokeDetected", 1)
]),
DefaultType("Active", "UInt8", "active", [
("inactive", 0),
("active", 1)
]),
DefaultType("SleepDiscoveryMode", "UInt8", "sleep-discovery-mode", [
("notDiscoverable", 0),
("alwaysDiscoverable", 1)
]),
DefaultType("ClosedCaptions", "UInt8", "closed-captions", [
("disabled", 0),
("enabled", 1)
]),
DefaultType("TargetMediaState", "UInt8", "media-state.target", [
("play", 0),
("pause", 1),
("stop", 2)
]),
DefaultType("PictureMode", "UInt16", "picture-mode", [
("other", 0),
("standard", 1),
("calibrated", 2),
("calibratedDark", 3),
("vivid", 4),
("game", 5),
("computer", 6),
("custom", 7)
]),
DefaultType("PowerModeSelection", "UInt8", "power-mode-selection", [
("show", 0),
("hide", 1)
]),
DefaultType("RemoteKey", "UInt8", "remote-key", [
("rewind", 0),
("fastForward", 1),
("nextTrack", 2),
("previousTrack", 3),
("arrowUp", 4),
("arrowDown", 5),
("arrowLeft", 6),
("arrowRight", 7),
("select", 8),
("back", 9),
("exit", 10),
("playPause", 11),
("information", 15)
]),
DefaultType("InputSourceType", "UInt8", "input-source-type", [
("other", 0),
("homeScreen", 1),
("tuner", 2),
("hdmi", 3),
("compositeVideo", 4),
("sVideo", 5),
("componentVideo", 6),
("dvi", 7),
("airplay", 8),
("usb", 9),
("application", 10)
]),
DefaultType("InputDeviceType", "UInt8", "input-device-type", [
("other", 0),
("tv", 1),
("recording", 2),
("tuner", 3),
("playback", 4),
("audioSystem", 5)
]),
DefaultType("CurrentVisibilityState", "UInt8", "visibility-state.current", [
("shown", 0),
("hidden", 1),
("state2", 2),
("state3", 3)
]),
DefaultType("TargetVisibilityState", "UInt8", "visibility-state.target", [
("shown", 0),
("hidden", 1)
]),
DefaultType("VolumeControlType", "UInt8", "volume-control-type", [
("none", 0),
("relative", 1),
("relativeWithCurrent", 2),
("absolute", 3)
]),
DefaultType("VolumeSelector", "UInt8", "volume-selector", [
("increment", 0),
("decrement", 1)
]),
DefaultType("IsConfigured", "UInt8", "is-configured", [
("notConfigured", 0),
("configured", 1)
]),
DefaultType("TemperatureDisplayUnits", "UInt8", "temperature.units", [
("celcius", 0),
("fahrenheit", 1)
])
]
struct FileHandlerOutputStream: TextOutputStream {
private let fileHandle: FileHandle
let encoding: String.Encoding
init(_ fileHandle: FileHandle, encoding: String.Encoding = .utf8) {
self.fileHandle = fileHandle
self.encoding = encoding
}
mutating func write(_ string: String) {
if let data = string.data(using: encoding) {
fileHandle.write(data)
}
}
}
// swiftlint:disable:next cyclomatic_complexity
class func inspect(source plistPath: URL, target outputPath: String) throws {
// Convert HAP unit names to swift instance variable name
func unitName(_ name: String) -> String {
name.lowercased()
.replacingOccurrences(of: "/", with: " per ")
.replacingOccurrences(of: "^3", with: " cubed ")
.parameterName()
}
// Convert HAP type to swift type name
func typeName(_ name: String) -> String {
let name = name.lowercased()
if name.first == "u" {
return name.prefix(2).uppercased() + name.dropFirst(2)
} else if name == "tlv8" {
return "Data"
}
return name.capitalized
}
// Convert HAP accessory category name to swift instance variable name
func categoryName(_ name: String) -> String {
let knownConversion = ["Apple TV": "appleTV", "Switch": "`switch`"]
if let knownName = knownConversion[name] {
return knownName
}
return name.parameterName()
}
// Convert HAP service name to swift instance variable name
func serviceName(_ name: String, uuid: String) -> String {
if uuid == "000000B7" {
return "fanV2"
}
let knownConversion = ["Accessory Information Service": "info", "Switch": "`switch`"]
if let knownName = knownConversion[name] {
return knownName
}
return name.parameterName()
}
// Convert HAP permission flags into comma seperated swift permission enum values
func permissions(_ permissions: Int) -> String {
var list = [String]()
if (permissions & 2) == 2 {
list.append(".read")
}
if (permissions & 4) == 4 {
list.append(".write")
}
if (permissions & 1) == 1 {
list.append(".events")
}
return list.joined(separator: ", ")
}
// Decode plist
guard let plist = NSDictionary(contentsOf: plistPath),
let plistDict = plist["PlistDictionary"] as? NSDictionary,
let assistantDict = plistDict["Assistant"] as? NSDictionary,
let hapDict = plistDict["HAP"] as? NSDictionary,
let homekitDict = plistDict["HomeKit"] as? NSDictionary,
let categories = homekitDict["Categories"] as? [String: NSDictionary],
let services = hapDict["Services"] as? [String: NSDictionary],
let characteristics = hapDict["Characteristics"] as? [String: NSDictionary],
let characteristicConstants = assistantDict["Characteristics"] as? [String: NSDictionary],
let units = hapDict["Units"] as? [String: NSDictionary],
let blacklist = homekitDict["Blacklist"] as? [String: [String]],
let blacklistApps = homekitDict["BlacklistFromApplications"] as? [String: [String]],
let blacklistCharacteristics = blacklist["Characteristics"],
let blacklistServices = blacklist["Services"],
let blacklistAppServices = blacklistApps["Services"] else {
print("Could not read plist")
return
}
var blacklistedServices = blacklistServices
blacklistedServices.append(contentsOf: blacklistAppServices)
let blacklistedCharacteristics = blacklistCharacteristics
// Don't remove characteristics from app blacklist
//blacklistedCharacteristics.append(contentsOf: blacklistAppCharacteristics)
print("Writing to \(outputPath)")
try FileManager.default.createDirectory(atPath: "\(outputPath)/Enums", withIntermediateDirectories: false, attributes: nil)
try FileManager.default.createDirectory(atPath: "\(outputPath)/Services", withIntermediateDirectories: false, attributes: nil)
try FileManager.default.createDirectory(atPath: "\(outputPath)/Characteristics", withIntermediateDirectories: false, attributes: nil)
func writeToFile(atPath path: String, generator: ((String) -> Void) -> Void) throws {
let url = URL(fileURLWithPath: "\(outputPath)/\(path)")
FileManager.default.createFile(atPath: url.path, contents: nil, attributes: nil)
let fileHandle = try FileHandle(forWritingTo: url)
var output = FileHandlerOutputStream(fileHandle)
defer {
fileHandle.closeFile()
}
func write(_ msg: String, terminator: String = "\n") {
print(msg, terminator: terminator, to: &output)
}
generator({ x in write(x) })
}
// File Header
try writeToFile(atPath: "README") { write in
let osVersion = ProcessInfo.processInfo.operatingSystemVersionString
let currentDateTime = Date()
let formatter = DateFormatter()
formatter.timeStyle = .none
formatter.dateStyle = .long
let today = formatter.string(from: currentDateTime)
write("""
The files in this directory have been generated automatically
from the macOS HomeKit framework definitions. Don't make changes
to these files directly. Update these files using the `hap-update`
tool.
Generated on: \(today)
HomeKit framework version: \(plist["Version"] ?? "?")
macOS: \(osVersion)
""")
}
// Categories
struct CategoryInfo {
let name: String
let id: Int
}
var categoryInfo = [CategoryInfo]()
for (_, dict) in categories {
if let title = dict["DefaultDescription"] as? String,
let id = dict["Identifier"] as? Int {
categoryInfo.append(CategoryInfo(name: title, id: id))
}
}
try writeToFile(atPath: "AccessoryType.swift") { write in
write("""
public enum AccessoryType: String, Codable {
""")
for category in categoryInfo.sorted(by: { $0.id < $1.id }) {
write(" case \(categoryName(category.name)) = \"\(category.id)\"")
}
write("""
}
extension AccessoryType: CustomStringConvertible {
public var description: String {
switch self {
""")
for category in categoryInfo.sorted(by: { $0.id < $1.id }) {
write(" case .\(categoryName(category.name)): return \"\(category.name)\"")
}
write("""
}
}
}
""")
}
struct ServiceInfo {
let name: String
let title: String
let paramName: String
let className: String
let id: String
let required: [String]
let optional: [String]
}
var serviceInfo = [ServiceInfo]()
var whitelistedCharacteristics = Set<String>()
for (name, dict) in services {
if let title = dict["DefaultDescription"] as? String,
let id = dict["ShortUUID"] as? String {
if !blacklistedServices.contains(name),
let serviceCharacteristics = dict["Characteristics"] as? [String: [String]] {
let required = serviceCharacteristics["Required"] ?? []
let optional = serviceCharacteristics["Optional"] ?? []
serviceInfo.append(ServiceInfo(name: name,
title: title,
paramName: serviceName(title, uuid: id),
className: serviceName(title, uuid: id).uppercasedFirstLetter(),
id: id,
required: required,
optional: optional
))
whitelistedCharacteristics = whitelistedCharacteristics.union(required)
whitelistedCharacteristics = whitelistedCharacteristics.union(optional)
}
}
}
// Service types
try writeToFile(atPath: "ServiceType.swift") { write in
write("""
public extension ServiceType {
""")
for service in serviceInfo.sorted(by: { $0.className < $1.className }) {
write(" static let \(serviceName(service.title, uuid: service.id)) = ServiceType(0x\(service.id.suffix(4)))")
}
write("""
}
extension ServiceType: CustomStringConvertible {
public var description: String {
switch self {
""")
for service in serviceInfo.sorted(by: { $0.className < $1.className }) {
if let id = Int(service.id, radix: 16) {
_ = String(id, radix: 16, uppercase: true)
write(" case .\(serviceName(service.title, uuid: service.id)): return \"\(service.title)\"")
}
}
write("""
case let .appleDefined(typeCode):
let hex = String(typeCode, radix: 16).uppercased()
return "Apple Defined (\\(hex))"
case let .custom(uuid):
return "\\(uuid)"
}
}
}
""")
}
// Characteristic types
struct CharacteristicInfo {
let hkname: String
let title: String
let id: String
let format: String
let maxValue: NSNumber?
let minValue: NSNumber?
let properties: Int
let stepValue: NSNumber?
let units: String?
var permissions: [CharacteristicInfoPermission] {
var list = [CharacteristicInfoPermission]()
if properties & 2 == 2 {
list.append(.read)
}
if properties & 4 == 4 {
list.append(.write)
}
if properties & 1 == 1 {
list.append(.events)
}
return list
}
var isReadable: Bool {
permissions.contains(.read)
}
}
var characteristicInfo = [CharacteristicInfo]()
var characteristicFormats = Set<String>()
for (name, dict) in characteristics {
if let title = dict["DefaultDescription"] as? String,
let id = dict["ShortUUID"] as? String,
let format = dict["Format"] as? String {
if !blacklistedCharacteristics.contains(name) && whitelistedCharacteristics.contains(name) {
characteristicInfo.append(
CharacteristicInfo(hkname: name,
title: title,
id: id,
format: format,
maxValue: dict["MaxValue"] as? NSNumber,
minValue: dict["MinValue"] as? NSNumber,
properties: dict["Properties"] as? Int ?? Int(dict["Properties"].debugDescription)!,
stepValue: dict["StepValue"] as? NSNumber,
units: dict["Units"] as? String))
characteristicFormats.insert(format)
}
}
}
try writeToFile(atPath: "CharacteristicType.swift") { write in
write("""
// swiftlint:disable no_grouping_extension
public extension CharacteristicType {
""")
for characteristic in characteristicInfo.sorted(by: { $0.title < $1.title }) {
write(" static let \(serviceName(characteristic.title, uuid: characteristic.id)) = CharacteristicType(0x\(characteristic.id.suffix(4)))")
}
write("""
}
extension CharacteristicType: CustomStringConvertible {
public var description: String {
switch self {
""")
for characteristic in characteristicInfo.sorted(by: { $0.title < $1.title }) {
if let id = Int(characteristic.id, radix: 16) {
_ = String(id, radix: 16, uppercase: true)
write(" case .\(serviceName(characteristic.title, uuid: characteristic.id)): return \"\(characteristic.title)\"")
}
}
write("""
case let .appleDefined(typeCode):
let hex = String(typeCode, radix: 16).uppercased()
return "Apple Defined (\\(hex))"
case let .custom(uuid):
return "\\(uuid)"
}
}
}
""")
}
// Characteristic Formats
characteristicFormats = characteristicFormats.union(["data", "uint16"])
try writeToFile(atPath: "CharacteristicFormat.swift") { write in
write("""
public enum CharacteristicFormat: String, Codable {
""")
for format in characteristicFormats.sorted(by: { $0 < $1 }) {
write(" case \(format.lowercased())")
}
write("}")
}
// Characteristic Units
var unitInfo = [String]()
for (name, dict) in units {
if (dict["DefaultDescription"] as? String) != nil {
unitInfo.append(unitName(name))
}
}
try writeToFile(atPath: "CharacteristicUnit.swift") { write in
write("""
public enum CharacteristicUnit: String, Codable {
""")
for unit in unitInfo.sorted(by: { $0 < $1 }) {
write(" case \(unit)")
}
write("}")
}
// Characteristic enumerated types
var enumeratedCharacteristics = Set<String>()
var defaultEnumCase = [String: String]()
func determineEnumerationCases(_ newValues: NSDictionary) -> NSDictionary? {
var values = newValues
// Check if keys are digits
let numberedKeys = values.allKeys.compactMap({ ($0 as? NSNumber)?.intValue ?? Int($0 as? String ?? "x") })
if numberedKeys.count == values.count {
// Check if vals are also all digits
let numberedValues = values.allValues.compactMap({ ($0 as? NSNumber)?.intValue ?? Int($0 as? String ?? "x") })
if numberedValues.count == values.count {
return nil
}
// Swap keys and values
let keys = values.allKeys
let vals = values.allValues
values = NSDictionary(objects: keys, forKeys: vals as! [NSCopying])
}
return values
}
try writeToFile(atPath: "Enums.swift") { write in
write("public class Enums { }")
}
func writeEnumeration(enumName: String, type: String, values: NSDictionary, max: NSNumber?) throws {
try writeToFile(atPath: "Enums/Enums.\(enumName).swift") { write in
write("public extension Enums {")
write(" enum \(enumName): \(type), CharacteristicValueType {")
let cases = values.sorted(by: {
if let number = $0.value as? NSNumber {
return number.intValue < ($1.value as! NSNumber).intValue
} else if let string = $0.value as? String {
return string < ($1.value as! String)
}
return false
}).filter({
guard let max = max else {
return true
}
let val: NSNumber
if let number = $0.value as? NSNumber {
val = number
} else if let string = $0.value as? String,
let num = NumberFormatter().number(from: string) {
val = num
} else {
return true
}
return !(max.compare(val) == .orderedAscending)
})
for enumCase in cases {
if let name = (enumCase.key as? String) {
write(" case \(name.parameterName()) = \(enumCase.value)")
}
}
write(" }")
write("}")
}
}
var enums = [(enumName: String, type: String, newValues: NSDictionary, info: CharacteristicInfo)]()
for (_, dict) in characteristicConstants {
let rName = dict["Read"] as? String
let wName = dict["Write"] as? String
let rwName = dict["ReadWrite"] as? String
let wValues = dict["Values"] as? NSDictionary
let rValues = dict["OutValues"] as? NSDictionary
if rName != nil && wName != nil && rValues != nil && wValues != nil {
print("r:\(rName!) w:\(wName!)")
}
if let rName = rName, let values = rValues,
let info = characteristicInfo.first(where: { $0.hkname == rName }) {
let enumName = info.title.parameterName().uppercasedFirstLetter()
let type = typeName(info.format)
enums.append((enumName: enumName, type: type, newValues: values, info: info))
} else if let rName = rName, let values = wValues,
let info = characteristicInfo.first(where: { $0.hkname == rName }) {
let enumName = info.title.parameterName().uppercasedFirstLetter()
let type = typeName(info.format)
enums.append((enumName: enumName, type: type, newValues: values, info: info))
}
if let wName = wName, let values = wValues,
let info = characteristicInfo.first(where: { $0.hkname == wName }) {
let enumName = info.title.parameterName().uppercasedFirstLetter()
let type = typeName(info.format)
enums.append((enumName: enumName, type: type, newValues: values, info: info))
}
if let rwName = rwName, let values = wValues,
let info = characteristicInfo.first(where: { $0.hkname == rwName }) {
let enumName = info.title.parameterName().uppercasedFirstLetter()
let type = typeName(info.format)
enums.append((enumName: enumName, type: type, newValues: values, info: info))
}
}
// Add any default enums which are not defined in the HAP config
for defaultType in Inspector.defaultTypes {
if enums.first(where: { $0.info.hkname == defaultType.characteristic }) != nil {
// Already defined
} else if let info = characteristicInfo.first(where: { $0.hkname == defaultType.characteristic }) {
print("Using predefined enum for '\(defaultType.enumName)'")
let valuedict = NSMutableDictionary()
for value in defaultType.values {
valuedict[value.0] = value.1
}
enums.append((enumName: defaultType.enumName, type: defaultType.baseType, newValues: valuedict, info: info))
}
}
for (enumName, type, values, info) in enums.sorted(by: { $0.enumName < $1.enumName }) {
if let enumCases = determineEnumerationCases(values) {
try writeEnumeration(enumName: enumName, type: type, values: enumCases, max: info.maxValue)
enumeratedCharacteristics.insert(info.hkname)
defaultEnumCase[info.hkname] = (enumCases.allKeys[0] as! String).parameterName()
} else if let defaultType = Inspector.defaultTypes.first(where: { $0.characteristic == info.hkname }) {
// The HAP config definition couldn't be written, likely because both key and values are digits
// Fallback to a default definition if it exists
print("Use predefined enum cases for '\(enumName)'")
let valuedict = NSMutableDictionary()
for value in defaultType.values {
valuedict[value.0] = value.1
}
try writeEnumeration(enumName: defaultType.enumName, type: defaultType.baseType, values: valuedict, max: info.maxValue)
enumeratedCharacteristics.insert(info.hkname)
defaultEnumCase[info.hkname] = defaultType.values[0].0.parameterName()
} else {
print("Could not determine enum cases for '\(enumName)'")
}
}
// Service classes
func valueType(_ characteristic: CharacteristicInfo) -> String {
let name = characteristic.title.parameterName()
let enumType = enumeratedCharacteristics.contains(characteristic.hkname) ?
"Enums.\(name.uppercasedFirstLetter())" :
typeName(characteristic.format)
return enumType + (characteristic.isReadable ? "" : "?")
}
for service in serviceInfo.sorted(by: { $0.className < $1.className }) {
try writeToFile(atPath: "Services/Service.\(service.className).swift") { write in
func writeCharacteristicProperty(info: CharacteristicInfo, isOptional: Bool) {
let name = info.title.parameterName()
write(" public let \(name): GenericCharacteristic<\(valueType(info))>\(isOptional ? "?" : "")")
}
write("""
import Foundation
extension Service {
""")
write(" open class \(service.className): Service {")
write("""
public init(characteristics: [AnyCharacteristic] = []) {
var unwrapped = characteristics.map { $0.wrapped }
""")
for characteristic in service.required {
if let info = characteristicInfo.first(where: { $0.hkname == characteristic }) {
let name = info.title.parameterName()
let characteristiceType = ".\(serviceName(info.title, uuid: info.id))"
write("""
\(name) = getOrCreateAppend(
type: \(characteristiceType),
characteristics: &unwrapped,
generator: { PredefinedCharacteristic.\(serviceName(info.title, uuid: info.id))() })
""")
}
}
for characteristic in service.optional {
if let info = characteristicInfo.first(where: { $0.hkname == characteristic }) {
let name = info.title.parameterName()
let characteristiceType = ".\(serviceName(info.title, uuid: info.id))"
write("""
\(name) = get(type: \(characteristiceType), characteristics: unwrapped)
""")
}
}
write("""
super.init(type: .\(serviceName(service.title, uuid: service.id)), characteristics: unwrapped)
}
""")
write(" // MARK: - Required Characteristics")
for characteristic in service.required {
if let info = characteristicInfo.first(where: { $0.hkname == characteristic }) {
writeCharacteristicProperty(info: info, isOptional: false)
}
}
write("\n // MARK: - Optional Characteristics")
for characteristic in service.optional {
if let info = characteristicInfo.first(where: { $0.hkname == characteristic }) {
writeCharacteristicProperty(info: info, isOptional: true)
}
}
write("""
}
}
""")
}
}
func defaultValue(_ characteristic: CharacteristicInfo) -> String {
if characteristic.isReadable {
if enumeratedCharacteristics.contains(characteristic.hkname) {
guard let defaultCase = defaultEnumCase[characteristic.hkname] else {
preconditionFailure("No default enum case for enum \(characteristic.hkname)")
}
return "." + defaultCase
} else {
switch valueType(characteristic) {
case "Bool": return "false"
case "Data": return "Data()"
case "String": return "\"\""
case "Float", "Int", "UInt8", "UInt16", "UInt32": return characteristic.minValue?.stringValue ?? "0"
default: preconditionFailure("No default value for value type \(valueType(characteristic))")
}
}
} else {
return "nil"
}
}
try writeToFile(atPath: "PredefinedCharacteristic.swift") { write in
write("public class PredefinedCharacteristic { }")
}
for characteristic in characteristicInfo.sorted(by: { $0.title < $1.title }) {
let name = serviceName(characteristic.title, uuid: characteristic.id)
try writeToFile(atPath: "Characteristics/Characteristic.\(name.uppercasedFirstLetter()).swift") { write in
func writeFactoryArgumentsWithDefaults() {
write(" _ value: \(valueType(characteristic)) = \(defaultValue(characteristic)),")
write(" permissions: [CharacteristicPermission] = \(characteristic.permissions.arrayLiteral),")
write(" description: String? = \"\(characteristic.title)\",")
write(" format: CharacteristicFormat? = .\(characteristic.format),")
write(" unit: CharacteristicUnit? = \(characteristic.units != nil ? ".\(unitName(characteristic.units!))" : "nil"),")
write(" maxLength: Int? = nil,")
write(" maxValue: Double? = \(characteristic.maxValue?.stringValue ?? "nil"),")
write(" minValue: Double? = \(characteristic.minValue?.stringValue ?? "nil"),")
write(" minStep: Double? = \(characteristic.stepValue?.stringValue ?? "nil"),")
write(" validValues: [Double] = [],")
write(" validValuesRange: Range<Double>? = nil")
}
write("import Foundation")
write("")
write("public extension AnyCharacteristic {")
write(" static func \(name)(")
writeFactoryArgumentsWithDefaults()
write(" ) -> AnyCharacteristic {")
write(" AnyCharacteristic(")
write(" PredefinedCharacteristic.\(name)(")
write(" value,")
write(" permissions: permissions,")
write(" description: description,")
write(" format: format,")
write(" unit: unit,")
write(" maxLength: maxLength,")
write(" maxValue: maxValue,")
write(" minValue: minValue,")
write(" minStep: minStep,")
write(" validValues: validValues,")
write(" validValuesRange: validValuesRange) as Characteristic)")
write(" }")
write("}")
write("")
write("public extension PredefinedCharacteristic {")
write(" static func \(name)(")
writeFactoryArgumentsWithDefaults()
write(" ) -> GenericCharacteristic<\(valueType(characteristic))> {")
write(" GenericCharacteristic<\(valueType(characteristic))>(")
write(" type: .\(name),")
write(" value: value,")
write(" permissions: permissions,")
write(" description: description,")
write(" format: format,")
write(" unit: unit,")
write(" maxLength: maxLength,")
write(" maxValue: maxValue,")
write(" minValue: minValue,")
write(" minStep: minStep,")
write(" validValues: validValues,")
write(" validValuesRange: validValuesRange)")
write(" }")
write("}")
}
}
}
}
enum CharacteristicInfoPermission: String {
case read
case write
case events
}
extension Array where Element == CharacteristicInfoPermission {
var arrayLiteral: String {
"[" + self.map { ".\($0)" }.joined(separator: ", ") + "]"
}
}
| 40.067612 | 156 | 0.496788 |
729ed130b950fe9f8caedae97e50cb9cc376b3c5
| 2,368 |
import Foundation
open class APDUCommand: NSObject, Serializable, APDUResponseProtocol {
open var commandId: String?
open var groupId: Int = 0
open var sequence: Int = 0
open var command: String?
open var type: String?
open var continueOnFailure: Bool = false
open var responseData: Data?
var links: [ResourceLink]?
private enum CodingKeys: String, CodingKey {
case links = "_links"
case commandId
case groupId
case sequence
case command
case type
case continueOnFailure
}
public required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
links = try container.decode(.links, transformer: ResourceLinkTypeTransform())
commandId = try? container.decode(.commandId)
groupId = try container.decodeIfPresent(Int.self, forKey: .groupId) ?? 0
sequence = try container.decodeIfPresent(Int.self, forKey: .sequence) ?? 0
command = try? container.decode(.command)
type = try? container.decode(.type)
continueOnFailure = try container.decodeIfPresent(Bool.self, forKey: .continueOnFailure) ?? false
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try? container.encode(links, forKey: .links, transformer: ResourceLinkTypeTransform())
try? container.encode(commandId, forKey: .commandId)
try? container.encode(groupId, forKey: .groupId)
try? container.encode(sequence, forKey: .sequence)
try? container.encode(command, forKey: .command)
try? container.encode(type, forKey: .type)
try? container.encode(continueOnFailure, forKey: .continueOnFailure)
}
open var responseDictionary: [String: Any] {
get {
var dic: [String: Any] = [:]
if let commandId = commandId {
dic["commandId"] = commandId
}
if let responseCode = responseCode {
dic["responseCode"] = responseCode.hex
}
if let responseData = responseData {
dic["responseData"] = responseData.hex
}
return dic
}
}
}
| 33.352113 | 105 | 0.611064 |
610771de2976b56243bf3695bb70cda974166324
| 460 |
import UIKit
class User {
var username: String = ""
var fullname: String = ""
var email: String = ""
}
var user1 = User()
user1.email = "[email protected]"
user1.fullname = "Alejandro Daniel Gonzalez Carrillo"
user1.username = "Alexcgzz"
class Post {
var samplePost: String = ""
var username: String = ""
}
var newPost = Post()
newPost.samplePost = "Its time get drunk and chill ass. "
newPost.username = user1.username
| 20 | 57 | 0.680435 |
e220c046b15784a891b9ae683bf8763ea8abe61d
| 2,713 |
//
// FailureDetailsViewController.swift
// AdForMerchant
//
// Created by 糖otk on 2017/2/23.
// Copyright © 2017年 Windward. All rights reserved.
//
import UIKit
class FailureDetailsViewController: BaseViewController {
lazy var headLabel: UILabel = {
let headLabel = UILabel(frame: CGRect(x: 10, y: 14, width: 100, height: 20))
headLabel.text = "审核不通过"
return headLabel
}()
lazy var lineView: UIView = {
let lineView = UIView(frame: CGRect(x: 10, y: 45, width: screenWidth-20, height: 1))
lineView.backgroundColor = UIColor.colorWithHex("e4e5f2")
return lineView
}()
lazy var errorLabel: UILabel = {
let errorLabel = UILabel(frame: CGRect(x: 10, y: 60, width: screenWidth-20, height: 0))
errorLabel.textColor = UIColor.colorWithHex("9498a9")
errorLabel.numberOfLines = 0
return errorLabel
}()
lazy var underView: UIView = {
let underView = UILabel(frame: CGRect(x: 0, y: 0, width: screenWidth, height: 0))
underView.backgroundColor = UIColor.colorWithHex("f5f5f5")
return underView
}()
var errorMessage = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
setupUI()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupUI() {
title = "商户认证"
view.backgroundColor = UIColor.white
view.addSubview(self.headLabel)
view.addSubview(self.lineView)
view.addSubview(self.errorLabel)
view.addSubview(self.underView)
let attriText = self.getAttributeStringWithString(errorMessage, lineSpace: 5.00)
let height = String.getLabHeigh(attriText.string, font: UIFont.systemFont(ofSize: 17), width: screenWidth-20)
errorLabel.height = height+30
errorLabel.attributedText = attriText
underView.y = errorLabel.y+errorLabel.height
underView.height = screenHeight - underView.y
}
fileprivate func getAttributeStringWithString(_ string: String, lineSpace: CGFloat
) -> NSAttributedString {
let attributedString = NSMutableAttributedString(string: string)
let paragraphStye = NSMutableParagraphStyle()
//调整行间距
paragraphStye.lineSpacing = lineSpace
let rang = NSRange(location: 0, length: CFStringGetLength(string as CFString!))
attributedString .addAttribute(NSParagraphStyleAttributeName, value: paragraphStye, range: rang)
return attributedString
}
}
| 33.085366 | 118 | 0.652414 |
ab6c139971773504360f05ede675b7b6e94eea17
| 4,051 |
//
// UserAPI.swift
// PictionSDK
//
// Created by jhseo on 17/05/2019.
// Copyright © 2019 Piction Network. All rights reserved.
//
import Foundation
import Moya
import UIKit
public enum UserAPI {
case signup(loginId: String, email: String, username: String, password: String, passwordCheck: String)
case findOne(id: String)
case me
case update(email: String, username: String, password: String, picture: String? = nil)
case updatePassword(password: String, newPassword: String, passwordCheck: String)
case uploadPicture(image: UIImage)
case findPublicAddress(address: String)
}
extension UserAPI: TargetType {
public var baseURL: URL { return URL(string: ServerInfo.baseApiUrl)! }
public var path: String {
switch self {
case .signup:
return "/users"
case .findOne(let id):
return "/users/\(id)"
case .me,
.update:
return "/users/me"
case .updatePassword:
return "/users/me/password"
case .uploadPicture:
return "/users/me/picture"
case .findPublicAddress(let address):
return "/users/wallet/\(address)"
}
}
public var method: Moya.Method {
switch self {
case .signup:
return .post
case .findOne,
.me,
.findPublicAddress:
return .get
case .update:
return .put
case .updatePassword,
.uploadPicture:
return .patch
}
}
public var sampleData: Data {
switch self {
case .signup,
.updatePassword:
return jsonSerializedUTF8(json: AuthenticationViewResponse.sampleData())
case .findOne,
.update,
.me,
.findPublicAddress:
return jsonSerializedUTF8(json: UserViewResponse.sampleData())
case .uploadPicture:
return jsonSerializedUTF8(json: StorageAttachmentViewResponse.sampleData())
}
}
public var task: Task {
switch self {
case .findOne,
.me,
.findPublicAddress:
return .requestPlain
case .signup(let loginId, let email, let username, let password, let passwordCheck):
var param: [String: Any] = [:]
param["loginId"] = loginId
param["email"] = email
param["username"] = username
param["password"] = password
param["passwordCheck"] = passwordCheck
return .requestParameters(parameters: param, encoding: JSONEncoding.default)
case .update(let email, let username, let password, let picture):
var param: [String: Any] = [:]
param["email"] = email
param["username"] = username
param["password"] = password
if let picture = picture {
param["picture"] = picture
}
return .requestParameters(parameters: param, encoding: JSONEncoding.default)
case .updatePassword(let password, let newPassword, let passwordCheck):
var param: [String: Any] = [:]
param["password"] = password
param["newPassword"] = newPassword
param["passwordCheck"] = passwordCheck
return .requestParameters(parameters: param, encoding: JSONEncoding.default)
case .uploadPicture(let image):
guard let imageData = image.jpegData(compressionQuality: 1.0) else {
return .requestPlain
}
let formData: [Moya.MultipartFormData] = [Moya.MultipartFormData(provider: .data(imageData), name: "file", fileName: "user.jpeg", mimeType: "image/jpeg")]
return .uploadMultipart(formData)
}
}
public var headers: [String: String]? {
switch self {
case .uploadPicture:
return ServerInfo.getMultipartFormDataHeader()
default:
return ServerInfo.getCustomHeader()
}
}
}
| 34.623932 | 166 | 0.58356 |
e4e698daa43a9d9fc2ae846940f14a714ec4af66
| 526 |
//
// AppDelegate.swift
// SimpleNote
//
// Created by sodas on 4/30/17.
// Copyright © 2017 sodastsai. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]? = nil) -> Bool {
print("Notes would be saved in '\(PureTextNote.storageURL.path)'.")
return true
}
}
| 23.909091 | 120 | 0.684411 |
eb915808c147981930cf877439ecfad0cc6699fd
| 20,294 |
import Basic
import Foundation
import TuistCore
import XcodeProj
// swiftlint:disable:next type_body_length
class ProjectFileElements {
struct GroupFileElement: Hashable {
var path: AbsolutePath
var group: ProjectGroup
var isReference: Bool
init(path: AbsolutePath, group: ProjectGroup, isReference: Bool = false) {
self.path = path
self.group = group
self.isReference = isReference
}
}
// MARK: - Static
// swiftlint:disable:next force_try
static let localizedRegex = try! NSRegularExpression(pattern: "(.+\\.lproj)/.+",
options: [])
// swiftlint:disable:next force_try
static let assetRegex = try! NSRegularExpression(pattern: ".+/.+\\.xcassets/.+",
options: [])
// MARK: - Attributes
var elements: [AbsolutePath: PBXFileElement] = [:]
var products: [String: PBXFileReference] = [:]
let playgrounds: Playgrounding
let filesSortener: ProjectFilesSortening
// MARK: - Init
init(_ elements: [AbsolutePath: PBXFileElement] = [:],
playgrounds: Playgrounding = Playgrounds(),
filesSortener: ProjectFilesSortening = ProjectFilesSortener()) {
self.elements = elements
self.playgrounds = playgrounds
self.filesSortener = filesSortener
}
func generateProjectFiles(project: Project,
graph: Graphing,
groups: ProjectGroups,
pbxproj: PBXProj,
sourceRootPath: AbsolutePath) throws {
var files = Set<GroupFileElement>()
var products = Set<String>()
project.targets.forEach { target in
files.formUnion(targetFiles(target: target))
products.formUnion(targetProducts(target: target))
}
let projectFileElements = projectFiles(project: project)
files.formUnion(projectFileElements)
let pathsSort = filesSortener.sort
let filesSort: (GroupFileElement, GroupFileElement) -> Bool = {
pathsSort($0.path, $1.path)
}
/// Files
try generate(files: files.sorted(by: filesSort),
groups: groups,
pbxproj: pbxproj,
sourceRootPath: sourceRootPath)
/// Products
generate(products: products.sorted(),
groups: groups,
pbxproj: pbxproj)
/// Playgrounds
generatePlaygrounds(path: project.path,
groups: groups,
pbxproj: pbxproj,
sourceRootPath: sourceRootPath)
let dependencies = graph.findAll(path: project.path)
/// Dependencies
try generate(dependencies: dependencies,
path: project.path,
groups: groups,
pbxproj: pbxproj,
sourceRootPath: sourceRootPath,
filesGroup: project.filesGroup)
}
func projectFiles(project: Project) -> Set<GroupFileElement> {
var fileElements = Set<GroupFileElement>()
/// Config files
let configFiles = project.settings.configurations.values.compactMap { $0?.xcconfig }
fileElements.formUnion(configFiles.map {
GroupFileElement(path: $0, group: project.filesGroup)
})
// Additional files
fileElements.formUnion(project.additionalFiles.map {
GroupFileElement(path: $0.path,
group: project.filesGroup,
isReference: $0.isReference)
})
return fileElements
}
func targetProducts(target: Target) -> Set<String> {
var products: Set<String> = Set()
products.insert(target.productNameWithExtension)
return products
}
func targetFiles(target: Target) -> Set<GroupFileElement> {
var files = Set<AbsolutePath>()
files.formUnion(target.sources)
files.formUnion(target.coreDataModels.map { $0.path })
files.formUnion(target.coreDataModels.flatMap { $0.versions })
if let headers = target.headers {
files.formUnion(headers.public)
files.formUnion(headers.private)
files.formUnion(headers.project)
}
// Support files
if let infoPlist = target.infoPlist {
files.insert(infoPlist)
}
if let entitlements = target.entitlements {
files.insert(entitlements)
}
// Config files
target.settings?.configurations.xcconfigs().forEach { configFilePath in
files.insert(configFilePath)
}
// Elements
var elements = Set<GroupFileElement>()
elements.formUnion(files.map { GroupFileElement(path: $0, group: target.filesGroup) })
elements.formUnion(target.resources.map {
GroupFileElement(path: $0.path,
group: target.filesGroup,
isReference: $0.isReference)
})
return elements
}
func generate(files: [GroupFileElement],
groups: ProjectGroups,
pbxproj: PBXProj,
sourceRootPath: AbsolutePath) throws {
try files.forEach {
try generate(fileElement: $0, groups: groups, pbxproj: pbxproj, sourceRootPath: sourceRootPath)
}
}
func generate(products: [String],
groups: ProjectGroups,
pbxproj: PBXProj) {
products.sorted().forEach { productName in
if self.products[productName] != nil { return }
let fileType = Xcode.filetype(extension: String(productName.split(separator: ".").last!))
let fileReference = PBXFileReference(sourceTree: .buildProductsDir,
explicitFileType: fileType,
path: productName,
includeInIndex: false)
pbxproj.add(object: fileReference)
groups.products.children.append(fileReference)
self.products[productName] = fileReference
}
}
func generatePlaygrounds(path: AbsolutePath,
groups: ProjectGroups,
pbxproj: PBXProj,
sourceRootPath _: AbsolutePath) {
let paths = playgrounds.paths(path: path)
if paths.isEmpty { return }
let group = groups.playgrounds
paths.forEach { playgroundPath in
let name = playgroundPath.components.last!
let reference = PBXFileReference(sourceTree: .group,
lastKnownFileType: "file.playground",
path: name,
xcLanguageSpecificationIdentifier: "xcode.lang.swift")
pbxproj.add(object: reference)
group!.children.append(reference)
}
}
func generate(dependencies: Set<GraphNode>,
path: AbsolutePath,
groups: ProjectGroups,
pbxproj: PBXProj,
sourceRootPath: AbsolutePath,
filesGroup: ProjectGroup) throws {
try dependencies.forEach { node in
if let targetNode = node as? TargetNode {
// Product name
let productName = targetNode.target.productNameWithExtension
if self.products[productName] != nil { return }
/// The dependency belongs to the same project and its product
/// has already been generated by generate(products:)
if targetNode.path == path { return }
// Add it
let fileType = Xcode.filetype(extension: targetNode.target.product.xcodeValue.fileExtension!)
let fileReference = PBXFileReference(sourceTree: .buildProductsDir,
explicitFileType: fileType,
path: productName,
includeInIndex: false)
pbxproj.add(object: fileReference)
groups.products.children.append(fileReference)
self.products[productName] = fileReference
} else if let precompiledNode = node as? PrecompiledNode {
let fileElement = GroupFileElement(path: precompiledNode.path,
group: filesGroup)
try generate(fileElement: fileElement,
groups: groups,
pbxproj: pbxproj,
sourceRootPath: sourceRootPath)
}
}
}
func generate(fileElement: GroupFileElement,
groups: ProjectGroups,
pbxproj: PBXProj,
sourceRootPath: AbsolutePath) throws {
// The file already exists
if elements[fileElement.path] != nil { return }
let closestRelativeRelativePath = closestRelativeElementPath(path: fileElement.path,
sourceRootPath: sourceRootPath)
let closestRelativeAbsolutePath = sourceRootPath.appending(closestRelativeRelativePath)
let fileElementRelativeToSourceRoot = fileElement.path.relative(to: sourceRootPath)
// Add the first relative element.
let group: PBXGroup
switch fileElement.group {
case let .group(name: groupName):
group = try groups.projectGroup(named: groupName)
}
guard let firstElement = addElement(relativePath: closestRelativeRelativePath,
isLeaf: closestRelativeRelativePath == fileElementRelativeToSourceRoot,
from: sourceRootPath,
toGroup: group,
pbxproj: pbxproj) else {
return
}
// If it matches the file that we are adding or it's not a group we can exit.
if (closestRelativeAbsolutePath == fileElement.path) || !(firstElement.element is PBXGroup) {
return
}
var lastGroup: PBXGroup! = firstElement.element as? PBXGroup
var lastPath: AbsolutePath = firstElement.path
let components = fileElement.path.relative(to: lastPath).components
for component in components.enumerated() {
if lastGroup == nil { return }
guard let element = addElement(relativePath: RelativePath(component.element),
isLeaf: component.offset == components.count - 1,
from: lastPath,
toGroup: lastGroup!,
pbxproj: pbxproj) else {
return
}
lastGroup = element.element as? PBXGroup
lastPath = element.path
}
}
// MARK: - Internal
@discardableResult func addElement(relativePath: RelativePath,
isLeaf: Bool,
from: AbsolutePath,
toGroup: PBXGroup,
pbxproj: PBXProj) -> (element: PBXFileElement, path: AbsolutePath)? {
let absolutePath = from.appending(relativePath)
if elements[absolutePath] != nil {
return (element: elements[absolutePath]!, path: from.appending(relativePath))
}
// If the path is ../../xx we specify the name
// to prevent Xcode from using that as a name.
var name: String?
let components = relativePath.components
if components.count != 1 {
name = components.last!
}
// Add the file element
if isLocalized(path: absolutePath) {
addVariantGroup(from: from,
absolutePath: absolutePath,
relativePath: relativePath,
toGroup: toGroup,
pbxproj: pbxproj)
return nil
} else if isVersionGroup(path: absolutePath) {
return addVersionGroupElement(from: from,
folderAbsolutePath: absolutePath,
folderRelativePath: relativePath,
name: name,
toGroup: toGroup,
pbxproj: pbxproj)
} else if !(isXcassets(path: absolutePath) || isLeaf) {
return addGroupElement(from: from,
folderAbsolutePath: absolutePath,
folderRelativePath: relativePath,
name: name,
toGroup: toGroup,
pbxproj: pbxproj)
} else {
addFileElement(from: from,
fileAbsolutePath: absolutePath,
fileRelativePath: relativePath,
name: name,
toGroup: toGroup,
pbxproj: pbxproj)
return nil
}
}
func addVariantGroup(from: AbsolutePath,
absolutePath: AbsolutePath,
relativePath _: RelativePath,
toGroup: PBXGroup,
pbxproj: PBXProj) {
// /path/to/*.lproj/*
absolutePath.glob("*").sorted().forEach { localizedFile in
let localizedName = localizedFile.components.last!
// Variant group
let variantGroupPath = absolutePath.parentDirectory.appending(component: localizedName)
var variantGroup: PBXVariantGroup! = elements[variantGroupPath] as? PBXVariantGroup
if variantGroup == nil {
variantGroup = PBXVariantGroup(children: [], sourceTree: .group, name: localizedName)
pbxproj.add(object: variantGroup)
toGroup.children.append(variantGroup)
elements[variantGroupPath] = variantGroup
}
// Localized element
let localizedFilePath = "\(absolutePath.components.last!)/\(localizedName)" // e.g: en.lproj/Main.storyboard
let lastKnownFileType = Xcode.filetype(extension: localizedName) // e.g. Main.storyboard
let name = absolutePath.components.last!.split(separator: ".").first! // e.g. en
let localizedFileReference = PBXFileReference(sourceTree: .group,
name: String(name),
lastKnownFileType: lastKnownFileType,
path: localizedFilePath)
pbxproj.add(object: localizedFileReference)
variantGroup.children.append(localizedFileReference)
}
}
func addVersionGroupElement(from: AbsolutePath,
folderAbsolutePath: AbsolutePath,
folderRelativePath: RelativePath,
name: String?,
toGroup: PBXGroup,
pbxproj: PBXProj) -> (element: PBXFileElement, path: AbsolutePath) {
let versionGroupType = Xcode.filetype(extension: folderRelativePath.extension!)
let group = XCVersionGroup(currentVersion: nil,
path: folderRelativePath.pathString,
name: name,
sourceTree: .group,
versionGroupType: versionGroupType)
pbxproj.add(object: group)
toGroup.children.append(group)
elements[folderAbsolutePath] = group
return (element: group, path: from.appending(folderRelativePath))
}
func addGroupElement(from: AbsolutePath,
folderAbsolutePath: AbsolutePath,
folderRelativePath: RelativePath,
name: String?,
toGroup: PBXGroup,
pbxproj: PBXProj) -> (element: PBXFileElement, path: AbsolutePath) {
let group = PBXGroup(children: [], sourceTree: .group, name: name, path: folderRelativePath.pathString)
pbxproj.add(object: group)
toGroup.children.append(group)
elements[folderAbsolutePath] = group
return (element: group, path: from.appending(folderRelativePath))
}
func addFileElement(from _: AbsolutePath,
fileAbsolutePath: AbsolutePath,
fileRelativePath: RelativePath,
name: String?,
toGroup: PBXGroup,
pbxproj: PBXProj) {
let lastKnownFileType = fileAbsolutePath.extension.flatMap { Xcode.filetype(extension: $0) }
let file = PBXFileReference(sourceTree: .group, name: name, lastKnownFileType: lastKnownFileType, path: fileRelativePath.pathString)
pbxproj.add(object: file)
toGroup.children.append(file)
elements[fileAbsolutePath] = file
}
func group(path: AbsolutePath) -> PBXGroup? {
return elements[path] as? PBXGroup
}
func product(name: String) -> PBXFileReference? {
return products[name]
}
func file(path: AbsolutePath) -> PBXFileReference? {
return elements[path] as? PBXFileReference
}
func isLocalized(path: AbsolutePath) -> Bool {
return path.extension == "lproj"
}
func isVersionGroup(path: AbsolutePath) -> Bool {
return path.extension == "xcdatamodeld"
}
func isXcassets(path: AbsolutePath) -> Bool {
return path.extension == "xcassets"
}
/// Normalizes a path. Some paths have no direct representation in Xcode,
/// like localizable files. This method normalizes those and returns a project
/// representable path.
///
/// - Example:
/// /test/es.lproj/Main.storyboard ~> /test/es.lproj
func normalize(_ path: AbsolutePath) -> AbsolutePath {
let pathString = path.pathString
let range = NSRange(location: 0, length: pathString.count)
if let localizedMatch = ProjectFileElements.localizedRegex.firstMatch(in: pathString,
options: [],
range: range) {
let lprojPath = (pathString as NSString).substring(with: localizedMatch.range(at: 1))
return AbsolutePath(lprojPath)
} else {
return path
}
}
/// Returns the relative path of the closest relative element to the source root path.
/// If source root path is /a/b/c/project/ and file path is /a/d/myfile.swift
/// this method will return ../../../d/
func closestRelativeElementPath(path: AbsolutePath, sourceRootPath: AbsolutePath) -> RelativePath {
let relativePathComponents = path.relative(to: sourceRootPath).components
let firstElementComponents = relativePathComponents.reduce(into: [String]()) { components, component in
let isLastRelative = components.last == ".." || components.last == "."
if components.last != nil, !isLastRelative { return }
components.append(component)
}
if firstElementComponents.isEmpty, !relativePathComponents.isEmpty {
return RelativePath(relativePathComponents.first!)
} else {
return RelativePath(firstElementComponents.joined(separator: "/"))
}
}
}
| 42.814346 | 140 | 0.544348 |
084d201a66b5aef96896ecc8c95e0dd646b8c132
| 1,819 |
//
// KeyValueStoreProtocol.swift
// CachingService
//
// Created by Alexander Cyon on 2018-02-22.
// Copyright © 2018 Alexander Cyon. All rights reserved.
//
import Foundation
public protocol KeyValueStoreProtocol: class {
func save<Value>(value: Value, for key: String) throws where Value: Codable
func loadValue<Value>(for key: String) -> Value? where Value: Codable
func deleteValue(for key: String)
func deleteAll()
var dictionaryRepresentation: [String: Any] { get }
}
//MARK: - Convenience Methods
public extension KeyValueStoreProtocol {
func string(for key: String) -> String? {
guard let value: String = loadValue(for: key) else { return nil }
return value
}
func int(for key: String) -> Int? {
guard let value: Int = loadValue(for: key) else { return nil }
return value
}
func bool(for key: String) -> Bool? {
guard let value: Bool = loadValue(for: key) else { return nil }
return value
}
func float(for key: String) -> Float? {
guard let value: Float = loadValue(for: key) else { return nil }
return value
}
func double(for key: String) -> Double? {
guard let value: Double = loadValue(for: key) else { return nil }
return value
}
}
public extension KeyValueStoreProtocol {
func hasString(for key: String) -> Bool {
return string(for: key) != nil
}
func hasInt(for key: String) -> Bool {
return int(for: key) != nil
}
func hasBool(for key: String) -> Bool {
return bool(for: key) != nil
}
func hasFloat(for key: String) -> Bool {
return float(for: key) != nil
}
func hasDouble(for key: String) -> Bool {
return double(for: key) != nil
}
}
| 26.75 | 79 | 0.606927 |
f886168d22960bce9fa5d4884be83d7d8eb05a3d
| 118 |
import Foundation
struct Account:Codable {
var notes = [String]()
var rates = [Date]()
var created = 0
}
| 14.75 | 26 | 0.618644 |
7a880d5c6abf2d4ed25eee8e2df24d210907865b
| 2,555 |
//
// DefinitionsModule.swift
// iosApp
//
// Created by Alexey Glushkov on 22.10.2020.
// Copyright © 2020 orgName. All rights reserved.
//
import Foundation
import Cleanse
import shared
class DefinitionsModule: Module {
typealias Scope = Singleton
static func configure(binder: Binder<Singleton>) {
binder.bind().sharedInScope().to(value: DefinitionsVM.State(word: nil) )
binder.bind().sharedInScope().to(factory: DefinitionsVM.init.self)
binder.bind().sharedInScope().to(factory: DefinitionsDisplayModeBlueprint.init.self)
binder.bind().sharedInScope().to(factory: WordDefinitionBlueprint.init.self)
binder.bind().sharedInScope().to(factory: WordDividerBlueprint.init.self)
binder.bind().sharedInScope().to(factory: WordExampleBlueprint.init.self)
binder.bind().sharedInScope().to(factory: WordPartOfSpeechBlueprint.init.self)
binder.bind().sharedInScope().to(factory: WordSubHeaderBlueprint.init.self)
binder.bind().sharedInScope().to(factory: WordSynonymBlueprint.init.self)
binder.bind().sharedInScope().to(factory: WordTitleBlueprint.init.self)
binder.bind().sharedInScope().to(factory: WordTranscriptionBlueprint.init.self)
binder.bind().sharedInScope().to(factory: { (
definitionsDisplayModeBlueprint: DefinitionsDisplayModeBlueprint,
wordDefinitionBlueprint: WordDefinitionBlueprint,
wordDividerBlueprint: WordDividerBlueprint,
wordExampleBlueprint: WordExampleBlueprint,
wordPartOfSpeechBlueprint: WordPartOfSpeechBlueprint,
wordSubHeaderBlueprint: WordSubHeaderBlueprint,
wordSynonymBlueprint: WordSynonymBlueprint,
wordTitleBlueprint: WordTitleBlueprint,
wordTranscriptionBlueprint: WordTranscriptionBlueprint
) in
return ItemViewBinder()
.addBlueprint(blueprint: definitionsDisplayModeBlueprint)
.addBlueprint(blueprint: wordDefinitionBlueprint)
.addBlueprint(blueprint: wordDividerBlueprint)
.addBlueprint(blueprint: wordExampleBlueprint)
.addBlueprint(blueprint: wordPartOfSpeechBlueprint)
.addBlueprint(blueprint: wordSubHeaderBlueprint)
.addBlueprint(blueprint: wordSynonymBlueprint)
.addBlueprint(blueprint: wordTitleBlueprint)
.addBlueprint(blueprint: wordTranscriptionBlueprint)
})
}
}
| 48.207547 | 92 | 0.689237 |
bfd4fb393a8a22291ddd61b508d82e27bbbf5f00
| 1,338 |
import Foundation
import Foundation
// simple textual dump to view how encoding is working, NOT intended to be decoded!
public class SimpleDebuggingTextEncoder : HierEncoder {
var buffer:String
var indentLevel:Int = 0
var indent = ""
public init() {
buffer = String()
}
private func updateIndent(by:Int)
{
indentLevel += by
indent = String(repeating:" ", count:2*indentLevel)
}
private func appendStr(_ str:String) {
buffer += "\n\(indent)\(str)"
}
public func encode(_ topObj:HierCodable) -> String {
// ench top of tree
ench(topObj)
return buffer
}
public func ench(_ value:String) {
appendStr("\"\(value)\":String")
}
public func ench<T>(_ value:T) {
appendStr("\(value):\(T.self)")
}
//TODO add other binary types
// pick up default protocols for ench HierCodable
// override [HierCodable] to describe that it's an array
public func ench(_ typedObjects:[HierCodable]) {
// nested collections start a new container
appendStr("[")
pushContext()
ench(typedObjects.count) // leading count in default format
typedObjects.forEach {
ench($0)
}
popContext()
appendStr("]")
}
public func pushContext() {
updateIndent(by:1)
}
public func popContext() {
updateIndent(by:-1)
}
}
| 20.90625 | 83 | 0.640508 |
1c0a4b11583934d5ade170e3edc34a55ff220cae
| 1,302 |
//
// NSLayoutConstraintExtensions.swift
// FarmaCalc
//
// Created by Breno Rezende on 25/06/21.
//
import UIKit
extension UIView {
func fill(top: NSLayoutYAxisAnchor? = nil, left: NSLayoutXAxisAnchor? = nil, bottom: NSLayoutYAxisAnchor? = nil, right: NSLayoutXAxisAnchor? = nil, andEdgeInsets edge: UIEdgeInsets? = nil) {
if let top = top {
self.topAnchor.constraint(equalTo: top, constant: edge?.top ?? 0).isActive = true
}
if let left = left {
self.leftAnchor.constraint(equalTo: left, constant: edge?.left ?? 0).isActive = true
}
if let bottom = bottom {
self.bottomAnchor.constraint(equalTo: bottom, constant: -(edge?.bottom ?? 0)).isActive = true
}
if let right = right {
self.rightAnchor.constraint(equalTo: right, constant: -(edge?.right ?? 0)).isActive = true
}
}
func centerHorizontallyInSuperview() {
guard let parent = superview else { return }
self.centerXAnchor.constraint(equalTo: parent.centerXAnchor).isActive = true
}
func centerVerticallyInSuperview() {
guard let parent = superview else { return }
self.centerYAnchor.constraint(equalTo: parent.centerYAnchor).isActive = true
}
}
| 33.384615 | 194 | 0.630568 |
6a60bdc0cd19bdc5994c3f4fed4e90c48fdb1d84
| 2,179 |
//
// AppDelegate.swift
// Flix_demo
//
// Created by Abraham De Alba on 9/5/18.
// Copyright © 2018 Abraham De Alba. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
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 invalidate graphics rendering callbacks. 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 active 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:.
}
}
| 46.361702 | 285 | 0.754933 |
4a2eced91d80ffda035577b3cc84b37d69bc93af
| 4,010 |
//
// MovieDetailViewController.swift
// Week1_Flicks
//
// Created by Edwin Wong on 10/14/16.
// Copyright © 2016 edwin. All rights reserved.
//
import UIKit
import NVActivityIndicatorView
class MovieDetailViewController: BaseMovieViewController, UIScrollViewDelegate {
@IBOutlet weak var backgroundImage: UIImageView!
var titleLabel: UILabel!
var dateLabel: UILabel!
var voteAvgLabel: UILabel!
var runTimeLabel: UILabel!
var genresLabel: UILabel!
var overviewLabel: UILabel!
@IBOutlet weak var networkErrorLabel: UILabel!
@IBOutlet weak var scrollView: UIScrollView!
// @IBOutlet weak var scrollViewWrapper: UIView!
var innerScrollView: UIView!
var movie: Movie?
override func viewWillAppear(_ animated: Bool) {
if MovieApiService.service.hasNetworkError{
super.toggleNetworkError(self.networkErrorLabel, turnOn: true)
}else{
super.toggleNetworkError(self.networkErrorLabel, turnOn: false)
}
}
override func viewDidLoad() {
super.viewDidLoad()
// set scroll view properties
self.scrollView.delegate = self
// Do any additional setup after loading the view.
// preload movie background
if self.movie != nil {
self.title = movie?.title
if let movieItemImagePath = self.movie?.posterFullPath{
Helper.loadImageHelper(imageView: self.backgroundImage, imageUrl: movieItemImagePath)
}else{
self.backgroundImage.image = UIImage(named: "default_image")
}
}
// load movie with more details
if self.movie?.id != nil{
// start animation for loading screen
super.showUILoadingBlocker()
MovieApiService.service.loadMovieDetails(movieId: (self.movie?.id)!){
(movieParam: Movie?, success: Bool) in
if success{
super.toggleNetworkError(self.networkErrorLabel, turnOn: false)
self.movie = movieParam
self.loadUIElements()
}else{
super.toggleNetworkError(self.networkErrorLabel, turnOn:true)
}
self.stopAnimating()
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func loadMovieProperties(_ movieParam: Movie, mTitleLabel: UILabel, mOverviewLabel: UILabel, mDateLabel: UILabel, mGenresLabel: UILabel, mVoteAvgLabel: UILabel, mRunTimeLabel: UILabel){
mTitleLabel.text = movieParam.title
mOverviewLabel.text = movieParam.overview
mOverviewLabel.sizeToFit()
mDateLabel.text = movieParam.releaseDateFormatted
mGenresLabel.text = movieParam.genresFormatted
mGenresLabel.sizeToFit()
mVoteAvgLabel.text = movieParam.voteAverageFormatted
mRunTimeLabel.text = movieParam.runtimeFormatted
}
private func loadUIElements(){
if let movieParam = self.movie{
// update scroll view
let ypos: CGFloat = CGFloat(400)
let movieDetailsView = MovieDetailsView(movie: movieParam, parentView: self.scrollView, yPos: ypos)
let contentWidth = scrollView.bounds.width
let contentHeightIncrement = movieDetailsView.bounds.height - (scrollView.bounds.height - CGFloat(ypos))
let contentHeight = (contentHeightIncrement > 0) ? scrollView.bounds.height + contentHeightIncrement + 20 : scrollView.bounds.height
//scrollView.bounds.height + (400-movieDetailsView.bounds.height)
self.scrollView.contentSize = CGSize(width: contentWidth, height: contentHeight)
self.scrollView.addSubview(movieDetailsView)
}
}
}
| 36.126126 | 197 | 0.634663 |
221e6a0305084d30c6fdcf4e59c2a4a52f0bf5cd
| 903 |
// Copyright (c) 2021 Payoneer Germany GmbH
// https://www.payoneer.com
//
// This file is open source and available under the MIT license.
// See the LICENSE file for more information.
#if canImport(UIKit)
import UIKit
/// Cell calls that delegate on some actions
protocol InputCellDelegate: class {
func inputCellBecameFirstResponder(cell: UICollectionViewCell)
func inputCellValueDidChange(to newValue: String?, cell: UICollectionViewCell)
func inputCellDidEndEditing(cell: UICollectionViewCell)
/// Action button was tapped (e.g. `Next` or `Done`)
func inputCellPrimaryActionTriggered(cell: UICollectionViewCell)
}
extension InputCellDelegate {
func inputCellBecameFirstResponder(cell: UICollectionViewCell) {}
}
/// Indicates that delegate could be set for that cell
protocol ContainsInputCellDelegate: class {
var delegate: InputCellDelegate? { get set }
}
#endif
| 31.137931 | 82 | 0.770764 |
d9f6f8b788a178fdeae9ba9a0521bdf6f1f98f0d
| 2,152 |
import Basic
import Foundation
import SPMUtility
import TuistCore
import XcodeProj
import XCTest
@testable import TuistCoreTesting
@testable import TuistKit
final class GraphCommandTests: TuistUnitTestCase {
var subject: GraphCommand!
var dotGraphGenerator: MockDotGraphGenerator!
var manifestLoader: MockGraphManifestLoader!
var parser: ArgumentParser!
override func setUp() {
super.setUp()
dotGraphGenerator = MockDotGraphGenerator()
manifestLoader = MockGraphManifestLoader()
parser = ArgumentParser.test()
subject = GraphCommand(parser: parser,
dotGraphGenerator: dotGraphGenerator,
manifestLoader: manifestLoader)
}
override func tearDown() {
dotGraphGenerator = nil
manifestLoader = nil
parser = nil
subject = nil
super.tearDown()
}
func test_command() {
XCTAssertEqual(GraphCommand.command, "graph")
}
func test_overview() {
XCTAssertEqual(GraphCommand.overview, "Generates a dot graph from the workspace or project in the current directory.")
}
func test_run() throws {
// Given
let temporaryPath = try self.temporaryPath()
let graphPath = temporaryPath.appending(component: "graph.dot")
let projectManifestPath = temporaryPath.appending(component: "Project.swift")
try FileHandler.shared.touch(graphPath)
try FileHandler.shared.touch(projectManifestPath)
manifestLoader.manifestsAtStub = {
if $0 == temporaryPath { return Set([.project]) }
else { return Set([]) }
}
let graph = "graph {}"
dotGraphGenerator.generateProjectStub = graph
// When
let result = try parser.parse([GraphCommand.command])
try subject.run(with: result)
// Then
XCTAssertEqual(try FileHandler.shared.readTextFile(graphPath), graph)
XCTAssertPrinterOutputContains("""
Deleting existing graph at \(graphPath.pathString)
Graph exported to \(graphPath.pathString)
""")
}
}
| 30.309859 | 126 | 0.652416 |
fc0697a4084e0725f617bb88af7e5034a03453cb
| 2,183 |
//
// PostcardTestViewController.swift
// PostcardControllerDemo
//
// Created by EamonLiang on 2019/9/9.
// Copyright © 2019 EamonLiang. All rights reserved.
//
import UIKit
class PostcardTestViewController: UIViewController {
deinit {
print("[%@ delloc]", NSStringFromClass(PostcardTestViewController.self))
}
override func viewDidLoad() {
super.viewDidLoad()
let r: CGFloat = CGFloat(arc4random() % 255);
let g: CGFloat = CGFloat(arc4random() % 255);
let b: CGFloat = CGFloat(arc4random() % 255);
view.backgroundColor = UIColor(red: r / 255.0, green: g / 255.0, blue: b / 255.0, alpha: 0.8)
let pushBtn = UIButton(type: .system)
pushBtn.setTitle("PUSH", for: .normal)
pushBtn.addTarget(self, action: #selector(onPushBtnPress), for: .touchUpInside)
view.addSubview(pushBtn)
pushBtn.snp.makeConstraints { (make) in
make.center.equalTo(view)
}
let popBtn = UIButton(type: .system)
popBtn.setTitle("POP", for: .normal)
popBtn.addTarget(self, action: #selector(onPopBtnPress), for: .touchUpInside)
view.addSubview(popBtn)
popBtn.snp.makeConstraints { (make) in
make.centerX.equalTo(pushBtn.snp.centerX)
make.top.equalTo(pushBtn.snp.bottom).offset(32)
}
}
@objc private func onPushBtnPress() {
let vc = PostcardTestViewController()
self.navigationController?.pushViewController(vc, animated: true)
}
@objc private func onPopBtnPress() {
if self.navigationController!.viewControllers.count <= 1 {
self.navigationController?.dismiss(animated: true, completion: nil)
}
else {
self.navigationController?.popViewController(animated: true)
}
}
}
extension PostcardTestViewController: PostcardNavigationControlling {
func didTappedOnTopBarAtPostcard(nav: PostcardNavigationController) {
}
func dismissInteractiveTransitionViewAtPostcard(nav: PostcardNavigationController) -> UIView? {
return self.view
}
}
| 31.185714 | 101 | 0.637655 |
ef8e32781dd35cc96e4ecdd210fc2723a52afce8
| 2,169 |
//
// AppDelegate.swift
// RimhTypingLetters
//
// Created by ming on 11/23/2017.
// Copyright (c) 2017 ming. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
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:.
}
}
| 46.148936 | 285 | 0.754265 |
03024de36d8c4fac06fbbe6406fdee6897c8e0da
| 309 |
//
// UseCaseProvider.swift
// Frames-App
//
// Created by Tyler Zhao on 11/19/18.
// Copyright © 2018 Tyler Zhao. All rights reserved.
//
import Foundation
public protocol UseCaseProvider {
func makeCommentUseCase() -> CommentUseCase
// func makeInitialLaunchUseCase() -> InitialLaunchUseCase
}
| 20.6 | 61 | 0.721683 |
d5462325b6bedd015b3dad2ea0f885cb9a86bb29
| 848 |
//
// SegueHandlerType.swift
// V2EX
//
// Created by wenxuan.zhang on 16/3/2.
// Copyright © 2016年 张文轩. All rights reserved.
//
import UIKit
protocol SegueHandlerType {
associatedtype SegueIdentifier: RawRepresentable
}
extension SegueHandlerType where Self: UIViewController, SegueIdentifier.RawValue == String {
func performSegueWithIdentifier(segueIdentifier: SegueIdentifier,
sender: AnyObject?) {
performSegueWithIdentifier(segueIdentifier.rawValue, sender: sender)
}
func segueIdentifierForSegue(segue: UIStoryboardSegue) -> SegueIdentifier {
guard let identifier = segue.identifier,
segueIdentifier = SegueIdentifier(rawValue: identifier) else {
fatalError("Invalid segue identifier \(segue.identifier).") }
return segueIdentifier
}
}
| 29.241379 | 93 | 0.705189 |
569ecef8e5e9ec681c55b4e9e7b135a216b6dfe3
| 1,316 |
//
// ModelError.swift
//
import Foundation
open class ModelError: JSONEncodable, Error {
public var errorType: String?
public var validationErrors: [ValidationError]?
public var status: String?
public init() {}
// MARK: JSONEncodable
open func encodeToJSON() -> Any {
var nillableDictionary = [String:Any?]()
nillableDictionary["error_type"] = self.errorType
nillableDictionary["validation_errors"] = self.validationErrors?.encodeToJSON()
nillableDictionary["status"] = self.status
let dictionary: [String:Any] = APIHelper.rejectNil(nillableDictionary) ?? [:]
return dictionary
}
open func toString() -> String {
var validationText = "[\n"
if let errorType = self.errorType {
validationText += "errorType: \(errorType) \n"
}
if let validationErrors = self.validationErrors {
validationErrors.forEach({ (validationError) in
validationText += "param: \(validationError.toString()) \n"
})
}
if let status = self.status {
validationText += "status: \(status) \n"
}
validationText += "]"
return validationText
}
}
| 26.32 | 87 | 0.573708 |
7ab926ac2a0fbd4f191d7b0e5f2fca60e77619fd
| 488 |
//
// BackgroundView.swift
// GlyphMaker
//
// Created by Patrik Hora on 18/03/2018.
// Copyright © 2018 Manicek. All rights reserved.
//
import UIKit
class BackgroundView: UIView {
init() {
super.init(frame: CGRect())
//image = UIImage()
//image = #imageLiteral(resourceName: "beardedDragon1")
backgroundColor = .white
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 20.333333 | 63 | 0.618852 |
29ea7d1b21f9dd8bc0d5397c960d30b5748d45fc
| 943 |
//
// Logger2Tests.swift
// Logger2Tests
//
// Created by 小林聖人 on 2020/06/14.
// Copyright © 2020 株式会社テクノモバイル. All rights reserved.
//
import XCTest
@testable import Logger2
class Logger2Tests: XCTestCase {
override func setUpWithError() throws {
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDownWithError() throws {
// Put teardown code here. This method is called after the invocation of each test method in the class.
}
func testExample() throws {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() throws {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 26.942857 | 111 | 0.66596 |
d5a0f1e3a3d73d5bce9a820da0700854c9e1dd22
| 957 |
//
// InukshukCompassPodTestTests.swift
// InukshukCompassPodTestTests
//
// Created by Mark on 10/23/19.
// Copyright © 2019 Inukshuk, LLC. All rights reserved.
//
import XCTest
@testable import InukshukCompassPodTest
class InukshukCompassPodTestTests: XCTestCase {
override func 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.
}
func testExample() {
// This is an example of a functional test case.
// Use XCTAssert and related functions to verify your tests produce the correct results.
}
func testPerformanceExample() {
// This is an example of a performance test case.
self.measure {
// Put the code you want to measure the time of here.
}
}
}
| 27.342857 | 111 | 0.672936 |
ef4124676da5e13fdd4e91f57fc8f464641ab70d
| 3,363 |
import Foundation
import CocoaLumberjackSwift
public class Router {
var IPv4NATRoutes: [Port: (IPv4Address, Port)] = [:]
let interfaceIP: IPv4Address
let fakeSourceIP: IPv4Address
let proxyServerIP: IPv4Address
let proxyServerPort: Port
// let IPv6NATRoutes: [UInt16] = []
public init(interfaceIP: String, fakeSourceIP: String, proxyServerIP: String, proxyServerPort: UInt16) {
self.interfaceIP = IPv4Address(fromString: interfaceIP)
self.fakeSourceIP = IPv4Address(fromString: fakeSourceIP)
self.proxyServerIP = IPv4Address(fromString: proxyServerIP)
self.proxyServerPort = Port(port: proxyServerPort)
}
public func rewritePacket(packet: IPMutablePacket) -> IPMutablePacket? {
// Support only TCP as for now
guard packet.proto == .TCP else {
return nil
}
guard let packet = packet as? TCPMutablePacket else {
return nil
}
if packet.sourceAddress == interfaceIP {
if packet.sourcePort == proxyServerPort {
guard let (address, port) = IPv4NATRoutes[packet.destinationPort] else {
DDLogError("Does not know how to handle packet: \(packet) because can't find entry in NAT table.")
return nil
}
packet.sourcePort = port
packet.sourceAddress = address
packet.destinationAddress = interfaceIP
return packet
} else {
IPv4NATRoutes[packet.sourcePort] = (packet.destinationAddress, packet.destinationPort)
packet.sourceAddress = fakeSourceIP
packet.destinationAddress = proxyServerIP
packet.destinationPort = proxyServerPort
return packet
}
} else {
DDLogError("Does not know how to handle packet.")
return nil
}
}
public func startProcessPacket() {
readAndProcessPackets()
}
func readAndProcessPackets() {
NetworkInterface.TunnelProvider.packetFlow.readPacketsWithCompletionHandler() {
var outputPackets = [IPMutablePacket]()
let packets = $0.0.map { data in
IPMutablePacket(payload: data)
}.filter { packet in
packet.version == .IPv4 && packet.proto == .TCP
}.map {
TCPMutablePacket(payload: $0.payload)
}
for packet in packets {
DDLogVerbose("Received packet of type: \(packet.proto) from \(packet.sourceAddress) to \(packet.destinationAddress)")
if let packet = self.rewritePacket(packet) {
outputPackets.append(packet)
} else {
DDLogVerbose("Failed to rewrite packet \(packet)")
}
}
let outputData = outputPackets.map { packet in
packet.payload
}
if outputData.count > 0 {
DDLogVerbose("Write out \(outputData.count) packets.")
NetworkInterface.TunnelProvider.packetFlow.writePackets(outputData, withProtocols: Array<NSNumber>(count: outputData.count, repeatedValue: Int(AF_INET)))
}
self.readAndProcessPackets()
}
}
}
| 38.655172 | 169 | 0.588165 |
2ffe983d71e182983aabde1fa9fe9417e69a4d64
| 4,941 |
//
// ProductView.swift
// Milkshakr
//
// Created by Guilherme Rambo on 10/06/18.
// Copyright © 2018 Guilherme Rambo. All rights reserved.
//
import UIKit
public class ProductView: UIView {
public var didReceiveTap: (() -> Void)?
public var viewModel: ProductViewModel? {
didSet {
updateUI()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
buildUI()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
buildUI()
}
private lazy var imageView: UIImageView = {
let v = UIImageView()
v.heightAnchor.constraint(equalToConstant: Metrics.productImageHeight).isActive = true
v.translatesAutoresizingMaskIntoConstraints = false
v.setContentCompressionResistancePriority(.required, for: .vertical)
return v
}()
private lazy var titleLabel: UILabel = {
let l = UILabel()
l.font = UIFont.systemFont(ofSize: Metrics.titleFontSize, weight: Metrics.titleFontWeight)
l.textColor = .primaryText
l.numberOfLines = 1
l.lineBreakMode = .byTruncatingTail
l.translatesAutoresizingMaskIntoConstraints = false
return l
}()
private lazy var priceLabel: UILabel = {
let l = UILabel()
l.font = UIFont.systemFont(ofSize: Metrics.priceFontSize, weight: Metrics.priceFontWeight)
l.textAlignment = .right
l.textColor = .primaryText
l.numberOfLines = 1
l.lineBreakMode = .byTruncatingTail
l.translatesAutoresizingMaskIntoConstraints = false
return l
}()
private lazy var subtitleLabel: UILabel = {
let l = UILabel()
l.numberOfLines = 0
l.lineBreakMode = .byWordWrapping
l.translatesAutoresizingMaskIntoConstraints = false
l.setContentCompressionResistancePriority(.required, for: .vertical)
return l
}()
private func buildUI() {
addSubview(imageView)
addSubview(titleLabel)
addSubview(priceLabel)
addSubview(subtitleLabel)
imageView.topAnchor.constraint(equalTo: topAnchor).isActive = true
imageView.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
imageView.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
titleLabel.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
titleLabel.topAnchor.constraint(equalTo: imageView.bottomAnchor, constant: Metrics.smallPadding).isActive = true
priceLabel.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
priceLabel.centerYAnchor.constraint(equalTo: titleLabel.centerYAnchor).isActive = true
titleLabel.trailingAnchor.constraint(equalTo: priceLabel.leadingAnchor, constant: Metrics.padding).isActive = true
subtitleLabel.leadingAnchor.constraint(equalTo: titleLabel.leadingAnchor).isActive = true
subtitleLabel.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
subtitleLabel.topAnchor.constraint(equalTo: titleLabel.bottomAnchor, constant: Metrics.smallPadding).isActive = true
subtitleLabel.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
let tap = UITapGestureRecognizer(target: self, action: #selector(tapped))
addGestureRecognizer(tap)
}
@objc private func tapped(_ sender: UITapGestureRecognizer) {
didReceiveTap?()
}
private func updateUI() {
guard let viewModel = viewModel else { return }
imageView.image = viewModel.image
titleLabel.text = viewModel.title
priceLabel.text = viewModel.formattedPrice
subtitleLabel.attributedText = viewModel.attributedDescription
}
// MARK: - Selection animation
public override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesBegan(touches, with: event)
compress()
}
public override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesEnded(touches, with: event)
expand()
}
public override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
super.touchesCancelled(touches, with: event)
expand()
}
private func compress() {
UIView.animate(withDuration: 0.24, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 2, options: [.allowUserInteraction, .beginFromCurrentState], animations: {
self.layer.transform = CATransform3DMakeScale(0.96, 0.96, 1)
}, completion: nil)
}
private func expand() {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 2, options: [.allowUserInteraction, .beginFromCurrentState], animations: {
self.layer.transform = CATransform3DIdentity
}, completion: nil)
}
}
| 32.506579 | 177 | 0.682453 |
f9fd12d063a4f2a8f60a6b6253f0199a48141ae6
| 3,149 |
//
// CryptoKeyTests.swift
// ledger-wallet-ios
//
// Created by Nicolas Bigot on 05/02/2015.
// Copyright (c) 2015 Ledger. All rights reserved.
//
import Foundation
import XCTest
class CryptoKeyTests: XCTestCase {
let privateKey = Crypto.Encode.dataFromBase16String("b208b83b23edfff327bb6e0098eeaa0a5c87a599d5d8b24ff2734d2aac8bbdde")!
let publicKey = Crypto.Encode.dataFromBase16String("04ae218d8080c7b9cd141b06f6b9f63ef3adf7aecdf49bb3916ac7f5d887fc4027bea6fd187b9fa810b6d251e1430f6555edd2d5b19828d51908917c03e3f7c436")!
let otherPrivateKey = Crypto.Encode.dataFromBase16String("2107cb67d49337fb9cf5e1585a308a72ba5aa17c6255010a01354f526b4e81cd")!
let otherPublicKey = Crypto.Encode.dataFromBase16String("040d1f94315fd489bbc233b75c69496d8f4aebcedfabb1937c312389750c9f096cd7a8bf42345800beeeb719bfb1c4b96ad57cd20aa22d33dfa59d3b4578aa9da2")!
func testIsSymmetric() {
let key = Crypto.Key(symmetricKey: NSData(bytes: "hello", length: 5))
XCTAssertTrue(key.isSymmetric, "key should be symmetric")
XCTAssertFalse(key.isAsymmetric, "key should not be asymmetric")
}
func testIsAsymmetric() {
let key = Crypto.Key()
XCTAssertFalse(key.isSymmetric, "key should not be symmetric")
XCTAssertTrue(key.isAsymmetric, "key should be asymmetric")
}
func testSymmetricKeyDataEqual() {
let key = Crypto.Key(symmetricKey: publicKey)
XCTAssertEqual(publicKey, key.symmetricKey, "symmetric key data should be equal")
XCTAssertEqual(publicKey.length, key.symmetricKey.length, "symmetric key size should be the same")
}
func testPrivateKeyDataEqual() {
let key = Crypto.Key(privateKey: privateKey)
XCTAssertEqual(privateKey, key.privateKey, "private key data should be equal")
XCTAssertEqual(publicKey, key.publicKey, "public key data should be equal")
XCTAssertEqual(key.privateKey.length, 32, "private key size should be 32")
}
func testPublicKeyDataEqual() {
let key = Crypto.Key(publicKey: publicKey)
XCTAssertEqual(publicKey, key.publicKey, "public key data should be equal")
XCTAssertEqual(NSData(), key.privateKey, "private key data should be empty")
XCTAssertEqual(key.publicKey.length, 65, "private key size should be 65")
}
func testNewKeyPair() {
let key = Crypto.Key()
XCTAssertNotEqual(NSData(), key.publicKey, "private key data should not be empty")
XCTAssertNotEqual(NSData(), key.privateKey, "private key data should not be empty")
XCTAssertEqual(key.publicKey.length, 65, "private key size should be 65")
XCTAssertEqual(key.privateKey.length, 32, "private key size should be 32")
}
func testGivenPrivateKey1() {
let key = Crypto.Key(privateKey: privateKey)
XCTAssertEqual(publicKey, key.publicKey, "public key data should empty equal")
}
func testGivenPrivateKey2() {
let key = Crypto.Key(privateKey: otherPrivateKey)
XCTAssertEqual(otherPublicKey, key.publicKey, "public key data should empty equal")
}
}
| 44.352113 | 194 | 0.721816 |
75b6478c4717d2019670f4a86ac9e69374636dea
| 14,220 |
/**
* Copyright IBM Corporation 2018
*
* 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.
**/
#if os(Linux)
#else
import Foundation
import AVFoundation
import RestKit
private var microphoneSession: SpeechToTextSession?
extension SpeechToText {
/**
Perform speech recognition for an audio file.
- parameter audio: The audio file to transcribe.
- parameter settings: The configuration to use for this recognition request.
- parameter model: The language and sample rate of the audio. For supported models, visit
https://cloud.ibm.com/docs/services/speech-to-text/input.html#models.
- parameter baseModelVersion: The version of the specified base model that is to be used for all requests sent
over the connection. Multiple versions of a base model can exist when a model is updated for internal improvements.
The parameter is intended primarily for use with custom models that have been upgraded for a new base model.
The default value depends on whether the parameter is used with or without a custom model. See
[Base model version](https://cloud.ibm.com/docs/services/speech-to-text/input.html#version).
- parameter languageCustomizationID: The customization ID (GUID) of a custom language model that is to be used
with the recognition request. The base model of the specified custom language model must match the model
specified with the `model` parameter. You must make the request with service credentials created for the instance
of the service that owns the custom model. By default, no custom language model is used. See [Custom
models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom).
- parameter learningOptOut: If `true`, then this request will not be logged for training.
- parameter customerID: Associates a customer ID with all data that is passed over the connection.
By default, no customer ID is associated with the data.
- parameter failure: A function executed whenever an error occurs.
- parameter success: A function executed with all transcription results whenever
a final or interim transcription is received.
*/
public func recognize(
audio: URL,
settings: RecognitionSettings,
model: String? = nil,
baseModelVersion: String? = nil,
languageCustomizationID: String? = nil,
learningOptOut: Bool? = nil,
customerID: String? = nil,
completionHandler: @escaping (WatsonResponse<SpeechRecognitionResults>?, WatsonError?) -> Void)
{
do {
let data = try Data(contentsOf: audio)
recognizeUsingWebSocket(
audio: data,
settings: settings,
model: model,
baseModelVersion: baseModelVersion,
languageCustomizationID: languageCustomizationID,
learningOptOut: learningOptOut,
customerID: customerID,
completionHandler: completionHandler
)
} catch {
let error = WatsonError.serialization(values: "audio data from \(audio)")
completionHandler(nil, error)
return
}
}
/**
Perform speech recognition for audio data using WebSockets.
- parameter audio: The audio data to transcribe.
- parameter settings: The configuration to use for this recognition request.
- parameter model: The language and sample rate of the audio. For supported models, visit
https://cloud.ibm.com/docs/services/speech-to-text/input.html#models.
- parameter baseModelVersion: The version of the specified base model that is to be used for all requests sent
over the connection. Multiple versions of a base model can exist when a model is updated for internal improvements.
The parameter is intended primarily for use with custom models that have been upgraded for a new base model.
The default value depends on whether the parameter is used with or without a custom model. See
[Base model version](https://cloud.ibm.com/docs/services/speech-to-text/input.html#version).
- parameter languageCustomizationID: The customization ID (GUID) of a custom language model that is to be used
with the recognition request. The base model of the specified custom language model must match the model
specified with the `model` parameter. You must make the request with service credentials created for the instance
of the service that owns the custom model. By default, no custom language model is used. See [Custom
models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom).
- parameter acousticCustomizationID: The customization ID (GUID) of a custom acoustic model
that is to be used with the recognition request. The base model of the specified custom
acoustic model must match the model specified with the `model` parameter. By default, no
custom acoustic model is used.
- parameter learningOptOut: If `true`, then this request will not be logged for training.
- parameter customerID: Associates a customer ID with all data that is passed over the connection.
By default, no customer ID is associated with the data.
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter failure: A function executed whenever an error occurs.
- parameter success: A function executed with all transcription results whenever
a final or interim transcription is received.
*/
public func recognizeUsingWebSocket(
audio: Data,
settings: RecognitionSettings,
model: String? = nil,
baseModelVersion: String? = nil,
languageCustomizationID: String? = nil,
acousticCustomizationID: String? = nil,
learningOptOut: Bool? = nil,
customerID: String? = nil,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<SpeechRecognitionResults>?, WatsonError?) -> Void)
{
// create SpeechToTextSession
let session = SpeechToTextSession(
authMethod: authMethod,
model: model,
baseModelVersion: baseModelVersion,
languageCustomizationID: languageCustomizationID,
acousticCustomizationID: acousticCustomizationID,
learningOptOut: learningOptOut,
customerID: customerID
)
// set urls
session.serviceURL = serviceURL
session.tokenURL = tokenURL
session.websocketsURL = websocketsURL
// set headers
session.defaultHeaders = defaultHeaders
if let headers = headers {
session.defaultHeaders.merge(headers) { (_, new) in new }
}
// set callbacks
session.onResults = { result in
var response = WatsonResponse<SpeechRecognitionResults>(statusCode: 0)
response.result = result
completionHandler(response, nil)
}
session.onError = { error in
completionHandler(nil, error)
}
// execute recognition request
session.connect()
session.startRequest(settings: settings)
session.recognize(audio: audio)
session.stopRequest()
session.disconnect()
}
/**
Perform speech recognition for microphone audio. To stop the microphone, invoke
`stopRecognizeMicrophone()`.
Microphone audio is compressed to Opus format unless otherwise specified by the `compress`
parameter. With compression enabled, the `settings` should specify a `contentType` of
"audio/ogg;codecs=opus". With compression disabled, the `settings` should specify a
`contentType` of "audio/l16;rate=16000;channels=1".
This function may cause the system to automatically prompt the user for permission
to access the microphone. Use `AVAudioSession.requestRecordPermission(_:)` if you
would prefer to ask for the user's permission in advance.
- parameter settings: The configuration for this transcription request.
- parameter model: The language and sample rate of the audio. For supported models, visit
https://cloud.ibm.com/docs/services/speech-to-text/input.html#models.
- parameter baseModelVersion: The version of the specified base model that is to be used for all requests sent
over the connection. Multiple versions of a base model can exist when a model is updated for internal improvements.
The parameter is intended primarily for use with custom models that have been upgraded for a new base model.
The default value depends on whether the parameter is used with or without a custom model. See
[Base model version](https://cloud.ibm.com/docs/services/speech-to-text/input.html#version).
- parameter languageCustomizationID: The customization ID (GUID) of a custom language model that is to be used
with the recognition request. The base model of the specified custom language model must match the model
specified with the `model` parameter. You must make the request with service credentials created for the instance
of the service that owns the custom model. By default, no custom language model is used. See [Custom
models](https://cloud.ibm.com/docs/services/speech-to-text/input.html#custom).
- parameter acousticCustomizationID: The customization ID (GUID) of a custom acoustic model
that is to be used with the recognition request. The base model of the specified custom
acoustic model must match the model specified with the `model` parameter. By default, no
custom acoustic model is used.
- parameter learningOptOut: If `true`, then this request will not be logged for training.
- parameter customerID: Associates a customer ID with all data that is passed over the connection.
By default, no customer ID is associated with the data.
- parameter compress: Should microphone audio be compressed to Opus format?
(Opus compression reduces latency and bandwidth.)
- parameter headers: A dictionary of request headers to be sent with this request.
- parameter failure: A function executed whenever an error occurs.
- parameter success: A function executed with all transcription results whenever
a final or interim transcription is received.
*/
public func recognizeMicrophone(
settings: RecognitionSettings,
model: String? = nil,
baseModelVersion: String? = nil,
languageCustomizationID: String? = nil,
acousticCustomizationID: String? = nil,
learningOptOut: Bool? = nil,
customerID: String? = nil,
compress: Bool = true,
headers: [String: String]? = nil,
completionHandler: @escaping (WatsonResponse<SpeechRecognitionResults>?, WatsonError?) -> Void)
{
// make sure the AVAudioSession shared instance is properly configured
do {
let audioSession = AVAudioSession.sharedInstance()
#if swift(>=4.2)
try audioSession.setCategory(AVAudioSession.Category.playAndRecord, mode: .default, options: [.defaultToSpeaker, .mixWithOthers])
#else
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: [.defaultToSpeaker, .mixWithOthers])
#endif
try audioSession.setActive(true)
} catch {
let failureReason = "Failed to setup the AVAudioSession sharedInstance properly."
let error = WatsonError.other(message: failureReason)
completionHandler(nil, error)
return
}
// validate settings
var settings = settings
settings.contentType = compress ? "audio/ogg;codecs=opus" : "audio/l16;rate=16000;channels=1"
// create SpeechToTextSession
let session = SpeechToTextSession(
authMethod: authMethod,
model: model,
baseModelVersion: baseModelVersion,
languageCustomizationID: languageCustomizationID,
acousticCustomizationID: acousticCustomizationID,
learningOptOut: learningOptOut,
customerID: customerID
)
// set urls
session.serviceURL = serviceURL
session.tokenURL = tokenURL
session.websocketsURL = websocketsURL
// set headers
session.defaultHeaders = defaultHeaders
if let headers = headers {
session.defaultHeaders.merge(headers) { (_, new) in new }
}
// set callbacks
session.onResults = { result in
var response = WatsonResponse<SpeechRecognitionResults>(statusCode: 200)
response.result = result
completionHandler(response, nil)
}
session.onError = { error in
completionHandler(nil, error)
}
// start recognition request
session.connect()
session.startRequest(settings: settings)
session.startMicrophone(compress: compress)
// store session
microphoneSession = session
}
/**
Stop performing speech recognition for microphone audio.
When invoked, this function will
1. Stop recording audio from the microphone.
2. Send a stop message to stop the current recognition request.
3. Wait to receive all recognition results then disconnect from the service.
*/
public func stopRecognizeMicrophone() {
microphoneSession?.stopMicrophone()
microphoneSession?.stopRequest()
microphoneSession?.disconnect()
}
}
#endif
| 48.865979 | 141 | 0.692053 |
1e82c19916a4c9b821e593532cb2f2b47bdc9e89
| 4,522 |
//
// DemandBuffer.swift
// RxCombine
//
// Created by Shai Mishali on 21/02/2020.
// Copyright © 2020 Combine Community. All rights reserved.
//
import Combine
import Darwin
import Foundation
/// A buffer responsible for managing the demand of a downstream
/// subscriber for an upstream publisher
///
/// It buffers values and completion events and forwards them dynamically
/// according to the demand requested by the downstream
///
/// In a sense, the subscription only relays the requests for demand, as well
/// the events emitted by the upstream — to this buffer, which manages
/// the entire behavior and backpressure contract
@available(iOS 13.0, *)
class DemandBuffer<S: Combine.Subscriber> {
private let lock = NSRecursiveLock()
private var buffer = [S.Input]()
private let subscriber: S
private var completion: Subscribers.Completion<S.Failure>?
private var demandState = Demand()
/// Initialize a new demand buffer for a provided downstream subscriber
///
/// - parameter subscriber: The downstream subscriber demanding events
init(subscriber: S) {
self.subscriber = subscriber
}
/// Buffer an upstream value to later be forwarded to
/// the downstream subscriber, once it demands it
///
/// - parameter value: Upstream value to buffer
///
/// - returns: The demand fulfilled by the bufferr
func buffer(value: S.Input) -> Subscribers.Demand {
precondition(self.completion == nil,
"How could a completed publisher sent values?! Beats me 🤷♂️")
switch demandState.requested {
case .unlimited:
return subscriber.receive(value)
default:
buffer.append(value)
return flush()
}
}
/// Complete the demand buffer with an upstream completion event
///
/// This method will deplete the buffer immediately,
/// based on the currently accumulated demand, and relay the
/// completion event down as soon as demand is fulfilled
///
/// - parameter completion: Completion event
func complete(completion: Subscribers.Completion<S.Failure>) {
precondition(self.completion == nil,
"Completion have already occured, which is quite awkward 🥺")
self.completion = completion
_ = flush()
}
/// Signal to the buffer that the downstream requested new demand
///
/// - note: The buffer will attempt to flush as many events rqeuested
/// by the downstream at this point
func demand(_ demand: Subscribers.Demand) -> Subscribers.Demand {
flush(adding: demand)
}
/// Flush buffered events to the downstream based on the current
/// state of the downstream's demand
///
/// - parameter newDemand: The new demand to add. If `nil`, the flush isn't the
/// result of an explicit demand change
///
/// - note: After fulfilling the downstream's request, if completion
/// has already occured, the buffer will be cleared and the
/// completion event will be sent to the downstream subscriber
private func flush(adding newDemand: Subscribers.Demand? = nil) -> Subscribers.Demand {
lock.lock()
defer { lock.unlock() }
if let newDemand = newDemand {
demandState.requested += newDemand
}
// If buffer isn't ready for flushing, return immediately
guard demandState.requested > 0 || newDemand == Subscribers.Demand.none else { return .none }
while !buffer.isEmpty && demandState.processed < demandState.requested {
demandState.requested += subscriber.receive(buffer.remove(at: 0))
demandState.processed += 1
}
if let completion = completion {
// Completion event was already sent
buffer = []
demandState = .init()
self.completion = nil
subscriber.receive(completion: completion)
return .none
}
let sentDemand = demandState.requested - demandState.sent
demandState.sent += sentDemand
return sentDemand
}
}
// MARK: - Private Helpers
@available(iOS 13.0, *)
private extension DemandBuffer {
/// A model that tracks the downstream's
/// accumulated demand state
struct Demand {
var processed: Subscribers.Demand = .none
var requested: Subscribers.Demand = .none
var sent: Subscribers.Demand = .none
}
}
| 34.784615 | 101 | 0.645069 |
22927a19bf8f88702581ebc4bca7f854dc70e4a6
| 819 |
import Foundation
extension ExpressibleByIntegerLiteral {
var data:Data {
var value:Self = self
let s:Int = MemoryLayout<`Self`>.size
return withUnsafeMutablePointer(to: &value) {
$0.withMemoryRebound(to: UInt8.self, capacity: s) {
Data(UnsafeBufferPointer(start: $0, count: s))
}
}
}
init(data:Data) {
let diff:Int = MemoryLayout<Self>.size - data.count
if (0 < diff) {
var buffer:Data = Data(repeating: 0, count: diff)
buffer.append(data)
self = buffer.withUnsafeBytes { $0.pointee }
return
}
self = data.withUnsafeBytes { $0.pointee }
}
init(data:MutableRangeReplaceableRandomAccessSlice<Data>) {
self.init(data: Data(data))
}
}
| 28.241379 | 63 | 0.571429 |
09cb738c3ab0f29cfedb84d328648df2e23d39d6
| 908 |
//
// String+NoonianKit.swift
// Noonian
//
// Created by Scott Hoyt on 11/4/16.
// Copyright © 2016 Scott Hoyt. All rights reserved.
//
import Foundation
public extension String {
func pathByAdding(component: String) -> String {
var path = self
var component = component
if !path.isEmpty && path.characters.last == "/" { path.remove(at: path.index(before: path.endIndex)) }
if !component.isEmpty && component.characters.first == "/" { component.remove(at: component.startIndex) }
return path + "/" + component
}
var isAbsolutePath: Bool {
return characters.first == "/"
}
public func absolutePathRepresentation(rootDirectory: String = FileManager.default.currentDirectoryPath) -> String {
if isAbsolutePath {
return self as String
}
return rootDirectory.pathByAdding(component: self)
}
}
| 26.705882 | 120 | 0.643172 |
69f950b8149abb869244ad9da0dc85e5e881f9ad
| 2,349 |
//
// WeatherForecastWeatherForecastViewController.swift
// weather
//
// Created by trykov on 26/08/2017.
// Copyright © 2017 trykov. All rights reserved.
//
import UIKit
import ViperMcFlurry
import RxDataSources
import RxCocoa
import RxSwift
class WeatherForecastViewController: UIViewController, WeatherForecastViewInput {
var output: WeatherForecastViewOutput!
@IBOutlet var tableView: UITableView!
let disposeBag = DisposeBag()
let dataSource = RxTableViewSectionedReloadDataSource<ForecastSection>(
configureCell: { _, tableView, _, item in
let reuseIdentifier = String(describing: WeatherForecastCell.self)
var cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier)
if cell == nil {
let nib = UINib(nibName: reuseIdentifier, bundle: nil)
tableView.register(nib, forCellReuseIdentifier: reuseIdentifier)
cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier)
}
if let currentCell = cell as? WeatherForecastCell {
currentCell.configure(with: item)
}
return cell!
})
// MARK: Life cycle
override func viewDidLoad() {
super.viewDidLoad()
output.viewIsReady()
}
// MARK: WeatherForecastViewInput
func setupInitialState(_ city: CityPlainObject) {
title = city.name
configureTableView()
}
func configureWithItems(_ items: [ForecastPlainObject]) {
tableView.dataSource = nil
tableView.delegate = nil
tableView?.refreshControl?.endRefreshing()
Observable.just([ForecastSection(items: items.map { forecast in
WeatherForecastCellObject(name: forecast.day, weather: forecast.name)
})])
.bind(to: tableView.rx.items(dataSource: dataSource))
.disposed(by: disposeBag)
}
private func configureTableView() {
let refreshControl = UIRefreshControl()
refreshControl.addTarget(self, action: #selector(refresh(_:)), for: .valueChanged)
tableView.refreshControl = refreshControl
}
@objc func refresh(_ refreshControl: UIRefreshControl) {
output.didTriggerPullToRefresh()
}
}
| 33.084507 | 90 | 0.647935 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.