repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
kingloveyy/SwiftBlog | refs/heads/master | SwiftBlog/SwiftBlog/Classes/BusinessModel/AccessToken.swift | mit | 1 | //
// AccessToken.swift
// SwiftBlog
//
// Created by King on 15/3/19.
// Copyright (c) 2015年 king. All rights reserved.
//
import UIKit
class AccessToken: NSObject,NSCoding {
/// 用于调用access_token,接口获取授权后的access token。
var access_token: String?
/// access_token的生命周期,单位是秒数。
var expires_in: NSNumber? {
didSet {
expiresDate = NSDate(timeIntervalSinceNow: expires_in!.doubleValue)
// println("过期日期 \(expiresDate)")
}
}
/// token过期日期
var expiresDate: NSDate?
/// 是否过期
var isExpired: Bool {
return expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedAscending
}
/// access_token的生命周期(该参数即将废弃,开发者请使用expires_in)。
var remind_in: NSNumber?
/// 当前授权用户的UID
var uid : Int = 0
init(dict: NSDictionary) {
super.init()
self.setValuesForKeysWithDictionary(dict as [NSObject : AnyObject])
}
/// 将数据保存到沙盒
func saveAccessToken() {
NSKeyedArchiver.archiveRootObject(self, toFile: AccessToken.tokenPath())
}
/// 从沙盒读取 token 数据
func loadAccessToken() -> AccessToken? {
return NSKeyedUnarchiver.unarchiveObjectWithFile(AccessToken.tokenPath()) as? AccessToken
}
/// 返回保存在沙盒的路径
class func tokenPath() -> String {
var path = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).last as! String
path = path.stringByAppendingPathComponent("token.plist")
println(path)
return path
}
// MARK: - 归档&接档
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeObject(access_token)
aCoder.encodeObject(access_token)
aCoder.encodeObject(expiresDate)
aCoder.encodeInteger(uid, forKey: "uid")
}
required init(coder aDecoder: NSCoder) {
access_token = aDecoder.decodeObject() as? String
expiresDate = aDecoder.decodeObject() as? NSDate
uid = aDecoder.decodeIntegerForKey("uid")
}
}
| fa53083da17a4b1d5e2ac18441e2f5a7 | 27.708333 | 157 | 0.641509 | false | false | false | false |
Ivacker/swift | refs/heads/master | test/SILGen/external_definitions.swift | apache-2.0 | 9 | // RUN: %target-swift-frontend -sdk %S/Inputs %s -emit-silgen | FileCheck %s
// REQUIRES: objc_interop
import ansible
var a = NSAnse(Ansible(bellsOn: NSObject()))
var anse = NSAnse
hasNoPrototype()
// CHECK-LABEL: sil @main
// -- Foreign function is referenced with C calling conv and ownership semantics
// CHECK: [[NSANSE:%.*]] = function_ref @NSAnse : $@convention(c) (ImplicitlyUnwrappedOptional<Ansible>) -> @autoreleased ImplicitlyUnwrappedOptional<Ansible>
// CHECK: [[ANSIBLE_CTOR:%.*]] = function_ref @_TFCSo7AnsibleC
// CHECK: [[NSOBJECT_CTOR:%.*]] = function_ref @_TFCSo8NSObjectC{{.*}} : $@convention(thin) (@thick NSObject.Type) -> @owned NSObject
// CHECK: [[ANSIBLE:%.*]] = apply [[ANSIBLE_CTOR]]
// CHECK: [[NSANSE_RESULT:%.*]] = apply [[NSANSE]]([[ANSIBLE]])
// CHECK: retain_autoreleased [[NSANSE_RESULT]]
// CHECK: release_value [[ANSIBLE]] : $ImplicitlyUnwrappedOptional<Ansible>
// -- Referencing unapplied C function goes through a thunk
// CHECK: [[NSANSE:%.*]] = function_ref @_TTOFSC6NSAnseFGSQCSo7Ansible_GSQS__ : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<Ansible>) -> @owned ImplicitlyUnwrappedOptional<Ansible>
// -- Referencing unprototyped C function passes no parameters
// CHECK: [[NOPROTO:%.*]] = function_ref @hasNoPrototype : $@convention(c) () -> ()
// CHECK: apply [[NOPROTO]]()
// -- Constructors for imported Ansible
// CHECK-LABEL: sil shared @_TFCSo7AnsibleC{{.*}} : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<AnyObject>, @thick Ansible.Type) -> @owned ImplicitlyUnwrappedOptional<Ansible>
// -- Constructors for imported NSObject
// CHECK-LABEL: sil shared @_TFCSo8NSObjectC{{.*}} : $@convention(thin) (@thick NSObject.Type) -> @owned NSObject
// -- Native Swift thunk for NSAnse
// CHECK: sil shared @_TTOFSC6NSAnseFGSQCSo7Ansible_GSQS__ : $@convention(thin) (@owned ImplicitlyUnwrappedOptional<Ansible>) -> @owned ImplicitlyUnwrappedOptional<Ansible> {
// CHECK: bb0(%0 : $ImplicitlyUnwrappedOptional<Ansible>):
// CHECK: %1 = function_ref @NSAnse : $@convention(c) (ImplicitlyUnwrappedOptional<Ansible>) -> @autoreleased ImplicitlyUnwrappedOptional<Ansible>
// CHECK: %2 = apply %1(%0) : $@convention(c) (ImplicitlyUnwrappedOptional<Ansible>) -> @autoreleased ImplicitlyUnwrappedOptional<Ansible>
// CHECK: strong_retain_autoreleased %2 : $ImplicitlyUnwrappedOptional<Ansible>
// CHECK: release_value %0 : $ImplicitlyUnwrappedOptional<Ansible>
// CHECK: return %2 : $ImplicitlyUnwrappedOptional<Ansible>
// CHECK: }
// -- Constructor for imported Ansible was unused, should not be emitted.
// CHECK-NOT: sil shared @_TFCSo7AnsibleC{{.*}} : $@convention(thin) (@thick Ansible.Type) -> @owned Ansible
| ade821ce18ee1b5141e23cdc6aaf3482 | 56.744681 | 193 | 0.713707 | false | false | false | false |
OneBusAway/onebusaway-iphone | refs/heads/develop | Carthage/Checkouts/SwiftEntryKit/Source/MessageViews/Notes/EKNoteMessageView.swift | apache-2.0 | 3 | //
// EKNoteMessageView.swift
// SwiftEntryKit
//
// Created by Daniel Huri on 4/19/18.
// Copyright (c) 2018 [email protected]. All rights reserved.
//
import UIKit
import QuickLayout
public class EKNoteMessageView: UIView {
// MARK: Props
private let label = UILabel()
private var horizontalConstrainsts: QLAxisConstraints!
private var verticalConstrainsts: QLAxisConstraints!
public var horizontalOffset: CGFloat = 10 {
didSet {
horizontalConstrainsts.first.constant = horizontalOffset
horizontalConstrainsts.second.constant = -horizontalOffset
layoutIfNeeded()
}
}
public var verticalOffset: CGFloat = 5 {
didSet {
verticalConstrainsts.first.constant = verticalOffset
verticalConstrainsts.second.constant = -verticalOffset
layoutIfNeeded()
}
}
// MARK: Setup
public init(with content: EKProperty.LabelContent) {
super.init(frame: UIScreen.main.bounds)
setup(with: content)
}
public required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setup(with content: EKProperty.LabelContent) {
clipsToBounds = true
addSubview(label)
label.content = content
horizontalConstrainsts = label.layoutToSuperview(axis: .horizontally, offset: horizontalOffset, priority: .must)
verticalConstrainsts = label.layoutToSuperview(axis: .vertically, offset: verticalOffset, priority: .must)
}
}
| 0f8289c79085693ca3da024baa422539 | 29.075472 | 120 | 0.664366 | false | false | false | false |
sadawi/PrimarySource | refs/heads/master | Pod/iOS/TextFieldCell.swift | mit | 1 | //
// TextFieldCell.swift
// Pods
//
// Created by Sam Williams on 11/30/15.
//
//
import UIKit
public enum TextEditingMode {
case inline
case push
}
/**
A cell that uses a UITextField as an input, but doesn't necessarily have a String value.
*/
open class TextFieldInputCell<Value: Equatable>: FieldCell<Value>, UITextFieldDelegate, TappableTableCell {
open var textField:UITextField?
open var editingMode:TextEditingMode = .inline
/**
The string that is set by and displayed in the text field, but isn't necessarily the primary value of this cell.
Subclasses should override this with getters and setters that translate it to their primary value type.
*/
open var stringValue:String? {
get {
return self.exportText(self.value)
}
set {
self.value = self.importText(newValue)
}
}
override open func buildView() {
super.buildView()
let textField = UITextField(frame: self.controlView!.bounds)
textField.autoresizingMask = [.flexibleHeight, .flexibleWidth]
textField.returnKeyType = UIReturnKeyType.continue
self.controlView!.addSubview(textField)
textField.addConstraint(NSLayoutConstraint(item: textField, attribute: .height, relatedBy: .equal, toItem: nil, attribute: .notAnAttribute, multiplier: 1, constant: 30))
textField.delegate = self
self.textField = textField
}
override open func commit() {
super.commit()
self.textField?.resignFirstResponder()
}
override open func stylize() {
super.stylize()
self.textField?.textAlignment = self.labelPosition == .left ? .right : .left
self.textField?.font = self.valueFont
self.textField?.textColor = self.valueTextColor
}
open func textFieldDidEndEditing(_ textField: UITextField) {
let newValue = self.textField?.text
if newValue != self.stringValue {
self.stringValue = newValue
}
}
open func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
self.textField?.inputAccessoryView = self.accessoryToolbar
return true
}
open func textFieldShouldReturn(_ textField: UITextField) -> Bool {
self.commit()
return true
}
override open func cancel() {
self.textField?.resignFirstResponder()
}
override open func clear() {
self.stringValue = nil
super.clear()
}
override open var isBlank:Bool {
get {
let string = self.stringValue
return string == nil || string?.characters.count == 0
}
}
override open func update() {
super.update()
self.textField?.text = self.stringValue
self.textField?.placeholder = self.placeholderText
self.textField?.isUserInteractionEnabled = !self.isReadonly
self.textField?.keyboardType = self.keyboardType
}
public func handleTap() {
self.textField?.becomeFirstResponder()
}
open override func prepareForReuse() {
super.prepareForReuse()
self.stringValue = nil
self.textField?.text = nil
self.textField?.isEnabled = true
self.textForValue = nil
self.valueForText = nil
}
open var keyboardType: UIKeyboardType = .default
open var textForValue:((Value) -> String)?
open var valueForText:((String) -> Value?)?
open func exportText(_ value: Value?) -> String? {
if let value = value {
if let formatter = self.textForValue {
return formatter(value)
} else {
return String(describing: value)
}
} else {
return nil // textfield will use placeholderText
}
}
open func importText(_ text: String?) -> Value? {
if let text = text, let importer = self.valueForText {
return importer(text)
} else {
return nil
}
}
}
/**
A cell that uses a UITextField as an input and has a String value
*/
open class TextFieldCell: TextFieldInputCell<String> {
open override var stringValue:String? {
get {
return self.value
}
set {
self.value = newValue
}
}
}
open class EmailAddressCell: TextFieldCell {
override open func buildView() {
super.buildView()
self.textField?.keyboardType = .emailAddress
self.textField?.autocapitalizationType = .none
self.textField?.autocorrectionType = .no
}
}
open class PasswordCell: TextFieldCell {
override open func buildView() {
super.buildView()
self.textField?.autocapitalizationType = .none
self.textField?.autocorrectionType = .no
self.textField?.isSecureTextEntry = true
}
}
open class PhoneNumberCell: TextFieldCell {
override open func buildView() {
super.buildView()
self.textField?.keyboardType = .phonePad
}
// TODO: extract this / use a library
func textField(_ textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {
if let text = textField.text {
let newString = (text as NSString).replacingCharacters(in: range, with: string)
let components = newString.components(separatedBy: CharacterSet.decimalDigits.inverted)
let decimalString = components.joined(separator: "") as NSString
let length = decimalString.length
let hasLeadingOne = length > 0 && decimalString.character(at: 0) == (1 as unichar)
if length == 0 || (length > 10 && !hasLeadingOne) || length > 11 {
let newLength = (text as NSString).length + (string as NSString).length - range.length as Int
return (newLength > 10) ? false : true
}
var index = 0 as Int
let formattedString = NSMutableString()
if hasLeadingOne {
formattedString.append("1 ")
index += 1
}
if (length - index) > 3 {
let areaCode = decimalString.substring(with: NSMakeRange(index, 3))
formattedString.appendFormat("(%@) ", areaCode)
index += 3
}
if length - index > 3 {
let prefix = decimalString.substring(with: NSMakeRange(index, 3))
formattedString.appendFormat("%@-", prefix)
index += 3
}
let remainder = decimalString.substring(from: index)
formattedString.append(remainder)
textField.text = formattedString as String
return false
} else {
return false
}
}
}
| 2fd55191f2ed441c473eb943945e4d8e | 29.885463 | 177 | 0.593639 | false | false | false | false |
bentford/iOSToolbelt | refs/heads/master | iOSToolbelt/TBEvent.swift | mit | 1 | //
// TBEvent.swift
// iOSToolbelt
//
// Created by Ben Ford on 2/1/16.
// Copyright © 2016 Ben Ford. All rights reserved.
//
import Foundation
open class TBEvent<T> {
fileprivate var eventHandlers = [TBEventHandler<T>]()
public init() {
}
open func raise(_ argument: T) {
for handler in self.eventHandlers {
handler.invoke(argument)
}
}
open func addHandler(_ target: AnyObject, handler: @escaping (_ parameter: T) -> ()) {
self.eventHandlers.append(TBEventHandler(target: target, handler: handler))
}
open func removeAllHandlers() {
self.eventHandlers.removeAll()
}
open func removeHandler(_ target: AnyObject) {
let handlers = self.eventHandlers.filter({$0.target === target})
for handler in handlers {
if let index = self.eventHandlers.index(where: { $0 === handler}) {
self.eventHandlers.remove(at: index)
}
}
}
}
private class TBEventHandler<T> {
weak var target: AnyObject?
let handler: (_ parameter: T) -> ()
init(target: AnyObject?, handler: @escaping (_ parameter: T) -> ()) {
self.target = target
self.handler = handler
}
func invoke(_ argument: T) {
if target != nil {
self.handler(argument)
}
}
}
| a7812226924a4ec7fe92b135b7d5d9aa | 22.724138 | 90 | 0.570494 | false | false | false | false |
BrisyIOS/TodayNewsSwift3.0 | refs/heads/master | TodayNews-Swift3.0/TodayNews-Swift3.0/Classes/Home/Controller/HomeListController.swift | apache-2.0 | 1 | //
// HomeListController.swift
// TodayNews-Swift3.0
//
// Created by zhangxu on 2016/10/26.
// Copyright © 2016年 zhangxu. All rights reserved.
//
import UIKit
import MJRefresh
class HomeListController: UIViewController, UITableViewDataSource, UITableViewDelegate {
// 设置cell标识
private let homeOneImageCellID = "homeOneImageCellID";
private let homeThreeImageCellID = "homeThreeImageCellID";
private let homeLargeImageCellID = "homeLargeImageCellID";
private let homeNoImageCellID = "homeNoImageCellID";
var homeTopModel: HomeTopModel?;
// 懒加载tableView
private lazy var tableView: UITableView = {
let tableView = UITableView.init(frame: .zero, style: .plain);
tableView.dataSource = self;
tableView.delegate = self;
return tableView;
}();
// 懒加载数组
private lazy var homeListArray: [HomeListModel] = [HomeListModel]();
override func loadView() {
super.loadView();
print("loadview");
}
override func viewDidLoad() {
super.viewDidLoad()
definesPresentationContext = true;
// 添加tableview
view.addSubview(tableView);
tableView.estimatedRowHeight = 100;
tableView.tableFooterView = UIView();
// 注册cell
tableView.register(HomeOneImageCell.self, forCellReuseIdentifier: homeOneImageCellID);
tableView.register(HomeThreeImageCell.self, forCellReuseIdentifier: homeThreeImageCellID);
tableView.register(HomeLargeImageCell.self, forCellReuseIdentifier: homeLargeImageCellID);
tableView.register(HomeNoImageCell.self, forCellReuseIdentifier: homeNoImageCellID);
// 下拉刷新
var pullTime: TimeInterval = 0;
let header = MJRefreshNormalHeader();
header.refreshingBlock = { [weak self] _ in
guard let weakSelf = self else {
return;
}
pullTime = Date().timeIntervalSince1970;
// 从服务器请求首页新闻列表数据
let urlString = "http://lf.snssdk.com/api/news/feed/v39";
let parameters: [String: Any] = ["iid": iid, "device_id": device_id, "category": weakSelf.homeTopModel?.category ?? ""];
weakSelf.getHomeListFromServer(urlString: urlString, parameters: parameters);
}
// 设置header
tableView.mj_header = header;
// 开始刷新
header.beginRefreshing();
// 上啦加载更多
let footer = MJRefreshAutoNormalFooter();
footer.refreshingBlock = { [weak self]
_ in
guard let weakSelf = self else {
return;
}
// 加载更多
let url = "http://lf.snssdk.com/api/news/feed/v39/";
let parameters: [String: Any] = ["device_id": device_id, "iid": iid, "last_refresh_sub_entrance_interval": pullTime];
HttpManager.shareInstance.request(.GET, urlString: url, parameters: parameters, finished: { (result, error) in
// 如果error 不为空,打印error,并直接返回
if let error = error {
print(error);
return;
}
// 如果没有数据,直接返回
guard let result = result else {
return;
}
// 如果有数据,对返回的数据做JSON解析
let resultDic = result as? [String: Any];
if let resultDic = resultDic {
let dataArray = resultDic["data"] as? [[String: Any]];
for dataDic in dataArray ?? [] {
let content = dataDic["content"] as? String ?? "";
let contentData = content.data(using: String.Encoding.utf8);
do {
let contentDic = try JSONSerialization.jsonObject(with: contentData!, options: .mutableContainers) as? [String: Any] ?? [:];
// 将字典转化为模型
let model = HomeListModel.modelWidthDic(dic: contentDic);
if model.template_md5 != "" {
continue;
}
// 将模型装入数组中
weakSelf.homeListArray.append(model);
} catch {
// 异常处理
print("JSON解析异常");
}
}
// 刷新数据
weakSelf.tableView.reloadData();
// 停止刷新
weakSelf.tableView.mj_header.endRefreshing();
}
})
}
// 设置footer
tableView.mj_footer = footer;
}
// MARK: - 从服务器请求首页新闻列表数据
func getHomeListFromServer(urlString: String, parameters: [String: Any]) -> Void {
HttpManager.shareInstance.request(.GET, urlString: urlString, parameters: parameters) { [weak self] (result, error) in
// 如果error不为空,直接返回
if let error = error {
print(error);
return;
}
// 释放self捕获的引用,并做安全处理
guard let weakSelf = self else {
return;
}
// 如果没有数据,直接返回
guard let result = result else {
return;
}
// 有数据, 对数据进行JSON解析
let resultDic = result as? [String: Any];
if let resultDic = resultDic {
let dataArray = resultDic["data"] as? [[String: Any]];
for dataDic in dataArray ?? [] {
let content = dataDic["content"] as? String ?? "";
let contentData = content.data(using: String.Encoding.utf8);
do {
let contentDic = try JSONSerialization.jsonObject(with: contentData!, options: .mutableContainers) as? [String: Any] ?? [:];
// 将字典转化为模型
let model = HomeListModel.modelWidthDic(dic: contentDic);
if model.template_md5 != "" {
continue;
}
// 将模型装入数组中
weakSelf.homeListArray.append(model);
} catch {
// 异常处理
print("JSON解析异常");
}
}
// 刷新数据
weakSelf.tableView.reloadData();
// 停止刷新
weakSelf.tableView.mj_header.endRefreshing();
}
}
}
// MARK: - 返回cell高度
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let model = homeListArray[indexPath.row];
return HomeListModel.cellHeight(model: model);
}
// MARK: - 返回行
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return homeListArray.count;
}
// MARK: - 返回cell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let homeListModel = homeListArray[indexPath.row];
// 有3张图的情况
if homeListModel.image_list?.count != 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: homeThreeImageCellID, for: indexPath) as? HomeThreeImageCell;
cell?.homeListModel = homeListModel;
return cell!;
} else {
if homeListModel.middle_image?.height != 0 {
// 显示一张可以播放的大图
if homeListModel.video_detail_info != nil || homeListModel.large_image_list?.count != 0 {
let cell = tableView.dequeueReusableCell(withIdentifier: homeLargeImageCellID, for: indexPath) as? HomeLargeImageCell;
cell?.homeListModel = homeListModel;
return cell!;
} else {
// 在右边显示一张图
let cell = tableView.dequeueReusableCell(withIdentifier: homeOneImageCellID, for: indexPath) as? HomeOneImageCell;
cell?.homeListModel = homeListModel;
return cell!;
}
} else {
// 没有图片
let cell = tableView.dequeueReusableCell(withIdentifier: homeNoImageCellID, for: indexPath) as? HomeNoImageCell;
cell?.homeListModel = homeListModel;
return cell!;
}
}
}
// MARK: - 选中cell进入详情页面
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: false);
let homeDetailVc = HomeDetailController();
let homeListModel = homeListArray[indexPath.row];
homeDetailVc.homeListModel = homeListModel;
navigationController?.pushViewController(homeDetailVc, animated: true);
}
// MARK: - 设置子控件的frame
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews();
let width = view.bounds.size.width;
let height = view.bounds.size.height;
let tableViewX = realValue(0);
let tableViewY = realValue(0);
let tableViewW = width;
let tableViewH = height - realValue(49);
tableView.frame = CGRect(x: tableViewX, y: tableViewY, width: tableViewW, height: tableViewH);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
| 65d7e8dd8324a087fd41d0504f28b352 | 37.365079 | 153 | 0.529686 | false | false | false | false |
JGiola/swift | refs/heads/main | stdlib/public/BackDeployConcurrency/AsyncThrowingMapSequence.swift | apache-2.0 | 5 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Swift
@available(SwiftStdlib 5.1, *)
extension AsyncSequence {
/// Creates an asynchronous sequence that maps the given error-throwing
/// closure over the asynchronous sequence’s elements.
///
/// Use the `map(_:)` method to transform every element received from a base
/// asynchronous sequence. Typically, you use this to transform from one type
/// of element to another.
///
/// In this example, an asynchronous sequence called `Counter` produces `Int`
/// values from `1` to `5`. The closure provided to the `map(_:)` method
/// takes each `Int` and looks up a corresponding `String` from a
/// `romanNumeralDict` dictionary. This means the outer `for await in` loop
/// iterates over `String` instances instead of the underlying `Int` values
/// that `Counter` produces. Also, the dictionary doesn't provide a key for
/// `4`, and the closure throws an error for any key it can't look up, so
/// receiving this value from `Counter` ends the modified sequence with an
/// error.
///
/// let romanNumeralDict: [Int : String] =
/// [1: "I", 2: "II", 3: "III", 5: "V"]
///
/// do {
/// let stream = Counter(howHigh: 5)
/// .map { (value) throws -> String in
/// guard let roman = romanNumeralDict[value] else {
/// throw MyError()
/// }
/// return roman
/// }
/// for try await numeral in stream {
/// print("\(numeral) ", terminator: " ")
/// }
/// } catch {
/// print ("Error: \(error)")
/// }
/// // Prints: I II III Error: MyError()
///
/// - Parameter transform: A mapping closure. `transform` accepts an element
/// of this sequence as its parameter and returns a transformed value of the
/// same or of a different type. `transform` can also throw an error, which
/// ends the transformed sequence.
/// - Returns: An asynchronous sequence that contains, in order, the elements
/// produced by the `transform` closure.
@inlinable
public __consuming func map<Transformed>(
_ transform: @escaping (Element) async throws -> Transformed
) -> AsyncThrowingMapSequence<Self, Transformed> {
return AsyncThrowingMapSequence(self, transform: transform)
}
}
/// An asynchronous sequence that maps the given error-throwing closure over the
/// asynchronous sequence’s elements.
@available(SwiftStdlib 5.1, *)
public struct AsyncThrowingMapSequence<Base: AsyncSequence, Transformed> {
@usableFromInline
let base: Base
@usableFromInline
let transform: (Base.Element) async throws -> Transformed
@usableFromInline
init(
_ base: Base,
transform: @escaping (Base.Element) async throws -> Transformed
) {
self.base = base
self.transform = transform
}
}
@available(SwiftStdlib 5.1, *)
extension AsyncThrowingMapSequence: AsyncSequence {
/// The type of element produced by this asynchronous sequence.
///
/// The map sequence produces whatever type of element its the transforming
/// closure produces.
public typealias Element = Transformed
/// The type of iterator that produces elements of the sequence.
public typealias AsyncIterator = Iterator
/// The iterator that produces elements of the map sequence.
public struct Iterator: AsyncIteratorProtocol {
@usableFromInline
var baseIterator: Base.AsyncIterator
@usableFromInline
let transform: (Base.Element) async throws -> Transformed
@usableFromInline
var finished = false
@usableFromInline
init(
_ baseIterator: Base.AsyncIterator,
transform: @escaping (Base.Element) async throws -> Transformed
) {
self.baseIterator = baseIterator
self.transform = transform
}
/// Produces the next element in the map sequence.
///
/// This iterator calls `next()` on its base iterator; if this call returns
/// `nil`, `next()` returns nil. Otherwise, `next()` returns the result of
/// calling the transforming closure on the received element. If calling
/// the closure throws an error, the sequence ends and `next()` rethrows
/// the error.
@inlinable
public mutating func next() async throws -> Transformed? {
guard !finished, let element = try await baseIterator.next() else {
return nil
}
do {
return try await transform(element)
} catch {
finished = true
throw error
}
}
}
@inlinable
public __consuming func makeAsyncIterator() -> Iterator {
return Iterator(base.makeAsyncIterator(), transform: transform)
}
}
| 27a67cbe8db8c1dfdb35c20d27a73420 | 35.528169 | 80 | 0.636784 | false | false | false | false |
vbudhram/firefox-ios | refs/heads/master | Client/Application/LeanplumIntegration.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import AdSupport
import Shared
import Leanplum
private let LPAppIdKey = "LeanplumAppId"
private let LPProductionKeyKey = "LeanplumProductionKey"
private let LPDevelopmentKeyKey = "LeanplumDevelopmentKey"
private let AppRequestedUserNotificationsPrefKey = "applicationDidRequestUserNotificationPermissionPrefKey"
private let FxaDevicesCountPrefKey = "FxaDevicesCount"
// FxA Custom Leanplum message template for A/B testing push notifications.
private struct LPMessage {
static let FxAPrePush = "FxA Prepush v1"
static let ArgAcceptAction = "Accept action"
static let ArgCancelAction = "Cancel action"
static let ArgTitleText = "Title.Text"
static let ArgTitleColor = "Title.Color"
static let ArgMessageText = "Message.Text"
static let ArgMessageColor = "Message.Color"
static let ArgAcceptButtonText = "Accept button.Text"
static let ArgCancelButtonText = "Cancel button.Text"
static let ArgCancelButtonTextColor = "Cancel button.Text color"
// These defaults are overridden though Leanplum webUI
static let DefaultAskToAskTitle = NSLocalizedString("Firefox Sync Requires Push", comment: "Default push to ask title")
static let DefaultAskToAskMessage = NSLocalizedString("Firefox will stay in sync faster with Push Notifications enabled.", comment: "Default push to ask message")
static let DefaultOkButtonText = NSLocalizedString("Enable Push", comment: "Default push alert ok button text")
static let DefaultLaterButtonText = NSLocalizedString("Don't Enable", comment: "Default push alert cancel button text")
}
private let log = Logger.browserLogger
enum LPEvent: String {
case firstRun = "E_First_Run"
case secondRun = "E_Second_Run"
case openedApp = "E_Opened_App"
case dismissedOnboarding = "E_Dismissed_Onboarding"
case dismissedOnboardingShowLogin = "E_Dismissed_Onboarding_Showed_Login"
case openedLogins = "Opened Login Manager"
case openedBookmark = "E_Opened_Bookmark"
case openedNewTab = "E_Opened_New_Tab"
case openedPocketStory = "E_Opened_Pocket_Story"
case interactWithURLBar = "E_Interact_With_Search_URL_Area"
case savedBookmark = "E_Saved_Bookmark"
case openedTelephoneLink = "Opened Telephone Link"
case openedMailtoLink = "E_Opened_Mailto_Link"
case saveImage = "E_Download_Media_Saved_Image"
case savedLoginAndPassword = "E_Saved_Login_And_Password"
case clearPrivateData = "E_Cleared_Private_Data"
case downloadedFocus = "E_User_Downloaded_Focus"
case downloadedPocket = "E_User_Downloaded_Pocket"
case userSharedWebpage = "E_User_Tapped_Share_Button"
case signsInFxa = "E_User_Signed_In_To_FxA"
case useReaderView = "E_User_Used_Reader_View"
case trackingProtectionSettings = "E_Tracking_Protection_Settings_Changed"
case fxaSyncedNewDevice = "E_FXA_Synced_New_Device"
case onboardingTestLoadedTooSlow = "E_Onboarding_Was_Swiped_Before_AB_Test_Could_Start"
}
struct LPAttributeKey {
static let focusInstalled = "Focus Installed"
static let klarInstalled = "Klar Installed"
static let signedInSync = "Signed In Sync"
static let mailtoIsDefault = "Mailto Is Default"
static let pocketInstalled = "Pocket Installed"
static let telemetryOptIn = "Telemetry Opt In"
static let fxaAccountVerified = "FxA account is verified"
static let fxaDeviceCount = "Number of devices in FxA account"
}
struct MozillaAppSchemes {
static let focus = "firefox-focus"
static let focusDE = "firefox-klar"
static let pocket = "pocket"
}
private let supportedLocales = ["en_US", "de_DE", "en_GB", "en_CA", "en_AU", "zh_TW", "en_HK", "en_SG",
"fr_FR", "it_IT", "id_ID", "id_ID", "pt_BR", "pl_PL", "ru_RU", "es_ES", "es_MX"]
private struct LPSettings {
var appId: String
var developmentKey: String
var productionKey: String
}
class LeanPlumClient {
static let shared = LeanPlumClient()
// Setup
private weak var profile: Profile?
private var prefs: Prefs? { return profile?.prefs }
private var enabled: Bool = true
// This defines an external Leanplum varible to enable/disable FxA prepush dialogs.
// The primary result is having a feature flag controlled by Leanplum, and falling back
// to prompting with native push permissions.
private var useFxAPrePush: LPVar = LPVar.define("useFxAPrePush", with: false)
var introScreenVars = LPVar.define("IntroScreen", with: IntroCard.defaultCards().flatMap({ $0.asDictonary() }))
private func isPrivateMode() -> Bool {
// Need to be run on main thread since isInPrivateMode requires to be on the main thread.
assert(Thread.isMainThread)
return UIApplication.isInPrivateMode
}
func isLPEnabled() -> Bool {
return enabled && Leanplum.hasStarted()
}
static func shouldEnable(profile: Profile) -> Bool {
return AppConstants.MOZ_ENABLE_LEANPLUM && (profile.prefs.boolForKey(AppConstants.PrefSendUsageData) ?? true)
}
func setup(profile: Profile) {
self.profile = profile
}
func recordSyncedClients(with profile: Profile?) {
guard let profile = profile as? BrowserProfile else {
return
}
profile.remoteClientsAndTabs.getClients() >>== { clients in
let oldCount = self.prefs?.intForKey(FxaDevicesCountPrefKey) ?? 0
if clients.count > oldCount {
self.track(event: .fxaSyncedNewDevice)
}
self.prefs?.setInt(Int32(clients.count), forKey: FxaDevicesCountPrefKey)
Leanplum.setUserAttributes([LPAttributeKey.fxaDeviceCount: clients.count])
}
}
fileprivate func start() {
guard let settings = getSettings(), supportedLocales.contains(Locale.current.identifier), !Leanplum.hasStarted() else {
enabled = false
log.error("LeanplumIntegration - Could not be started")
return
}
if UIDevice.current.name.contains("MozMMADev") {
log.info("LeanplumIntegration - Setting up for Development")
Leanplum.setDeviceId(UIDevice.current.identifierForVendor?.uuidString)
Leanplum.setAppId(settings.appId, withDevelopmentKey: settings.developmentKey)
} else {
log.info("LeanplumIntegration - Setting up for Production")
Leanplum.setAppId(settings.appId, withProductionKey: settings.productionKey)
}
Leanplum.syncResourcesAsync(true)
let attributes: [AnyHashable: Any] = [
LPAttributeKey.mailtoIsDefault: mailtoIsDefault(),
LPAttributeKey.focusInstalled: focusInstalled(),
LPAttributeKey.klarInstalled: klarInstalled(),
LPAttributeKey.pocketInstalled: pocketInstalled(),
LPAttributeKey.signedInSync: profile?.hasAccount() ?? false,
LPAttributeKey.fxaAccountVerified: profile?.hasSyncableAccount() ?? false
]
self.setupCustomTemplates()
Leanplum.start(withUserId: nil, userAttributes: attributes, responseHandler: { _ in
self.track(event: .openedApp)
// We need to check if the app is a clean install to use for
// preventing the What's New URL from appearing.
if self.prefs?.intForKey(PrefsKeys.IntroSeen) == nil {
self.prefs?.setString(AppInfo.appVersion, forKey: LatestAppVersionProfileKey)
self.track(event: .firstRun)
} else if self.prefs?.boolForKey("SecondRun") == nil {
self.prefs?.setBool(true, forKey: "SecondRun")
self.track(event: .secondRun)
}
self.checkIfAppWasInstalled(key: PrefsKeys.HasFocusInstalled, isAppInstalled: self.focusInstalled(), lpEvent: .downloadedFocus)
self.checkIfAppWasInstalled(key: PrefsKeys.HasPocketInstalled, isAppInstalled: self.pocketInstalled(), lpEvent: .downloadedPocket)
self.recordSyncedClients(with: self.profile)
})
}
// Events
func track(event: LPEvent, withParameters parameters: [String: AnyObject]? = nil) {
guard isLPEnabled() else {
return
}
ensureMainThread {
guard !self.isPrivateMode() else {
return
}
if let params = parameters {
Leanplum.track(event.rawValue, withParameters: params)
} else {
Leanplum.track(event.rawValue)
}
}
}
func set(attributes: [AnyHashable: Any]) {
guard isLPEnabled() else {
return
}
ensureMainThread {
if !self.isPrivateMode() {
Leanplum.setUserAttributes(attributes)
}
}
}
func set(enabled: Bool) {
// Setting up Test Mode stops sending things to server.
if enabled { start() }
self.enabled = enabled
Leanplum.setTestModeEnabled(!enabled)
}
func isFxAPrePushEnabled() -> Bool {
return AppConstants.MOZ_FXA_LEANPLUM_AB_PUSH_TEST && useFxAPrePush.boolValue()
}
/*
This is used to determine if an app was installed after firefox was installed
*/
private func checkIfAppWasInstalled(key: String, isAppInstalled: Bool, lpEvent: LPEvent) {
// if no key is present. create one and set it.
// if the app is already installed then the flag will set true and the second block will never run
if self.prefs?.boolForKey(key) == nil {
self.prefs?.setBool(isAppInstalled, forKey: key)
}
// on a subsquent launch if the app is installed and the key is false then switch the flag to true
if !(self.prefs?.boolForKey(key) ?? false), isAppInstalled {
self.prefs?.setBool(isAppInstalled, forKey: key)
self.track(event: lpEvent)
}
}
private func canOpenApp(scheme: String) -> Bool {
return URL(string: "\(scheme)://").flatMap { UIApplication.shared.canOpenURL($0) } ?? false
}
private func focusInstalled() -> Bool {
return canOpenApp(scheme: MozillaAppSchemes.focus)
}
private func klarInstalled() -> Bool {
return canOpenApp(scheme: MozillaAppSchemes.focusDE)
}
private func pocketInstalled() -> Bool {
return canOpenApp(scheme: MozillaAppSchemes.pocket)
}
private func mailtoIsDefault() -> Bool {
return (prefs?.stringForKey(PrefsKeys.KeyMailToOption) ?? "mailto:") == "mailto:"
}
private func getSettings() -> LPSettings? {
let bundle = Bundle.main
guard let appId = bundle.object(forInfoDictionaryKey: LPAppIdKey) as? String,
let productionKey = bundle.object(forInfoDictionaryKey: LPProductionKeyKey) as? String,
let developmentKey = bundle.object(forInfoDictionaryKey: LPDevelopmentKeyKey) as? String else {
return nil
}
return LPSettings(appId: appId, developmentKey: developmentKey, productionKey: productionKey)
}
// This must be called before `Leanplum.start` in order to correctly setup
// custom message templates.
private func setupCustomTemplates() {
// These properties are exposed through the Leanplum web interface.
// Ref: https://github.com/Leanplum/Leanplum-iOS-Samples/blob/master/iOS_customMessageTemplates/iOS_customMessageTemplates/LPMessageTemplates.m
let args: [LPActionArg] = [
LPActionArg(named: LPMessage.ArgTitleText, with: LPMessage.DefaultAskToAskTitle),
LPActionArg(named: LPMessage.ArgTitleColor, with: UIColor.black),
LPActionArg(named: LPMessage.ArgMessageText, with: LPMessage.DefaultAskToAskMessage),
LPActionArg(named: LPMessage.ArgMessageColor, with: UIColor.black),
LPActionArg(named: LPMessage.ArgAcceptButtonText, with: LPMessage.DefaultOkButtonText),
LPActionArg(named: LPMessage.ArgCancelAction, withAction: nil),
LPActionArg(named: LPMessage.ArgCancelButtonText, with: LPMessage.DefaultLaterButtonText),
LPActionArg(named: LPMessage.ArgCancelButtonTextColor, with: UIColor.gray)
]
let responder: LeanplumActionBlock = { (context) -> Bool in
// Before proceeding, double check that Leanplum FxA prepush config value has been enabled.
if !self.isFxAPrePushEnabled() {
return false
}
guard let context = context else {
return false
}
// Don't display permission screen if they have already allowed/disabled push permissions
if self.prefs?.boolForKey(AppRequestedUserNotificationsPrefKey) ?? false {
FxALoginHelper.sharedInstance.readyForSyncing()
return false
}
// Present Alert View onto the current top view controller
let rootViewController = UIApplication.topViewController()
let alert = UIAlertController(title: context.stringNamed(LPMessage.ArgTitleText), message: context.stringNamed(LPMessage.ArgMessageText), preferredStyle: .alert)
alert.addAction(UIAlertAction(title: context.stringNamed(LPMessage.ArgCancelButtonText), style: .cancel, handler: { (action) -> Void in
// Log cancel event and call ready for syncing
context.runTrackedActionNamed(LPMessage.ArgCancelAction)
FxALoginHelper.sharedInstance.readyForSyncing()
}))
alert.addAction(UIAlertAction(title: context.stringNamed(LPMessage.ArgAcceptButtonText), style: .default, handler: { (action) -> Void in
// Log accept event and present push permission modal
context.runTrackedActionNamed(LPMessage.ArgAcceptAction)
FxALoginHelper.sharedInstance.requestUserNotifications(UIApplication.shared)
self.prefs?.setBool(true, forKey: AppRequestedUserNotificationsPrefKey)
}))
rootViewController?.present(alert, animated: true, completion: nil)
return true
}
// Register or update the custom Leanplum message
Leanplum.defineAction(LPMessage.FxAPrePush, of: kLeanplumActionKindMessage, withArguments: args, withOptions: [:], withResponder: responder)
}
}
extension UIApplication {
// Extension to get the current top most view controller
class func topViewController(base: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? {
if let nav = base as? UINavigationController {
return topViewController(base: nav.visibleViewController)
}
if let tab = base as? UITabBarController {
if let selected = tab.selectedViewController {
return topViewController(base: selected)
}
}
if let presented = base?.presentedViewController {
return topViewController(base: presented)
}
return base
}
}
| f5f85b3ceae9732309cd20de041c37e3 | 43.790087 | 173 | 0.670637 | false | false | false | false |
proversity-org/edx-app-ios | refs/heads/master | Source/ProfileImageView.swift | apache-2.0 | 1 | //
// ProfileImageView.swift
// edX
//
// Created by Michael Katz on 9/17/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
@IBDesignable
class ProfileImageView: UIImageView {
var borderWidth: CGFloat = 1.0
var borderColor: UIColor?
private func setup() {
var borderStyle = OEXStyles.shared().profileImageViewBorder(width: borderWidth)
if borderColor != nil {
borderStyle = BorderStyle(cornerRadius: borderStyle.cornerRadius, width: borderStyle.width, color: borderColor)
}
applyBorderStyle(style: borderStyle)
backgroundColor = OEXStyles.shared().profileImageBorderColor()
}
convenience init() {
self.init(frame: CGRect.zero)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init (frame: CGRect) {
super.init(frame: frame)
let bundle = Bundle(for: type(of: self))
image = UIImage(named: "profilePhotoPlaceholder", in: bundle, compatibleWith: self.traitCollection)
setup()
}
override func layoutSubviews() {
super.layoutSubviews()
setup()
}
override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
setup()
let bundle = Bundle(for: type(of: self))
image = UIImage(named: "profilePhotoPlaceholder", in: bundle, compatibleWith: self.traitCollection)
}
func blurimate() -> Removable {
let blur = UIBlurEffect(style: .light)
let blurView = UIVisualEffectView(effect: blur)
let vib = UIVibrancyEffect(blurEffect: blur)
let vibView = UIVisualEffectView(effect: vib)
let spinner = SpinnerView(size: .Medium, color: .White)
vibView.contentView.addSubview(spinner)
spinner.snp.makeConstraints { make in
make.center.equalTo(spinner.superview!)
}
spinner.startAnimating()
insertSubview(blurView, at: 0)
blurView.contentView.addSubview(vibView)
vibView.snp.makeConstraints { make in
make.edges.equalTo(vibView.superview!)
}
blurView.snp.makeConstraints { make in
make.edges.equalTo(self)
}
return BlockRemovable() {
UIView.animate(withDuration: 0.4, animations: {
spinner.stopAnimating()
}) { _ in
blurView.removeFromSuperview()
}
}
}
}
| d79b3b0357e54fc19042f9e9c55fdb99 | 28.894118 | 123 | 0.611177 | false | false | false | false |
Friend-LGA/LGSideMenuController | refs/heads/master | Demo/_shared_files/Helper.swift | mit | 1 | //
// Helper.swift
// LGSideMenuControllerDemo
//
import Foundation
import UIKit
private let isStoryboardBasedKey = "IsStoryboardBased"
private let backgroundImageNames: [String] = ["imageRoot0", "imageRoot1", "imageRoot2", "imageRoot3"]
private var currentBackgroundImageNameIndex = 0
let menuIconImage: UIImage = {
let size = CGSize(width: 24.0, height: 16.0)
let renderer = UIGraphicsImageRenderer(size: size)
return renderer.image { context in
let ctx = context.cgContext
let lineHeight: CGFloat = 2.0
ctx.setFillColor(UIColor.black.cgColor)
ctx.setStrokeColor(UIColor.black.cgColor)
ctx.setLineWidth(lineHeight)
ctx.setLineCap(.round)
ctx.beginPath()
ctx.move(to: CGPoint(x: lineHeight, y: lineHeight / 2.0))
ctx.addLine(to: CGPoint(x: size.width - lineHeight, y: lineHeight / 2.0))
ctx.move(to: CGPoint(x: lineHeight, y: size.height / 2.0))
ctx.addLine(to: CGPoint(x: size.width - lineHeight, y: size.height / 2.0))
ctx.move(to: CGPoint(x: lineHeight, y: size.height - lineHeight / 2.0))
ctx.addLine(to: CGPoint(x: size.width - lineHeight, y: size.height - lineHeight / 2.0))
ctx.strokePath()
}
}()
func tabBarIconImage(_ title: String) -> UIImage {
let fontSize: CGFloat = 24.0
let insetVertical: CGFloat = 4.0
let size = CGSize(width: fontSize, height: fontSize + insetVertical)
let renderer = UIGraphicsImageRenderer(size: size)
return renderer.image { context in
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.alignment = .center
let attrs = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: fontSize),
NSAttributedString.Key.paragraphStyle: paragraphStyle]
title.draw(with: CGRect(x: 0.0, y: 0.0, width: size.width, height: size.height),
options: .usesLineFragmentOrigin,
attributes: attrs,
context: nil)
}
}
func isStoryboardBasedDemo() -> Bool {
guard let dict = Bundle.main.infoDictionary else { return false }
return dict[isStoryboardBasedKey] as! Bool
}
func isLightTheme() -> Bool {
if #available(iOS 13.0, *) {
let currentStyle = UITraitCollection.current.userInterfaceStyle
return currentStyle == .light || currentStyle == .unspecified
}
else {
return true
}
}
func getBackgroundImageNameDefault() -> String {
currentBackgroundImageNameIndex = 0
return backgroundImageNames[currentBackgroundImageNameIndex]
}
func getBackgroundImageNameRandom() -> String {
var newIndex = currentBackgroundImageNameIndex
while newIndex == currentBackgroundImageNameIndex {
newIndex = Int.random(in: 0...3)
}
currentBackgroundImageNameIndex = newIndex
return backgroundImageNames[currentBackgroundImageNameIndex]
}
func getKeyWindow() -> UIWindow? {
if #available(iOS 13.0, *) {
return UIApplication.shared.windows.first(where: { $0.isKeyWindow })
} else {
return UIApplication.shared.keyWindow
}
}
func getStatusBarFrame() -> CGRect {
if #available(iOS 13.0, *) {
return getKeyWindow()?.windowScene?.statusBarManager?.statusBarFrame ?? .zero
} else {
return UIApplication.shared.statusBarFrame
}
}
func getTitle(for presentationStyle: LGSideMenuController.PresentationStyle) -> String {
switch presentationStyle {
case .scaleFromBig:
return "Scale From Big"
case .scaleFromLittle:
return "Scale From Little"
case .slideBelow:
return "Slide Below"
case .slideBelowShifted:
return "Slide Below Shifted"
case .slideAbove:
return "Slide Above"
case .slideAboveBlurred:
return "Slide Above Blurred"
case .slideAside:
return "Slide Aside"
}
}
extension UIView {
class func fromNib() -> Self {
return Bundle.main.loadNibNamed(String(describing: self), owner: nil, options: nil)!.first as! Self
}
}
extension UIColor {
convenience init(hexString: String, alpha: CGFloat = 1.0) {
let hexint = Int(Self.intFromHexString(hexStr: hexString))
let red = CGFloat((hexint & 0xff0000) >> 16) / 255.0
let green = CGFloat((hexint & 0xff00) >> 8) / 255.0
let blue = CGFloat((hexint & 0xff) >> 0) / 255.0
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
static private func intFromHexString(hexStr: String) -> UInt32 {
var hexInt: UInt32 = 0
let scanner: Scanner = Scanner(string: hexStr)
scanner.charactersToBeSkipped = CharacterSet(charactersIn: "#")
scanner.scanHexInt32(&hexInt)
return hexInt
}
}
enum SideViewCellItem: Equatable {
case close
case openLeft
case openRight
case changeRootVC
case pushVC(title: String)
var description: String {
switch self {
case .close:
return "Close"
case .openLeft:
return "Open Left View"
case .openRight:
return "Open Right View"
case .changeRootVC:
return "Change Root VC"
case let .pushVC(title):
return title
}
}
}
| 3f59176ce927795f45d50dfda27e42f1 | 30.45509 | 107 | 0.651437 | false | false | false | false |
djwbrown/swift | refs/heads/master | test/Constraints/closures.swift | apache-2.0 | 3 | // RUN: %target-typecheck-verify-swift
func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {}
var intArray : [Int]
_ = myMap(intArray, { String($0) })
_ = myMap(intArray, { x -> String in String(x) } )
// Closures with too few parameters.
func foo(_ x: (Int, Int) -> Int) {}
foo({$0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
struct X {}
func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {}
func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {}
var strings : [String]
_ = mySort(strings, { x, y in x < y })
// Closures with inout arguments.
func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U {
var t2 = t
return f(&t2)
}
struct X2 {
func g() -> Float { return 0 }
}
_ = f0(X2(), {$0.g()})
// Autoclosure
func f1(f: @autoclosure () -> Int) { }
func f2() -> Int { }
f1(f: f2) // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}}{{9-9=()}}
f1(f: 5)
// Ternary in closure
var evenOrOdd : (Int) -> String = {$0 % 2 == 0 ? "even" : "odd"}
// <rdar://problem/15367882>
func foo() {
not_declared({ $0 + 1 }) // expected-error{{use of unresolved identifier 'not_declared'}}
}
// <rdar://problem/15536725>
struct X3<T> {
init(_: (T) -> ()) {}
}
func testX3(_ x: Int) {
var x = x
_ = X3({ x = $0 })
_ = x
}
// <rdar://problem/13811882>
func test13811882() {
var _ : (Int) -> (Int, Int) = {($0, $0)}
var x = 1
var _ : (Int) -> (Int, Int) = {($0, x)}
x = 2
}
// <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement
// <https://bugs.swift.org/browse/SR-3671>
func r21544303() {
var inSubcall = true
{
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
// This is a problem, but isn't clear what was intended.
var somethingElse = true {
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
var v2 : Bool = false
v2 = inSubcall
{ // expected-error {{cannot call value of non-function type 'Bool'}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }}
}
}
// <https://bugs.swift.org/browse/SR-3671>
func SR3671() {
let n = 42
func consume(_ x: Int) {}
{ consume($0) }(42)
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ print($0) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ [n] in print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ consume($0) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ (x: Int) in consume(x) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
// This is technically a valid call, so nothing goes wrong until (42)
{ $0(3) }
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) })
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
{ $0(3) }
{ [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) })
{ [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
// Equivalent but more obviously unintended.
{ $0(3) } // expected-note {{callee is here}}
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
({ $0(3) }) // expected-note {{callee is here}}
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
// Also a valid call (!!)
{ $0 { $0 } } { $0 { 1 } } // expected-error {{expression resolves to an unused function}}
consume(111)
}
// <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure
func r22162441(_ lines: [String]) {
_ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
_ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
}
func testMap() {
let a = 42
[1,a].map { $0 + 1.0 } // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }}
}
// <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier
[].reduce { $0 + $1 } // expected-error {{missing argument for parameter #1 in call}}
// <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments
var _: () -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }}
var _: (Int) -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}}
var _: (Int) -> Int = { 0 }
// expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }}
var _: (Int, Int) -> Int = {0}
// expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
var _: (Int,Int) -> Int = {$0+$1+$2}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {$0+$1}
var _: () -> Int = {a in 0}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}}
var _: (Int) -> Int = {a,b in 0}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}}
var _: (Int) -> Int = {a,b,c in 0}
var _: (Int, Int) -> Int = {a in 0}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {a, b in a+b}
// <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument
func r15998821() {
func take_closure(_ x : (inout Int) -> ()) { }
func test1() {
take_closure { (a : inout Int) in
a = 42
}
}
func test2() {
take_closure { a in
a = 42
}
}
func withPtr(_ body: (inout Int) -> Int) {}
func f() { withPtr { p in return p } }
let g = { x in x = 3 }
take_closure(g)
}
// <rdar://problem/22602657> better diagnostics for closures w/o "in" clause
var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
// Crash when re-typechecking bodies of non-single expression closures
struct CC {}
func callCC<U>(_ f: (CC) -> U) -> () {}
func typeCheckMultiStmtClosureCrash() {
callCC { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{11-11= () -> Int in }}
_ = $0
return 1
}
}
// SR-832 - both these should be ok
func someFunc(_ foo: ((String) -> String)?,
bar: @escaping (String) -> String) {
let _: (String) -> String = foo != nil ? foo! : bar
let _: (String) -> String = foo ?? bar
}
// SR-1069 - Error diagnostic refers to wrong argument
class SR1069_W<T> {
func append<Key: AnyObject>(value: T, forKey key: Key) where Key: Hashable {}
}
class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() }
struct S<T> {
let cs: [SR1069_C<T>] = []
func subscribe<Object: AnyObject>(object: Object?, method: (Object, T) -> ()) where Object: Hashable {
let wrappedMethod = { (object: AnyObject, value: T) in }
// expected-error @+1 {{value of optional type 'Object?' not unwrapped; did you mean to use '!' or '?'?}}
cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) }
}
}
// Make sure we cannot infer an () argument from an empty parameter list.
func acceptNothingToInt (_: () -> Int) {}
func testAcceptNothingToInt(ac1: @autoclosure () -> Int) {
acceptNothingToInt({ac1($0)})
// expected-error@-1{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}}
}
// <rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference)
struct Thing {
init?() {}
}
// This throws a compiler error
let things = Thing().map { thing in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{34-34=-> (Thing) }}
// Commenting out this makes it compile
_ = thing
return thing
}
// <rdar://problem/21675896> QoI: [Closure return type inference] Swift cannot find members for the result of inlined lambdas with branches
func r21675896(file : String) {
let x: String = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{20-20= () -> String in }}
if true {
return "foo"
}
else {
return file
}
}().pathExtension
}
// <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _")
func ident<T>(_ t: T) -> T {}
var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}}
// <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block
var afterMessageCount : Int?
func uintFunc() -> UInt {}
func takeVoidVoidFn(_ a : () -> ()) {}
takeVoidVoidFn { () -> Void in
afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int?'}}
}
// <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure
func f19997471(_ x: String) {}
func f19997471(_ x: Int) {}
func someGeneric19997471<T>(_ x: T) {
takeVoidVoidFn {
f19997471(x) // expected-error {{cannot invoke 'f19997471' with an argument list of type '(T)'}}
// expected-note @-1 {{overloads for 'f19997471' exist with these partially matching parameter lists: (String), (Int)}}
}
}
// <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information
func f20371273() {
let x: [Int] = [1, 2, 3, 4]
let y: UInt = 4
_ = x.filter { ($0 + y) > 42 } // expected-warning {{deprecated}}
}
// <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r }
[0].map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{5-5=-> Int }}
_ in
let r = (1,2).0
return r
}
// <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type
func rdar21078316() {
var foo : [String : String]?
var bar : [(String, String)]?
bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) -> [(String, String)]' expects 1 argument, but 2 were used in closure body}}
}
// <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure
var numbers = [1, 2, 3]
zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}}
// <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type'
func foo20868864(_ callback: ([String]) -> ()) { }
func rdar20868864(_ s: String) {
var s = s
foo20868864 { (strings: [String]) in
s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}}
}
}
// <rdar://problem/22058555> crash in cs diags in withCString
func r22058555() {
var firstChar: UInt8 = 0
"abc".withCString { chars in
firstChar = chars[0] // expected-error {{cannot assign value of type 'Int8' to type 'UInt8'}}
}
}
// <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type
func r20789423() {
class C {
func f(_ value: Int) { }
}
let p: C
print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}}
let _f = { (v: Int) in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{23-23=-> String }}
print("a")
return "hi"
}
}
// Make sure that behavior related to allowing trailing closures to match functions
// with Any as a final parameter is the same after the changes made by SR-2505, namely:
// that we continue to select function that does _not_ have Any as a final parameter in
// presence of other possibilities.
protocol SR_2505_Initable { init() }
struct SR_2505_II : SR_2505_Initable {}
protocol P_SR_2505 {
associatedtype T: SR_2505_Initable
}
extension P_SR_2505 {
func test(it o: (T) -> Bool) -> Bool {
return o(T.self())
}
}
class C_SR_2505 : P_SR_2505 {
typealias T = SR_2505_II
func test(_ o: Any) -> Bool {
return false
}
func call(_ c: C_SR_2505) -> Bool {
// Note: no diagnostic about capturing 'self', because this is a
// non-escaping closure -- that's how we know we have selected
// test(it:) and not test(_)
return c.test { o in test(o) }
}
}
let _ = C_SR_2505().call(C_SR_2505())
// <rdar://problem/28909024> Returning incorrect result type from method invocation can result in nonsense diagnostic
extension Collection {
func r28909024(_ predicate: (Iterator.Element)->Bool) -> Index {
return startIndex
}
}
func fn_r28909024(n: Int) {
return (0..<10).r28909024 { // expected-error {{unexpected non-void return value in void function}}
_ in true
}
}
// SR-2994: Unexpected ambiguous expression in closure with generics
struct S_2994 {
var dataOffset: Int
}
class C_2994<R> {
init(arg: (R) -> Void) {}
}
func f_2994(arg: String) {}
func g_2994(arg: Int) -> Double {
return 2
}
C_2994<S_2994>(arg: { (r: S_2994) in f_2994(arg: g_2994(arg: r.dataOffset)) }) // expected-error {{cannot convert value of type 'Double' to expected argument type 'String'}}
let _ = { $0[$1] }(1, 1) // expected-error {{cannot subscript a value of incorrect or ambiguous type}}
let _ = { $0 = ($0 = {}) } // expected-error {{assigning a variable to itself}}
let _ = { $0 = $0 = 42 } // expected-error {{assigning a variable to itself}}
// https://bugs.swift.org/browse/SR-403
// The () -> T => () -> () implicit conversion was kicking in anywhere
// inside a closure result, not just at the top-level.
let mismatchInClosureResultType : (String) -> ((Int) -> Void) = {
(String) -> ((Int) -> Void) in
return { }
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}}
}
// SR-3520: Generic function taking closure with inout parameter can result in a variety of compiler errors or EXC_BAD_ACCESS
func sr3520_1<T>(_ g: (inout T) -> Int) {}
sr3520_1 { $0 = 1 } // expected-error {{cannot convert value of type '()' to closure result type 'Int'}}
func sr3520_2<T>(_ item: T, _ update: (inout T) -> Void) {
var x = item
update(&x)
}
var sr3250_arg = 42
sr3520_2(sr3250_arg) { $0 += 3 } // ok
// This test makes sure that having closure with inout argument doesn't crash with member lookup
struct S_3520 {
var number1: Int
}
func sr3520_set_via_closure<S, T>(_ closure: (inout S, T) -> ()) {}
sr3520_set_via_closure({ $0.number1 = $1 }) // expected-error {{type of expression is ambiguous without more context}}
// SR-1976/SR-3073: Inference of inout
func sr1976<T>(_ closure: (inout T) -> Void) {}
sr1976({ $0 += 2 }) // ok
// SR-3073: UnresolvedDotExpr in single expression closure
struct SR3073Lense<Whole, Part> {
let set: (inout Whole, Part) -> ()
}
struct SR3073 {
var number1: Int
func lenses() {
let _: SR3073Lense<SR3073, Int> = SR3073Lense(
set: { $0.number1 = $1 } // ok
)
}
}
// SR-3479: Segmentation fault and other error for closure with inout parameter
func sr3497_unfold<A, B>(_ a0: A, next: (inout A) -> B) {}
func sr3497() {
let _ = sr3497_unfold((0, 0)) { s in 0 } // ok
}
// SR-3758: Swift 3.1 fails to compile 3.0 code involving closures and IUOs
let _: ((Any?) -> Void) = { (arg: Any!) in }
// This example was rejected in 3.0 as well, but accepting it is correct.
let _: ((Int?) -> Void) = { (arg: Int!) in }
// rdar://30429709 - We should not attempt an implicit conversion from
// () -> T to () -> Optional<()>.
func returnsArray() -> [Int] { return [] }
returnsArray().flatMap { $0 }.flatMap { }
// expected-warning@-1 {{expression of type 'Int' is unused}}
// expected-warning@-2 {{result of call to 'flatMap' is unused}}
// rdar://problem/30271695
_ = ["hi"].flatMap { $0.isEmpty ? nil : $0 }
// rdar://problem/32432145 - compiler should emit fixit to remove "_ in" in closures if 0 parameters is expected
func r32432145(_ a: () -> ()) {}
r32432145 { _ in let _ = 42 } // Ok in Swift 3
r32432145 { _ in // Ok in Swift 3
print("answer is 42")
}
r32432145 { _,_ in
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 2 were used in closure body}} {{13-19=}}
print("answer is 42")
}
// rdar://problem/30106822 - Swift ignores type error in closure and presents a bogus error about the caller
[1, 2].first { $0.foo = 3 }
// expected-error@-1 {{value of type 'Int' has no member 'foo'}}
// rdar://problem/32433193, SR-5030 - Higher-order function diagnostic mentions the wrong contextual type conversion problem
protocol A_SR_5030 {
associatedtype Value
func map<U>(_ t : @escaping (Self.Value) -> U) -> B_SR_5030<U>
}
struct B_SR_5030<T> : A_SR_5030 {
typealias Value = T
func map<U>(_ t : @escaping (T) -> U) -> B_SR_5030<U> { fatalError() }
}
func sr5030_exFalso<T>() -> T {
fatalError()
}
extension A_SR_5030 {
func foo() -> B_SR_5030<Int> {
let tt : B_SR_5030<Int> = sr5030_exFalso()
return tt.map { x in (idx: x) }
// expected-error@-1 {{cannot convert value of type '(idx: (Int))' to closure result type 'Int'}}
}
}
| 80532990141fc630df15d32015d35c16 | 33.429084 | 254 | 0.637117 | false | false | false | false |
RMizin/PigeonMessenger-project | refs/heads/main | FalconMessenger/Supporting Files/UIComponents/TypingIndicator/TypingBubble.swift | gpl-3.0 | 1 | /*
MIT License
Copyright (c) 2017-2018 MessageKit
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
/// A subclass of `UIView` that mimics the iMessage typing bubble
open class TypingBubble: UIView {
// MARK: - Properties
open var isPulseEnabled: Bool = true
public private(set) var isAnimating: Bool = false
open override var backgroundColor: UIColor? {
set {
[contentBubble, cornerBubble, tinyBubble].forEach { $0.backgroundColor = newValue }
}
get {
return contentBubble.backgroundColor
}
}
private struct AnimationKeys {
static let pulse = "typingBubble.pulse"
}
// MARK: - Subviews
/// The indicator used to display the typing animation.
public let typingIndicator = TypingIndicator()
public let contentBubble = UIView()
public let cornerBubble = BubbleCircle()
public let tinyBubble = BubbleCircle()
// MARK: - Animation Layers
open var contentPulseAnimationLayer: CABasicAnimation {
let animation = CABasicAnimation(keyPath: "transform.scale")
animation.fromValue = 1
animation.toValue = 1.04
animation.duration = 1
animation.repeatCount = .infinity
animation.autoreverses = true
return animation
}
open var circlePulseAnimationLayer: CABasicAnimation {
let animation = CABasicAnimation(keyPath: "transform.scale")
animation.fromValue = 1
animation.toValue = 1.1
animation.duration = 0.5
animation.repeatCount = .infinity
animation.autoreverses = true
return animation
}
public override init(frame: CGRect) {
super.init(frame: frame)
setupSubviews()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupSubviews()
}
open func setupSubviews() {
addSubview(tinyBubble)
addSubview(cornerBubble)
addSubview(contentBubble)
contentBubble.addSubview(typingIndicator)
backgroundColor = .white
}
// MARK: - Layout
open override func layoutSubviews() {
super.layoutSubviews()
// To maintain the iMessage like bubble the width:height ratio of the frame
// must be close to 1.65
let ratio = bounds.width / bounds.height
let extraRightInset = bounds.width - 1.65/ratio*bounds.width
let tinyBubbleRadius: CGFloat = bounds.height / 6
tinyBubble.frame = CGRect(x: 0,
y: bounds.height - tinyBubbleRadius,
width: tinyBubbleRadius,
height: tinyBubbleRadius)
let cornerBubbleRadius = tinyBubbleRadius * 2
let offset: CGFloat = tinyBubbleRadius / 6
cornerBubble.frame = CGRect(x: tinyBubbleRadius - offset,
y: bounds.height - (1.5 * cornerBubbleRadius) + offset,
width: cornerBubbleRadius,
height: cornerBubbleRadius)
let contentBubbleFrame = CGRect(x: tinyBubbleRadius + offset,
y: 0,
width: bounds.width - (tinyBubbleRadius + offset) - extraRightInset,
height: bounds.height - (tinyBubbleRadius + offset))
let contentBubbleFrameCornerRadius = contentBubbleFrame.height / 2
contentBubble.frame = contentBubbleFrame
contentBubble.layer.cornerRadius = contentBubbleFrameCornerRadius
let insets = UIEdgeInsets(top: offset, left: contentBubbleFrameCornerRadius / 1.25, bottom: offset, right: contentBubbleFrameCornerRadius / 1.25)
typingIndicator.frame = contentBubble.bounds.inset(by: insets)// UIEdgeInsetsInsetRect(contentBubble.bounds, insets)
}
// MARK: - Animation API
open func startAnimating() {
defer { isAnimating = true }
guard !isAnimating else { return }
typingIndicator.startAnimating()
if isPulseEnabled {
contentBubble.layer.add(contentPulseAnimationLayer, forKey: AnimationKeys.pulse)
[cornerBubble, tinyBubble].forEach { $0.layer.add(circlePulseAnimationLayer, forKey: AnimationKeys.pulse) }
}
}
open func stopAnimating() {
defer { isAnimating = false }
guard isAnimating else { return }
typingIndicator.stopAnimating()
[contentBubble, cornerBubble, tinyBubble].forEach { $0.layer.removeAnimation(forKey: AnimationKeys.pulse) }
}
}
| f07c6707211a0eb610c3e665326f21c7 | 36.032258 | 153 | 0.643728 | false | false | false | false |
BennyHarv3/habitica-ios | refs/heads/master | HabitRPG/TableviewCells/YesterdailyTaskCell.swift | gpl-3.0 | 1 | //
// File.swift
// Habitica
//
// Created by Phillip on 08.06.17.
// Copyright © 2017 Phillip Thelen. All rights reserved.
//
import UIKit
class YesterdailyTaskCell: UITableViewCell {
@IBOutlet weak var wrapperView: UIView!
@IBOutlet weak var checkbox: HRPGCheckBoxView!
@IBOutlet weak var titleTextView: UILabel!
@IBOutlet weak var checklistStackview: UIStackView!
var onChecklistItemChecked: ((ChecklistItem) -> Void)?
var checklistItems: [ChecklistItem]?
override func awakeFromNib() {
super.awakeFromNib()
self.selectionStyle = .none
self.wrapperView.layer.borderWidth = 1
self.wrapperView.layer.borderColor = UIColor.lightGray.cgColor
}
func configure(task: Task) {
checkbox.configure(for: task)
titleTextView.text = task.text?.unicodeEmoji
checklistStackview.subviews.forEach { view in
view.removeFromSuperview()
}
guard let checklist = task.checklist else {
return
}
checklistItems = checklist.array as? [ChecklistItem]
for item in checklist {
if let view = UIView.fromNib(nibName: "YesterdailyChecklistItem"), let checklistItem = item as? ChecklistItem {
let label = view.viewWithTag(2) as? UILabel
label?.text = checklistItem.text.unicodeEmoji
let checkbox = view.viewWithTag(1) as? HRPGCheckBoxView
checkbox?.configure(for: checklistItem, for: task)
checkbox?.backgroundColor = UIColor.gray700()
checklistStackview.addArrangedSubview(view)
let recognizer = UITapGestureRecognizer(target: self, action:#selector(YesterdailyTaskCell.handleChecklistTap(recognizer:)))
view.addGestureRecognizer(recognizer)
}
}
}
override func layoutSubviews() {
super.layoutSubviews()
}
func handleChecklistTap(recognizer: UITapGestureRecognizer) {
for (index, view) in checklistStackview.arrangedSubviews.enumerated() where view == recognizer.view {
if let checked = self.onChecklistItemChecked, let item = checklistItems?[index] {
checked(item)
}
return
}
}
}
| 5be57af21a06b97cc0ba0b03fbc90335 | 33.268657 | 140 | 0.641115 | false | false | false | false |
hassanabidpk/umapit_ios | refs/heads/master | uMAPit/controllers/CommentListViewController.swift | mit | 1 | //
// CommentListViewController.swift
// uMAPit
//
// Created by Hassan Abid on 04/03/2017.
// Copyright © 2017 uMAPit. All rights reserved.
//
import Foundation
import SwiftyJSON
import RealmSwift
import Kingfisher
import Alamofire
import SlackTextViewController
#if DEBUG
let COMMENTS_LIST_URL = "http://localhost:8000/place/api/v1/comments/"
#else
let COMMENTS_LIST_URL = "https://umapit.azurewebsites.net/place/api/v1/comments/"
#endif
class CommentListViewController: SLKTextViewController {
//MARK : - Propeties
var activityIndicatorView: UIActivityIndicatorView!
var realm: Realm!
var commentsResult: Results<Comment>?
var notificationToken: NotificationToken?
var commentPlace: Place?
var pipWindow: UIWindow?
override var tableView: UITableView {
get {
return super.tableView!
}
}
// MARK: - Initialisation
override class func tableViewStyle(for decoder: NSCoder) -> UITableViewStyle {
return .plain
}
func commonInit() {
NotificationCenter.default.addObserver(self.tableView, selector: #selector(UITableView.reloadData), name: NSNotification.Name.UIContentSizeCategoryDidChange, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(CommentListViewController.textInputbarDidMove(_:)), name: NSNotification.Name.SLKTextInputbarDidMove, object: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.commonInit()
setUI()
realm = try! Realm()
// Set realm notification block
notificationToken = realm.addNotificationBlock { [unowned self] note, realm in
self.tableView.reloadData()
}
getPlaceComments()
}
func setUI() {
activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray)
self.tableView.backgroundView = activityIndicatorView
// SLKTVC's configuration
self.bounces = true
self.shakeToClearEnabled = true
self.isKeyboardPanningEnabled = true
self.shouldScrollToBottomAfterKeyboardShows = false
self.isInverted = false
self.leftButton.setImage(UIImage(named: "icn_upload"), for: UIControlState())
self.leftButton.tintColor = UIColor.gray
self.rightButton.setTitle(NSLocalizedString("Send", comment: ""), for: UIControlState())
self.textInputbar.autoHideRightButton = true
self.textInputbar.maxCharCount = 256
self.textInputbar.counterStyle = .split
self.textInputbar.counterPosition = .top
self.textInputbar.editorTitle.textColor = UIColor.darkGray
self.textInputbar.editorLeftButton.tintColor = UIColor(red: 0/255, green: 122/255, blue: 255/255, alpha: 1)
self.textInputbar.editorRightButton.tintColor = UIColor(red: 0/255, green: 122/255, blue: 255/255, alpha: 1)
self.tableView.separatorStyle = .none
self.tableView.register(MessageTableViewCell.classForCoder(), forCellReuseIdentifier: CommentCellIdentifier)
self.autoCompletionView.register(MessageTableViewCell.classForCoder(), forCellReuseIdentifier: AutoCompletionCellIdentifier)
self.registerPrefixes(forAutoCompletion: ["@", "#", ":", "+:", "/"])
self.textView.placeholder = "Add a comment...";
self.textView.registerMarkdownFormattingSymbol("*", withTitle: "Bold")
self.textView.registerMarkdownFormattingSymbol("_", withTitle: "Italics")
self.textView.registerMarkdownFormattingSymbol("~", withTitle: "Strike")
self.textView.registerMarkdownFormattingSymbol("`", withTitle: "Code")
self.textView.registerMarkdownFormattingSymbol("```", withTitle: "Preformatted")
self.textView.registerMarkdownFormattingSymbol(">", withTitle: "Quote")
let refreshItem = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(CommentListViewController.toggleRefreshButton(_:)))
self.navigationItem.rightBarButtonItem = refreshItem
}
// MARK: - UITableViewDataSource Methods
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
return self.commentCellForRowAtIndexPath(indexPath)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let result = commentsResult {
return result.count
}
return 0
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if tableView == self.tableView {
if let result = commentsResult {
let comment = result[indexPath.row]
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineBreakMode = .byWordWrapping
paragraphStyle.alignment = .left
let pointSize = MessageTableViewCell.defaultFontSize()
let attributes = [
NSFontAttributeName : UIFont.systemFont(ofSize: pointSize),
NSParagraphStyleAttributeName : paragraphStyle
]
var width = tableView.frame.width-kMessageTableViewCellAvatarHeight
width -= 25.0
let titleBounds = ("\(comment.user!.first_name) \(comment.user!.last_name)" as NSString).boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
let bodyBounds = (comment.text as NSString).boundingRect(with: CGSize(width: width, height: CGFloat.greatestFiniteMagnitude), options: .usesLineFragmentOrigin, attributes: attributes, context: nil)
if comment.text.characters.count == 0 {
return 0
}
var height = titleBounds.height
height += bodyBounds.height
height += 40
if height < kMessageTableViewCellMinimumHeight {
height = kMessageTableViewCellMinimumHeight
}
return height
}
else {
return kMessageTableViewCellMinimumHeight
}
} else {
return kMessageTableViewCellMinimumHeight
}
}
//MARK: - Helper methods
func commentCellForRowAtIndexPath(_ indexPath: IndexPath) -> MessageTableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: CommentCellIdentifier, for: indexPath) as! MessageTableViewCell
if let result = commentsResult {
let object = result[indexPath.row]
if let first_name = object.user?.first_name, let last_name = object.user?.last_name {
cell.titleLabel.text = "\(first_name) \(last_name)"
}
cell.bodyLabel.text = object.text
cell.indexPath = indexPath
cell.usedForMessage = true
// Cells must inherit the table view's transform
// This is very important, since the main table view may be inverted
cell.transform = self.tableView.transform
let hash = object.user?.email.md5
cell.thumbnailView.kf.setImage(with: URL(string: "\(ProfileViewController.GRAVATAR_IMAGE_URL)\(hash!)?s=150")!,
placeholder: nil,
options: [.transition(.fade(1))],
progressBlock: nil,
completionHandler: nil)
}
return cell
}
func togglePIPWindow(_ sender: AnyObject) {
if self.pipWindow == nil {
self.showPIPWindow(sender)
}
else {
self.hidePIPWindow(sender)
}
}
func showPIPWindow(_ sender: AnyObject) {
var frame = CGRect(x: self.view.frame.width - 60.0, y: 0.0, width: 50.0, height: 50.0)
frame.origin.y = self.textInputbar.frame.minY - 60.0
self.pipWindow = UIWindow(frame: frame)
self.pipWindow?.backgroundColor = UIColor.black
self.pipWindow?.layer.cornerRadius = 10
self.pipWindow?.layer.masksToBounds = true
self.pipWindow?.isHidden = false
self.pipWindow?.alpha = 0.0
UIApplication.shared.keyWindow?.addSubview(self.pipWindow!)
UIView.animate(withDuration: 0.25, animations: { [unowned self] () -> Void in
self.pipWindow?.alpha = 1.0
})
}
func hidePIPWindow(_ sender: AnyObject) {
UIView.animate(withDuration: 0.3, animations: { [unowned self] () -> Void in
self.pipWindow?.alpha = 0.0
}, completion: { [unowned self] (finished) -> Void in
self.pipWindow?.isHidden = true
self.pipWindow = nil
})
}
func textInputbarDidMove(_ note: Notification) {
guard let pipWindow = self.pipWindow else {
return
}
guard let userInfo = (note as NSNotification).userInfo else {
return
}
guard let value = userInfo["origin"] as? NSValue else {
return
}
var frame = pipWindow.frame
frame.origin.y = value.cgPointValue.y - 60.0
pipWindow.frame = frame
}
func getPlaceComments() {
self.deleteCommentsForPlace()
activityIndicatorView.startAnimating()
if let place = commentPlace {
// let predicate = NSPredicate(format: "place = %@", "\(place)")
commentsResult = realm.objects(Comment.self)
.filter("place == %@", place)
.sorted(byKeyPath: "created_at", ascending: false)
if ((commentsResult?.count)! > 0 ) {
print("comments Result found in DB");
self.activityIndicatorView.stopAnimating()
} else {
let userDefaults = UserDefaults.standard
let strToken = userDefaults.value(forKey: "userToken")
let authToken = "Token \(strToken!)"
print("authToken : \(authToken)")
let headers = [
"Authorization": authToken
]
Alamofire.request("\(COMMENTS_LIST_URL)\(place.id)", parameters: nil, encoding: JSONEncoding.default,
headers: headers)
.responseJSON { response in
debugPrint(response)
if response.result.isSuccess {
if let comments_raw = response.result.value {
let json = JSON(comments_raw)
print("json: \(json)")
if let error = json["detail"].string {
print("couldn't fetch places : \(error)")
} else {
if(json.count > 0 ) {
self.addCommentsinBackground(JSON(comments_raw).array)
} else {
print("No comments added yet")
}
}
}
}
self.activityIndicatorView.stopAnimating()
}
}
}
}
func addCommentsinBackground(_ data : Array<JSON>!) {
DispatchQueue.global().async {
print("writing new comments to REALM db")
let realm = try! Realm()
realm.beginWrite()
for subJson in data {
let comment = realm.create(Comment.self, value: ["text": subJson["text"].stringValue,
"created_at": self.dateFromStringConverter(date: subJson["created_at"].stringValue)!,
"id": subJson["id"].int!,
"approved_comment": subJson["approved_comment"].bool!])
let user = subJson["user"]
let existing_user = try! Realm().objects(User.self).filter("id = \(user["id"].int!)")
if(existing_user.count < 1) {
let place_user = realm.create(User.self, value : ["id" : user["id"].int!,
"username": user["username"].stringValue,
"first_name": user["first_name"].stringValue,
"last_name": user["last_name"].stringValue,
"email": user["email"].stringValue] )
comment.user = place_user
} else {
comment.user = existing_user[0]
}
let place_id = subJson["place"].int!
let existing_place = try! Realm().objects(Place.self).filter("id = \(place_id)")
// if let place = self.commentPlace {
comment.place = existing_place[0]
// }
}
try! realm.commitWrite()
}
}
func dateFromStringConverter(date: String)-> Date? {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ" //or you can use "yyyy-MM-dd'T'HH:mm:ssX"
return dateFormatter.date(from: date)
}
// MARK - Overriden methods
override func didPressRightButton(_ sender: Any?) {
print("Post comment")
// This little trick validates any pending auto-correction or auto-spelling just after hitting the 'Send' button
// self.textView.refreshFirstResponder()
if(self.textView.text.characters.count > 0) {
let indexPath = IndexPath(row: 0, section: 0)
let rowAnimation: UITableViewRowAnimation = self.isInverted ? .bottom : .top
let scrollPosition: UITableViewScrollPosition = self.isInverted ? .bottom : .top
let userDefaults = UserDefaults.standard
let strToken = userDefaults.value(forKey: "userToken")
let authToken = "Token \(strToken!)"
let headers = [
"Authorization": authToken
]
let place_id = commentPlace!.id
print("comment for place_id \(place_id) with text : \(self.textView.text!)")
let parameters: Parameters = ["place": place_id,
"text": self.textView.text!,
"approved_comment" : true]
Alamofire.request("\(COMMENTS_LIST_URL)\(place_id)/",
method: .post,
parameters: parameters,
encoding: JSONEncoding.default,
headers: headers).responseJSON { response in
debugPrint(response)
if let commentStatus = response.result.value {
let json = JSON(commentStatus)
print("comment JSON: \(json)")
print("writing new comments to REALM db")
let realm = try! Realm()
realm.beginWrite()
let comment = realm.create(Comment.self, value: ["text": json["text"].stringValue,
"created_at": self.dateFromStringConverter(date: json["created_at"].stringValue)!,
"id": json["id"].int!,
"approved_comment": json["approved_comment"].bool!])
let user = json["user"]
let existing_user = try! Realm().objects(User.self).filter("id = \(user["id"].int!)")
if(existing_user.count < 1) {
let place_user = realm.create(User.self, value : ["id" : user["id"].int!,
"username": user["username"].stringValue,
"first_name": user["first_name"].stringValue,
"last_name": user["last_name"].stringValue,
"email": user["email"].stringValue] )
comment.user = place_user
} else {
comment.user = existing_user[0]
}
let place_id = json["place"].int!
let existing_place = try! Realm().objects(Place.self).filter("id = \(place_id)")
comment.place = existing_place[0]
try! realm.commitWrite()
self.tableView.scrollToRow(at: indexPath, at: scrollPosition, animated: true)
// Fixes the cell from blinking (because of the transform, when using translucent cells)
// See https://github.com/slackhq/SlackTextViewController/issues/94#issuecomment-69929927
self.tableView.reloadRows(at: [indexPath], with: .automatic)
super.didPressRightButton(sender)
} else {
print("error posting new comments")
}
}
}
}
// - MARK- Actions
func toggleRefreshButton(_ sender: AnyObject) {
self.getPlaceComments()
}
func deleteCommentsForPlace() {
try! realm.write {
if let results = self.commentsResult {
realm.delete(results)
}
}
}
}
| d28bfb8ec6bd215b9ea0029835d4655d | 36.98556 | 258 | 0.473294 | false | false | false | false |
tkremenek/swift | refs/heads/master | test/refactoring/ConvertAsync/convert_result.swift | apache-2.0 | 1 | func simple(_ completion: (Result<String, Error>) -> Void) { }
func simpleWithArg(_ arg: Int, _ completion: (Result<String, Error>) -> Void) { }
func noError(_ completion: (Result<String, Never>) -> Void) { }
func test(_ str: String) -> Bool { return false }
// RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-RESULT %s
func voidResult(completion: (Result<Void, Never>) -> Void) {}
// VOID-RESULT: func voidResult() async {}
// RUN: %refactor -add-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix VOID-AND-ERROR-RESULT %s
func voidAndErrorResult(completion: (Result<Void, Error>) -> Void) {}
// VOID-AND-ERROR-RESULT: func voidAndErrorResult() async throws {}
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=SIMPLE %s
simple { res in
print("result \(res)")
}
// SIMPLE: let res = try await simple()
// SIMPLE-NEXT: print("result \(<#res#>)")
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NOERROR %s
noError { res in
print("result \(res)")
}
// NOERROR: let res = await noError()
// NOERROR-NEXT: print("result \(<#res#>)")
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DOBLOCK %s
simple { res in
print("before")
switch res {
case .success(let str):
print("result \(str)")
case .failure(let err):
print("error \(err)")
}
print("after")
}
// DOBLOCK: do {
// DOBLOCK-NEXT: let str = try await simple()
// DOBLOCK-NEXT: print("before")
// DOBLOCK-NEXT: print("result \(str)")
// DOBLOCK-NEXT: print("after")
// DOBLOCK-NEXT: } catch let err {
// DOBLOCK-NEXT: print("error \(err)")
// DOBLOCK-NEXT: }
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DOBLOCK %s
simple { res in
print("before")
if case .success(let str) = res {
print("result \(str)")
} else if case .failure(let err) = res {
print("error \(err)")
}
print("after")
}
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DOBLOCK %s
simple { res in
print("before")
switch res {
case .success(let str):
print("result \(str)")
break
case .failure(let err):
print("error \(err)")
break
}
print("after")
}
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DOBLOCK %s
simple { res in
print("before")
switch res {
case .success(let str):
print("result \(str)")
return
case .failure(let err):
print("error \(err)")
return
}
print("after")
}
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=SUCCESS %s
simple { res in
print("before")
if case .success(let str) = res {
print("result \(str)")
}
print("after")
}
// SUCCESS: convert_result.swift
// SUCCESS-NEXT: let str = try await simple()
// SUCCESS-NEXT: print("before")
// SUCCESS-NEXT: print("result \(str)")
// SUCCESS-NEXT: print("after")
// SUCCESS-NOT: }
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=SUCCESS %s
simple { res in
print("before")
guard case .success(let str) = res else {
return
}
print("result \(str)")
print("after")
}
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DOBLOCKUNBOUND %s
simple { res in
print("before")
guard case .success(let str) = res else {
print("err")
return
}
print("result \(str)")
print("after")
}
// DOBLOCKUNBOUND: do {
// DOBLOCKUNBOUND-NEXT: let str = try await simple()
// DOBLOCKUNBOUND-NEXT: print("before")
// DOBLOCKUNBOUND-NEXT: print("result \(str)")
// DOBLOCKUNBOUND-NEXT: print("after")
// DOBLOCKUNBOUND-NEXT: } catch {
// DOBLOCKUNBOUND-NEXT: print("err")
// DOBLOCKUNBOUND-NEXT: }
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=SUCCESS %s
simple { res in
print("before")
if let str = try? res.get() {
print("result \(str)")
}
print("after")
}
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=DOBLOCKUNBOUND %s
simple { res in
print("before")
guard let str = try? res.get() else {
print("err")
return
}
print("result \(str)")
print("after")
}
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=UNKNOWN %s
simple { res in
print("before \(res)")
if case .success(let str) = res {
print("result \(str) \(try! res.get())")
}
print("after")
}
// UNKNOWN: convert_result.swift
// UNKNOWN-NEXT: let str = try await simple()
// UNKNOWN-NEXT: print("before \(<#str#>)")
// UNKNOWN-NEXT: print("result \(str) \(try! <#str#>.get())")
// UNKNOWN-NEXT: print("after")
// UNKNOWN-NOT: }
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=UNKNOWNUNBOUND %s
simple { res in
print("before \(res)")
if case .success = res {
print("result \(res) \(try! res.get())")
}
print("after")
}
// UNKNOWNUNBOUND: convert_result.swift
// UNKNOWNUNBOUND-NEXT: let res = try await simple()
// UNKNOWNUNBOUND-NEXT: print("before \(<#res#>)")
// UNKNOWNUNBOUND-NEXT: print("result \(<#res#>) \(try! <#res#>.get())")
// UNKNOWNUNBOUND-NEXT: print("after")
// UNKNOWN-NOT: }
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=MULTIPLE-BINDS %s
simple { res in
print("before")
if case .success(let str) = res {
print("result \(str)")
}
if case .success(let str2) = res {
print("result \(str2)")
}
print("after")
}
// MULTIPLE-BINDS: convert_result.swift
// MULTIPLE-BINDS-NEXT: let str = try await simple()
// MULTIPLE-BINDS-NEXT: print("before")
// MULTIPLE-BINDS-NEXT: print("result \(str)")
// MULTIPLE-BINDS-NEXT: print("result \(str)")
// MULTIPLE-BINDS-NEXT: print("after")
// MULTIPLE-BINDS-NOT: }
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
simple { res in
print("before")
switch res {
case .success(let str):
print("result \(str)")
case .failure(let err):
print("error \(err)")
default:
print("default")
}
print("after")
}
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
simple { res in
print("before")
switch res {
case .success(let str):
print("result \(str)")
default:
print("err")
}
print("after")
}
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
simple { res in
print("before")
switch res {
case .success, .failure:
print("either")
}
print("after")
}
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
simple { res in
print("before")
switch res {
case .success, .failure:
print("either")
}
print("after")
}
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
simple { res in
print("before")
switch res {
case .success:
fallthrough
case .failure:
print("either")
}
print("after")
}
// RUN: not %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1
simple { res in
print("before")
switch res {
case .success(let str) where str.hasPrefix("match"):
print("pattern matched result \(str)")
case .success(let str):
print("result \(str)")
case .failure(let err):
print("error \(err)")
}
print("after")
}
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NESTEDRET %s
simple { res in
print("before")
switch res {
case .success(let str):
if test(str) {
return
}
print("result \(str)")
case .failure:
break
}
print("after")
}
// NESTEDRET: convert_result.swift
// NESTEDRET-NEXT: let str = try await simple()
// NESTEDRET-NEXT: print("before")
// NESTEDRET-NEXT: if test(str) {
// NESTEDRET-NEXT: <#return#>
// NESTEDRET-NEXT: }
// NESTEDRET-NEXT: print("result \(str)")
// NESTEDRET-NEXT: print("after")
// NESTEDRET-NOT: }
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NESTEDBREAK %s
simple { res in
print("before")
switch res {
case .success(let str):
if test(str) {
break
}
print("result \(str)")
case .failure:
break
}
print("after")
}
// NESTEDBREAK: convert_result.swift
// NESTEDBREAK-NEXT: let str = try await simple()
// NESTEDBREAK-NEXT: print("before")
// NESTEDBREAK-NEXT: if test(str) {
// NESTEDBREAK-NEXT: <#break#>
// NESTEDBREAK-NEXT: }
// NESTEDBREAK-NEXT: print("result \(str)")
// NESTEDBREAK-NEXT: print("after")
// NESTEDBREAK-NOT: }
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=NESTEDBREAK-COMMENT %s
simple { res in // a
// b
print("before")
// c
switch res {
// d
case .success(let str): // e
if test(str) {
// f
break
// g
}
// h
print("result \(str)")
// i
case .failure:
// j
break
// k
}
// l
print("after")
// m
}
// NESTEDBREAK-COMMENT: let str = try await simple()
// NESTEDBREAK-COMMENT-NEXT: // a
// NESTEDBREAK-COMMENT-NEXT: // b
// NESTEDBREAK-COMMENT-NEXT: print("before")
// NESTEDBREAK-COMMENT-NEXT: // c
// NESTEDBREAK-COMMENT-NEXT: // d
// NESTEDBREAK-COMMENT-NEXT: // e
// NESTEDBREAK-COMMENT-NEXT: if test(str) {
// NESTEDBREAK-COMMENT-NEXT: // f
// NESTEDBREAK-COMMENT-NEXT: <#break#>
// NESTEDBREAK-COMMENT-NEXT: // g
// NESTEDBREAK-COMMENT-NEXT: }
// NESTEDBREAK-COMMENT-NEXT: // h
// NESTEDBREAK-COMMENT-NEXT: print("result \(str)")
// NESTEDBREAK-COMMENT-NEXT: // i
// NESTEDBREAK-COMMENT-NEXT: // j
// NESTEDBREAK-COMMENT-NEXT: // k
// NESTEDBREAK-COMMENT-NEXT: // l
// NESTEDBREAK-COMMENT-NEXT: print("after")
// NESTEDBREAK-COMMENT-NEXT: // m
// NESTEDBREAK-COMMENT-EMPTY:
// NESTEDBREAK-COMMENT-NOT: }
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=ERROR-BLOCK-COMMENT %s
simple { res in
// a
print("before")
// b
switch res {
case .success(let str):
// c
print("result \(str)")
// d
case .failure:
// e
print("fail")
// f
return
// g
}
// h
print("after")
// i
}
// ERROR-BLOCK-COMMENT: do {
// ERROR-BLOCK-COMMENT-NEXT: let str = try await simple()
// ERROR-BLOCK-COMMENT-NEXT: // a
// ERROR-BLOCK-COMMENT-NEXT: print("before")
// ERROR-BLOCK-COMMENT-NEXT: // b
// ERROR-BLOCK-COMMENT-NEXT: // c
// ERROR-BLOCK-COMMENT-NEXT: print("result \(str)")
// ERROR-BLOCK-COMMENT-NEXT: // d
// ERROR-BLOCK-COMMENT-NEXT: // h
// ERROR-BLOCK-COMMENT-NEXT: print("after")
// ERROR-BLOCK-COMMENT-NEXT: // i
// ERROR-BLOCK-COMMENT-EMPTY:
// ERROR-BLOCK-COMMENT-NEXT: } catch {
// ERROR-BLOCK-COMMENT-NEXT: // e
// ERROR-BLOCK-COMMENT-NEXT: print("fail")
// ERROR-BLOCK-COMMENT-NEXT: // f
// ERROR-BLOCK-COMMENT-NEXT: // g
// ERROR-BLOCK-COMMENT-NEXT: {{ }}
// ERROR-BLOCK-COMMENT-NEXT: }
// ERROR-BLOCK-COMMENT-NOT: }
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=VOID-RESULT-CALL %s
voidResult { res in
print(res)
}
// VOID-RESULT-CALL: {{^}}await voidResult()
// VOID-RESULT-CALL: {{^}}print(<#res#>)
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=VOID-AND-ERROR-RESULT-CALL %s
voidAndErrorResult { res in
print(res)
}
// VOID-AND-ERROR-RESULT-CALL: {{^}}try await voidAndErrorResult()
// VOID-AND-ERROR-RESULT-CALL: {{^}}print(<#res#>)
// Make sure we ignore an unrelated switch.
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=IGNORE-UNRELATED %s
simple { res in
print("before")
switch Bool.random() {
case true:
break
case false:
break
}
print("after")
}
// IGNORE-UNRELATED: let res = try await simple()
// IGNORE-UNRELATED-NEXT: print("before")
// IGNORE-UNRELATED-NEXT: switch Bool.random() {
// IGNORE-UNRELATED-NEXT: case true:
// IGNORE-UNRELATED-NEXT: {{^}} break{{$}}
// IGNORE-UNRELATED-NEXT: case false:
// IGNORE-UNRELATED-NEXT: {{^}} break{{$}}
// IGNORE-UNRELATED-NEXT: }
// IGNORE-UNRELATED-NEXT: print("after")
// RUN: %refactor -convert-call-to-async-alternative -dump-text -source-filename %s -pos=%(line+1):1 | %FileCheck -check-prefix=BREAK-RET-PLACEHOLDER %s
simpleWithArg({ return 0 }()) { res in
switch res {
case .success:
if .random() { break }
x: if .random() { break x }
case .failure:
break
}
func foo<T>(_ x: T) {
if .random() { return }
}
foo(res)
let fn = {
if .random() { return }
return
}
fn()
_ = { return }()
switch Bool.random() {
case true:
break
case false:
if .random() { break }
y: if .random() { break y }
return
}
x: if .random() {
break x
}
if .random() { return }
}
// Make sure we replace lifted break/returns with placeholders, but keep nested
// break/returns in e.g closures or labelled control flow in place.
// BREAK-RET-PLACEHOLDER: let res = try await simpleWithArg({ return 0 }())
// BREAK-RET-PLACEHOLDER-NEXT: if .random() { <#break#> }
// BREAK-RET-PLACEHOLDER-NEXT: x: if .random() { break x }
// BREAK-RET-PLACEHOLDER-NEXT: func foo<T>(_ x: T) {
// BREAK-RET-PLACEHOLDER-NEXT: if .random() { return }
// BREAK-RET-PLACEHOLDER-NEXT: }
// BREAK-RET-PLACEHOLDER-NEXT: foo(<#res#>)
// BREAK-RET-PLACEHOLDER-NEXT: let fn = {
// BREAK-RET-PLACEHOLDER-NEXT: if .random() { return }
// BREAK-RET-PLACEHOLDER-NEXT: {{^}} return{{$}}
// BREAK-RET-PLACEHOLDER-NEXT: }
// BREAK-RET-PLACEHOLDER-NEXT: fn()
// BREAK-RET-PLACEHOLDER-NEXT: _ = { return }()
// BREAK-RET-PLACEHOLDER-NEXT: switch Bool.random() {
// BREAK-RET-PLACEHOLDER-NEXT: case true:
// BREAK-RET-PLACEHOLDER-NEXT: {{^}} break{{$}}
// BREAK-RET-PLACEHOLDER-NEXT: case false:
// BREAK-RET-PLACEHOLDER-NEXT: if .random() { break }
// BREAK-RET-PLACEHOLDER-NEXT: y: if .random() { break y }
// BREAK-RET-PLACEHOLDER-NEXT: <#return#>
// BREAK-RET-PLACEHOLDER-NEXT: }
// BREAK-RET-PLACEHOLDER-NEXT: x: if .random() {
// BREAK-RET-PLACEHOLDER-NEXT: {{^}} break x{{$}}
// BREAK-RET-PLACEHOLDER-NEXT: }
// BREAK-RET-PLACEHOLDER-NEXT: if .random() { <#return#> }
| 43654709e37637b4a9745fcb37d1bdb2 | 28.741683 | 157 | 0.642321 | false | false | false | false |
yangchenghu/actor-platform | refs/heads/master | actor-apps/app-ios/ActorSwift/Strings.swift | mit | 2 | //
// Copyright (c) 2014-2015 Actor LLC. <https://actor.im>
//
import Foundation
extension String {
var length: Int { return self.characters.count }
func trim() -> String {
return stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet());
}
subscript (i: Int) -> Character {
return self[self.startIndex.advancedBy(i)]
}
subscript (i: Int) -> String {
return String(self[i] as Character)
}
func first(count: Int) -> String {
let realCount = min(count, length);
return substringToIndex(startIndex.advancedBy(realCount));
}
func strip(set: NSCharacterSet) -> String {
return componentsSeparatedByCharactersInSet(set).joinWithSeparator("")
}
func replace(src: String, dest:String) -> String {
return stringByReplacingOccurrencesOfString(src, withString: dest, options: NSStringCompareOptions(), range: nil)
}
func toLong() -> Int64? {
return NSNumberFormatter().numberFromString(self)?.longLongValue
}
func toJLong() -> jlong {
return jlong(toLong()!)
}
func smallValue() -> String {
let trimmed = trim();
if (trimmed.isEmpty){
return "#";
}
let letters = NSCharacterSet.letterCharacterSet()
let res: String = self[0];
if (res.rangeOfCharacterFromSet(letters) != nil) {
return res.uppercaseString;
} else {
return "#";
}
}
func hasPrefixInWords(prefix: String) -> Bool {
var components = self.componentsSeparatedByString(" ")
for i in 0..<components.count {
if components[i].lowercaseString.hasPrefix(prefix.lowercaseString) {
return true
}
}
return false
}
func contains(text: String) -> Bool {
return self.rangeOfString(text, options: NSStringCompareOptions.CaseInsensitiveSearch, range: nil, locale: nil) != nil
}
func rangesOfString(text: String) -> [Range<String.Index>] {
var res = [Range<String.Index>]()
var searchRange = Range<String.Index>(start: self.startIndex, end: self.endIndex)
while true {
let found = self.rangeOfString(text, options: NSStringCompareOptions.CaseInsensitiveSearch, range: searchRange, locale: nil)
if found != nil {
res.append(found!)
searchRange = Range<String.Index>(start: found!.endIndex, end: self.endIndex)
} else {
break
}
}
return res
}
func repeatString(count: Int) -> String {
var res = ""
for _ in 0..<count {
res += self
}
return res
}
var asNS: NSString { return (self as NSString) }
}
extension NSAttributedString {
func append(text: NSAttributedString) -> NSAttributedString {
let res = NSMutableAttributedString()
res.appendAttributedString(self)
res.appendAttributedString(text)
return res
}
func append(text: String, font: UIFont) -> NSAttributedString {
return append(NSAttributedString(string: text, attributes: [NSFontAttributeName: font]))
}
convenience init(string: String, font: UIFont) {
self.init(string: string, attributes: [NSFontAttributeName: font])
}
}
extension NSMutableAttributedString {
func appendFont(font: UIFont) {
self.addAttribute(NSFontAttributeName, value: font, range: NSMakeRange(0, self.length))
}
func appendColor(color: UIColor) {
self.addAttribute(NSForegroundColorAttributeName, value: color.CGColor, range: NSMakeRange(0, self.length))
}
}
| 8b0acad160904fef32d6efa6759a93cf | 28.527132 | 136 | 0.601995 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/ImportResolution/Inputs/overload_vars.swift | apache-2.0 | 37 | public var something : Int = 1
public var ambiguousWithVar : Int = 2
public var scopedVar : Int = 3
public var localVar : Int = 4
public var scopedFunction : Int = 5
public var typeNameWins : Int = 6
public protocol HasFoo {
var foo: Int { get }
}
public protocol HasBar {
var bar: Int { get }
}
public class HasFooGeneric<T> {
public var foo: Int = 0
}
extension HasFooGeneric {
public var bar: Int { return 0 }
}
public class HasFooNonGeneric {
public var foo: Int = 0
}
extension HasFooNonGeneric {
public var bar: Int { return 0 }
}
| 0a6be5de04c625b7b09bfd066fb762fc | 16.40625 | 37 | 0.691203 | false | false | false | false |
Lordxen/MagistralSwift | refs/heads/master | Carthage/Checkouts/CryptoSwift/CryptoSwiftTests/Poly1305Tests.swift | mit | 2 | //
// Poly1305Tests.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 29/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
import XCTest
@testable import CryptoSwift
final class Poly1305Tests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testPoly1305() {
let key:Array<UInt8> = [0xdd,0xde,0xdf,0xe0,0xe1,0xe2,0xe3,0xe4,0xe5,0xe6,0xe7,0xe8,0xe9,0xea,0xeb,0xec,0xed,0xee,0xef,0xf0,0xf1,0xf2,0xf3,0xf4,0xf5,0xf6,0xf7,0xf8,0xf9,0xfa,0xfb,0xfc]
let msg:Array<UInt8> = [0x79,0x7a,0x7b,0x7c,0x7d,0x7e,0x7f,0x80,0x81,0x82,0x83,0x84,0x85,0x86,0x87,0x88,0x89,0x8a,0x8b,0x8c,0x8d,0x8e,0x8f,0x90,0x91,0x92,0x93,0x94,0x95,0x96,0x97,0x98,0x99,0x9a,0x9b,0x9c,0x9d,0x9e,0x9f,0xa0,0xa1,0xa2,0xa3,0xa4,0xa5,0xa6,0xa7,0xa8,0xa9,0xaa,0xab,0xac,0xad,0xae,0xaf,0xb0,0xb1,0xb2,0xb3,0xb4,0xb5,0xb6,0xb7,0xb8,0xb9,0xba,0xbb,0xbc,0xbd,0xbe,0xbf,0xc0,0xc1]
let expectedMac:Array<UInt8> = [0xdd,0xb9,0xda,0x7d,0xdd,0x5e,0x52,0x79,0x27,0x30,0xed,0x5c,0xda,0x5f,0x90,0xa4]
let mac = try! Authenticator.Poly1305(key: key).authenticate(msg)
XCTAssertEqual(mac, expectedMac, "Invalid authentication result")
// extensions
let msgData = NSData.withBytes(msg)
let mac2 = try! msgData.authenticate(Authenticator.Poly1305(key: key))
XCTAssertEqual(mac2, NSData.withBytes(expectedMac), "Invalid authentication result")
}
}
| 89cb421b7f8be72ef4b9f7fb49c13300 | 42.828571 | 397 | 0.697523 | false | true | false | false |
Mayfleet/SimpleChat | refs/heads/master | Frontend/iOS/SimpleChat/SimpleChat/Screens/Chat/SignUp/SignUpViewController.swift | mit | 1 | //
// Created by Maxim Pervushin on 10/03/16.
// Copyright (c) 2016 Maxim Pervushin. All rights reserved.
//
import UIKit
class SignUpViewController: UIViewController {
// MARK: SignUpViewController @IB
@IBOutlet weak var usernameTextField: UITextField?
@IBOutlet weak var passwordTextField: UITextField?
@IBOutlet weak var containerView: UIView?
@IBOutlet weak var containerToBottomLayoutConstraint: NSLayoutConstraint?
@IBAction func closeButtonAction(sender: AnyObject) {
onClose?()
}
@IBAction func signUpButtonAction(sender: AnyObject) {
didSignUp?(username: usernameTextField?.text, password: passwordTextField?.text)
}
@IBAction func tapGestureRecognizerAction(sender: AnyObject) {
if usernameTextField?.isFirstResponder() == true {
usernameTextField?.resignFirstResponder()
} else if passwordTextField?.isFirstResponder() == true {
passwordTextField?.resignFirstResponder()
}
}
// MARK: SignUpViewController
var onClose: (Void -> Void)?
var didSignUp: ((username: String?, password: String?) -> Void)?
private func keyboardWillChangeFrameNotification(notification: NSNotification) {
guard let
viewHeight = view?.bounds.size.height,
frameEnd = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue(),
animationDuration = notification.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval else {
return
}
view.layoutIfNeeded()
UIView.animateWithDuration(animationDuration) {
() -> Void in
self.containerToBottomLayoutConstraint?.constant = viewHeight - frameEnd.origin.y
self.view.layoutIfNeeded()
}
}
private func subscribe() {
NSNotificationCenter.defaultCenter().addObserverForName(UIKeyboardWillChangeFrameNotification, object: nil, queue: nil, usingBlock: keyboardWillChangeFrameNotification)
}
private func unsubscribe() {
NSNotificationCenter.defaultCenter().removeObserver(self, name: UIKeyboardWillChangeFrameNotification, object: nil)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
subscribe()
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
unsubscribe()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return .LightContent
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if traitCollection.horizontalSizeClass == .Compact {
return [.Portrait]
}
return [.All]
}
}
| f5d0838dac2bc40db57a3c1eb188f8fa | 32 | 176 | 0.691493 | false | false | false | false |
wireapp/wire-ios-data-model | refs/heads/develop | Source/Model/Confirmation/ZMMessageConfirmation.swift | gpl-3.0 | 1 | //
// Wire
// Copyright (C) 2016 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import CoreData
@objc public enum MessageConfirmationType: Int16 {
case delivered, read
static func convert(_ zmConfirmationType: Confirmation.TypeEnum) -> MessageConfirmationType {
switch zmConfirmationType {
case .delivered:
return .delivered
case .read:
return .read
}
}
}
@objc(ZMMessageConfirmation) @objcMembers
open class ZMMessageConfirmation: ZMManagedObject, ReadReceipt {
@NSManaged open var type: MessageConfirmationType
@NSManaged open var serverTimestamp: Date?
@NSManaged open var message: ZMMessage
@NSManaged open var user: ZMUser
public var userType: UserType {
return user
}
override open class func entityName() -> String {
return "MessageConfirmation"
}
open override var modifiedKeys: Set<AnyHashable>? {
get {
return Set()
} set {
// do nothing
}
}
/// Creates a ZMMessageConfirmation objects that holds a reference to a message that was confirmed and the user who confirmed it.
/// It can have 2 types: Delivered and Read depending on the confirmation type
@discardableResult
public static func createMessageConfirmations(_ confirmation: Confirmation, conversation: ZMConversation, updateEvent: ZMUpdateEvent) -> [ZMMessageConfirmation] {
let type = MessageConfirmationType.convert(confirmation.type)
guard
let managedObjectContext = conversation.managedObjectContext,
let senderUUID = updateEvent.senderUUID,
let serverTimestamp = updateEvent.timestamp
else {
return []
}
let sender = ZMUser.fetchOrCreate(with: senderUUID, domain: updateEvent.senderDomain, in: managedObjectContext)
let moreMessageIds = confirmation.moreMessageIds
let confirmedMesssageIds = ([confirmation.firstMessageID] + moreMessageIds).compactMap({ UUID(uuidString: $0) })
return confirmedMesssageIds.compactMap { confirmedMessageId in
guard let message = ZMMessage.fetch(withNonce: confirmedMessageId, for: conversation, in: managedObjectContext),
!message.confirmations.contains(where: { $0.user == sender && $0.type == type }) else { return nil }
return ZMMessageConfirmation(type: type, message: message, sender: sender, serverTimestamp: serverTimestamp, managedObjectContext: managedObjectContext)
}
}
convenience init(type: MessageConfirmationType, message: ZMMessage, sender: ZMUser, serverTimestamp: Date, managedObjectContext: NSManagedObjectContext) {
let entityDescription = NSEntityDescription.entity(forEntityName: ZMMessageConfirmation.entityName(), in: managedObjectContext)!
self.init(entity: entityDescription, insertInto: managedObjectContext)
self.message = message
self.user = sender
self.type = type
self.serverTimestamp = serverTimestamp
}
}
| dd9b40da22555e1ac07f6ffe44225d7d | 37.957895 | 166 | 0.705215 | false | false | false | false |
liuchuo/LeetCode-practice | refs/heads/master | Swift/21. Merge Two Sorted Lists.swift | gpl-3.0 | 1 | // 21. Merge Two Sorted Lists
// 24 ms, 60.98%
func mergeTwoLists(_ l1: ListNode?, _ l2: ListNode?) -> ListNode? {
var arr = [Int](), p1 = l1, p2 = l2, r = l1
while let q1 = p1, let q2 = p2 {
if q1.val < q2.val {
arr.append(q1.val)
p1 = q1.next
} else {
arr.append(q2.val)
p2 = q2.next
}
}
while let q1 = p1 {
arr.append(q1.val)
p1 = q1.next
if p1 == nil {
q1.next = l2
r = l1
}
}
while let q2 = p2 {
arr.append(q2.val)
p2 = q2.next
if p2 == nil {
q2.next = l1
r = l2
}
}
p1 = r
arr.forEach {
p1?.val = $0
p1 = p1?.next
}
return r
} | c1ae0d83a7c90d59e824d5d77a113bea | 19 | 67 | 0.39923 | false | false | false | false |
XSega/Words | refs/heads/master | Words/MeaningsAPI.swift | mit | 1 | //
// SkyengProduct.swift
// Words
//
// Created by Sergey Ilyushin on 20/07/2017.
// Copyright © 2017 Sergey Ilyushin. All rights reserved.
//
import Foundation
// MARK:- API protocol
protocol IAPI: class{
func requestMeanings(identifiers: [Int], completionHandler: @escaping([APIMeaning]) -> Void, errorHandler: @escaping(Error) -> Void)
}
// MARK:- Skyeng API protocol implementation
class SkyengAPI: IAPI {
fileprivate var session: Session!
init(session: Session) {
self.session = session
}
func requestMeanings(identifiers: [Int], completionHandler: @escaping([APIMeaning]) -> Void, errorHandler: @escaping(Error) -> Void) {
let stringArray = identifiers.flatMap { String($0) }
let string = stringArray.joined(separator: ",")
let parameters: Dictionary = [
"ids": string
]
session.request(url: "https://dictionary.skyeng.ru/api/public/v1/meanings", parameters: parameters, completionHandler: { (json) in
if let jsonArray = json as? [[String: Any]] {
let meanings = SkyengParser.parseMeanings(jsonArray: jsonArray)
completionHandler(meanings)
}
}) { (error) in
print(error.localizedDescription)
errorHandler(error)
}
}
}
// MARK:- Fake API protocol implementation
class FakeAPI {
func requestMeanings(identifiers: [Int], completionHandler: @escaping(APIMeaning) -> Void, errorHandler: @escaping(Error) -> Void) {
let filePath = Bundle.main.path (forResource: "Meaning192984", ofType:"json")
let data = try! Data.init(contentsOf: URL(fileURLWithPath: filePath!))
let jsonArray = try! JSONSerialization.jsonObject (with: data, options: JSONSerialization.ReadingOptions.mutableLeaves) as! [[String: Any]]
let meaning = SkyengParser.parseMeaning(jsonObject: jsonArray[0]) //Meaning()
completionHandler(meaning)
}
}
// MARK:- SkyengParser class
class SkyengParser {
class func parseMeanings(jsonArray: [[String: Any]]) -> [APIMeaning] {
var meanings = [APIMeaning]()
for jsonObject in jsonArray {
let meaning = SkyengParser.parseMeaning(jsonObject: jsonObject)
meanings.append(meaning)
}
return meanings
}
class func parseMeaning(jsonObject: [String: Any]) -> APIMeaning {
let meaning = APIMeaning()
if let id = jsonObject["id"] as? String {
meaning.identifier = Int(id)
}
meaning.text = jsonObject["text"] as? String
if let soundUrl = jsonObject["soundUrl"] as? String {
meaning.soundUrl = "http:" + soundUrl
}
if let jsonTranslation = jsonObject["translation"] as? [String: Any] {
meaning.translation = jsonTranslation["text"] as? String
}
if let jsonImages = jsonObject["images"] as? [[String: String]], jsonImages.count > 0 {
meaning.imageUrl = "http:" + jsonImages[0]["url"]!
}
// Parse alternative translations
if let jsonAlternatives = jsonObject["alternativeTranslations"] as? [[String: Any]] {
var alternatives = [APIAlternative]()
for jsonAlternative in jsonAlternatives {
let alternative = APIAlternative()
alternative.text = jsonAlternative["text"] as? String
if let jsonTranslation = jsonAlternative["translation"] as? [String: Any] {
alternative.translation = jsonTranslation["text"] as? String
}
alternatives.append(alternative)
}
meaning.alternatives = alternatives
}
return meaning
}
}
| f93f586721a3d953456561e4da7012a8 | 34.915094 | 147 | 0.612293 | false | false | false | false |
arbitur/Func | refs/heads/master | source/Geocoding/Geocoding.swift | mit | 1 | //
// Geocoding-new.swift
// Pods
//
// Created by Philip Fryklund on 22/Aug/17.
//
//
import Foundation
import CoreLocation
public typealias GeocodingBounds = (sw: CLLocationCoordinate2D, ne: CLLocationCoordinate2D)
public class GeocodingApiClient: ApiClient {
// public static private(set) var shared: GeocodingApiClient?
// public static func initialize(withKey key: String, language: String) {
// shared = .init(withKey: key, language: language)
// }
public let baseUrl: String = "https://maps.googleapis.com/maps/api/geocode"
public var interceptors: [(RequestBuilder) -> Void] = []
public var logger: HttpLogger = BaseHttpLogger(level: .medium)
internal let key: String
internal let language: String
public init(withKey key: String, language: String) {
self.key = key
self.language = language
}
}
public extension GeocodingApiClient {
func geocode(address: String? = nil, components: [Component: String]? = nil, bounds: GeocodingBounds? = nil, region: String? = nil) -> Request<GeocodingResponse> {
return self.request(decoder: DecodableDecoder(decoder: GeocodingResponse.init)) {
$0.method = .get
$0.url = "json"
$0.bodyEncoder = URLBodyEncoder(parameters: [
"address": address ?? "",
"bounds": bounds.map { "\($0.sw.description)|\($0.ne.description)" } ?? "",
"components": components?.map { "\($0.key.rawValue):\($0.value)" }.joined(by: "|") ?? "",
"region": region ?? "",
"language": language,
"key": key
])
}
}
func reverseGeocode(coordinate: CLLocationCoordinate2D, resultTypes: [AddressType]? = nil, locationTypes: [LocationType]? = nil, sensor: Bool? = nil) -> Request<GeocodingResponse> {
return self.request(decoder: DecodableDecoder(decoder: GeocodingResponse.init)) {
$0.method = .get
$0.url = "json"
$0.bodyEncoder = URLBodyEncoder(parameters: [
"latlng": "\(coordinate.latitude),\(coordinate.longitude)",
"result_type": resultTypes?.map { $0.rawValue }.joined(by: "|") ?? "",
"location_type": locationTypes?.map { $0.rawValue }.joined(by: "|") ?? "",
"sensor": sensor?.description ?? "",
"language": language,
"key": key
])
}
}
func reverseGeocode(placeId: String) -> Request<GeocodingResponse> {
return self.request(decoder: DecodableDecoder(decoder: GeocodingResponse.init)) {
$0.method = .get
$0.url = "json"
$0.bodyEncoder = URLBodyEncoder(parameters: [
"place_id": placeId,
"language": language,
"key": key
])
}
}
}
| 1ae323e4b74bb21e490066ccb51241c4 | 28.738095 | 182 | 0.667734 | false | false | false | false |
NUKisZ/MyTools | refs/heads/master | MyTools/MyTools/ThirdLibrary/XWSwiftRefresh/Header/XWRefreshStateHeader.swift | mit | 1 | //
// XWRefreshStateHeader.swift
// XWSwiftRefresh
//
// Created by Xiong Wei on 15/10/4.
// Copyright © 2015年 Xiong Wei. All rights reserved.
// 简书:猫爪
import UIKit
/** headerView 只有状态文字 */
open class XWRefreshStateHeader: XWRefreshHeader {
//MARK: 私有的
/** 每个状态对应的文字 */
fileprivate var stateTitles:Dictionary<XWRefreshState, String> = [
XWRefreshState.idle : XWRefreshHeaderStateIdleText,
XWRefreshState.refreshing : XWRefreshHeaderStateRefreshingText,
XWRefreshState.pulling : XWRefreshHeaderStatePullingText
]
//MARK: 外界接口
/** 利用这个colsure来决定显示的更新时间 */
var closureCallLastUpdatedTimeTitle:((_ lastUpdatedTime:Date) -> String)?
/** 显示上一次刷新时间的label */
lazy var lastUpdatedTimeLabel:UILabel = {
[unowned self] in
let lable = UILabel().Lable()
self.addSubview(lable)
return lable
}()
/** 显示刷新状态的label */
lazy var stateLabel:UILabel = {
[unowned self] in
let lable = UILabel().Lable()
self.addSubview(lable)
return lable
}()
/** 设置状态的显示文字 */
open func setTitle(_ title:String, state:XWRefreshState){
self.stateLabel.text = self.stateTitles[self.state];
}
/** 文字刷新状态下的显示与隐藏 */
open var refreshingTitleHidden:Bool = false {
didSet{
if oldValue == refreshingTitleHidden { return }
self.stateLabel.isHidden = refreshingTitleHidden
}
}
/** 时间刷新状态下的显示与隐藏*/
open var refreshingTimeHidden:Bool = false {
didSet{
if oldValue == refreshingTimeHidden { return }
self.lastUpdatedTimeLabel.isHidden = refreshingTimeHidden
}
}
//MARK: 重写
override var lastUpdatedateKey:String{
didSet{
if let lastUpdatedTimeDate = UserDefaults.standard.object(forKey: lastUpdatedateKey) {
let realLastUpdateTimeDate:Date = lastUpdatedTimeDate as! Date
//如果有闭包
if let internalClosure = self.closureCallLastUpdatedTimeTitle {
self.lastUpdatedTimeLabel.text = internalClosure(realLastUpdateTimeDate)
return
}
//得到精准的时间
self.lastUpdatedTimeLabel.text = realLastUpdateTimeDate.xwConvertStringTime()
}else{
self.lastUpdatedTimeLabel.text = "最后更新:无记录"
}
}
}
override var state:XWRefreshState{
didSet{
if state == oldValue { return }
self.stateLabel.text = self.stateTitles[self.state];
//self.lastUpdatedateKey = self.lastUpdatedateKey
}
}
override func prepare() {
super.prepare()
//初始化文字
self.setTitle(XWRefreshHeaderStateIdleText, state: .idle)
self.setTitle(XWRefreshHeaderStatePullingText, state: .pulling)
self.setTitle(XWRefreshHeaderStateRefreshingText, state: .refreshing)
}
override func placeSubvies() {
super.placeSubvies()
//如果状态隐藏 就直接返回
if self.stateLabel.isHidden { return }
if self.lastUpdatedTimeLabel.isHidden {
//状态
self.stateLabel.frame = self.bounds
}else {
//状态
self.stateLabel.frame = CGRect(x: 0, y: 0, width: self.xw_width, height: self.xw_height * 0.5)
//跟新的时间
self.lastUpdatedTimeLabel.xw_x = 0
self.lastUpdatedTimeLabel.xw_y = self.stateLabel.xw_height
self.lastUpdatedTimeLabel.xw_width = self.xw_width
self.lastUpdatedTimeLabel.xw_height = self.xw_height - self.lastUpdatedTimeLabel.xw_y
}
}
}
| 1b0a9d1c01c188e008d17f9a0953bd22 | 27.783582 | 106 | 0.584133 | false | false | false | false |
zeeshankhan/WeatherApp | refs/heads/master | WeatherApp/HistoryStore.swift | mit | 1 | //
// HistoryStore.swift
// WeatherApp
//
// Created by Zeeshan Khan on 10/15/16.
// Copyright © 2016 Zeeshan. All rights reserved.
//
import Foundation
private let key = "WeatherAppSearchHistory"
private let cacheCount = 10
@available(*, deprecated, message: "use Recent Store file instead")
class History {
private var cities = UserDefaults.standard.stringArray(forKey: key)
private var queue = DispatchQueue(label: "com.zeeshan.weatherapp.DispatchQueue")
/// Adds the city to history, if not already present
func add(_ city: String, completion: @escaping (Bool) -> Void) {
guard city.characters.count > 0 else {
return completion(false)
}
queue.async(flags: .barrier) { [weak self] in
if self?.cities == nil {
self?.cities = [String]()
}
if (self?.cities?.count)! > 0 && (self?.cities?.contains(city.lowercased()))! {
return completion(false)
}
if (self?.cities?.count)! == cacheCount {
self?.cities?.remove(at: cacheCount-1)
}
self?.cities?.insert(city.lowercased(), at: 0)
UserDefaults.standard.set(self?.cities, forKey: key)
return completion(true)
}
}
func getAll() -> [String] {
return cities ?? []
}
}
| fd6049500849c4fd2aede18192eb6305 | 24.090909 | 91 | 0.576812 | false | false | false | false |
MartySchmidt/phonertc | refs/heads/master | src/ios/SessionDescriptionDelegate.swift | apache-2.0 | 9 | import Foundation
class SessionDescriptionDelegate : UIResponder, RTCSessionDescriptionDelegate {
var session: Session
init(session: Session) {
self.session = session
}
func peerConnection(peerConnection: RTCPeerConnection!,
didCreateSessionDescription originalSdp: RTCSessionDescription!, error: NSError!) {
if error != nil {
println("SDP OnFailure: \(error)")
return
}
var sdp = RTCSessionDescription(
type: originalSdp.type,
sdp: self.session.preferISAC(originalSdp.description)
)
self.session.peerConnection.setLocalDescriptionWithDelegate(self, sessionDescription: sdp)
dispatch_async(dispatch_get_main_queue()) {
var jsonError: NSError?
let json: AnyObject = [
"type": sdp.type,
"sdp": sdp.description
]
let data = NSJSONSerialization.dataWithJSONObject(json,
options: NSJSONWritingOptions.allZeros,
error: &jsonError)
self.session.sendMessage(data!)
}
}
func peerConnection(peerConnection: RTCPeerConnection!,
didSetSessionDescriptionWithError error: NSError!) {
if error != nil {
println("SDP OnFailure: \(error)")
return
}
dispatch_async(dispatch_get_main_queue()) {
if self.session.config.isInitiator {
if self.session.peerConnection.remoteDescription != nil {
println("SDP onSuccess - drain candidates")
self.drainRemoteCandidates()
}
} else {
if self.session.peerConnection.localDescription != nil {
self.drainRemoteCandidates()
} else {
self.session.peerConnection.createAnswerWithDelegate(self,
constraints: self.session.constraints)
}
}
}
}
func drainRemoteCandidates() {
for candidate in self.session.queuedRemoteCandidates! {
self.session.peerConnection.addICECandidate(candidate)
}
self.session.queuedRemoteCandidates = nil
}
} | 6eb8ff7a3a4aa541f059847818a3164c | 32.28169 | 98 | 0.557578 | false | false | false | false |
lanjing99/RxSwiftDemo | refs/heads/master | 23-mvvm-with-rxswift/challenge/Tweetie/TwitterAPI/TwitterAPI.swift | mit | 3 | /*
* Copyright (c) 2016-2017 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
import Foundation
import Accounts
import Social
import RxSwift
import RxCocoa
typealias JSONObject = [String: Any]
typealias ListIdentifier = (username: String, slug: String)
protocol TwitterAPIProtocol {
static func timeline(of username: String) -> (ACAccount, TimelineCursor) -> Observable<[JSONObject]>
static func timeline(of list: ListIdentifier) -> (ACAccount, TimelineCursor) -> Observable<[JSONObject]>
static func members(of list: ListIdentifier) -> (ACAccount) -> Observable<[JSONObject]>
}
struct TwitterAPI: TwitterAPIProtocol {
// MARK: - API Addresses
fileprivate enum Address: String {
case timeline = "statuses/user_timeline.json"
case listFeed = "lists/statuses.json"
case listMembers = "lists/members.json"
private var baseURL: String { return "https://api.twitter.com/1.1/" }
var url: URL {
return URL(string: baseURL.appending(rawValue))!
}
}
// MARK: - API errors
enum Errors: Error {
case requestFailed
case badResponse
case httpError(Int)
}
// MARK: - API Endpoint Requests
static func timeline(of username: String) -> (ACAccount, TimelineCursor) -> Observable<[JSONObject]> {
return { account, cursor in
return request(account, address: TwitterAPI.Address.timeline, parameters: ["screen_name": username, "contributor_details": "false", "count": "100", "include_rts": "true"])
}
}
static func timeline(of list: ListIdentifier) -> (ACAccount, TimelineCursor) -> Observable<[JSONObject]> {
return { account, cursor in
var params = ["owner_screen_name": list.username, "slug": list.slug]
if cursor != TimelineCursor.none {
params["max_id"] = String(cursor.maxId)
params["since_id"] = String(cursor.sinceId)
}
return request(
account, address: TwitterAPI.Address.listFeed,
parameters: params)
}
}
static func members(of list: ListIdentifier) -> (ACAccount) -> Observable<[JSONObject]> {
return { account in
let params = ["owner_screen_name": list.username,
"slug": list.slug,
"skip_status": "1",
"include_entities": "false",
"count": "100"]
let response: Observable<JSONObject> = request(
account, address: TwitterAPI.Address.listMembers,
parameters: params)
return response
.map { result in
guard let users = result["users"] as? [JSONObject] else {return []}
return users
}
}
}
// MARK: - generic request to send an SLRequest
static private func request<T: Any>(_ account: ACAccount, address: Address, parameters: [String: String] = [:]) -> Observable<T> {
return Observable.create { observer in
guard let request = SLRequest(
forServiceType: SLServiceTypeTwitter,
requestMethod: .GET,
url: address.url,
parameters: parameters
) else {
observer.onError(Errors.requestFailed)
return Disposables.create()
}
request.account = account
request.perform {data, response, error in
if let error = error {
observer.onError(error)
}
if let response = response, response.statusCode >= 400 && response.statusCode < 600 {
observer.onError(Errors.httpError(response.statusCode))
}
if let data = data, let json = try? JSONSerialization.jsonObject(with: data, options: []) as? T, let result = json {
observer.onNext(result)
}
observer.onCompleted()
}
return Disposables.create()
}
}
}
| 531ca22ad26771b7792a3f04a92ed64e | 35.129771 | 177 | 0.667653 | false | false | false | false |
snapsure-insurance-bot/snapsure-sdk-ios | refs/heads/master | Sources/Core/Network/NetworkService/NetworkService.swift | mit | 1 | //
// NetworkService.swift
// Picsure
//
// Created by Artem Novichkov on 10/03/2017.
// Copyright © 2017 Picsure. All rights reserved.
//
import Foundation
private typealias TaskHandler = (Data?, URLResponse?, Error?) -> Void
typealias ParsedTaskHandler = (_ json: JSON?, _ statusCode: Int?, _ error: Error?) -> Void
final class NetworkService {
private enum Constants {
static let host = URL(string: "https://dev-api.picsure.ai")!
}
private let session = URLSession(configuration: .default)
static let shared = NetworkService()
var token: String?
var language: String = "en"
private init() {}
/// Upload the image and returns recognition information.
///
/// - Parameters:
/// - endpoint: The upload endpoint with image data.
/// - completion: The completion with recognition information or error if it occurred.
func uploadData(for endpoint: ImageUploadEndpoint, completion: @escaping Completion) {
guard let token = token else {
completion(.failure(PicsureErrors.TokenErrors.missingToken))
return
}
let request = RequestFactory.makeRequest(host: Constants.host, endpoint: endpoint, token: token)
let task = session.dataTask(with: request, completionHandler: taskHandler { json, _, error in
if let error = error {
completion(.failure(error))
}
else if let json = json {
guard let imageID = json["token"] as? String else {
completion(.failure(PicsureErrors.NetworkErrors.cannotParseResponse))
return
}
self.lookup(imageID: imageID, completion: completion)
}
else {
completion(.failure(PicsureErrors.NetworkErrors.emptyServerData))
return
}
})
task.resume()
}
@discardableResult
private func dataTask(for endpoint: RequestEndpoint, completion: @escaping ParsedTaskHandler) -> URLSessionDataTask? {
guard let token = token else {
return nil
}
let request = RequestFactory.makeRequest(host: Constants.host, endpoint: endpoint, token: token, language: language)
let task = session.dataTask(with: request, completionHandler: taskHandler(with: completion))
task.resume()
return task
}
private func taskHandler(with completion: @escaping ParsedTaskHandler) -> TaskHandler {
return { data, response, error in
let statusCode = (response as? HTTPURLResponse)?.statusCode
if statusCode == 401 {
completion(nil, statusCode, PicsureErrors.TokenErrors.invalidToken)
return
}
if statusCode == 500 {
completion(nil, statusCode, PicsureErrors.NetworkErrors.server)
return
}
if let error = error {
completion(nil, statusCode, error)
return
}
guard let unwrappedData = data else {
completion(nil, statusCode, PicsureErrors.NetworkErrors.emptyServerData)
return
}
guard let json = ResponseParser.parseJSON(from: unwrappedData) else {
completion(nil, statusCode, PicsureErrors.NetworkErrors.cannotParseResponse)
return
}
completion(json, statusCode, nil)
}
}
private func lookup(imageID: String, completion: @escaping Completion) {
let lookupTask = dataTask(for: LookupEndpoint.lookup(imageID)) { json, _, error in
if let error = error {
completion(.failure(error))
}
else if let json = json {
completion(.success(json))
}
}
lookupTask?.resume()
}
}
| dc852a3583b179c18b224f125450510c | 34.097345 | 124 | 0.586737 | false | false | false | false |
IngmarStein/swift | refs/heads/master | test/Interpreter/SDK/object_literals.swift | apache-2.0 | 17 | // RUN: rm -rf %t && mkdir -p %t/Test.app/Contents/MacOS
// RUN: cp -r %S/Inputs/object_literals-Resources %t/Test.app/Contents/Resources
// RUN: %target-build-swift %s -o %t/Test.app/Contents/MacOS/main
// RUN: %target-run %t/Test.app/Contents/MacOS/main
// REQUIRES: executable_test
// REQUIRES: OS=macosx
import AppKit
import StdlibUnittest
var LiteralsTestSuite = TestSuite("ObjectLiterals")
LiteralsTestSuite.test("file") {
// This is what requires the proper bundle folder structure.
let resource = #fileLiteral(resourceName: "testData.plist")
let contents = NSDictionary(contentsOf: resource) as! [String: NSObject]?
_ = expectNotNil(contents)
expectEqual(["test": true as NSObject], contents!)
}
LiteralsTestSuite.test("image") {
let image = #imageLiteral(resourceName: NSImageNameComputer)
expectTrue(image.isValid)
}
LiteralsTestSuite.test("color") {
let color = #colorLiteral(red: 1.0, green: 0.0, blue: 0.0, alpha: 1.0)
expectEqual(NSColor(srgbRed: 1.0, green: 0.0, blue: 0.0, alpha: 1.0), color)
}
runAllTests()
| 5ce0f48c3502958237344ea81bd4001b | 30.848485 | 80 | 0.722169 | false | true | false | false |
nekrich/GlobalMessageService-iOS | refs/heads/master | Source/InboxViewController/GlobalMessageServiceMessageJSQ.swift | apache-2.0 | 1 | //
// GlobalMessageServiceMessageJSQ.swift
// GlobalMessageService
//
// Created by Vitalii Budnik on 2/29/16.
// Copyright © 2016 Global Message Services Worldwide. All rights reserved.
//
import Foundation
import JSQMessagesViewController
/**
`JSQMessageData` wrapper for `GlobalMessageServiceMessage`
*/
public class GlobalMessageServiceMessageJSQ: NSObject, JSQMessageData {
/**
An instance of `GlobalMessageServiceMessage`
*/
let message: GlobalMessageServiceMessage
/**
Initlizes `self` with `GlobalMessageServiceMessage` object
- Parameter message: `GlobalMessageServiceMessage` object to initialize with
*/
init(message: GlobalMessageServiceMessage) {
self.message = message
}
/**
`String` representing senders alpha name. Can be `nil`
*/
var alphaName: String {
return message.alphaName
}
/**
- Returns: A string identifier that uniquely identifies the user who sent the message.
*
* @discussion If you need to generate a unique identifier, consider using
* `[[NSProcessInfo processInfo] globallyUniqueString]`
*
* @warning You must not return `nil` from this method. This value must be unique.
*/
public func senderId() -> String! {
return message.alphaName
}
/**
- Returns: The display name for the user who sent the message.
*
* @warning You must not return `nil` from this method.
*/
public func senderDisplayName() -> String! {
return message.alphaName
}
/**
The date that the message was delivered
- Returns: The date that the message was sent.
*/
public func date() -> NSDate! {
return message.deliveredDate
}
/**
This method is used to determine if the message data item contains text or media.
If this method returns `YES`, an instance of `JSQMessagesViewController` will ignore
the `text` method of this protocol when dequeuing a `JSQMessagesCollectionViewCell`
and only call the `media` method.
Similarly, if this method returns `NO` then the `media` method will be ignored and
and only the `text` method will be called.
- Returns: A boolean value specifying whether or not this is a media message or a text message.
Return `YES` if this item is a media message, and `NO` if it is a text message.
*/
public func isMediaMessage() -> Bool {
return false
}
/**
An integer that can be used as a table address in a hash table structure.
- Returns: An integer that can be used as a table address in a hash table structure.
- Note: This value must be unique for each message with distinct contents.
This value is used to cache layout information in the collection view.
*/
public func messageHash() -> UInt {
return UInt(abs(message.hashValue))
}
/**
`String` representing message body. Can be `nil`
- Returns: `String` representing message body. Can be `nil`
*/
public func text() -> String! {
return message.message
}
/**
Message type
- Returns: Message type
- SeeAlso: `GlobalMessageServiceMessageType` for details
*/
public var type: GlobalMessageServiceMessageType {
return message.type
}
}
/**
Compares two `GlobalMessageServiceMessageJSQ`s
- Parameter lhs: frirst `GlobalMessageServiceMessageJSQ`
- Parameter rhs: second `GlobalMessageServiceMessageJSQ`
- Returns: `true` if both messages are equal, otherwise returns `false`
*/
func == (lhs: GlobalMessageServiceMessageJSQ, rhs: GlobalMessageServiceMessageJSQ) -> Bool {
return lhs.message == rhs.message
}
| 881ef65fce7a2d93a80331dbefa60609 | 28.691667 | 98 | 0.705305 | false | false | false | false |
delasteve/Gonzales | refs/heads/master | Gonzales/Matchers/EquatableMatcher.swift | mit | 1 | public class EquatableMatcher<T: Equatable> : BaseMatcher {
private let actual: T
private var negate: Bool
public init(_ actual: T, xctestProxy: XCTestProxyProtocol = XCTestProxy()) {
self.actual = actual
self.negate = false
super.init(xctestProxy: xctestProxy)
}
public var be: EquatableMatcher {
return self
}
public var not: EquatableMatcher {
negate = !negate
return self
}
public func equal(expected: T, file: String = __FILE__, line: UInt = __LINE__) {
var comparison = actual != expected
if negate {
comparison = !comparison
}
if comparison {
let message = buildMessage("Expected <\(actual)> to", end: "equal <\(expected)>", negate: negate)
fail(message, file: file, line: line)
}
}
}
| e619aaf269b56b16be271717ede80700 | 21.371429 | 103 | 0.641124 | false | true | false | false |
busybusy/AnalyticsKit | refs/heads/master | Providers/Mixpanel/AnalyticsKitMixpanelProvider.swift | mit | 1 | import Foundation
import Mixpanel
public class AnalyticsKitMixpanelProvider: NSObject, AnalyticsKitProvider {
public init(withAPIKey apiKey: String) {
Mixpanel.sharedInstance(withToken: apiKey)
}
public func uncaughtException(_ exception: NSException) {
Mixpanel.sharedInstance()?.track("Uncaught Exceptions", properties: [
"ename" : exception.name,
"reason" : exception.reason ?? "nil",
"userInfo" : exception.userInfo ?? "nil"
])
}
// Logging
public func applicationWillEnterForeground() {}
public func applicationDidEnterBackground() {}
public func applicationWillTerminate() {}
public func logScreen(_ screenName: String) {
logEvent("Screen - \(screenName)")
}
public func logScreen(_ screenName: String, withProperties properties: [String: Any]) {
logEvent("Screen - \(screenName)", withProperties: properties)
}
public func logEvent(_ event: String) {
Mixpanel.sharedInstance()?.track(event)
}
public func logEvent(_ event: String, withProperties properties: [String: Any]) {
Mixpanel.sharedInstance()?.track(event, properties: properties)
}
public func logEvent(_ event: String, timed: Bool) {
if timed {
Mixpanel.sharedInstance()?.timeEvent(event)
} else {
Mixpanel.sharedInstance()?.track(event)
}
}
public func logEvent(_ event: String, withProperties properties: [String: Any], timed: Bool) {
if timed {
Mixpanel.sharedInstance()?.timeEvent(event)
} else {
Mixpanel.sharedInstance()?.track(event, properties: properties)
}
}
public func logEvent(_ event: String, withProperty key: String, andValue value: String) {
logEvent(event, withProperties: [key: value])
}
public func endTimedEvent(_ event: String, withProperties properties: [String: Any]) {
// Mixpanel documentation: timeEvent followed by a track with the same event name would record the duration
Mixpanel.sharedInstance()?.track(event, properties: properties)
}
public func logError(_ name: String, message: String?, exception: NSException?) {
var properties = [AnyHashable: Any]()
properties["name"] = name
properties["message"] = message
if let exception = exception {
properties["ename"] = exception.name
properties["reason"] = exception.reason
properties["userInfo"] = exception.userInfo
}
Mixpanel.sharedInstance()?.track("Exceptions", properties: properties)
}
public func logError(_ name: String, message: String?, error: Error?) {
var properties = [AnyHashable: Any]()
properties["name"] = name
properties["message"] = message
if let error = error {
properties["description"] = error.localizedDescription
}
Mixpanel.sharedInstance()?.track("Errors", properties: properties)
}
}
| 5b23ac782ec2d9fdbc1db02910de3981 | 33.590909 | 115 | 0.638633 | false | false | false | false |
CallMeDaKing/DouYuAPP | refs/heads/master | DouYuProject/DouYuProject/Classes/Main/View/PageContentView.swift | mit | 1 | //
// PageContentView.swift
// DouYuProject
//
// Created by li king on 2017/11/6.
// Copyright © 2017年 li king. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(contentView:PageContentView , progress: CGFloat , sourceIndex :Int ,targetIndex :Int)
}
private let cellID = "cellID"
class PageContentView: UIView {
//MARK - 自定义属性
private var childVcs : [UIViewController]
private weak var parentViewController : UIViewController?
private var startOffsetX :CGFloat = 0
private var isForbidScrollDelegate :Bool = false
weak var delegate : PageContentViewDelegate?
//MARK -- 懒加载属性
private lazy var collectionView : UICollectionView = { [weak self] in
//1 创建layout 布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
//创建UICollectionView
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: cellID)
collectionView.delegate = self
return collectionView
}()
//自定义构造函数 区别开便利构造函数
init(frame: CGRect , chikdVcs : [UIViewController], parentViewController :UIViewController?) {
self.childVcs = chikdVcs
self.parentViewController = parentViewController
super.init(frame: frame)
//设置UI
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK -- 设置UI 界面
extension PageContentView{
private func setUpUI(){
//1. 将所有的子控制器,添加到父控制器中
for childVc in childVcs{
parentViewController?.addChildViewController(childVc)
}
//2.添加UICollectionView ,用于在cell 中存放控制器的View,在这用到collectionview ,懒加载
addSubview(collectionView)
collectionView.frame = bounds
}
}
extension PageContentView: UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
//创建cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath)
//因为cell 会重复利用,导致可能往contentview添加多次view 针对cell 做的相关优化
for view in cell.contentView.subviews{
view .removeFromSuperview()
}
cell.contentView.addSubview(childVcs[indexPath.item].view)
return cell
}
}
//MARK-- 对外暴露的方法
extension PageContentView{
func setCurrentIndex(currentIndex:Int){
//1 .记录需要禁止执行滚动代理方法
isForbidScrollDelegate = true
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
}
}
//MARK -- 遵守UIcollectionViewDelegate
extension PageContentView : UICollectionViewDelegate{
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
//判断是否是点击事件
if isForbidScrollDelegate {return}
//1 定义获取需要的数据
var progress :CGFloat = 0
var sourceIndex :Int = 0
var targetIndex :Int = 0
//2.根据和scrollview 的偏移量进行比教判断是左滑还是右滑
let currentOffset = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffset > startOffsetX {
//左滑动 比例
// 计算progress 在这有个只是点, floor 函数 是取整函数
progress = currentOffset/scrollViewW - floor(currentOffset/scrollViewW)
//计算sourceIndex
sourceIndex = Int(currentOffset/scrollViewW)
//计算targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVcs.count{
targetIndex = childVcs.count - 1
}
//如果完全滑动过去 progress 应该为1
if currentOffset - startOffsetX == scrollViewW{
progress = 1
targetIndex = sourceIndex
}
}else{
//右滑动
progress = 1 - (currentOffset/scrollViewW - floor(currentOffset/scrollViewW))
//计算targetIndex
targetIndex = Int(currentOffset/scrollViewW)
//计算sourceIndex
sourceIndex = targetIndex + 1
if sourceIndex >= childVcs.count{
sourceIndex = childVcs.count - 1
}
//如果完全滑动过去
if startOffsetX - currentOffset == scrollViewW {
sourceIndex = targetIndex
}
}
//3 .将progress /sourceIndex/ targetIndex 传递给titleView
// print("progress:\(progress) sourceIndex \(sourceIndex) targetIndex \(targetIndex)")
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
| f9f07749d8f3e60bbc2960329f52823f | 31.847953 | 124 | 0.632722 | false | false | false | false |
Sharelink/Bahamut | refs/heads/master | Bahamut/UIImagePlayerController.swift | mit | 1 | //
// UIImagePlayerController.swift
// Bahamut
//
// Created by AlexChow on 15/9/6.
// Copyright © 2015年 GStudio. All rights reserved.
//
import UIKit
protocol ImageProvider
{
func getImageCount() -> Int
func startLoad(index:Int)
func getThumbnail(index:Int) -> UIImage?
func registImagePlayerObserver(observer:LoadImageObserver)
}
class UIFetchImageView: UIScrollView,UIScrollViewDelegate
{
private var progress:KDCircularProgress!{
didSet{
progress.trackColor = UIColor.blackColor()
progress.IBColor1 = UIColor.whiteColor()
progress.IBColor2 = UIColor.whiteColor()
progress.IBColor3 = UIColor.whiteColor()
}
}
private var refreshButton:UIButton!{
didSet{
refreshButton.titleLabel?.text = "LOAD_IMG_ERROR".localizedString()
refreshButton.hidden = true
refreshButton.addTarget(self, action: #selector(UIFetchImageView.refreshButtonClick(_:)), forControlEvents: UIControlEvents.TouchUpInside)
self.addSubview(refreshButton)
}
}
private var imageView:UIImageView!
func refreshButtonClick(_:UIButton)
{
startLoadImage()
}
func startLoadImage()
{
canScale = false
refreshButton.hidden = true
self.progress.setProgressValue(0)
}
func imageLoaded(image:UIImage)
{
self.progress.setProgressValue(0)
dispatch_async(dispatch_get_main_queue()){
self.imageView.image = image
self.canScale = true
self.refreshUI()
}
}
func imageLoadError()
{
self.progress.setProgressValue(0)
dispatch_async(dispatch_get_main_queue()){
self.refreshButton.hidden = false
self.canScale = false
self.refreshUI()
}
}
func loadImageProgress(progress:Float)
{
self.progress.setProgressValue(0)
}
func setThumbnail(thumbnail:UIImage)
{
self.canScale = false
self.imageView.image = thumbnail
}
private func initImageView()
{
imageView = UIImageView()
imageView.contentMode = .ScaleAspectFit
self.addSubview(imageView)
}
private func initErrorButton()
{
self.refreshButton = UIButton(type: UIButtonType.InfoDark)
}
private func initGesture()
{
self.minimumZoomScale = 1
self.maximumZoomScale = 2
self.userInteractionEnabled = true
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(UIFetchImageView.doubleTap(_:)))
doubleTapGesture.numberOfTapsRequired = 2
self.addGestureRecognizer(doubleTapGesture)
}
private func initProgress()
{
progress = KDCircularProgress(frame: CGRect(x: 0, y: 0, width: 32, height: 32))
progress.startAngle = -90
progress.progressThickness = 0.2
progress.trackThickness = 0.6
progress.clockwise = true
progress.gradientRotateSpeed = 2
progress.roundedCorners = false
progress.glowMode = .Forward
progress.glowAmount = 0.9
progress.setColors(UIColor.cyanColor() ,UIColor.whiteColor(), UIColor.magentaColor(), UIColor.whiteColor(), UIColor.orangeColor())
self.addSubview(progress)
progress.hidden = true
}
private func refreshUI()
{
self.setZoomScale(self.minimumZoomScale, animated: true)
progress.center = CGPoint(x: self.center.x, y: self.center.y)
refreshButton.center = CGPoint(x: self.center.x, y: self.center.y)
imageView.frame = UIApplication.sharedApplication().keyWindow!.bounds
imageView.layoutIfNeeded()
}
private var isScale:Bool = false
private var isScrollling:Bool = false
private var canScale:Bool = false
func doubleTap(ges:UITapGestureRecognizer)
{
if !canScale{return}
let touchPoint = ges.locationInView(self)
if (self.zoomScale != self.minimumZoomScale) {
self.setZoomScale(self.minimumZoomScale, animated: true)
} else {
let newZoomScale = CGFloat(2.0)
let xsize = self.bounds.size.width / newZoomScale
let ysize = self.bounds.size.height / newZoomScale
self.zoomToRect(CGRectMake(touchPoint.x - xsize / 2, touchPoint.y - ysize / 2, xsize, ysize), animated: true)
}
}
func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
return self.imageView
}
func scrollViewWillBeginZooming(scrollView: UIScrollView, withView view: UIView?) {
self.scrollEnabled = true
}
func scrollViewDidZoom(scrollView: UIScrollView) {
self.setNeedsLayout()
self.setNeedsDisplay()
}
convenience init()
{
self.init(frame: CGRectZero)
}
override init(frame: CGRect)
{
super.init(frame: frame)
initScrollView()
initImageView()
initProgress()
initErrorButton()
initGesture()
}
private func initScrollView()
{
self.delegate = self
self.showsHorizontalScrollIndicator = false
self.showsVerticalScrollIndicator = false
self.decelerationRate = UIScrollViewDecelerationRateFast
self.autoresizingMask = [UIViewAutoresizing.FlexibleWidth, UIViewAutoresizing.FlexibleHeight]
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
protocol LoadImageObserver
{
func imageLoaded(index:Int,image:UIImage)
func imageLoadError(index:Int)
func imageLoadingProgress(index:Int,progress:Float)
}
class UIImagePlayerController: UIViewController,UIScrollViewDelegate,LoadImageObserver
{
private var imageCount:Int = 0
private let spaceOfItem:CGFloat = 23
var imageProvider:ImageProvider!{
didSet{
imageProvider.registImagePlayerObserver(self)
imageCount = imageProvider.getImageCount()
}
}
var images = [UIFetchImageView]()
func supportedViewOrientations() -> UIInterfaceOrientationMask
{
return UIInterfaceOrientationMask.All
}
@IBOutlet weak var scrollView: UIScrollView!{
didSet{
scrollView.backgroundColor = UIColor.blackColor()
scrollView.showsHorizontalScrollIndicator = false
scrollView.showsVerticalScrollIndicator = false
scrollView.pagingEnabled = false
scrollView.delegate = self
}
}
var currentIndex:Int = -1{
didSet{
if currentIndex >= 0 && currentIndex != oldValue && currentIndex < imageCount
{
images[currentIndex].startLoadImage()
if let thumb = imageProvider.getThumbnail(currentIndex)
{
images[currentIndex].setThumbnail(thumb)
}
self.imageProvider.startLoad(currentIndex)
}
}
}
private func scrollToCurrentIndex()
{
let x:CGFloat = CGFloat(integerLiteral: currentIndex) * (self.scrollView.frame.width + spaceOfItem);
self.scrollView.contentOffset = CGPointMake(x, 0);
}
private func getNearestTargetPoint(offset:CGPoint) -> CGPoint{
let pageSize = self.scrollView.frame.width + spaceOfItem
let targetIndex = Int(roundf(Float(offset.x / pageSize)))
currentIndex += targetIndex == currentIndex ? 0 : targetIndex > currentIndex ? 1 : -1
let targetX = pageSize * CGFloat(currentIndex);
return CGPointMake(targetX, offset.y);
}
func scrollViewWillEndDragging(scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
let offset = getNearestTargetPoint(targetContentOffset.memory)
targetContentOffset.memory.x = offset.x
}
func imageLoaded(index: Int, image: UIImage) {
if images.count > index{
images[index].imageLoaded(image)
}
}
func imageLoadError(index: Int) {
if images.count > index{
images[index].imageLoadError()
}
}
func imageLoadingProgress(index: Int, progress: Float) {
if images.count > index{
images[index].loadImageProgress(progress)
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return [UIInterfaceOrientationMask.Portrait,UIInterfaceOrientationMask.Landscape]
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
initImageViews()
initPageControl()
initObserver()
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
deinitObserver()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
resizeScrollView()
}
private func initPageControl()
{
self.pageControl.numberOfPages = imageCount
}
@IBOutlet weak var pageControl: UIPageControl!{
didSet{
if pageControl != nil
{
pageControl.hidden = imageCount <= 1
}
}
}
func initImageViews()
{
for _ in 0..<imageCount
{
let uiImageView = UIFetchImageView()
scrollView.addSubview(uiImageView)
images.append(uiImageView)
}
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(UIImagePlayerController.tapScollView(_:)))
let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(UIImagePlayerController.doubleTapScollView(_:)))
doubleTapGesture.numberOfTapsRequired = 2
tapGesture.requireGestureRecognizerToFail(doubleTapGesture)
tapGesture.delaysTouchesBegan = true
self.view.addGestureRecognizer(tapGesture)
self.view.addGestureRecognizer(doubleTapGesture)
}
private func initObserver()
{
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(UIImagePlayerController.didChangeStatusBarOrientation(_:)), name: UIApplicationDidChangeStatusBarOrientationNotification, object: UIApplication.sharedApplication())
}
private func deinitObserver()
{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
func didChangeStatusBarOrientation(_: NSNotification)
{
resizeScrollView()
}
func resizeScrollView()
{
let svFrame = UIApplication.sharedApplication().keyWindow!.bounds
let imageWidth = svFrame.width
let imageHeight = svFrame.height
let pageSize = imageWidth + spaceOfItem
for i:Int in 0 ..< images.count
{
let imageX = CGFloat(integerLiteral: i) * pageSize
let frame = CGRectMake( imageX , 0, imageWidth, imageHeight)
images[i].frame = frame
images[i].refreshUI()
}
scrollView.frame = svFrame
scrollView.contentSize = CGSizeMake(CGFloat(integerLiteral:imageCount) * pageSize, imageHeight)
}
enum OrientationAngle:CGFloat
{
case Portrait = 0.0
case LandscapeLeft = 270.0
case LandscapeRight = 90.0
case PortraitUpsideDown = 180.0
}
func getRotationAngle() -> OrientationAngle
{
switch UIApplication.sharedApplication().statusBarOrientation
{
case .Portrait: return OrientationAngle.Portrait
case .LandscapeLeft: return OrientationAngle.LandscapeLeft
case .LandscapeRight: return OrientationAngle.LandscapeRight
case .PortraitUpsideDown: return OrientationAngle.PortraitUpsideDown
case .Unknown: return OrientationAngle.Portrait
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let scrollviewW:CGFloat = scrollView.frame.width;
let x = scrollView.contentOffset.x;
let page:Int = Int((x + scrollviewW / 2) / scrollviewW);
if pageControl != nil
{
self.pageControl.currentPage = page
}
}
func doubleTapScollView(_:UIGestureRecognizer)
{
}
func tapScollView(_:UIGestureRecognizer)
{
self.dismissViewControllerAnimated(false) { () -> Void in
}
}
deinit
{
NSNotificationCenter.defaultCenter().removeObserver(self)
}
static func showImagePlayer(currentController:UIViewController,imageProvider:ImageProvider,imageIndex:Int = 0)
{
let controller = instanceFromStoryBoard("Component", identifier: "imagePlayerController",bundle: Sharelink.mainBundle()) as!UIImagePlayerController
controller.imageProvider = imageProvider
currentController.presentViewController(controller, animated: true, completion: { () -> Void in
controller.currentIndex = imageIndex
controller.scrollToCurrentIndex()
})
}
}
| a35471ffb55af8cbb74f6f86951996b6 | 30.521327 | 247 | 0.639829 | false | false | false | false |
robert-hatfield/PicFeed | refs/heads/master | PicFeed/PicFeed/GalleryCollectionViewLayout.swift | mit | 1 | //
// GalleryCollectionViewLayout.swift
// PicFeed
//
// Created by Robert Hatfield on 3/29/17.
// Copyright © 2017 Robert Hatfield. All rights reserved.
//
import UIKit
class GalleryCollectionViewLayout: UICollectionViewFlowLayout {
var columns : Int
let spacing: CGFloat = 1.0
var screenWidth : CGFloat {
return UIScreen.main.bounds.width
}
var itemWidth : CGFloat {
let availableScreen = screenWidth - (CGFloat(self.columns) * self.spacing)
return availableScreen / CGFloat(self.columns)
}
init (columns : Int) {
self.columns = columns
super.init()
self.minimumLineSpacing = spacing
self.minimumInteritemSpacing = spacing
self.itemSize = CGSize(width: itemWidth, height: itemWidth)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 82bd87288e717f927f05b9e65f1a60a5 | 23.282051 | 82 | 0.636748 | false | false | false | false |
ahoppen/swift | refs/heads/main | SwiftCompilerSources/Sources/SIL/Instruction.swift | apache-2.0 | 1 | //===--- Instruction.swift - Defines the Instruction classes --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Basic
import SILBridging
//===----------------------------------------------------------------------===//
// Instruction base classes
//===----------------------------------------------------------------------===//
public class Instruction : ListNode, CustomStringConvertible, Hashable {
final public var next: Instruction? {
SILInstruction_next(bridged).instruction
}
final public var previous: Instruction? {
SILInstruction_previous(bridged).instruction
}
// Needed for ReverseList<Instruction>.reversed(). Never use directly.
public var _firstInList: Instruction { SILBasicBlock_firstInst(block.bridged).instruction! }
// Needed for List<Instruction>.reversed(). Never use directly.
public var _lastInList: Instruction { SILBasicBlock_lastInst(block.bridged).instruction! }
final public var block: BasicBlock {
SILInstruction_getParent(bridged).block
}
final public var function: Function { block.function }
final public var description: String {
var s = SILNode_debugDescription(bridgedNode)
return String(cString: s.c_str())
}
final public var operands: OperandArray {
return OperandArray(opArray: SILInstruction_getOperands(bridged))
}
fileprivate var resultCount: Int { 0 }
fileprivate func getResult(index: Int) -> Value { fatalError() }
public struct Results : RandomAccessCollection {
fileprivate let inst: Instruction
fileprivate let numResults: Int
public var startIndex: Int { 0 }
public var endIndex: Int { numResults }
public subscript(_ index: Int) -> Value { inst.getResult(index: index) }
}
final public var results: Results {
Results(inst: self, numResults: resultCount)
}
final public var location: Location {
return Location(bridged: SILInstruction_getLocation(bridged))
}
public var mayTrap: Bool { false }
final public var mayHaveSideEffects: Bool {
return mayTrap || mayWriteToMemory
}
final public var mayReadFromMemory: Bool {
switch SILInstruction_getMemBehavior(bridged) {
case MayReadBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior:
return true
default:
return false
}
}
final public var mayWriteToMemory: Bool {
switch SILInstruction_getMemBehavior(bridged) {
case MayWriteBehavior, MayReadWriteBehavior, MayHaveSideEffectsBehavior:
return true
default:
return false
}
}
final public var mayReadOrWriteMemory: Bool {
switch SILInstruction_getMemBehavior(bridged) {
case MayReadBehavior, MayWriteBehavior, MayReadWriteBehavior,
MayHaveSideEffectsBehavior:
return true
default:
return false
}
}
public final var mayRelease: Bool {
return SILInstruction_mayRelease(bridged)
}
public static func ==(lhs: Instruction, rhs: Instruction) -> Bool {
lhs === rhs
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
public var bridged: BridgedInstruction {
BridgedInstruction(obj: SwiftObject(self))
}
var bridgedNode: BridgedNode { BridgedNode(obj: SwiftObject(self)) }
}
extension BridgedInstruction {
public var instruction: Instruction { obj.getAs(Instruction.self) }
public func getAs<T: Instruction>(_ instType: T.Type) -> T { obj.getAs(T.self) }
public var optional: OptionalBridgedInstruction {
OptionalBridgedInstruction(obj: self.obj)
}
}
extension OptionalBridgedInstruction {
var instruction: Instruction? { obj.getAs(Instruction.self) }
public static var none: OptionalBridgedInstruction {
OptionalBridgedInstruction(obj: nil)
}
}
public class SingleValueInstruction : Instruction, Value {
final public var definingInstruction: Instruction? { self }
final public var definingBlock: BasicBlock { block }
fileprivate final override var resultCount: Int { 1 }
fileprivate final override func getResult(index: Int) -> Value { self }
}
public final class MultipleValueInstructionResult : Value {
final public var description: String {
var s = SILNode_debugDescription(bridgedNode)
return String(cString: s.c_str())
}
public var instruction: Instruction {
MultiValueInstResult_getParent(bridged).instruction
}
public var definingInstruction: Instruction? { instruction }
public var definingBlock: BasicBlock { instruction.block }
public var index: Int { MultiValueInstResult_getIndex(bridged) }
var bridged: BridgedMultiValueResult {
BridgedMultiValueResult(obj: SwiftObject(self))
}
var bridgedNode: BridgedNode { BridgedNode(obj: SwiftObject(self)) }
}
extension BridgedMultiValueResult {
var result: MultipleValueInstructionResult {
obj.getAs(MultipleValueInstructionResult.self)
}
}
public class MultipleValueInstruction : Instruction {
fileprivate final override var resultCount: Int {
return MultipleValueInstruction_getNumResults(bridged)
}
fileprivate final override func getResult(index: Int) -> Value {
MultipleValueInstruction_getResult(bridged, index).result
}
}
/// Instructions, which have a single operand.
public protocol UnaryInstruction : AnyObject {
var operands: OperandArray { get }
var operand: Value { get }
}
extension UnaryInstruction {
public var operand: Value { operands[0].value }
}
//===----------------------------------------------------------------------===//
// no-value instructions
//===----------------------------------------------------------------------===//
/// Used for all non-value instructions which are not implemented here, yet.
/// See registerBridgedClass() in SILBridgingUtils.cpp.
final public class UnimplementedInstruction : Instruction {
}
public protocol StoringInstruction : AnyObject {
var operands: OperandArray { get }
}
extension StoringInstruction {
public var sourceOperand: Operand { return operands[0] }
public var destinationOperand: Operand { return operands[1] }
public var source: Value { return sourceOperand.value }
public var destination: Value { return destinationOperand.value }
}
final public class StoreInst : Instruction, StoringInstruction {
// must match with enum class StoreOwnershipQualifier
public enum StoreOwnership: Int {
case unqualified = 0, initialize = 1, assign = 2, trivial = 3
}
public var destinationOwnership: StoreOwnership {
StoreOwnership(rawValue: StoreInst_getStoreOwnership(bridged))!
}
}
final public class StoreWeakInst : Instruction, StoringInstruction { }
final public class StoreUnownedInst : Instruction, StoringInstruction { }
final public class CopyAddrInst : Instruction {
public var sourceOperand: Operand { return operands[0] }
public var destinationOperand: Operand { return operands[1] }
public var source: Value { return sourceOperand.value }
public var destination: Value { return destinationOperand.value }
public var isTakeOfSrc: Bool {
CopyAddrInst_isTakeOfSrc(bridged) != 0
}
public var isInitializationOfDest: Bool {
CopyAddrInst_isInitializationOfDest(bridged) != 0
}
}
final public class EndAccessInst : Instruction, UnaryInstruction {
public var beginAccess: BeginAccessInst {
return operand as! BeginAccessInst
}
}
final public class EndBorrowInst : Instruction, UnaryInstruction {}
final public class DeallocStackInst : Instruction, UnaryInstruction {
public var allocstack: AllocStackInst {
return operand as! AllocStackInst
}
}
final public class DeallocStackRefInst : Instruction, UnaryInstruction {
public var allocRef: AllocRefInstBase { operand as! AllocRefInstBase }
}
final public class CondFailInst : Instruction, UnaryInstruction {
public override var mayTrap: Bool { true }
public var message: String { CondFailInst_getMessage(bridged).string }
}
final public class FixLifetimeInst : Instruction, UnaryInstruction {}
final public class DebugValueInst : Instruction, UnaryInstruction {}
final public class UnconditionalCheckedCastAddrInst : Instruction {
public override var mayTrap: Bool { true }
}
final public class SetDeallocatingInst : Instruction, UnaryInstruction {}
final public class DeallocRefInst : Instruction, UnaryInstruction {}
public class RefCountingInst : Instruction, UnaryInstruction {
public var isAtomic: Bool { RefCountingInst_getIsAtomic(bridged) }
}
final public class StrongRetainInst : RefCountingInst {
}
final public class RetainValueInst : RefCountingInst {
}
final public class StrongReleaseInst : RefCountingInst {
}
final public class ReleaseValueInst : RefCountingInst {
}
final public class DestroyValueInst : Instruction, UnaryInstruction {}
final public class DestroyAddrInst : Instruction, UnaryInstruction {}
final public class InjectEnumAddrInst : Instruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { InjectEnumAddrInst_caseIndex(bridged) }
}
final public class UnimplementedRefCountingInst : RefCountingInst {}
//===----------------------------------------------------------------------===//
// single-value instructions
//===----------------------------------------------------------------------===//
/// Used for all SingleValueInstructions which are not implemented here, yet.
/// See registerBridgedClass() in SILBridgingUtils.cpp.
final public class UnimplementedSingleValueInst : SingleValueInstruction {
}
final public class LoadInst : SingleValueInstruction, UnaryInstruction {}
final public class LoadWeakInst : SingleValueInstruction, UnaryInstruction {}
final public class LoadUnownedInst : SingleValueInstruction, UnaryInstruction {}
final public class LoadBorrowInst : SingleValueInstruction, UnaryInstruction {}
final public class BuiltinInst : SingleValueInstruction {
// TODO: find a way to directly reuse the BuiltinValueKind enum
public enum ID {
case None
case DestroyArray
}
public var id: ID? {
switch BuiltinInst_getID(bridged) {
case DestroyArrayBuiltin: return .DestroyArray
default: return .None
}
}
}
final public class UpcastInst : SingleValueInstruction, UnaryInstruction {}
final public
class UncheckedRefCastInst : SingleValueInstruction, UnaryInstruction {}
final public
class RawPointerToRefInst : SingleValueInstruction, UnaryInstruction {}
final public
class AddressToPointerInst : SingleValueInstruction, UnaryInstruction {}
final public
class PointerToAddressInst : SingleValueInstruction, UnaryInstruction {}
final public
class IndexAddrInst : SingleValueInstruction {}
final public
class InitExistentialRefInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialRefInst : SingleValueInstruction, UnaryInstruction {}
final public
class InitExistentialValueInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialValueInst : SingleValueInstruction, UnaryInstruction {}
final public
class InitExistentialAddrInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialAddrInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialBoxInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialBoxValueInst : SingleValueInstruction, UnaryInstruction {}
final public
class InitExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {}
final public
class OpenExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {}
final public
class ValueMetatypeInst : SingleValueInstruction, UnaryInstruction {}
final public
class ExistentialMetatypeInst : SingleValueInstruction, UnaryInstruction {}
public class GlobalAccessInst : SingleValueInstruction {
final public var global: GlobalVariable {
GlobalAccessInst_getGlobal(bridged).globalVar
}
}
final public class FunctionRefInst : GlobalAccessInst {
public var referencedFunction: Function {
FunctionRefInst_getReferencedFunction(bridged).function
}
}
final public class GlobalAddrInst : GlobalAccessInst {}
final public class GlobalValueInst : GlobalAccessInst {}
final public class IntegerLiteralInst : SingleValueInstruction {}
final public class StringLiteralInst : SingleValueInstruction {
public var string: String { StringLiteralInst_getValue(bridged).string }
}
final public class TupleInst : SingleValueInstruction {
}
final public class TupleExtractInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { TupleExtractInst_fieldIndex(bridged) }
}
final public
class TupleElementAddrInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { TupleElementAddrInst_fieldIndex(bridged) }
}
final public class StructInst : SingleValueInstruction {
}
final public class StructExtractInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { StructExtractInst_fieldIndex(bridged) }
}
final public
class StructElementAddrInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { StructElementAddrInst_fieldIndex(bridged) }
}
public protocol EnumInstruction : AnyObject {
var caseIndex: Int { get }
}
final public class EnumInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { EnumInst_caseIndex(bridged) }
public var operand: Value? { operands.first?.value }
}
final public class UncheckedEnumDataInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { UncheckedEnumDataInst_caseIndex(bridged) }
}
final public class InitEnumDataAddrInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { InitEnumDataAddrInst_caseIndex(bridged) }
}
final public class UncheckedTakeEnumDataAddrInst : SingleValueInstruction, UnaryInstruction, EnumInstruction {
public var caseIndex: Int { UncheckedTakeEnumDataAddrInst_caseIndex(bridged) }
}
final public class RefElementAddrInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { RefElementAddrInst_fieldIndex(bridged) }
}
final public class RefTailAddrInst : SingleValueInstruction, UnaryInstruction {}
final public
class UnconditionalCheckedCastInst : SingleValueInstruction, UnaryInstruction {
public override var mayTrap: Bool { true }
}
final public
class ConvertFunctionInst : SingleValueInstruction, UnaryInstruction {}
final public
class ThinToThickFunctionInst : SingleValueInstruction, UnaryInstruction {}
final public
class ObjCExistentialMetatypeToObjectInst : SingleValueInstruction,
UnaryInstruction {}
final public
class ObjCMetatypeToObjectInst : SingleValueInstruction, UnaryInstruction {}
final public
class ValueToBridgeObjectInst : SingleValueInstruction, UnaryInstruction {}
final public
class MarkDependenceInst : SingleValueInstruction {
public var value: Value { return operands[0].value }
public var base: Value { return operands[1].value }
}
final public class RefToBridgeObjectInst : SingleValueInstruction,
UnaryInstruction {}
final public class BridgeObjectToRefInst : SingleValueInstruction,
UnaryInstruction {}
final public class BridgeObjectToWordInst : SingleValueInstruction,
UnaryInstruction {}
final public class BeginAccessInst : SingleValueInstruction, UnaryInstruction {}
final public class BeginBorrowInst : SingleValueInstruction, UnaryInstruction {}
final public class ProjectBoxInst : SingleValueInstruction, UnaryInstruction {
public var fieldIndex: Int { ProjectBoxInst_fieldIndex(bridged) }
}
final public class CopyValueInst : SingleValueInstruction, UnaryInstruction {}
final public class EndCOWMutationInst : SingleValueInstruction, UnaryInstruction {}
final public
class ClassifyBridgeObjectInst : SingleValueInstruction, UnaryInstruction {}
final public class PartialApplyInst : SingleValueInstruction, ApplySite {
public var numArguments: Int { PartialApplyInst_numArguments(bridged) }
public var isOnStack: Bool { PartialApplyInst_isOnStack(bridged) != 0 }
public func calleeArgIndex(callerArgIndex: Int) -> Int {
PartialApply_getCalleeArgIndexOfFirstAppliedArg(bridged) + callerArgIndex
}
public func callerArgIndex(calleeArgIndex: Int) -> Int? {
let firstIdx = PartialApply_getCalleeArgIndexOfFirstAppliedArg(bridged)
if calleeArgIndex >= firstIdx {
return calleeArgIndex - firstIdx
}
return nil
}
}
final public class ApplyInst : SingleValueInstruction, FullApplySite {
public var numArguments: Int { ApplyInst_numArguments(bridged) }
public var singleDirectResult: Value? { self }
}
final public class ClassMethodInst : SingleValueInstruction, UnaryInstruction {}
final public class SuperMethodInst : SingleValueInstruction, UnaryInstruction {}
final public class ObjCMethodInst : SingleValueInstruction, UnaryInstruction {}
final public class ObjCSuperMethodInst : SingleValueInstruction, UnaryInstruction {}
final public class WitnessMethodInst : SingleValueInstruction {}
final public class IsUniqueInst : SingleValueInstruction, UnaryInstruction {}
final public class IsEscapingClosureInst : SingleValueInstruction, UnaryInstruction {}
//===----------------------------------------------------------------------===//
// single-value allocation instructions
//===----------------------------------------------------------------------===//
public protocol Allocation : AnyObject { }
final public class AllocStackInst : SingleValueInstruction, Allocation {
}
public class AllocRefInstBase : SingleValueInstruction, Allocation {
final public var isObjC: Bool { AllocRefInstBase_isObjc(bridged) != 0 }
final public var canAllocOnStack: Bool {
AllocRefInstBase_canAllocOnStack(bridged) != 0
}
}
final public class AllocRefInst : AllocRefInstBase {
}
final public class AllocRefDynamicInst : AllocRefInstBase {
}
final public class AllocBoxInst : SingleValueInstruction, Allocation {
}
final public class AllocExistentialBoxInst : SingleValueInstruction, Allocation {
}
//===----------------------------------------------------------------------===//
// multi-value instructions
//===----------------------------------------------------------------------===//
final public class BeginCOWMutationInst : MultipleValueInstruction,
UnaryInstruction {
public var uniquenessResult: Value { return getResult(index: 0) }
public var bufferResult: Value { return getResult(index: 1) }
}
final public class DestructureStructInst : MultipleValueInstruction, UnaryInstruction {
}
final public class DestructureTupleInst : MultipleValueInstruction, UnaryInstruction {
}
final public class BeginApplyInst : MultipleValueInstruction, FullApplySite {
public var numArguments: Int { BeginApplyInst_numArguments(bridged) }
public var singleDirectResult: Value? { nil }
}
//===----------------------------------------------------------------------===//
// terminator instructions
//===----------------------------------------------------------------------===//
public class TermInst : Instruction {
final public var successors: SuccessorArray {
SuccessorArray(succArray: TermInst_getSuccessors(bridged))
}
}
final public class UnreachableInst : TermInst {
}
final public class ReturnInst : TermInst, UnaryInstruction {
}
final public class ThrowInst : TermInst, UnaryInstruction {
}
final public class YieldInst : TermInst {
}
final public class UnwindInst : TermInst {
}
final public class TryApplyInst : TermInst, FullApplySite {
public var numArguments: Int { TryApplyInst_numArguments(bridged) }
public var normalBlock: BasicBlock { successors[0] }
public var errorBlock: BasicBlock { successors[1] }
public var singleDirectResult: Value? { normalBlock.arguments[0] }
}
final public class BranchInst : TermInst {
public var targetBlock: BasicBlock { BranchInst_getTargetBlock(bridged).block }
public func getArgument(for operand: Operand) -> Argument {
return targetBlock.arguments[operand.index]
}
}
final public class CondBranchInst : TermInst {
var trueBlock: BasicBlock { successors[0] }
var falseBlock: BasicBlock { successors[1] }
var condition: Value { operands[0].value }
var trueOperands: OperandArray { operands[1...CondBranchInst_getNumTrueArgs(bridged)] }
var falseOperands: OperandArray {
let ops = operands
return ops[(CondBranchInst_getNumTrueArgs(bridged) &+ 1)..<ops.count]
}
public func getArgument(for operand: Operand) -> Argument {
let argIdx = operand.index - 1
let numTrueArgs = CondBranchInst_getNumTrueArgs(bridged)
if (0..<numTrueArgs).contains(argIdx) {
return trueBlock.arguments[argIdx]
} else {
return falseBlock.arguments[argIdx - numTrueArgs]
}
}
}
final public class SwitchValueInst : TermInst {
}
final public class SwitchEnumInst : TermInst {
public var enumOp: Value { operands[0].value }
public struct CaseIndexArray : RandomAccessCollection {
fileprivate let switchEnum: SwitchEnumInst
public var startIndex: Int { return 0 }
public var endIndex: Int { SwitchEnumInst_getNumCases(switchEnum.bridged) }
public subscript(_ index: Int) -> Int {
SwitchEnumInst_getCaseIndex(switchEnum.bridged, index)
}
}
var caseIndices: CaseIndexArray { CaseIndexArray(switchEnum: self) }
var cases: Zip2Sequence<CaseIndexArray, SuccessorArray> {
zip(caseIndices, successors)
}
// This does not handle the special case where the default covers exactly
// the "missing" case.
public func getUniqueSuccessor(forCaseIndex: Int) -> BasicBlock? {
cases.first(where: { $0.0 == forCaseIndex })?.1
}
// This does not handle the special case where the default covers exactly
// the "missing" case.
public func getUniqueCase(forSuccessor: BasicBlock) -> Int? {
cases.first(where: { $0.1 == forSuccessor })?.0
}
}
final public class SwitchEnumAddrInst : TermInst {
}
final public class DynamicMethodBranchInst : TermInst {
}
final public class AwaitAsyncContinuationInst : TermInst, UnaryInstruction {
}
final public class CheckedCastBranchInst : TermInst, UnaryInstruction {
}
final public class CheckedCastAddrBranchInst : TermInst, UnaryInstruction {
}
| d4af5ddb6dd306ef36fc7b66f72781b3 | 31.24507 | 110 | 0.728007 | false | false | false | false |
mike-ferenduros/SwiftySockets | refs/heads/master | Sources/BufferedSocket.swift | mit | 1 | //
// BufferedSocket.swift
// SwiftySockets
//
// Created by Michael Ferenduros on 11/09/2016.
// Copyright © 2016 Mike Ferenduros. All rights reserved.
//
import Foundation
open class BufferedSocket : DispatchSocket, DispatchSocketReadableDelegate, DispatchSocketWritableDelegate {
override public var debugDescription: String {
return "BufferedSocket(\(socket.debugDescription))"
}
override open func close() throws {
readQueue.removeAll()
writeQueue.removeAll()
try super.close()
}
/**
Read exactly `count` bytes.
- Parameter count: Number of bytes to read
- Parameter completion: Completion-handler, invoked on DispatchQueue.main on success
*/
public func read(_ count: Int, completion: @escaping (Data)->()) {
read(min: count, max: count, completion: completion)
}
/**
Read up to `max` bytes
- Parameter max: Maximum number of bytes to read
- Parameter completion: Completion-handler, invoked on DispatchQueue.main on success
*/
public func read(max: Int, completion: @escaping (Data)->()) {
read(min: 1, max: max, completion: completion)
}
/**
Read at least `min` bytes, up to `max` bytes
- Parameter min: Minimum number of bytes to read
- Parameter min: Maximum number of bytes to read
- Parameter completion: Completion-handler, invoked on DispatchQueue.main on success
*/
public func read(min: Int, max: Int, completion: @escaping (Data)->()) {
precondition(min <= max)
precondition(min > 0)
guard isOpen else { return }
let newItem = ReadItem(buffer: Data(capacity: max), min: min, max: max, completion: completion)
readQueue.append(newItem)
readableDelegate = self
}
private struct ReadItem {
var buffer: Data
let min, max: Int
let completion: (Data)->()
}
private var readQueue: [ReadItem] = []
open func dispatchSocketReadable(_ socket: DispatchSocket, count: Int) {
guard count > 0 else { try? close(); return }
do {
while var item = readQueue.first {
let wanted = item.max - item.buffer.count
let buffer = try self.socket.recv(length: min(wanted, count), options: .dontWait)
item.buffer.append(buffer)
readQueue[0] = item
if item.buffer.count >= item.min {
readQueue.removeFirst()
item.completion(item.buffer)
} else {
break
}
}
}
catch POSIXError(EAGAIN) {}
catch POSIXError(EWOULDBLOCK) {}
catch {
try? close()
}
if readQueue.count == 0 {
readableDelegate = nil
}
}
private var writeQueue: [Data] = []
/**
Asynchronously write data to the connected socket.
For stream-type sockets, the entire contents of `data` is always written
For datagram-type sockets, only a single datagram is sent, hence the data may be truncated.
- Parameter data: Data to be written.
*/
public func write(_ data: Data) {
guard isOpen else { return }
var data = data
//Try and shortcut the whole dispatch-source stuff if possible.
if writeQueue.count == 0, let written = try? self.socket.send(buffer: data, options: .dontWait), written > 0 {
if written == data.count || self.type == .datagram {
return
} else {
data = data.subdata(in: written ..< data.count)
}
}
writeQueue.append(data)
writableDelegate = self
}
open func dispatchSocketWritable(_ socket: DispatchSocket) {
do {
while let packet = writeQueue.first {
let written = try self.socket.send(buffer: packet, options: .dontWait)
if written == packet.count || self.type == .datagram {
//Datagrams are truncated to whatever gets accepted by a single send()
_ = writeQueue.removeFirst()
} else {
if written > 0 {
//For streams, we try and send the entire packet, even if it takes multiple calls
writeQueue[0] = packet.subdata(in: written ..< packet.count)
}
break
}
}
} catch POSIXError(EAGAIN) {
} catch POSIXError(EWOULDBLOCK) {
} catch {
try? close()
return
}
if writeQueue.count == 0 {
writableDelegate = nil
}
}
}
| 1e2b58741005bfd86550b59747864941 | 31.14966 | 118 | 0.570673 | false | false | false | false |
wangmingjob/Dodo | refs/heads/master | Dodo/Style/DodoBarStyle.swift | mit | 2 | import UIKit
/// Defines styles related to the bar view in general.
public class DodoBarStyle {
/// The parent style is used to get the property value if the object is missing one.
var parent: DodoBarStyle?
init(parentStyle: DodoBarStyle? = nil) {
self.parent = parentStyle
}
/// Clears the styles for all properties for this style object. The styles will be taken from parent and default properties.
public func clear() {
_animationHide = nil
_animationHideDuration = nil
_animationShow = nil
_animationShowDuration = nil
_backgroundColor = nil
_borderColor = nil
_borderWidth = nil
_cornerRadius = nil
_debugMode = nil
_hideAfterDelaySeconds = nil
_hideOnTap = nil
_locationTop = nil
_marginToSuperview = nil
}
// -----------------------------
private var _animationHide: DodoAnimation?
/// Specify a function for animating the bar when it is hidden.
public var animationHide: DodoAnimation {
get {
return (_animationHide ?? parent?.animationHide) ?? DodoBarDefaultStyles.animationHide
}
set {
_animationHide = newValue
}
}
// ---------------------------
private var _animationHideDuration: NSTimeInterval?
/// Duration of hide animation. When nil it uses default duration for selected animation function.
public var animationHideDuration: NSTimeInterval? {
get {
return (_animationHideDuration ?? parent?.animationHideDuration) ??
DodoBarDefaultStyles.animationHideDuration
}
set {
_animationHideDuration = newValue
}
}
// ---------------------------
private var _animationShow: DodoAnimation?
/// Specify a function for animating the bar when it is shown.
public var animationShow: DodoAnimation {
get {
return (_animationShow ?? parent?.animationShow) ?? DodoBarDefaultStyles.animationShow
}
set {
_animationShow = newValue
}
}
// ---------------------------
private var _animationShowDuration: NSTimeInterval?
/// Duration of show animation. When nil it uses default duration for selected animation function.
public var animationShowDuration: NSTimeInterval? {
get {
return (_animationShowDuration ?? parent?.animationShowDuration) ??
DodoBarDefaultStyles.animationShowDuration
}
set {
_animationShowDuration = newValue
}
}
// ---------------------------
private var _backgroundColor: UIColor?
/// Background color of the bar.
public var backgroundColor: UIColor? {
get {
return _backgroundColor ?? parent?.backgroundColor ?? DodoBarDefaultStyles.backgroundColor
}
set {
_backgroundColor = newValue
}
}
// -----------------------------
private var _borderColor: UIColor?
/// Color of the bar's border.
public var borderColor: UIColor? {
get {
return _borderColor ?? parent?.borderColor ?? DodoBarDefaultStyles.borderColor
}
set {
_borderColor = newValue
}
}
// -----------------------------
private var _borderWidth: CGFloat?
/// Border width of the bar.
public var borderWidth: CGFloat {
get {
return _borderWidth ?? parent?.borderWidth ?? DodoBarDefaultStyles.borderWidth
}
set {
_borderWidth = newValue
}
}
// -----------------------------
private var _cornerRadius: CGFloat?
/// Corner radius of the bar view.
public var cornerRadius: CGFloat {
get {
return _cornerRadius ?? parent?.cornerRadius ?? DodoBarDefaultStyles.cornerRadius
}
set {
_cornerRadius = newValue
}
}
// -----------------------------
private var _debugMode: Bool?
/// When true it highlights the view background for spotting layout issues.
public var debugMode: Bool {
get {
return _debugMode ?? parent?.debugMode ?? DodoBarDefaultStyles.debugMode
}
set {
_debugMode = newValue
}
}
// ---------------------------
private var _hideAfterDelaySeconds: NSTimeInterval?
/**
Hides the bar automatically after the specified number of seconds.
If nil the bar is kept on screen.
*/
public var hideAfterDelaySeconds: NSTimeInterval {
get {
return _hideAfterDelaySeconds ?? parent?.hideAfterDelaySeconds ??
DodoBarDefaultStyles.hideAfterDelaySeconds
}
set {
_hideAfterDelaySeconds = newValue
}
}
// -----------------------------
private var _hideOnTap: Bool?
/// When true the bar is hidden when user taps on it.
public var hideOnTap: Bool {
get {
return _hideOnTap ?? parent?.hideOnTap ??
DodoBarDefaultStyles.hideOnTap
}
set {
_hideOnTap = newValue
}
}
// -----------------------------
private var _locationTop: Bool?
/// Position of the bar. When true the bar is shown on top of the screen.
public var locationTop: Bool {
get {
return _locationTop ?? parent?.locationTop ?? DodoBarDefaultStyles.locationTop
}
set {
_locationTop = newValue
}
}
// -----------------------------
private var _marginToSuperview: CGSize?
/// Margin between the bar edge and its superview.
public var marginToSuperview: CGSize {
get {
return _marginToSuperview ?? parent?.marginToSuperview ??
DodoBarDefaultStyles.marginToSuperview
}
set {
_marginToSuperview = newValue
}
}
// -----------------------------
} | 31503c88476798fa9e655f76c2ce6618 | 22.584746 | 126 | 0.599102 | false | false | false | false |
CodeEagle/RainbowTransition | refs/heads/master | Sources/ETNavBarTransparent.swift | mit | 1 | //
// ETNavBarTransparent.swift
// ETNavBarTransparentDemo
//
// Created by Bing on 2017/3/1.
// Copyright © 2017年 tanyunbing. All rights reserved.
//
import UIKit
import KVOBlock
extension UIColor {
// System default bar tint color
open class var defaultNavBarTintColor: UIColor {
return UIColor(red: 0, green: 0.478431, blue: 1, alpha: 1.0)
}
}
extension DispatchQueue {
private static var onceTracker = [String]()
public class func once(token: String, block: () -> Void) {
objc_sync_enter(self)
defer { objc_sync_exit(self) }
if onceTracker.contains(token) { return }
onceTracker.append(token)
block()
}
}
// MARK: - UINavigationController
extension UINavigationController {
public func enableRainbowTransition(with color: UIColor = .white, shadow enable: Bool = true) {
UINavigationController._initialize()
let bgg = NavigationBarrOverlay(frame: .zero)
let parent = getBarView().0
let barBackgroundView = getBarView().1
parent.addSubview(bgg)
parent.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[bgg]-0-|", options: NSLayoutFormatOptions.alignAllTop, metrics: nil, views: ["bgg": bgg]))
parent.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[bgg]-0-|", options: NSLayoutFormatOptions.directionLeftToRight, metrics: nil, views: ["bgg": bgg]))
bgg.tag = 9854
bgg.backgroundColor = color
bgg.shadowParent = barBackgroundView.layer
bgg.enableShadow(enable: enable)
}
fileprivate var lo_bg: NavigationBarrOverlay? {
let parent = getBarView().0
return parent.viewWithTag(9854) as? NavigationBarrOverlay
}
private func getBarView() -> (UIView, UIView) {
let barBackgroundView = navigationBar.subviews[0]
let valueForKey = barBackgroundView.value(forKey:)
var parenet = barBackgroundView
if navigationBar.isTranslucent {
if #available(iOS 10.0, *) {
if let backgroundEffectView = valueForKey("_backgroundEffectView") as? UIVisualEffectView, navigationBar.backgroundImage(for: .default) == nil {
parenet = backgroundEffectView.contentView
}
} else {
if let adaptiveBackdrop = valueForKey("_adaptiveBackdrop") as? UIView, let backdropEffectView = adaptiveBackdrop.value(forKey: "_backdropEffectView") as? UIVisualEffectView {
parenet = backdropEffectView.contentView
}
}
}
return (parenet, barBackgroundView)
}
public func enableShadow(enable: Bool = true) {
lo_bg?.enableShadow(enable: enable)
}
public var globalNavBarTintColor: UIColor {
get {
guard let tintColor = objc_getAssociatedObject(self, &AssociatedKeys.globalNavBarTintColor) as? UIColor else {
return UIColor.defaultNavBarTintColor
}
return tintColor
}
set {
navigationController?.navigationBar.tintColor = newValue
objc_setAssociatedObject(self, &AssociatedKeys.globalNavBarTintColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
open override var preferredStatusBarStyle: UIStatusBarStyle {
return topViewController?.preferredStatusBarStyle ?? .default
}
private static let onceToken = UUID().uuidString
internal static func _initialize() {
guard self == UINavigationController.self else { return }
DispatchQueue.once(token: onceToken) {
let needSwizzleSelectorArr = [
NSSelectorFromString("_updateInteractiveTransition:"),
#selector(popToViewController),
#selector(popToRootViewController),
]
for selector in needSwizzleSelectorArr {
let str = ("et_" + selector.description).replacingOccurrences(of: "__", with: "_")
// popToRootViewControllerAnimated: et_popToRootViewControllerAnimated:
let originalMethod = class_getInstanceMethod(self, selector)
let swizzledMethod = class_getInstanceMethod(self, Selector(str))
method_exchangeImplementations(originalMethod, swizzledMethod)
}
}
}
// MARK: swizzMethod
func et_updateInteractiveTransition(_ percentComplete: CGFloat) {
guard let topViewController = topViewController, let coordinator = topViewController.transitionCoordinator else {
et_updateInteractiveTransition(percentComplete)
return
}
let fromViewController = coordinator.viewController(forKey: .from)
let toViewController = coordinator.viewController(forKey: .to)
// Bg Alpha
let fromAlpha = fromViewController?.navBarBgAlpha ?? 0
let toAlpha = toViewController?.navBarBgAlpha ?? 0
let newAlpha = fromAlpha + (toAlpha - fromAlpha) * percentComplete
setNeedsNavigationBackground(alpha: newAlpha)
enableShadow(enable: toViewController?.navBarBgShadow ?? false)
// Tint Color
let fromColor = fromViewController?.navBarTintColor ?? globalNavBarTintColor
let toColor = toViewController?.navBarTintColor ?? globalNavBarTintColor
let newColor = averageColor(fromColor: fromColor, toColor: toColor, percent: percentComplete)
navigationBar.tintColor = newColor
let midColor = averageColor(fromColor: (fromViewController?.navBarBGColor ?? .white), toColor: (toViewController?.navBarBGColor ?? .white), percent: percentComplete)
lo_bg?.update(color: midColor.withAlphaComponent(toAlpha), drag: false)
et_updateInteractiveTransition(percentComplete)
}
// Calculate the middle Color with translation percent
private func averageColor(fromColor: UIColor, toColor: UIColor, percent: CGFloat) -> UIColor {
var fromRed: CGFloat = 0
var fromGreen: CGFloat = 0
var fromBlue: CGFloat = 0
var fromAlpha: CGFloat = 0
fromColor.getRed(&fromRed, green: &fromGreen, blue: &fromBlue, alpha: &fromAlpha)
var toRed: CGFloat = 0
var toGreen: CGFloat = 0
var toBlue: CGFloat = 0
var toAlpha: CGFloat = 0
toColor.getRed(&toRed, green: &toGreen, blue: &toBlue, alpha: &toAlpha)
let nowRed = fromRed + (toRed - fromRed) * percent
let nowGreen = fromGreen + (toGreen - fromGreen) * percent
let nowBlue = fromBlue + (toBlue - fromBlue) * percent
let nowAlpha = fromAlpha + (toAlpha - fromAlpha) * percent
return UIColor(red: nowRed, green: nowGreen, blue: nowBlue, alpha: nowAlpha)
}
func et_popToViewController(_ viewController: UIViewController, animated: Bool) -> [UIViewController]? {
setNeedsNavigationBackground(alpha: viewController.navBarBgAlpha)
let color = viewController.navBarBGColor
lo_bg?.update(color: color.withAlphaComponent(viewController.navBarBgAlpha), drag: lo_poping)
navigationBar.tintColor = viewController.navBarTintColor ?? globalNavBarTintColor
return et_popToViewController(viewController, animated: animated)
}
func et_popToRootViewControllerAnimated(_ animated: Bool) -> [UIViewController]? {
let alpha = viewControllers.first?.navBarBgAlpha ?? 0
setNeedsNavigationBackground(alpha: alpha)
let color = viewControllers.first?.navBarBGColor ?? .white
lo_bg?.update(color: color.withAlphaComponent(alpha), drag: lo_poping)
navigationBar.tintColor = viewControllers.first?.navBarTintColor ?? globalNavBarTintColor
return et_popToRootViewControllerAnimated(animated)
}
public func setNeedsNavigationBackground(alpha: CGFloat, animated: Bool = false) {
let barBackgroundView = navigationBar.subviews[0]
let valueForKey = barBackgroundView.value(forKey:)
if let shadowView = valueForKey("_shadowView") as? UIView {
shadowView.alpha = alpha
}
let color = topViewController?.navBarBGColor ?? .white
lo_bg?.update(color: color.withAlphaComponent(alpha), drag: lo_poping)
func aniamte(action: @escaping () -> Void) {
UIView.animate(withDuration: 0.2) {
action()
}
}
if navigationBar.isTranslucent {
if #available(iOS 10.0, *) {
if let backgroundEffectView = valueForKey("_backgroundEffectView") as? UIView, navigationBar.backgroundImage(for: .default) == nil {
if animated {
aniamte {
backgroundEffectView.alpha = alpha
}
} else {
backgroundEffectView.alpha = alpha
}
return
}
} else {
if let adaptiveBackdrop = valueForKey("_adaptiveBackdrop") as? UIView, let backdropEffectView = adaptiveBackdrop.value(forKey: "_backdropEffectView") as? UIView {
if animated {
aniamte {
backdropEffectView.alpha = alpha
}
} else {
backdropEffectView.alpha = alpha
}
return
}
}
}
if animated {
aniamte {
barBackgroundView.alpha = alpha
}
} else {
barBackgroundView.alpha = alpha
}
}
}
// MARK: - UINavigationBarDelegate
extension UINavigationController: UINavigationBarDelegate {
public func navigationBar(_ navigationBar: UINavigationBar, shouldPop _: UINavigationItem) -> Bool {
if let topVC = topViewController, let coor = topVC.transitionCoordinator, coor.initiallyInteractive {
if #available(iOS 10.0, *) {
coor.notifyWhenInteractionChanges { context in
self.dealInteractionChanges(context)
}
} else {
coor.notifyWhenInteractionEnds { context in
self.dealInteractionChanges(context)
}
}
return true
}
let itemCount = navigationBar.items?.count ?? 0
let n = viewControllers.count >= itemCount ? 2 : 1
let popToVC = viewControllers[viewControllers.count - n]
enableShadow(enable: popToVC.navBarBgShadow)
lo_bg?.update(color: popToVC.navBarBGColor, drag: false)
popToViewController(popToVC, animated: true)
return true
}
public func navigationBar(_ navigationBar: UINavigationBar, shouldPush _: UINavigationItem) -> Bool {
setNeedsNavigationBackground(alpha: topViewController?.navBarBgAlpha ?? 0)
enableShadow(enable: topViewController?.navBarBgShadow ?? false)
lo_bg?.update(color: (topViewController?.navBarBGColor ?? .white).withAlphaComponent(topViewController?.navBarBgAlpha ?? 1), drag: false)
navigationBar.tintColor = topViewController?.navBarTintColor ?? globalNavBarTintColor
return true
}
private func dealInteractionChanges(_ context: UIViewControllerTransitionCoordinatorContext) {
let animations: (UITransitionContextViewControllerKey) -> Void = {
let nowAlpha = context.viewController(forKey: $0)?.navBarBgAlpha ?? 0
self.setNeedsNavigationBackground(alpha: nowAlpha)
self.navigationBar.tintColor = (context.viewController(forKey: $0)?.navBarTintColor) ?? self.globalNavBarTintColor
}
if context.isCancelled {
let cancelDuration: TimeInterval = context.transitionDuration * Double(context.percentComplete)
let vc = context.viewController(forKey: .to)
vc?.lo_poping = true
let shadow = context.viewController(forKey: .from)?.navBarBgShadow ?? false
enableShadow(enable: shadow)
lo_bg?.update(color: (topViewController?.navBarBGColor ?? .white).withAlphaComponent(topViewController?.navBarBgAlpha ?? 1), drag: false)
UIView.animate(withDuration: cancelDuration, animations: {
animations(.from)
}, completion: { _ in
vc?.lo_poping = false
})
} else {
let finishDuration: TimeInterval = context.transitionDuration * Double(1 - context.percentComplete)
UIView.animate(withDuration: finishDuration) {
animations(.to)
}
}
}
}
// MARK: - UIViewController extension
extension UIViewController {
fileprivate struct AssociatedKeys {
static var navBarBgShadow: String = "navBarBgShadow"
static var navBarBgAlpha: CGFloat = 1.0
static var globalNavBarTintColor: UIColor = UIColor.defaultNavBarTintColor
static var navBarTintColor: UIColor = UIColor.defaultNavBarTintColor
static var navBarBGColor: UIColor = UIColor.white
static var bg = "bg"
static var poping = "poping"
static let keyPath = "contentOffset"
static var distance = "distance"
static var scrollView = "_RKeys_.scrollView"
static var scrollViewWrapper = "_RKeys_.scrollViewWrapper"
}
public var navBarBgShadow: Bool {
get {
guard let value = objc_getAssociatedObject(self, &AssociatedKeys.navBarBgShadow) as? Bool else { return false }
return value
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.navBarBgShadow, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
navigationController?.lo_bg?.enableShadow(enable: newValue)
}
}
public var navBarBgAlpha: CGFloat {
get {
guard let alpha = objc_getAssociatedObject(self, &AssociatedKeys.navBarBgAlpha) as? CGFloat else { return 1.0 }
return alpha
}
set {
let alpha = max(min(newValue, 1), 0) // 必须在 0~1的范围
objc_setAssociatedObject(self, &AssociatedKeys.navBarBgAlpha, alpha, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
navigationController?.setNeedsNavigationBackground(alpha: alpha)
}
}
public func setNavBarBgAlphaAnimated(value: CGFloat) {
let alpha = max(min(value, 1), 0) // 必须在 0~1的范围
objc_setAssociatedObject(self, &AssociatedKeys.navBarBgAlpha, alpha, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
navigationController?.setNeedsNavigationBackground(alpha: value, animated: true)
}
public var navBarTintColor: UIColor? {
get {
let tintColor = objc_getAssociatedObject(self, &AssociatedKeys.navBarTintColor) as? UIColor
return tintColor
}
set {
navigationController?.navigationBar.tintColor = newValue
objc_setAssociatedObject(self, &AssociatedKeys.navBarTintColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public var navBarBGColor: UIColor {
get {
guard let tintColor = objc_getAssociatedObject(self, &AssociatedKeys.navBarBGColor) as? UIColor else {
return UIColor.white
}
return tintColor
}
set {
objc_setAssociatedObject(self, &AssociatedKeys.navBarBGColor, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate var lo_poping: Bool {
get { return (objc_getAssociatedObject(self, &AssociatedKeys.poping) as? Bool) ?? false }
set { objc_setAssociatedObject(self, &AssociatedKeys.poping, newValue, .OBJC_ASSOCIATION_RETAIN) }
}
private var lo_ob: Bool {
get { return (objc_getAssociatedObject(self, &AssociatedKeys.scrollView) as? Bool) ?? false }
set { objc_setAssociatedObject(self, &AssociatedKeys.scrollView, newValue, .OBJC_ASSOCIATION_RETAIN) }
}
private var lo_distance: CGFloat {
get { return (objc_getAssociatedObject(self, &AssociatedKeys.distance) as? CGFloat) ?? 0 }
set { objc_setAssociatedObject(self, &AssociatedKeys.distance, newValue, .OBJC_ASSOCIATION_RETAIN) }
}
private var _wrapper: ScrollViewWrapper {
get {
if let wrapper = objc_getAssociatedObject(self, &AssociatedKeys.scrollViewWrapper) as? ScrollViewWrapper {
return wrapper
}
let wrapper = ScrollViewWrapper()
objc_setAssociatedObject(self, &AssociatedKeys.scrollViewWrapper, wrapper, .OBJC_ASSOCIATION_RETAIN)
return wrapper
}
set { objc_setAssociatedObject(self, &AssociatedKeys.scrollViewWrapper, newValue, .OBJC_ASSOCIATION_RETAIN) }
}
public func transparent(with scroll: UIScrollView?, total distance: CGFloat = 200, force: Bool = false, setAlphaForFirstTime: Bool = true) {
guard let value = scroll else { return }
if force == false, lo_ob == true { return }
lo_ob = true
if let sc = _wrapper.scrollView { sc.removeObserver(for: AssociatedKeys.keyPath) }
_wrapper.scrollView = value
lo_distance = distance
var fisrtTime = false
value.observeKeyPath(AssociatedKeys.keyPath, with: { [weak self]
_, oldValue, newValue in
guard let navi = self?.navigationController, navi.topViewController == self, self?.lo_poping == false else { return }
guard let v = newValue as? CGPoint, let o = oldValue as? CGPoint else { return }
if v == o, v == .zero { return }
var a = v.y / distance
if a < 0 { a = 0 }
if a > 1 { a = 1 }
if fisrtTime, setAlphaForFirstTime == false {
fisrtTime = false
return
}
self?.navBarBgAlpha = a
self?.setNeedsStatusBarAppearanceUpdate()
})
}
public func rt_alpha(for scrollView: UIScrollView) -> CGFloat {
if lo_distance == 0 { return 1 }
var a = scrollView.contentOffset.y / lo_distance
if a < 0 { a = 0 }
if a > 1 { a = 1 }
return a
}
public func unregister(scollView: UIScrollView?) {
scollView?.removeObserver(for: AssociatedKeys.keyPath)
}
}
private final class ScrollViewWrapper {
weak var scrollView: UIScrollView?
}
// MARK: - NavigationBarrOverlay
private final class NavigationBarrOverlay: UIView {
weak var shadowParent: CALayer?
lazy var shadowMask: CAGradientLayer = {
let gMask = CAGradientLayer()
gMask.colors = [UIColor(white: 0, alpha: 0.4).cgColor, UIColor.clear.cgColor]
gMask.locations = [0, 1]
gMask.anchorPoint = CGPoint.zero
gMask.startPoint = CGPoint(x: 0.5, y: 0)
gMask.endPoint = CGPoint(x: 0.5, y: 1)
gMask.opacity = 0
return gMask
}()
fileprivate func enableShadow(enable: Bool = true) {
if enable {
if shadowMask.superlayer != layer {
shadowParent?.addSublayer(shadowMask)
}
} else {
shadowMask.removeFromSuperlayer()
}
}
override init(frame _: CGRect) {
super.init(frame: .zero)
initialize()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialize()
}
private func initialize() {
isUserInteractionEnabled = false
translatesAutoresizingMaskIntoConstraints = false
shadowParent?.addSublayer(shadowMask)
}
fileprivate override func layoutSubviews() {
super.layoutSubviews()
shadowMask.frame = bounds
}
fileprivate func update(color value: UIColor, drag: Bool) {
let alpha = Float(value.cgColor.alpha)
if drag { shadowMask.opacity = 1 - alpha }
else {
if alpha != 0 { shadowMask.opacity = 0 }
else if shadowMask.opacity != 1 {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2, execute: { [weak self] in
self?.shadowMask.opacity = 1
})
}
}
backgroundColor = value
}
}
| 1a1ef805e2d1c3dd5d7f6c13ad1248cd | 39.896761 | 190 | 0.633173 | false | false | false | false |
coach-plus/ios | refs/heads/master | Pods/SwiftDate/Sources/SwiftDate/Formatters/RelativeFormatter/RelativeFormatterLanguage.swift | mit | 1 | //
// SwiftDate
// Parse, validate, manipulate, and display dates, time and timezones in Swift
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
//
import Foundation
internal class RelativeFormatterLanguagesCache {
static let shared = RelativeFormatterLanguagesCache()
private(set) var cachedValues = [String: [String: Any]]()
func flavoursForLocaleID(_ langID: String) -> [String: Any]? {
do {
guard let fullURL = Bundle(for: RelativeFormatter.self).resourceURL?.appendingPathComponent("langs/\(langID).json") else {
return nil
}
let data = try Data(contentsOf: fullURL)
let json = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions.allowFragments)
if let value = json as? [String: Any] {
cachedValues[langID] = value
return value
} else {
return nil
}
} catch {
debugPrint("Failed to read data for language id: \(langID)")
return nil
}
}
}
public enum RelativeFormatterLanguage: String, CaseIterable {
case af = "af" // Locales.afrikaans
case am = "am" // Locales.amharic
case ar_AE = "ar_AE" // Locales.arabicUnitedArabEmirates
case ar = "ar" // Locales.arabic
case `as` = "as" // Locales.assamese
case az = "az" // Locales.assamese
case be = "be" // Locales.belarusian
case bg = "bg" // Locales.bulgarian
case bn = "bn" // Locales.bengali
case br = "br" // Locales.breton
case bs = "bs" // Locales.bosnian
case bs_Cyrl = "bs-Cyrl" // Locales.belarusian
case ca = "ca" // Locales.catalan
case cz = "cz" // Locales.czech
case cy = "cy" // Locales.welsh
case cs = "cs" // Locales.czech
case da = "da" // Locales.danish
case de = "de" // Locales.dutch
case dsb = "dsb" // Locales.lowerSorbian
case dz = "dz" // Locales.dzongkha
case ee = "ee" // Locales.ewe
case el = "el" // Locales.greek
case en = "en" // Locales.english
case es_AR = "es_AR" // Locales.spanishArgentina
case es_PY = "es_PY" // Locales.spanishParaguay
case es_MX = "es_MX" // Locales.spanishMexico
case es_US = "es_US" // Locales.spanishUnitedStates
case es = "es" // Locales.spanish
case et = "et" // Locales.estonian
case eu = "eu" // Locales.basque
case fa = "fa" // Locales.persian
case fi = "fi" // Locales.finnish
case fil = "fil" // Locales.filipino
case fo = "fo" // Locales.faroese
case fr_CA = "fr_CA" // French (Canada)
case fr = "fr" // French
case fur = "fur" // Friulian
case fy = "fy" // Western Frisian
case ga = "ga" // Irish
case gd = "gd" // Scottish Gaelic
case gl = "gl" // Galician
case gu = "gu" // Gujarati
case he = "he" // Hebrew
case hi = "hi" // Hindi
case hr = "hr" // Croatian
case hsb = "hsb" // Upper Sorbian
case hu = "hu" // Hungarian
case hy = "hy" // Armenian
case id = "id" // Indonesian
case `is` = "is" // Icelandic
case it = "it" // Locales.italian
case ja = "ja" // Japanese
case jgo = "jgo" // Ngomba
case ka = "ka" // Georgian
case kea = "kea" // Kabuverdianu
case kk = "kk" // Kazakh
case kl = "kl" // Kalaallisut
case km = "km" // Khmer
case kn = "kn" // Kannada
case ko = "ko" // Korean
case kok = "kok" // Konkani
case ksh = "ksh" // Colognian
case ky = "ky" // Kyrgyz
case lb = "lb" // Luxembourgish
case lkt = "lkt" // Lakota
case lo = "lo" // Lao
case lt = "lt" // Lithuanian
case lv = "lv" // Latvian
case mk = "mk" // Macedonian
case ml = "ml" // Malayalam
case mn = "mn" // Mongolian
case mr = "mr" // Marathi
case ms = "ms" // Malay
case mt = "mt" // Maltese
case my = "my" // Burmese
case mzn = "mzn" // Mazanderani
case nb = "nb" // Norwegian Bokmål
case ne = "ne" // Nepali
case nl = "nl" // Netherland
case nn = "nn" // Norwegian Nynorsk
case or = "or" // Odia
case pa = "pa" // Punjabi
case pl = "pl" // Polish
case ps = "ps" // Pashto
case pt = "pt" // Portuguese
case ro = "ro" // Romanian
case ru = "ru" // Russian
case sah = "sah" // Sakha
case sd = "sd" // Sindhi
case se_FI = "se_FI" // Northern Sami (Finland)
case se = "se" // Northern Sami
case si = "si" // Sinhala
case sk = "sk" // Slovak
case sl = "sl" // Slovenian
case sq = "sq" // Albanian
case sr_Latn = "sr_Latn" // Serbian (Latin)
case sr = "sr" // Serbian
case sv = "sv" // Swedish
case sw = "sw" // Swedish
case ta = "ta" // Tamil
case te = "te" // Telugu
case th = "th" // Thai
case ti = "ti" // Tigrinya
case tk = "tk" // Turkmen
case to = "to" // Tongan
case tr = "tr" // Turkish
case ug = "ug" // Uyghur
case uk = "uk" // Ukrainian
case ur_IN = "ur_IN" // Urdu (India)
case ur = "ur" // Urdu
case uz_Cyrl = "uz_Cyrl" // Uzbek (Cyrillic)
case uz = "uz" // Uzbek (Cyrillic)
case vi = "vi" // Vietnamese
case wae = "wae" // Walser
case yue_Hans = "yue_Hans" // Cantonese (Simplified)
case yue_Hant = "yue_Hant" // Cantonese (Traditional)
case zh_Hans_HK = "zh_Hans_HK" // Chinese (Simplified, Hong Kong [China])
case zh_Hans_MO = "zh_Hans_MO" // Chinese (Simplified, Macau [China])
case zh_Hans_SG = "zh_Hans_SG" // Chinese (Simplified, Singapore)
case zh_Hant_HK = "zh_Hant_HK" // Chinese (Traditional, Hong Kong [China])
case zh_Hant_MO = "zh_Hant_MO" // Chinese (Traditional, Macau [China])
case zh_Hans = "zh_Hans" // Chinese (Simplified)
case zh_Hant = "zh_Hant" // Chinese (Traditional)
case zh = "zh" // Chinese
case zu = "zu" // Zulu
/// Table with the data of the language.
/// Data is structured in:
/// { flavour: { unit : { data } } }
public var flavours: [String: Any] {
return RelativeFormatterLanguagesCache.shared.flavoursForLocaleID(self.rawValue) ?? [:]
}
public var identifier: String {
return self.rawValue
}
public func quantifyKey(forValue value: Double) -> RelativeFormatter.PluralForm? {
switch self {
case .sr_Latn, .sr, .uk:
let mod10 = Int(value) % 10
let mod100 = Int(value) % 100
switch mod10 {
case 1:
switch mod100 {
case 11:
break
default:
return .one
}
case 2, 3, 4:
switch mod100 {
case 12, 13, 14:
break
default:
return .few
}
default:
break
}
return .many
case .ru, .sk, .sl:
let mod10 = Int(value) % 10
let mod100 = Int(value) % 100
switch mod100 {
case 11...14:
break
default:
switch mod10 {
case 1:
return .one
case 2...4:
return .few
default:
break
}
}
return .many
case .ro:
let mod100 = Int(value) % 100
switch value {
case 0:
return .few
case 1:
return .one
default:
if mod100 > 1 && mod100 <= 19 {
return .few
}
}
return .other
case .pa:
switch value {
case 0, 1:
return .one
default:
return .other
}
case .mt:
switch value {
case 1: return .one
case 0: return .few
case 2...10: return .few
case 11...19: return .many
default: return .other
}
case .lt, .lv:
let mod10 = Int(value) % 10
let mod100 = Int(value) % 100
if value == 0 {
return .zero
}
if value == 1 {
return .one
}
switch mod10 {
case 1:
if mod100 != 11 {
return .one
}
return .many
default:
return .many
}
case .ksh, .se:
switch value {
case 0: return .zero
case 1: return .one
default: return .other
}
case .`is`:
let mod10 = Int(value) % 10
let mod100 = Int(value) % 100
if value == 0 {
return .zero
}
if value == 1 {
return .one
}
switch mod10 {
case 1:
if mod100 != 11 {
return .one
}
default:
break
}
return .many
case .id, .ja, .ms, .my, .mzn, .sah, .se_FI, .si, .th, .yue_Hans, .yue_Hant,
.zh_Hans_HK, .zh_Hans_MO, .zh_Hans_SG, .zh_Hant_HK, .zh_Hant_MO, .zh:
return .other
case .hy:
return (value >= 0 && value < 2 ? .one : .other)
case .ga, .gd:
switch Int(value) {
case 1: return .one
case 2: return .two
case 3...6: return .few
case 7...10: return .many
default: return .other
}
case .fr_CA, .fr:
return (value >= 0 && value < 2 ? .one : .other)
case .dz, .kea, .ko, .kok, .lkt, .lo:
return nil
case .cs: // Locales.czech
switch value {
case 1:
return .one
case 2, 3, 4:
return .few
default:
return .other
}
case .cy:
switch value {
case 0: return .zero
case 1: return .one
case 2: return .two
case 3: return .few
case 6: return .many
default: return .other
}
case .cz, .dsb:
switch value {
case 1:
return .one
case 2, 3, 4:
return .few
default:
return .other
}
case .br:
let n = Int(value)
return n % 10 == 1 && n % 100 != 11 && n % 100 != 71 && n % 100 != 91 ? .zero : n % 10 == 2 && n % 100 != 12 && n % 100 != 72 && n % 100 != 92 ? .one : (n % 10 == 3 || n % 10 == 4 || n % 10 == 9) && n % 100 != 13 && n % 100 != 14 && n % 100 != 19 && n % 100 != 73 && n % 100 != 74 && n % 100 != 79 && n % 100 != 93 && n % 100 != 94 && n % 100 != 99 ? .two : n % 1_000_000 == 0 && n != 0 ? .many : .other
case .be, .bs, .bs_Cyrl, .hr, .hsb, .pl:
let mod10 = Int(value) % 10
let mod100 = Int(value) % 100
switch mod10 {
case 1:
switch mod100 {
case 11:
break
default:
return .one
}
case 2, 3, 4:
switch mod100 {
case 12, 13, 14:
break
default:
return .few
}
default:
break
}
return .many
case .ar, .ar_AE, .he:
switch value {
case 0: return .zero
case 1: return .one
case 2: return .two
default:
let mod100 = Int(value) % 100
if mod100 >= 3 && mod100 <= 10 {
return .few
} else if mod100 >= 11 {
return .many
} else {
return .other
}
}
case .am, .bn, .fa, .gu, .kn, .mr, .zu:
return (value >= 0 && value <= 1 ? .one : .other)
default:
return (value == 1 ? .one : .other)
}
}
}
| c9c3da2cf054bd402da6882fb3717c9d | 28.615202 | 415 | 0.462785 | false | false | false | false |
dn-m/PitchSpellingTools | refs/heads/master | PitchSpellingTools/PitchSpellingDyad.swift | mit | 1 | //
// PitchSpellingDyad.swift
// PitchSpellingTools
//
// Created by James Bean on 5/2/16.
//
//
import ArithmeticTools
/**
Pair of two `PitchSpelling` objects.
- TODO: Consider transfering concerns to `SpelledDyad`.
*/
public struct PitchSpellingDyad {
internal let a: PitchSpelling
internal let b: PitchSpelling
// MARK: - Instance Properties
/**
`true` if `quarterStep` values of both `PitchSpelling` objects are equivalent.
Otherwise `false`.
*/
public var isCoarseMatching: Bool {
return a.quarterStep == b.quarterStep
}
/**
`true` if `quarterStep.direction` value of either `PitchSpelling` is `natural` or if
`isCoarseCoarseCompatible`. Otherwise `false`.
*/
public var isCoarseCompatible: Bool {
return eitherIsNatural || isCoarseMatching
}
/**
`true` if `quarterStep.direction` values of both `PitchSpelling` values are equivalent.
Otherwise `false`.
*/
public var isCoarseDirectionMatching: Bool {
return a.quarterStep.direction == b.quarterStep.direction
}
/**
`true` if `quarterStep.direction` value of either `PitchSpelling` is `natural` or if
`isCoarseDirectionMatching`. Otherwise `false`.
*/
public var isCoarseDirectionCompatible: Bool {
return eitherIsNatural || isCoarseDirectionMatching
}
/**
`true` if `quarterStep.resolution` values of both `PitchSpelling` values are equivalent.
Otherwise `false`.
*/
public var isCoarseResolutionMatching: Bool {
return a.quarterStep.resolution == b.quarterStep.resolution
}
/**
`true` if `quarterStep.direction` value of either `PitchSpelling` is `natural` or if
`isCoarseResolutionMatching`. Otherwise `false`.
*/
public var isCoarseResolutionCompatible: Bool {
return eitherIsNatural || isCoarseResolutionMatching
}
/**
`true` if the `letterName` values of both `PitchSpelling` values are equivalent.
Otherwise, `false.
*/
public var isLetterNameMatching: Bool {
return a.letterName == b.letterName
}
/**
`true if `eighthStep` values of `PitchSpelling` objects are equivalent. Otherwise `false`.
*/
public var isFineMatching: Bool {
return a.eighthStep == b.eighthStep
}
/**
- warning: Undocumented!
*/
public var isFineCompatible: Bool {
// manage close seconds
guard eitherHasEighthStepModifier else { return true }
if eitherHasNoEighthStepModifier && (eitherIsNatural || isCoarseMatching) {
return !isLetterNameMatching
}
return isFineMatching
}
/// Mean of `spellingDistance` values of both `PitchSpelling` objects.
public var meanSpellingDistance: Float {
return mean(Float(a.spellingDistance), Float(b.spellingDistance))
}
/// Mean of `quarterStep.distance` values of both `PitchSpelling objects.
public var meanCoarseDistance: Float {
return mean(Float(a.quarterStep.distance), Float(b.quarterStep.distance))
}
/// Amount of steps between two `PitchSpelling` objects.
internal var steps: Int {
let difference = b.letterName.steps - a.letterName.steps
return abs(difference % 7)
//return abs(Int.mod(difference, 7))
}
fileprivate var eitherIsNatural: Bool {
return a.quarterStep == .natural || b.quarterStep == .natural
}
fileprivate var eitherHasNoEighthStepModifier: Bool {
return a.eighthStep == .none || b.eighthStep == .none
}
fileprivate var eitherHasEighthStepModifier: Bool {
return a.eighthStep != .none || b.eighthStep != .none
}
// MARK: - Initializers
/**
Create a `PitchSpellingDyad` with two `PitchSpelling` objects.
*/
public init(_ a: PitchSpelling, _ b: PitchSpelling) {
self.a = a
self.b = b
}
}
extension PitchSpellingDyad: Hashable {
// MARK: - Hashable
/// Hash value.
public var hashValue: Int { return b.hashValue * a.hashValue }
}
extension PitchSpellingDyad: Equatable { }
public func == (lhs: PitchSpellingDyad, rhs: PitchSpellingDyad) -> Bool {
return lhs.b == rhs.b && lhs.a == rhs.a
}
extension PitchSpellingDyad: CustomStringConvertible {
// MARK: - CustomStringConvertible
/// Printed description.
public var description: String {
return "(\(a) , \(b))"
}
}
| 50095601d680dffe859f255436b368cf | 27.198758 | 95 | 0.642952 | false | false | false | false |
CuriousLLC/RobotController | refs/heads/master | RobotController/Message.swift | mit | 1 | //
// Message.swift
// RobotController
//
// Created by ryan day on 11/26/15.
// Copyright © 2015 Curious. All rights reserved.
//
import Foundation
enum MessageTyoe {
case AddServo, RotateType, RotateServo, ClearServo
}
class Message {
let SOM:UInt8 = 0xf0
let EOM:UInt8 = 0xf1
func serialize() -> [UInt8] {
return []
}
}
class AddServoMessage : Message {
let messageType:UInt8 = 1
let size:UInt8 = 3
var _servoType: UInt8
var _gpio: UInt8
init(gpio: UInt8, servoType: UInt8) {
_servoType = servoType
_gpio = gpio
}
func setInverse() {
_servoType |= 0x80
}
override func serialize() -> [UInt8]{
return [SOM, size, messageType, _servoType, _gpio, EOM]
}
}
class RotateServoTypeMessage : Message {
let messageType:UInt8 = 2
let size:UInt8 = 4
var _mask: UInt8
var _pulseWidth: UInt16
init(mask: UInt8, pulseWidth: UInt16) {
_mask = mask
_pulseWidth = pulseWidth
}
override func serialize() -> [UInt8]{
return [SOM, size, messageType, _mask, UInt8(_pulseWidth >> 8), UInt8(_pulseWidth & 0xff), EOM]
}
}
class RotateServoMessage : Message {
let messageType:UInt8 = 3
let size:UInt8 = 4
var _gpio: UInt8
var _pulseWidth: UInt16
init(gpio: UInt8, pulseWidth: UInt16) {
_gpio = gpio
_pulseWidth = pulseWidth
}
override func serialize() -> [UInt8]{
return [SOM, size, messageType, _gpio, UInt8(_pulseWidth >> 8), UInt8(_pulseWidth & 0xff), EOM]
}
}
class ClearServosMessage : Message {
let messageType:UInt8 = 6
let size:UInt8 = 1
override func serialize() -> [UInt8]{
return [SOM, size, messageType, EOM]
}
} | a4fc2e9f374facb05d41bf945efcb9de | 20.385542 | 103 | 0.602593 | false | false | false | false |
KrishMunot/swift | refs/heads/master | stdlib/internal/SwiftExperimental/SwiftExperimental.swift | apache-2.0 | 5 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
// Experimental APIs of the Swift Standard Library
//
// This library contains experimental APIs that can be subject to change or
// removal. We don't guarantee API or ABI stability for this library.
//
//===----------------------------------------------------------------------===//
import Swift
/// The function composition operator is the only user-defined operator that
/// operates on functions. That's why the numeric value of precedence does
/// not matter right now.
infix operator ∘ {
// The character is U+2218 RING OPERATOR.
//
// Confusables:
//
// U+00B0 DEGREE SIGN
// U+02DA RING ABOVE
// U+25CB WHITE CIRCLE
// U+25E6 WHITE BULLET
associativity left
precedence 100
}
/// Compose functions.
///
/// (g ∘ f)(x) == g(f(x))
///
/// - Returns: a function that applies ``g`` to the result of applying ``f``
/// to the argument of the new function.
public func ∘<T, U, V>(g: U -> V, f: T -> U) -> (T -> V) {
return { g(f($0)) }
}
infix operator ∖ { associativity left precedence 140 }
infix operator ∖= { associativity right precedence 90 assignment }
infix operator ∪ { associativity left precedence 140 }
infix operator ∪= { associativity right precedence 90 assignment }
infix operator ∩ { associativity left precedence 150 }
infix operator ∩= { associativity right precedence 90 assignment }
infix operator ⨁ { associativity left precedence 140 }
infix operator ⨁= { associativity right precedence 90 assignment }
infix operator ∈ { associativity left precedence 130 }
infix operator ∉ { associativity left precedence 130 }
infix operator ⊂ { associativity left precedence 130 }
infix operator ⊄ { associativity left precedence 130 }
infix operator ⊆ { associativity left precedence 130 }
infix operator ⊈ { associativity left precedence 130 }
infix operator ⊃ { associativity left precedence 130 }
infix operator ⊅ { associativity left precedence 130 }
infix operator ⊇ { associativity left precedence 130 }
infix operator ⊉ { associativity left precedence 130 }
/// - Returns: The relative complement of `lhs` with respect to `rhs`.
public func ∖ <
T, S: Sequence where S.Iterator.Element == T
>(lhs: Set<T>, rhs: S) -> Set<T> {
return lhs.subtract(rhs)
}
/// Assigns the relative complement between `lhs` and `rhs` to `lhs`.
public func ∖= <
T, S: Sequence where S.Iterator.Element == T
>(lhs: inout Set<T>, rhs: S) {
lhs.subtractInPlace(rhs)
}
/// - Returns: The union of `lhs` and `rhs`.
public func ∪ <
T, S: Sequence where S.Iterator.Element == T
>(lhs: Set<T>, rhs: S) -> Set<T> {
return lhs.union(rhs)
}
/// Assigns the union of `lhs` and `rhs` to `lhs`.
public func ∪= <
T, S: Sequence where S.Iterator.Element == T
>(lhs: inout Set<T>, rhs: S) {
lhs.unionInPlace(rhs)
}
/// - Returns: The intersection of `lhs` and `rhs`.
public func ∩ <
T, S: Sequence where S.Iterator.Element == T
>(lhs: Set<T>, rhs: S) -> Set<T> {
return lhs.intersect(rhs)
}
/// Assigns the intersection of `lhs` and `rhs` to `lhs`.
public func ∩= <
T, S: Sequence where S.Iterator.Element == T
>(lhs: inout Set<T>, rhs: S) {
lhs.intersectInPlace(rhs)
}
/// - Returns: A set with elements in `lhs` or `rhs` but not in both.
public func ⨁ <
T, S: Sequence where S.Iterator.Element == T
>(lhs: Set<T>, rhs: S) -> Set<T> {
return lhs.exclusiveOr(rhs)
}
/// Assigns to `lhs` the set with elements in `lhs` or `rhs` but not in both.
public func ⨁= <
T, S: Sequence where S.Iterator.Element == T
>(lhs: inout Set<T>, rhs: S) {
lhs.exclusiveOrInPlace(rhs)
}
/// - Returns: True if `x` is in the set.
public func ∈ <T>(x: T, rhs: Set<T>) -> Bool {
return rhs.contains(x)
}
/// - Returns: True if `x` is not in the set.
public func ∉ <T>(x: T, rhs: Set<T>) -> Bool {
return !rhs.contains(x)
}
/// - Returns: True if `lhs` is a strict subset of `rhs`.
public func ⊂ <
T, S: Sequence where S.Iterator.Element == T
>(lhs: Set<T>, rhs: S) -> Bool {
return lhs.isStrictSubsetOf(rhs)
}
/// - Returns: True if `lhs` is not a strict subset of `rhs`.
public func ⊄ <
T, S: Sequence where S.Iterator.Element == T
>(lhs: Set<T>, rhs: S) -> Bool {
return !lhs.isStrictSubsetOf(rhs)
}
/// - Returns: True if `lhs` is a subset of `rhs`.
public func ⊆ <
T, S: Sequence where S.Iterator.Element == T
>(lhs: Set<T>, rhs: S) -> Bool {
return lhs.isSubsetOf(rhs)
}
/// - Returns: True if `lhs` is not a subset of `rhs`.
public func ⊈ <
T, S: Sequence where S.Iterator.Element == T
>(lhs: Set<T>, rhs: S) -> Bool {
return !lhs.isSubsetOf(rhs)
}
/// - Returns: True if `lhs` is a strict superset of `rhs`.
public func ⊃ <
T, S: Sequence where S.Iterator.Element == T
>(lhs: Set<T>, rhs: S) -> Bool {
return lhs.isStrictSupersetOf(rhs)
}
/// - Returns: True if `lhs` is not a strict superset of `rhs`.
public func ⊅ <
T, S: Sequence where S.Iterator.Element == T
>(lhs: Set<T>, rhs: S) -> Bool {
return !lhs.isStrictSupersetOf(rhs)
}
/// - Returns: True if `lhs` is a superset of `rhs`.
public func ⊇ <
T, S: Sequence where S.Iterator.Element == T
>(lhs: Set<T>, rhs: S) -> Bool {
return lhs.isSupersetOf(rhs)
}
/// - Returns: True if `lhs` is not a superset of `rhs`.
public func ⊉ <
T, S: Sequence where S.Iterator.Element == T
>(lhs: Set<T>, rhs: S) -> Bool {
return !lhs.isSupersetOf(rhs)
}
| 735f0d579f52acbfa797192bee723eaf | 30.497297 | 80 | 0.633259 | false | false | false | false |
diwu/LeetCode-Solutions-in-Swift | refs/heads/master | Solutions/SolutionsTests/Hard/Hard_037_Sudoku_Solver_Test.swift | mit | 1 | //
// Hard_037_Sudoku_Solver_Test.swift
// Solutions
//
// Created by Di Wu on 5/13/15.
// Copyright (c) 2015 diwu. All rights reserved.
//
import XCTest
class Hard_037_Sudoku_Solver_Test: XCTestCase, SolutionsTestCase {
func test_001() {
let input: [[Character]] = [
["5", "3", ".", ".", "7", ".", ".", ".", "."],
["6", ".", ".", "1", "9", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."],
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."],
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
[".", ".", ".", ".", "8", ".", ".", "7", "9"],
]
let expected: [[Character]] = [
["5", "3", "4", "6", "7", "8", "9", "1", "2"],
["6", "7", "2", "1", "9", "5", "3", "4", "8"],
["1", "9", "8", "3", "4", "2", "5", "6", "7"],
["8", "5", "9", "7", "6", "1", "4", "2", "3"],
["4", "2", "6", "8", "5", "3", "7", "9", "1"],
["7", "1", "3", "9", "2", "4", "8", "5", "6"],
["9", "6", "1", "5", "3", "7", "2", "8", "4"],
["2", "8", "7", "4", "1", "9", "6", "3", "5"],
["3", "4", "5", "2", "8", "6", "1", "7", "9"],
]
asyncHelper(input: input, expected: expected)
}
func test_002() {
let input: [[Character]] = [
[".", "3", ".", ".", "7", ".", "9", ".", "."],
["6", ".", ".", "1", "9", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."],
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."],
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
[".", ".", ".", ".", "8", ".", ".", "7", "9"],
]
let expected: [[Character]] = [
["5", "3", "4", "6", "7", "8", "9", "1", "2"],
["6", "7", "2", "1", "9", "5", "3", "4", "8"],
["1", "9", "8", "3", "4", "2", "5", "6", "7"],
["8", "5", "9", "7", "6", "1", "4", "2", "3"],
["4", "2", "6", "8", "5", "3", "7", "9", "1"],
["7", "1", "3", "9", "2", "4", "8", "5", "6"],
["9", "6", "1", "5", "3", "7", "2", "8", "4"],
["2", "8", "7", "4", "1", "9", "6", "3", "5"],
["3", "4", "5", "2", "8", "6", "1", "7", "9"],
]
asyncHelper(input: input, expected: expected)
}
func test_003() {
let input: [[Character]] = [
["5", "3", ".", ".", "7", ".", ".", ".", "."],
["6", ".", ".", "1", "9", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."],
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", ".", ".", "1"],
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."],
[".", ".", ".", "4", ".", "9", ".", ".", "5"],
["3", ".", ".", ".", "8", ".", ".", "7", "9"],
]
let expected: [[Character]] = [
["5", "3", "4", "6", "7", "8", "9", "1", "2"],
["6", "7", "2", "1", "9", "5", "3", "4", "8"],
["1", "9", "8", "3", "4", "2", "5", "6", "7"],
["8", "5", "9", "7", "6", "1", "4", "2", "3"],
["4", "2", "6", "8", "5", "3", "7", "9", "1"],
["7", "1", "3", "9", "2", "4", "8", "5", "6"],
["9", "6", "1", "5", "3", "7", "2", "8", "4"],
["2", "8", "7", "4", "1", "9", "6", "3", "5"],
["3", "4", "5", "2", "8", "6", "1", "7", "9"],
]
asyncHelper(input: input, expected: expected)
}
func test_004() {
let input: [[Character]] = [
["5", "3", ".", ".", "7", ".", ".", ".", "."],
["6", ".", ".", "1", ".", "5", ".", ".", "."],
[".", "9", "8", ".", ".", ".", ".", "6", "."],
["8", ".", ".", ".", "6", ".", ".", ".", "3"],
["4", ".", ".", "8", ".", "3", "7", ".", "1"],
["7", ".", ".", ".", "2", ".", ".", ".", "6"],
[".", "6", ".", ".", ".", ".", "2", "8", "."],
[".", ".", ".", "4", "1", "9", ".", ".", "5"],
[".", ".", ".", ".", "8", ".", ".", "7", "9"],
]
let expected: [[Character]] = [
["5", "3", "4", "6", "7", "8", "9", "1", "2"],
["6", "7", "2", "1", "9", "5", "3", "4", "8"],
["1", "9", "8", "3", "4", "2", "5", "6", "7"],
["8", "5", "9", "7", "6", "1", "4", "2", "3"],
["4", "2", "6", "8", "5", "3", "7", "9", "1"],
["7", "1", "3", "9", "2", "4", "8", "5", "6"],
["9", "6", "1", "5", "3", "7", "2", "8", "4"],
["2", "8", "7", "4", "1", "9", "6", "3", "5"],
["3", "4", "5", "2", "8", "6", "1", "7", "9"],
]
asyncHelper(input: input, expected: expected)
}
private func asyncHelper(input ipt: [[Character]], expected: [[Character]]) {
var input = ipt
weak var expectation: XCTestExpectation? = self.expectation(description:timeOutName())
serialQueue().async(execute: { () -> Void in
Hard_037_Sudoku_Solver.solveSudoku(&input)
let result: [[Character]] = input
for i in 0..<9 {
assertHelper(expected[i] == result[i], problemName:self.problemName(), input: input, resultValue: result, expectedValue: expected)
}
if let unwrapped = expectation {
unwrapped.fulfill()
}
})
waitForExpectations(timeout:timeOut()) { (error: Error?) -> Void in
if error != nil {
assertHelper(false, problemName:self.problemName(), input: input, resultValue:self.timeOutName(), expectedValue: expected)
}
}
}
}
| 32dd01897a0b845831eaaba167ac5833 | 40.734694 | 146 | 0.241076 | false | true | false | false |
james-gray/selektor | refs/heads/master | Selektor/MetadataParser.swift | gpl-3.0 | 1 | //
// MetadataParser.swift
// Selektor
//
// Created by James Gray on 2016-06-20.
// Copyright © 2016 James Gray. All rights reserved.
//
import AVFoundation
import Foundation
class MetadataParser {
// MARK: Custom lets for 3-character ID3 v2.3 tag names
static let AVMetadataID322MetadataKeyTitle: String = "TT2"
static let AVMetadataID322MetadataKeyArtist: String = "TP1"
static let AVMetadataID322MetadataKeyAlbum: String = "TAL"
static let AVMetadataID322MetadataKeyInitialKey: String = "TKE"
static let AVMetadataID322MetadataKeyBeatsPerMin: String = "TBP"
/// Formats parseable by `MetadataParser.`
let formats: Dictionary<String, String> = [
"itunes": AVMetadataFormatiTunesMetadata,
"id3": AVMetadataFormatID3Metadata,
]
/// Mapping of standard tag names to the corresponding `TrackEntity` properties
/// by metadata format.
let tags: [String: [String: String]] = [
// iTunes
AVMetadataFormatiTunesMetadata: [
AVMetadataiTunesMetadataKeySongName: "name",
AVMetadataiTunesMetadataKeyArtist: "artist",
AVMetadataiTunesMetadataKeyAlbum: "album",
AVMetadataiTunesMetadataKeyUserGenre: "genre",
AVMetadataiTunesMetadataKeyBeatsPerMin: "tempo",
],
// id3
AVMetadataFormatID3Metadata: [
AVMetadataID3MetadataKeyTitleDescription: "name",
AVMetadataID3MetadataKeyOriginalArtist: "artist",
AVMetadataID3MetadataKeyLeadPerformer: "artist",
AVMetadataID3MetadataKeyBand: "artist",
AVMetadataID3MetadataKeyAlbumTitle: "album",
AVMetadataID3MetadataKeyBeatsPerMinute: "tempo",
MetadataParser.AVMetadataID322MetadataKeyTitle: "name",
MetadataParser.AVMetadataID322MetadataKeyArtist: "artist",
MetadataParser.AVMetadataID322MetadataKeyAlbum: "album",
MetadataParser.AVMetadataID322MetadataKeyBeatsPerMin: "tempo",
],
// Quicktime Meta
AVMetadataFormatQuickTimeMetadata: [
AVMetadataQuickTimeMetadataKeyTitle: "name",
AVMetadataQuickTimeMetadataKeyArtist: "artist",
AVMetadataQuickTimeMetadataKeyOriginalArtist: "artist",
AVMetadataQuickTimeMetadataKeyAlbum: "album",
AVMetadataQuickTimeMetadataKeyGenre: "genre",
],
// Quicktime User
AVMetadataFormatQuickTimeUserData: [
AVMetadataQuickTimeUserDataKeyTrackName: "name",
AVMetadataQuickTimeUserDataKeyArtist: "artist",
AVMetadataQuickTimeUserDataKeyOriginalArtist: "artist",
AVMetadataQuickTimeUserDataKeyAlbum: "album",
],
]
/**
Parse a given asset's metadata, choosing from among the available metadata
formats.
- parameter asset: The track asset to parse metadata from.
- returns: A dictionary of values that can be used to instantiate
a `TrackEntity`.
*/
func parse(asset: AVURLAsset) -> [String: AnyObject] {
var trackMeta = [String: AnyObject]()
for format in asset.availableMetadataFormats {
trackMeta = parseMetadataFormat(asset, trackMeta: trackMeta, format: format)
}
return trackMeta
}
/**
Extract metadata of format `format` from the given asset's metadata tags
and add it to the `trackMeta` dictionary.
- parameter asset: The asset to extract metadata from.
- parameter trackMeta: The metadata dict to populate.
- parameter format: The string metadata format (for example "com.apple.itunes").
- returns: The mutated `trackMeta` dict.
*/
func parseMetadataFormat(asset: AVURLAsset, trackMeta: [String: AnyObject], format: String)
-> [String: AnyObject] {
var trackMeta = trackMeta
var key: String = ""
guard let tags = self.tags[format] else {
print("Found unknown tag format '\(format)', skipping")
return trackMeta
}
let meta = asset.metadataForFormat(format).filter {
(item) in tags.keys.contains(item.keyString)
}
for item in meta {
// Set each metadata item in the track meta dict if it isn't already set
key = tags[item.keyString]!
if let value = item.value {
trackMeta[key] = trackMeta[key] ?? value
}
}
return trackMeta
}
} | c5e88516b3a50afdff1777726b94d906 | 33.475 | 93 | 0.711557 | false | false | false | false |
KhunLam/Swift_weibo | refs/heads/master | LKSwift_weibo/LKSwift_weibo/Classes/Library/PhotoBrowser/Animation/LKPhotoBrowserModalAnimation.swift | apache-2.0 | 1 | //
// LKPhotoBrowserModalAnimation.swift
// LKSwift_weibo
//
// Created by lamkhun on 15/11/11.
// Copyright © 2015年 lamKhun. All rights reserved.
//
import UIKit
class LKPhotoBrowserModalAnimation: NSObject, UIViewControllerAnimatedTransitioning {
// 返回动画的时间
func transitionDuration(transitionContext: UIViewControllerContextTransitioning?) -> NSTimeInterval {
return 0.5
}
// 自定义动画
func animateTransition(transitionContext: UIViewControllerContextTransitioning) {
// 获取modal出来的控制器的view
let toView = transitionContext.viewForKey(UITransitionContextToViewKey)!
// 让图片View 隐藏 动画显示出来
toView.alpha = 0
// 添加到容器视图
transitionContext.containerView()?.addSubview(toView)
// 获取Modal出来的控制器
let toVC = transitionContext.viewControllerForKey(UITransitionContextToViewControllerKey) as! LKPhotoBrowserViewController
// 获取过渡的视图
let tempImageView = toVC.modalTempImageView()
// TODO: 测试,添加到window上面
// UIApplication.sharedApplication().keyWindow?.addSubview(tempImageView)
transitionContext.containerView()?.addSubview(tempImageView)
// 隐藏collectionView
toVC.collectionView.hidden = true
// 动画
UIView.animateWithDuration(transitionDuration(nil), animations: { () -> Void in
// 设置透明
toView.alpha = 1
// 设置过渡视图的frame 移动到这里
tempImageView.frame = toVC.modalTargetFrame()
}) { (_) -> Void in
// 移除过渡视图
tempImageView.removeFromSuperview()
// 显示collectioView
toVC.collectionView.hidden = false
// 转场完成
transitionContext.completeTransition(true)
}
}
}
| 00c317cc19520a1556f733a2c45890c3 | 27.985075 | 130 | 0.593718 | false | false | false | false |
ffried/FFUIKit | refs/heads/master | Sources/FFUIKit/Extensions/UIScrollView+Keyboard.swift | apache-2.0 | 1 | //
// UIScrollView+Keyboard.swift
// FFUIkit
//
// Created by Florian Friedrich on 20.2.15.
// Copyright 2015 Florian Friedrich
//
// 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(watchOS)
import enum ObjectiveC.objc_AssociationPolicy
import func ObjectiveC.objc_getAssociatedObject
import func ObjectiveC.objc_setAssociatedObject
import Foundation
import UIKit
private var _keyboardNotificationObserversKey = "KeyboardNotificationsObserver"
@available(tvOS, unavailable)
extension UIScrollView {
private typealias UserInfoDictionary = Dictionary<AnyHashable, Any>
private final var notificationObservers: Array<NSObjectProtocol> {
get {
guard let observers = objc_getAssociatedObject(self, &_keyboardNotificationObserversKey) as? Array<NSObjectProtocol>
else { return [] }
return observers
}
set { objc_setAssociatedObject(self, &_keyboardNotificationObserversKey, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) }
}
// MARK: Register / Unregister
public final func registerForKeyboardNotifications() {
typealias ObserverBlock = (Notification) -> Void
func block(for selector: @escaping (UserInfoDictionary) -> ()) -> ObserverBlock {
return { $0.userInfo.map(selector) }
}
let tuples: [(Notification.Name, ObserverBlock)] = [
(UIResponder.keyboardWillChangeFrameNotification, block(for: keyboardWillChangeFrame)),
(UIResponder.keyboardWillShowNotification, block(for: keyboardWillShow)),
(UIResponder.keyboardDidHideNotification, block(for: keyboardDidHide))
]
notificationObservers = tuples.map { NotificationCenter.default.addObserver(forName: $0, object: nil, queue: .main, using: $1) }
}
public final func unregisterFromKeyboardNotifications() {
notificationObservers.removeAll()
}
// MARK: Keyboard functions
private final func keyboardWillChangeFrame(userInfo: UserInfoDictionary) {
guard keyboardVisible else { return }
let beginFrame = rect(for: UIResponder.keyboardFrameBeginUserInfoKey, in: userInfo)
let endFrame = rect(for: UIResponder.keyboardFrameEndUserInfoKey, in: userInfo)
let oldHeight = keyboardHeight(from: beginFrame)
let newHeight = keyboardHeight(from: endFrame)
if newHeight != oldHeight {
setInsetsTo(keyboardHeight: newHeight, animated: true, withKeyboardUserInfo: userInfo)
}
}
private final func keyboardWillShow(userInfo: UserInfoDictionary) {
guard !keyboardVisible else { return }
saveEdgeInsets()
keyboardVisible = true
let endFrame = rect(for: UIResponder.keyboardFrameEndUserInfoKey, in: userInfo)
let endHeight = keyboardHeight(from: endFrame)
setInsetsTo(keyboardHeight: endHeight, animated: true, withKeyboardUserInfo: userInfo)
}
private final func keyboardDidHide(userInfo: UserInfoDictionary) {
guard keyboardVisible else { return }
keyboardVisible = false
restoreEdgeInsets(animated: true, userInfo: userInfo)
}
// MARK: Height Adjustments
private final func setInsetsTo(keyboardHeight height: CGFloat, animated: Bool = false, withKeyboardUserInfo userInfo: UserInfoDictionary? = nil) {
let changes: () -> () = {
self.contentInset.bottom = height
if #available(iOS 11.1, tvOS 11.1, macCatalyst 13.0, *) {
self.horizontalScrollIndicatorInsets.bottom = height
self.verticalScrollIndicatorInsets.bottom = height
} else {
self.scrollIndicatorInsets.bottom = height
}
}
let offsetChanges: () -> () = {
if let fr = UIResponder.firstResponder(in: self) as? UIView {
let respFrame = self.convert(fr.frame, from: fr.superview)
self.scrollRectToVisible(respFrame, animated: animated)
}
}
if animated {
animate(changes, withKeyboardUserInfo: userInfo) { _ in offsetChanges() }
} else {
changes()
offsetChanges()
}
}
// MARK: EdgeInsets
private final func saveEdgeInsets() {
originalContentInsets = contentInset
if #available(iOS 11.1, tvOS 11.1, macCatalyst 13.0, *) {
originalHorizontalScrollIndicatorInsets = horizontalScrollIndicatorInsets
originalVerticalScrollIndicatorInsets = verticalScrollIndicatorInsets
} else {
originalScrollIndicatorInsets = scrollIndicatorInsets
}
}
private final func restoreEdgeInsets(animated: Bool = false, userInfo: UserInfoDictionary? = nil) {
let changes: () -> () = {
self.contentInset = self.originalContentInsets
if #available(iOS 11.1, tvOS 11.1, macCatalyst 13.0, *) {
self.horizontalScrollIndicatorInsets = self.originalHorizontalScrollIndicatorInsets
self.verticalScrollIndicatorInsets = self.originalVerticalScrollIndicatorInsets
} else {
self.scrollIndicatorInsets = self.originalScrollIndicatorInsets
}
}
if animated {
animate(changes, withKeyboardUserInfo: userInfo)
} else {
changes()
}
}
// MARK: Helpers
private final func rect(for key: String, in userInfo: UserInfoDictionary) -> CGRect {
(userInfo[key] as? NSValue)?.cgRectValue ?? .zero
}
private final func keyboardHeight(from rect: CGRect) -> CGFloat {
guard let w = window else { return 0 }
let windowFrame = w.convert(bounds, from: self)
let keyboardFrame = windowFrame.intersection(rect)
let coveredFrame = w.convert(keyboardFrame, to: self)
return coveredFrame.size.height
}
private final func animate(_ animations: @escaping () -> (), withKeyboardUserInfo userInfo: UserInfoDictionary? = nil, completion: ((_ finished: Bool) -> ())? = nil) {
var duration: TimeInterval = 1 / 3
var curve: UIView.AnimationCurve = .linear
let options: UIView.AnimationOptions
if let info = userInfo {
if let d = info[UIResponder.keyboardAnimationDurationUserInfoKey] as? TimeInterval { duration = d }
if let c = UIView.AnimationCurve(rawValue: (info[UIResponder.keyboardAnimationCurveUserInfoKey] as? UIView.AnimationCurve.RawValue ?? curve.rawValue)) { curve = c }
}
if #available(iOS 13, tvOS 13, watchOS 6, macCatalyst 13, *) {
assert(UIView.AnimationOptions.curveEaseIn.rawValue == UInt(UIView.AnimationCurve.easeIn.rawValue) << 16)
options = [.beginFromCurrentState, .allowAnimatedContent, .allowUserInteraction, UIView.AnimationOptions(rawValue: UInt(curve.rawValue) << 16)]
} else {
options = [.beginFromCurrentState, .allowAnimatedContent, .allowUserInteraction]
}
UIView.animate(withDuration: duration, delay: 0, options: options, animations: {
if #available(iOS 13, tvOS 13, watchOS 6, macCatalyst 13, *) {} else {
UIView.setAnimationCurve(curve)
}
animations()
}, completion: completion)
}
}
private var _originalContentInsetsKey = "OriginalContentInsets"
private var _originalScrollIndicatorInsetsKey = "OriginalScrollIndicatorInsets"
private var _originalHorizontalScrollIndicatorInsetsKey = "OriginalHorizontalScrollIndicatorInsets"
private var _originalVerticalScrollIndicatorInsetsKey = "OriginalVerticalScrollIndicatorInsets"
private var _keyboardVisibleKey = "KeyboardVisible"
fileprivate extension UIScrollView {
private func edgeInsets(forKey key: UnsafeRawPointer) -> UIEdgeInsets? {
(objc_getAssociatedObject(self, key) as? NSValue)?.uiEdgeInsetsValue
}
private func setEdgeInsets(_ edgeInsets: UIEdgeInsets?, forKey key: UnsafeRawPointer) {
objc_setAssociatedObject(self, key, edgeInsets.map(NSValue.init(uiEdgeInsets:)), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
final var originalContentInsets: UIEdgeInsets {
get { edgeInsets(forKey: &_originalContentInsetsKey) ?? .zero }
set { setEdgeInsets(newValue, forKey: &_originalContentInsetsKey) }
}
final var originalScrollIndicatorInsets: UIEdgeInsets {
get { edgeInsets(forKey: &_originalScrollIndicatorInsetsKey) ?? .zero }
set { setEdgeInsets(newValue, forKey: &_originalScrollIndicatorInsetsKey) }
}
final var originalHorizontalScrollIndicatorInsets: UIEdgeInsets {
get { edgeInsets(forKey: &_originalHorizontalScrollIndicatorInsetsKey) ?? .zero }
set { setEdgeInsets(newValue, forKey: &_originalHorizontalScrollIndicatorInsetsKey) }
}
final var originalVerticalScrollIndicatorInsets: UIEdgeInsets {
get { edgeInsets(forKey: &_originalVerticalScrollIndicatorInsetsKey) ?? .zero }
set { setEdgeInsets(newValue, forKey: &_originalVerticalScrollIndicatorInsetsKey) }
}
final var keyboardVisible: Bool {
get { (objc_getAssociatedObject(self, &_keyboardVisibleKey) as? Bool) ?? false }
set { objc_setAssociatedObject(self, &_keyboardVisibleKey, newValue, .OBJC_ASSOCIATION_ASSIGN) }
}
}
#endif
| 726e20569a47cd8cac2f7f9a58ee0779 | 44.712963 | 176 | 0.682905 | false | false | false | false |
dboyliao/NumSwift | refs/heads/master | NumSwift/Source/Exponential.swift | mit | 1 | //
// Dear maintainer:
//
// When I wrote this code, only I and God
// know what it was.
// Now, only God knows!
//
// So if you are done trying to 'optimize'
// this routine (and failed),
// please increment the following counter
// as warning to the next guy:
//
// var TotalHoursWastedHere = 0
//
// Reference: http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered
import Accelerate
/**
Compute e^(x). (Vectorized)
- Parameters:
- x: array of single precision floating numbers.
- Returns: An array of single precision floating number where its i-th element is e^(x[i]).
*/
public func exp(_ x:[Float]) -> [Float] {
var y = [Float](repeating: 0.0, count: x.count)
var N = Int32(x.count)
vvexpf(&y, x, &N)
return y
}
/**
Compute e^(x). (Vectorized)
- Parameters:
- x: array of double precision floating numbers.
- Returns: An array of double precision floating number where its i-th element is e^(x[i]).
*/
public func exp(_ x: [Double]) -> [Double] {
var y = [Double](repeating: 0.0, count: x.count)
var N = Int32(x.count)
vvexp(&y, x, &N)
return y
}
/**
Logrithm with Base
- Parameters:
- x: array of single precision floating numbers.
- base: the base of the logrithm (default: `e`).
- Returns: An array of single precision floating numbers. Its i-th element is the logrithm of x[i]
with base as given by `base`.
*/
public func log(_ x: [Float], base: Float? = nil) -> [Float] {
var y = [Float](repeating: 0.0, count: x.count)
var N = Int32(x.count)
vvlogf(&y, x, &N)
if base != nil {
var base = base!
var scale:Float = 0.0
var one = Int32(1)
var tempArray = [Float](repeating: 0.0, count: y.count)
vvlogf(&scale, &base, &one)
vDSP_vsdiv(&y, 1, &scale, &tempArray, 1, vDSP_Length(y.count))
y = tempArray
}
return y
}
/**
Logrithm with Base
- Parameters:
- x: array of double precision floating numbers.
- base: the base of the logrithm (default: `e`).
- Returns: An array of double precision floating numbers. Its i-th element is the logrithm of x[i]
with base as given by `base`.
*/
public func log(_ x: [Double], base: Double? = nil) -> [Double] {
var y = [Double](repeating: 0.0, count: x.count)
var N = Int32(x.count)
vvlog(&y, x, &N)
if base != nil {
var base = base!
var scale: Double = 0.0
var one = Int32(1)
var tempArray = [Double](repeating: 0.0, count: y.count)
vvlog(&scale, &base, &one)
vDSP_vsdivD(&y, 1, &scale, &tempArray, 1, vDSP_Length(y.count))
y = tempArray
}
return y
}
| 233fcddb2b5c4e5ddc4013410ab3884b | 23.371681 | 121 | 0.60167 | false | false | false | false |
Recover-Now/iOS-App | refs/heads/master | Recover Now/Recover Now/ViewControllers/LoginViewController.swift | mit | 1 | //
// LoginViewController.swift
// Recover-Now
//
// Created by Cliff Panos on 10/14/17.
// Copyright © 2017 Clifford Panos. All rights reserved.
//
import UIKit
import SafariServices
class LoginViewController: ManagedViewController {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var primaryView: UIView!
@IBOutlet weak var titleStackView: UIStackView!
@IBOutlet weak var loginTitle: UILabel!
var textFieldSelected: Bool = false
var textFieldManager: CPTextFieldManager!
let feedbackGenerator = UINotificationFeedbackGenerator()
static var preFilledEmail: String?
override func viewDidLoad() {
super.viewDidLoad()
textFieldManager = CPTextFieldManager(textFields: [emailTextField, passwordTextField], in: self)
textFieldManager.setupTextFields(withAccessory: .done)
textFieldManager.setFinalReturn(keyType: .go) {
self.signInPressed(Int(0))
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(true)
setNeedsStatusBarAppearanceUpdate()
passwordTextField.text = ""
if let email = LoginViewController.preFilledEmail {
emailTextField.text = email
LoginViewController.preFilledEmail = nil
passwordTextField.becomeFirstResponder()
}
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
//Check to see if an information controller or version update controller should be shown
/*let firstLaunchedEver = C.getFromUserDefaults(withKey: Shared.FIRST_LAUNCH_OF_APP_EVER) as? Bool ?? true
if firstLaunchedEver {
//self.performSegue(withIdentifier: "toTruePassInfo", sender: nil)
C.persistUsingUserDefaults(false, forKey: Shared.FIRST_LAUNCH_OF_APP_EVER)
}*/
}
@IBAction func infoButtonPressed(_ sender: Any) {
let url = URL(string: "http://www.recovernowapp.com")!
let safariVC = SFSafariViewController(url: url)
safariVC.modalPresentationStyle = .pageSheet
self.present(safariVC, animated: true, completion: nil)
}
//MARK: Sign-in & Account Creation ------------------------------------------ :
@IBAction func signInPressed(_ sender: Any) {
feedbackGenerator.prepare()
guard let email = emailTextField.text?.trimmingCharacters(in: .whitespaces),
let password = passwordTextField.text?.trimmingCharacters(in: .whitespaces) else {
self.showSimpleAlert("Incomplete Fields", message: "Surprise! You need to enter both an email and a password to log in.")
return
}
Accounts.shared.standardLogin(withEmail: email, password: password, completion: { success in
if success {
//CHECK TO SEE IF EMAIL IS VERIFIED
/*if let current = Accounts.shared.current, !current.isEmailVerified {
self.showOptionsAlert("Email Not Yet Verified", message: "For your security, you must verify your email address before logging into your account", left: "Send Email Again", right: "OK", handlerOne: {
current.sendEmailVerification(completion: { error in
if let error = error {
self.showSimpleAlert("Error While Resending Email", message: error.localizedDescription)
} else {
self.showSimpleAlert("Verification Email Sent", message: nil)
}
})
})
self.feedbackGenerator.notificationOccurred(.warning)
return // ! -- CRITICAL -- !//
}*/
let newUserService = FirebaseService(entity: "RNUser")
newUserService.retrieveData(forIdentifier: Accounts.shared.current!.uid) { object in
let newUser = object as! RNUser
Accounts.saveToUserDefaults(user: newUser, updateImage: true)
//At this point, the user is about to be logged in
self.feedbackGenerator.notificationOccurred(.success)
self.loginTitle.text = "Success"
self.animateOff()
}
} else {
self.shakeTextFields()
self.feedbackGenerator.notificationOccurred(.error)
}
})
}
@IBAction func newAccount(_ sender: Any) {
print("fill in this code to make a new account")
//let vc = C.storyboard.instantiateViewController(withIdentifier: "newAccountViewController")
self.view.endEditing(true)
//self.navigationController?.pushViewController(vc, animated: true)
}
//MARK: - Animations ---------------------- :
func shakeTextFields() {
let animation = CABasicAnimation(keyPath: "transform.translation.x")
animation.timingFunction = CAMediaTimingFunction(name: kCAMediaTimingFunctionLinear)
animation.repeatCount = 3
animation.duration = 0.08
animation.autoreverses = true
animation.byValue = 9 //how much it moves
self.passwordTextField.layer.add(animation, forKey: "position")
self.emailTextField.layer.add(animation, forKey: "position")
}
override func keyboardWillShow(notification: Notification) {
guard !textFieldSelected else { return }
UIView.animate(withDuration: 0.6, delay: 0.0, usingSpringWithDamping: 0.68, initialSpringVelocity: 4, options: .curveEaseIn, animations: {
self.primaryView.transform = CGAffineTransform(translationX: 0, y: -75)
}, completion: {_ in self.textFieldSelected = true })
}
override func keyboardWillHide(notification: Notification) {
guard textFieldSelected else { return }
UIView.animate(withDuration: 0.6, delay: 0.0, usingSpringWithDamping: 0.68, initialSpringVelocity: 4, options: .curveEaseIn, animations: {
self.primaryView.transform = CGAffineTransform(translationX: 0, y: 0)
}, completion: {_ in self.textFieldSelected = false })
}
func dismissKeyboard() {
self.view.endEditing(true)
}
func animateOff() {
dismissKeyboard()
UIView.animate(withDuration: 0.7, delay: 0.5, usingSpringWithDamping: 0.7, initialSpringVelocity: 2.5, options: .curveEaseOut, animations: {
self.primaryView.transform = CGAffineTransform(translationX: 0, y: UIScreen.main.bounds.height)
self.titleStackView.transform = CGAffineTransform(translationX: 0, y: -150)
}, completion: {_ in
self.textFieldSelected = false
let storyBoard = UIStoryboard(name: "Main", bundle: nil)
let tabBarController = storyBoard.instantiateInitialViewController() as! UITabBarController
let appDelegate = UIApplication.shared.delegate
appDelegate!.window!?.rootViewController = tabBarController
tabBarController.selectedIndex = 0
})
}
}
| 4ca3dbf53b20fbc518f260c3bd963350 | 37.843434 | 219 | 0.603953 | false | false | false | false |
1457792186/JWOCLibertyDemoWithPHP | refs/heads/master | Carthage/Checkouts/Charts/Source/Charts/Highlight/PieRadarHighlighter.swift | apache-2.0 | 54 | //
// PieRadarHighlighter.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
@objc(PieRadarChartHighlighter)
open class PieRadarHighlighter: ChartHighlighter
{
open override func getHighlight(x: CGFloat, y: CGFloat) -> Highlight?
{
guard let chart = self.chart as? PieRadarChartViewBase
else { return nil }
let touchDistanceToCenter = chart.distanceToCenter(x: x, y: y)
// check if a slice was touched
if touchDistanceToCenter > chart.radius
{
// if no slice was touched, highlight nothing
return nil
}
else
{
var angle = chart.angleForPoint(x: x ,y: y)
if chart is PieChartView
{
angle /= CGFloat(chart.chartAnimator.phaseY)
}
let index = chart.indexForAngle(angle)
// check if the index could be found
if index < 0 || index >= chart.data?.maxEntryCountSet?.entryCount ?? 0
{
return nil
}
else
{
return closestHighlight(index: index, x: x, y: y)
}
}
}
/// - returns: The closest Highlight object of the given objects based on the touch position inside the chart.
/// - parameter index:
/// - parameter x:
/// - parameter y:
open func closestHighlight(index: Int, x: CGFloat, y: CGFloat) -> Highlight?
{
fatalError("closestHighlight(index, x, y) cannot be called on PieRadarChartHighlighter")
}
}
| 05c9f638884ad5c8e268e683f2b998b8 | 28.016129 | 114 | 0.568093 | false | false | false | false |
takamashiro/XDYZB | refs/heads/master | XDYZB/XDYZB/Classes/Home/Controller/RecommendViewController.swift | mit | 1 | //
// RecommendViewController.swift
// XDYZB
//
// Created by takamashiro on 2016/9/27.
// Copyright © 2016年 com.takamashiro. All rights reserved.
//
import UIKit
import MJRefresh
private let kCycleViewH = kScreenW * 3 / 8
private let kGameViewH : CGFloat = 90
class RecommendViewController: BaseAnchorViewController {
//MARK: -懒加载属性
fileprivate lazy var recommandViewModel : RecommandViewModel = RecommandViewModel()
fileprivate lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH)
return cycleView
}()
lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
}
extension RecommendViewController {
override func setupUI() {
// 1.先调用super.setupUI()
super.setupUI()
//2.将cycleView添加到CollectionView中
collectionView.addSubview(cycleView)
// 3.将gameView添加collectionView中
collectionView.addSubview(gameView)
collectionView.mj_header = header
collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0)
header.ignoredScrollViewContentInsetTop = kCycleViewH + kGameViewH
collectionView.mj_header = header
let x = UIScreen.main.bounds.size.width - 44
let y = collectionView.bounds.size.height - 44 - kCycleViewH - kGameViewH
let livingBtn = UIButton(frame: CGRect(x: x, y: y, width: 44, height: 44))
livingBtn.setImage(UIImage(named:"home_play_btn_44x44_"), for: UIControlState.normal)
livingBtn.addTarget(self, action: #selector(presentLiveVC), for: UIControlEvents.touchUpInside)
view.insertSubview(livingBtn, aboveSubview: gameView)
}
func presentLiveVC() {
present(LiveMySelfViewController(), animated: true, completion: nil)
}
}
//MARK:- 请求数据
extension RecommendViewController {
override func loadData() {
// 0.给父类中的ViewModel进行赋值
baseVM = recommandViewModel
recommandViewModel.requestData() {
// 1.展示推荐数据
self.collectionView.reloadData()
// 2.将数据传递给GameView
var tempGroups = self.recommandViewModel.anchorGroups
tempGroups.removeFirst()
tempGroups.removeFirst()
let moreGroup = AnchorGroup()
moreGroup.tag_name = "更多"
tempGroups.append(moreGroup)
self.gameView.groups = tempGroups
//3.数据请求完成
self.loadDataFinished()
}
// 2.请求轮播数据
recommandViewModel.requestCycleData {
self.cycleView.cycleModels = self.recommandViewModel.cycleModels
}
}
}
extension RecommendViewController : UICollectionViewDelegateFlowLayout {
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
if indexPath.section == 1 {
// 1.取出PrettyCell
let prettyCell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell
// 2.设置数据
prettyCell.anchor = recommandViewModel.anchorGroups[indexPath.section].anchors[indexPath.item]
return prettyCell
} else {
return super.collectionView(collectionView, cellForItemAt: indexPath)
}
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kNormalItemW, height: kPrettyItemH)
}
return CGSize(width: kNormalItemW, height: kNormalItemH)
}
}
| 30c0e989c92e364f6b982d47c5a74e6e | 33.033058 | 160 | 0.65153 | false | false | false | false |
jamalping/XPUtil | refs/heads/master | XPUtil/Random.swift | mit | 1 | //
// Random.swift
// XPUtilExample
//
// Created by Apple on 2019/3/18.
// Copyright © 2019年 xyj. All rights reserved.
//
import Foundation
/// 获取随机数协议
public protocol Randomable {
}
public extension Randomable {
/// 随机数生成 闭区间 [min, max]支持负数 eg: [1, 10],[-3,3]
func randomCustom(min: Int, max: Int) -> Int {
// [min, max) [0, 100)
// var x = arc4random() % UInt32(max);
// return Int(x)
// [min, max)
var y: UInt32
if min >= 0 {
y = arc4random() % UInt32(max) + UInt32(min)
return Int(y)
}else {
y = arc4random() % UInt32(max-min+1)
let r: Int = Int(y)
return Int(r + min)
}
}
/// 随机生成正负1
func randomPosiOrNega() -> Int {
let random = (arc4random()%2+1)%2
if random == 0 {
return -1
}
return 1
}
}
| e9e2460f11c3fd7b3c1c49f334819730 | 19.622222 | 56 | 0.474138 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox | refs/heads/master | nRF Toolbox/Profiles/UART/Model/UARTPreset.swift | bsd-3-clause | 1 | /*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import Foundation
import AEXML
struct UARTPreset {
enum Error: Swift.Error {
case wrongXMLFormat
}
var commands: [UARTCommandModel] = Array(repeating: EmptyModel(), count: 9)
var name: String
var document: AEXMLDocument {
let doc = AEXMLDocument()
let root = AEXMLElement(name: "uart-configuration", attributes: [
"name":name
])
let commands = AEXMLElement(name: "commands", attributes: [
"length":"9"
])
commands.addChildren(self.commands.map { $0.xml })
root.addChild(commands)
doc.addChild(root)
return doc
}
mutating func updateCommand(_ command: UARTCommandModel, at index: Int) {
commands[index] = command
}
init(commands: [UARTCommandModel], name: String) {
self.commands = commands
self.name = name
}
init(data: Data) throws {
let document = try AEXMLDocument(xml: data)
let children = document.children
guard let rootNode = children.first(where: { (e) -> Bool in
e.name == "uart-configuration"
}) else {
throw Error.wrongXMLFormat
}
name = rootNode.attributes["name"] ?? ""
guard let commandsNode = rootNode.children.first(where: { $0.name == "commands" }) else {
throw Error.wrongXMLFormat
}
var commands: [UARTCommandModel] = []
for node in commandsNode.children {
guard commands.count < 9 else {
break
}
guard let text = node.value else {
commands.append(EmptyModel())
continue
}
let image = CommandImage(name: (node.attributes["icon"] ?? ""), modernIcon: node.attributes["system_icon"].map({ModernIcon(name: $0)}))
if let type = node.attributes["type"], type == "data" {
commands.append(DataCommand(data: Data(text.hexa), image: image))
} else {
commands.append(TextCommand(text: text, image: image))
}
}
while commands.count < 9 {
commands.append(EmptyModel())
}
self.commands = commands
}
}
extension UARTPreset {
static let `default` = UARTPreset(commands: [
DataCommand(data: Data([0x01]), image: .number1),
DataCommand(data: Data([0x02]), image: .number2),
DataCommand(data: Data([0x03]), image: .number3),
TextCommand(text: "Pause", image: .pause),
TextCommand(text: "Play", image: .play),
TextCommand(text: "Stop", image: .stop),
TextCommand(text: "Rew", image: .rewind),
TextCommand(text: "Start", image: .start),
TextCommand(text: "Repeat", image: .repeat)
], name: "Demo")
static let empty = UARTPreset(commands: Array(repeating: EmptyModel(), count: 9), name: "")
}
extension UARTPreset: Codable {
enum CodingKeys: String, CodingKey {
case commands, name
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
let commandContainers = try container.decode([UARTCommandContainer].self, forKey: .commands)
commands = commandContainers.compactMap { $0.command as? UARTCommandModel }
name = try container.decode(String.self, forKey: .name)
}
func encode(to encoder: Encoder) throws {
let modelContainers = commands.map { UARTCommandContainer($0) }
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(modelContainers, forKey: .commands)
try container.encode(name, forKey: .name)
}
}
| c112c374b45173271a35c39b1601f16c | 35.678082 | 147 | 0.637908 | false | false | false | false |
willpowell8/UIDesignKit_iOS | refs/heads/master | UIDesignKit/Classes/Editor/ColourView/PickerImage.swift | mit | 1 | import UIKit
import ImageIO
open class PickerImage {
var provider:CGDataProvider!
var imageSource:CGImageSource?
var image:UIImage?
var mutableData:CFMutableData
var width:Int
var height:Int
let lockQueue = DispatchQueue(label: "PickerImage")
fileprivate func createImageFromData(_ width:Int, height:Int) {
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedFirst.rawValue)
guard let p = CGDataProvider(data: mutableData) else {
return
}
provider = p
imageSource = CGImageSourceCreateWithDataProvider(provider, nil)
let cgimg = CGImage(width: Int(width), height: Int(height), bitsPerComponent: Int(8), bitsPerPixel: Int(32), bytesPerRow: Int(width) * Int(4),
space: colorSpace, bitmapInfo: bitmapInfo, provider: provider!, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent)
image = UIImage(cgImage: cgimg!)
}
func changeSize(_ width:Int, height:Int) {
lockQueue.sync() {
self.width = width
self.height = height
let size:Int = width * height * 4
mutableData = CFDataCreateMutable(kCFAllocatorDefault, size)
CFDataSetLength(mutableData, size)
createImageFromData(width, height: height)
}
}
init(width:Int, height:Int) {
self.width = width
self.height = height
let size:Int = width * height * 4
mutableData = CFDataCreateMutable(kCFAllocatorDefault, size)
CFDataSetLength(mutableData, size)
createImageFromData(width, height: height)
}
open func writeColorData(_ h:CGFloat, a:CGFloat) {
lockQueue.sync() {
let d = CFDataGetMutableBytePtr(self.mutableData)
if width == 0 || height == 0 {
return
}
var i:Int = 0
let h360:CGFloat = ((h == 1 ? 0 : h) * 360) / 60.0
let sector:Int = Int(floor(h360))
let f:CGFloat = h360 - CGFloat(sector)
let f1:CGFloat = 1.0 - f
var p:CGFloat = 0.0
var q:CGFloat = 0.0
var t:CGFloat = 0.0
let sd:CGFloat = 1.0 / CGFloat(width)
let vd:CGFloat = 1 / CGFloat(height)
var double_s:CGFloat = 0
var pf:CGFloat = 0
let v_range = 0..<height
let s_range = 0..<width
for v in v_range {
pf = 255 * CGFloat(v) * vd
for s in s_range {
i = (v * width + s) * 4
d?[i] = UInt8(255)
if s == 0 {
q = pf
d?[i+1] = UInt8(q)
d?[i+2] = UInt8(q)
d?[i+3] = UInt8(q)
continue
}
double_s = CGFloat(s) * sd
p = pf * (1.0 - double_s)
q = pf * (1.0 - double_s * f)
t = pf * ( 1.0 - double_s * f1)
switch(sector) {
case 0:
d?[i+1] = UInt8(pf)
d?[i+2] = UInt8(t)
d?[i+3] = UInt8(p)
case 1:
d?[i+1] = UInt8(q)
d?[i+2] = UInt8(pf)
d?[i+3] = UInt8(p)
case 2:
d?[i+1] = UInt8(p)
d?[i+2] = UInt8(pf)
d?[i+3] = UInt8(t)
case 3:
d?[i+1] = UInt8(p)
d?[i+2] = UInt8(q)
d?[i+3] = UInt8(pf)
case 4:
d?[i+1] = UInt8(t)
d?[i+2] = UInt8(p)
d?[i+3] = UInt8(pf)
default:
d?[i+1] = UInt8(pf)
d?[i+2] = UInt8(p)
d?[i+3] = UInt8(q)
}
}
}
}
}
}
| a2a3e2d863a2ff6973a8abd7016722d5 | 34.209677 | 159 | 0.428768 | false | false | false | false |
richardpiazza/SOSwift | refs/heads/master | Sources/SOSwift/AccessibilityControl.swift | mit | 1 | import Foundation
/// Identifies one or more input methods that allow access to all of the application functionality.
public enum AccessibilityControl: String, CaseIterable, Codable {
case fullKeyboardControl = "fullKeyboardControl"
case fullMouseControl = "fullMouseControl"
case fullSwitchControl = "fullSwitchControl"
case fullTouchControl = "fullTouchControl"
case fullVideoControl = "fullVideoControl"
case fullVoiceControl = "fullVoiceControl"
public var displayValue: String {
switch self {
case .fullKeyboardControl: return "Full Keyboard Control"
case .fullMouseControl: return "Full Mouse Control"
case .fullSwitchControl: return "Full Switch Control"
case .fullTouchControl: return "Full Touch Control"
case .fullVideoControl: return "Full Video Control"
case .fullVoiceControl: return "Full Voice Control"
}
}
}
| 2a63ab2b9d3d98176fc2921e09ebaef8 | 41.090909 | 99 | 0.725702 | false | false | false | false |
Tylerflick/ImageDiff | refs/heads/master | ImageDiff/MetalDiffer.swift | apache-2.0 | 1 |
// ImageDiffer.swift
// ImageDiff
//
// Created by Tyler Hoeflicker on 7/6/17.
// Copyright © 2017 Tyler Hoeflicker. All rights reserved.
//
import Foundation
import Metal
import MetalKit
class MetalDiffer : NSObject, Differ {
/// A Metal device
lazy var device: MTLDevice! = MTLCreateSystemDefaultDevice()
/// A Metal library
lazy var defaultLibrary: MTLLibrary! = {
self.device.makeDefaultLibrary()
}()
/// A Metal command queue
lazy var commandQueue: MTLCommandQueue! = {
print("Using \(self.device.name)")
return self.device.makeCommandQueue()
}()
var inTextureOne: MTLTexture!
var inTextureTwo: MTLTexture!
var outTexture: MTLTexture!
var diffCount: [UInt] = [0]
let bytesPerPixel: Int = 4
/// A Metal compute pipeline state
var pipelineState: MTLComputePipelineState!
public func applyDiff(to first: String, second: String, output: String) -> Int32 {
setUpMetal()
guard let firstImage = NSImage(byReferencingFile: first) else {
fatalError("Image \(first) does not exist")
}
guard let secondImage = NSImage(byReferencingFile: second) else {
fatalError("Image \(second) does not exist")
}
if (firstImage.size != secondImage.size) {
fatalError("Input image sizes must match")
}
self.inTextureOne = createTexture(from: firstImage)
self.inTextureTwo = createTexture(from: secondImage)
if (self.inTextureOne.pixelFormat != self.inTextureTwo.pixelFormat) {
fatalError("Input image pixel formats must match")
}
self.outTexture = createTexture(from: self.inTextureOne.width, height: self.inTextureOne.height, pixelFormat: MTLPixelFormat.rgba8Unorm)
let commandBuffer = commandQueue.makeCommandBuffer()
let commandEncoder = commandBuffer?.makeComputeCommandEncoder()
commandEncoder?.setComputePipelineState(pipelineState)
commandEncoder?.setTexture(inTextureOne, index: 0)
commandEncoder?.setTexture(inTextureTwo, index: 1)
commandEncoder?.setTexture(outTexture, index: 2)
let diffCntBuffer = device.makeBuffer(bytes: &diffCount, length: (diffCount.count * MemoryLayout<UInt>.size), options: [])
commandEncoder?.setBuffer(diffCntBuffer, offset: 0, index: 0)
let threadsPerThreadgroup = MTLSizeMake(16, 16, 1)
let threadgroupsPerGrid = MTLSizeMake(Int(self.outTexture.width) / threadsPerThreadgroup.width, Int(self.outTexture.height) / threadsPerThreadgroup.height, 1)
commandEncoder?.dispatchThreadgroups(threadgroupsPerGrid, threadsPerThreadgroup: threadsPerThreadgroup)
commandEncoder?.endEncoding()
commandBuffer?.commit()
commandBuffer?.waitUntilCompleted()
var sumOfDiff: Int32 = 0
let nsData = NSData(bytesNoCopy: (diffCntBuffer?.contents())!,
length: (diffCntBuffer?.length)!,
freeWhenDone: false)
nsData.getBytes(&sumOfDiff, length:(diffCntBuffer?.length)!)
if sumOfDiff > 0 {
print("Found \(sumOfDiff) differences between the two images")
let image = self.createImage(from: self.outTexture)
if !writeCGImage(image, toPath: NSURL.fileURL(withPath: output)) {
fatalError("Fatal Error: Writing output to file \(arguments[2]) failed")
}
} else {
print("No differences found")
}
return sumOfDiff
}
private func setUpMetal() {
if let kernelFunction = defaultLibrary.makeFunction(name: "kernel_metalDiff") {
do {
pipelineState = try device.makeComputePipelineState(function: kernelFunction)
}
catch {
fatalError("Impossible to setup Metal")
}
}
}
private func createTexture(from image: NSImage) -> MTLTexture {
guard let cgImage = image.cgImage(forProposedRect: nil, context: nil, hints: nil) else {
fatalError("Can't open image \(image)")
}
let textureLoader = MTKTextureLoader(device: self.device)
do {
let textureOut = try textureLoader.newTexture(cgImage: cgImage, options: [:])
return textureOut
}
catch {
fatalError("Can't load texture")
}
}
private func createTexture(from width: Int, height: Int, pixelFormat: MTLPixelFormat) -> MTLTexture {
let textureDescriptor = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: pixelFormat, width: width, height: height, mipmapped: false)
textureDescriptor.usage = MTLTextureUsage.shaderWrite
return self.device.makeTexture(descriptor: textureDescriptor)!
}
private func createImage(from texture: MTLTexture) -> CGImage {
let imageByteCount = texture.width * texture.height * bytesPerPixel
let bytesPerRow = texture.width * bytesPerPixel
var src = [UInt8](repeating: 0, count: Int(imageByteCount))
let region = MTLRegionMake2D(0, 0, texture.width, texture.height)
texture.getBytes(&src, bytesPerRow: bytesPerRow, from: region, mipmapLevel: 0)
let bitmapInfo = CGBitmapInfo(rawValue: (CGBitmapInfo.byteOrder32Big.rawValue | CGImageAlphaInfo.premultipliedLast.rawValue))
let colorSpace = CGColorSpaceCreateDeviceRGB()
let bitsPerComponent = 8
let context = CGContext(data: &src,
width: texture.width,
height: texture.height,
bitsPerComponent: bitsPerComponent,
bytesPerRow: bytesPerRow,
space: colorSpace,
bitmapInfo: bitmapInfo.rawValue)
return context!.makeImage()!
}
}
| b38edc8d25d0bf14c4c7f545284c78ae | 38.4 | 166 | 0.621582 | false | false | false | false |
mozilla-mobile/prox | refs/heads/master | Prox/Prox/Utilities/SDKs.swift | mpl-2.0 | 1 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Firebase
import FirebaseRemoteConfig
import GoogleMaps
struct SDKs {
private static var isSetup = false
// Not currently used but potentially useful.
private(set) static var firebaseAuthorizedUser: FIRUser?
private static let remoteConfigCacheExpiration: TimeInterval = {
if AppConstants.isDebug {
// Refresh the config if it hasn't been refreshed in 60 seconds.
return 0.0
}
return RemoteConfigKeys.remoteConfigCacheExpiration.value
}()
static func setUp() {
guard !isSetup else { fatalError("SDKs.setup already called") } // sanity check.
setUpFirebase()
setUpRemoteConfig()
setUpGoogleMaps()
BuddyBuildSDK.setup()
isSetup = true
}
private static func setUpFirebase() {
FIRApp.configure()
if let user = FIRAuth.auth()?.currentUser {
self.firebaseAuthorizedUser = user
} else {
FIRAuth.auth()?.signInAnonymously { (user, error) in
guard let user = user else {
return log.error("sign in failed \(error)")
}
self.firebaseAuthorizedUser = user
dump(user)
}
}
FIRDatabase.database().persistenceEnabled = false
}
private static func setUpRemoteConfig() {
let remoteConfig = FIRRemoteConfig.remoteConfig()
let isDeveloperMode = AppConstants.isDebug || AppConstants.MOZ_LOCATION_FAKING
remoteConfig.configSettings = FIRRemoteConfigSettings(developerModeEnabled: isDeveloperMode)!
remoteConfig.setDefaultsFromPlistFileName("RemoteConfigDefaults")
let defaults = UserDefaults.standard
// Declare this here, because it's not needed anywhere else.
let pendingUpdateKey = "pendingUpdate"
remoteConfig.fetch(withExpirationDuration: remoteConfigCacheExpiration) { status, err in
if status == FIRRemoteConfigFetchStatus.success {
log.info("RemoteConfig fetched")
// The config will be applied next time we load.
// We don't do it now, because we want the update to be atomic,
// at the beginning of a session with the app.
defaults.set(true, forKey: pendingUpdateKey)
defaults.synchronize()
} else {
// We'll revert back to the latest update, or the RemoteConfigDefaults plist.
log.warn("RemoteConfig fetch failed")
}
}
if defaults.bool(forKey: pendingUpdateKey) {
remoteConfig.activateFetched()
log.info("RemoteConfig updated")
defaults.set(false, forKey: pendingUpdateKey)
defaults.synchronize()
}
}
private static func setUpGoogleMaps() {
guard let path = Bundle.main.path(forResource: "GoogleService-Info", ofType: "plist"),
let googleServiceInfo = NSDictionary(contentsOfFile: path),
let apiKey = googleServiceInfo["API_KEY"] as? String else {
fatalError("Unable to initialize gmaps - did you include GoogleService-Info?")
}
GMSServices.provideAPIKey(apiKey)
}
}
| bdc75cc3379049827cb6668d6c3752b9 | 35.93617 | 101 | 0.630472 | false | true | false | false |
diegosanchezr/Chatto | refs/heads/master | Chatto/Source/Chat Items/BaseChatItemPresenter.swift | mit | 1 | /*
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
public enum ChatItemVisibility {
case Hidden
case Appearing
case Visible
}
public class BaseChatItemPresenter<CellT: UICollectionViewCell>: ChatItemPresenterProtocol {
public final weak var cell: CellT?
public init() { }
public class func registerCells(collectionView: UICollectionView) {
assert(false, "Implement in subclass")
}
public var canCalculateHeightInBackground: Bool {
return false
}
public func heightForCell(maximumWidth width: CGFloat, decorationAttributes: ChatItemDecorationAttributesProtocol?) -> CGFloat {
assert(false, "Implement in subclass")
return 0
}
public func dequeueCell(collectionView collectionView: UICollectionView, indexPath: NSIndexPath) -> UICollectionViewCell {
assert(false, "Implemenent in subclass")
return UICollectionViewCell()
}
public func configureCell(cell: UICollectionViewCell, decorationAttributes: ChatItemDecorationAttributesProtocol?) {
assert(false, "Implemenent in subclass")
}
final public private(set) var itemVisibility: ChatItemVisibility = .Hidden
// Need to override default implementatios. Otherwise subclasses's code won't be executed
// http://stackoverflow.com/questions/31795158/swift-2-protocol-extension-not-calling-overriden-method-correctly
public final func cellWillBeShown(cell: UICollectionViewCell) {
if let cell = cell as? CellT {
self.cell = cell
self.itemVisibility = .Appearing
self.cellWillBeShown()
self.itemVisibility = .Visible
} else {
assert(false, "Invalid cell was given to presenter!")
}
}
public func cellWillBeShown() {
// Hook for subclasses
}
public func shouldShowMenu() -> Bool {
return false
}
public final func cellWasHidden(cell: UICollectionViewCell) {
// Carefull!! This doesn't mean that this is no longer visible
// If cell is replaced (due to a reload for instance) we can have the following sequence:
// - New cell is taken from the pool and configured. We'll get cellWillBeShown
// - Old cell is removed. We'll get cellWasHidden
// --> We need to check that this cell is the last one made visible
if let cell = cell as? CellT {
if cell === self.cell {
self.cell = nil
self.itemVisibility = .Hidden
self.cellWasHidden()
}
} else {
assert(false, "Invalid cell was given to presenter!")
}
}
public func cellWasHidden() {
// Hook for subclasses. Here we are not visible for real.
}
public func canPerformMenuControllerAction(action: Selector) -> Bool {
return false
}
public func performMenuControllerAction(action: Selector) {
assert(self.canPerformMenuControllerAction(action))
}
}
| bb6e51125271c55c251c3b935938b2f6 | 35.846847 | 132 | 0.696088 | false | false | false | false |
robertoseidenberg/MixerBox | refs/heads/master | MixerBox/KnobContainerView+Setup.swift | mit | 1 | extension KnobContainerView {
func setup() {
setupView()
setupKnob()
}
func setupView() {
clipsToBounds = true
}
func setupKnob() {
knob = RoundedCornerView(frame: CGRect.zero)
knob.translatesAutoresizingMaskIntoConstraints = false
knob.backgroundColor = knobColor
knob.innerborderColor = knobInnerBorderColor
knob.outerborderColor = knobOuterBorderColor
knob.borderWidth = knobBorderWidth
addSubview(knob)
knob.autoLayoutFixedWidth(knobSize)
knob.autoLayoutFixedHeight(knobSize)
knob.autoLayoutBindTopToSuperviewTop()
knob.autoLayoutBindTopToSuperviewLeft()
}
}
| d7af18b1baea50a92eee052c3fb69b48 | 22.777778 | 58 | 0.732087 | false | false | false | false |
whereuat/whereuat-ios | refs/heads/master | whereuat-ios/Views/FloatingActionButton.swift | apache-2.0 | 1 | //
// FloatingActionButton.swift
// whereuat-ios
//
// Created by Raymond Jacobson on 4/14/16.
// Copyright © 2016 whereu@. All rights reserved.
//
import UIKit
import LiquidFloatingActionButton
@objc protocol FABDelegate : class {
optional func addContact()
optional func addKeyLocation()
}
/*
* FABType represents two types of notifications, alerts and push notifications
*/
enum FABType {
case Main
case KeyLocationOnly
}
/*
* FloatingActionButton manages a floating action button for whereu@
*/
class FloatingActionButton: LiquidFloatingActionButtonDataSource, LiquidFloatingActionButtonDelegate {
var delegate: FABDelegate!
var cells: [LiquidFloatingCell] = []
var floatingActionButton: LiquidFloatingActionButton!
var type: FABType!
/*
* init creates the floating action button
* @param color - the color to be drawn
*/
init(color: UIColor, type: FABType) {
self.type = type
let createButton: (CGRect, LiquidFloatingActionButtonAnimateStyle) -> LiquidFloatingActionButton = { (frame, style) in
let floatingActionButton = LiquidFloatingActionButton(frame: frame)
floatingActionButton.animateStyle = style
floatingActionButton.dataSource = self
floatingActionButton.delegate = self
return floatingActionButton
}
let cellFactory: (String) -> LiquidFloatingCell = { (iconName) in
return LiquidFloatingCell(icon: UIImage(named: iconName)!)
}
cells.append(cellFactory("ic_add_location"))
if (self.type == FABType.Main) {
cells.append(cellFactory("ic_person_add"))
}
// A FAB has an absolute positioning relative to the UI Main Screen
let floatingFrame = CGRect(x: UIScreen.mainScreen().bounds.width - 56 - 16, y: UIScreen.mainScreen().bounds.height - 56 - 16, width: 56, height: 56)
let bottomRightButton = createButton(floatingFrame, .Up)
bottomRightButton.color = color
self.floatingActionButton = bottomRightButton
}
/*
* numberOfCells gets the number of items in the FAB
* @param liquidFloatingActionButton - the target FAB
* @return the number of cells
*/
@objc func numberOfCells(liquidFloatingActionButton: LiquidFloatingActionButton) -> Int {
return cells.count
}
@objc func cellForIndex(index: Int) -> LiquidFloatingCell {
return cells[index]
}
/*
* liquidFloatingActionButton handles the selection of items in the FAB
*/
@objc func liquidFloatingActionButton(liquidFloatingActionButton: LiquidFloatingActionButton, didSelectItemAtIndex index: Int) {
if self.type == FABType.Main {
switch index {
case 0: // Add key location
self.delegate.addKeyLocation!()
case 1: // Add contact
self.delegate.addContact!()
default:
print("Incorrect selection in floating action button")
}
}
else if self.type == FABType.KeyLocationOnly {
switch index {
case 0: // Add key location
self.delegate.addKeyLocation!()
default:
print("Incorrect selection in floating action button")
}
}
liquidFloatingActionButton.close()
}
}
| bf805f7783f6ae8c218bd8b70e03ec0b | 32.086538 | 156 | 0.641674 | false | false | false | false |
gezi0630/weiboDemo | refs/heads/master | weiboDemo/weiboDemo/Classes/Message/MessageViewController.swift | apache-2.0 | 1 | //
// MessageViewController.swift
// weiboDemo
//
// Created by MAC on 2016/12/23.
// Copyright © 2016年 GuoDongge. All rights reserved.
//
import UIKit
class MessageViewController: BaseTableViewController {
override func viewDidLoad() {
super.viewDidLoad()
// 1.如果没有登录, 就设置未登录界面的信息
if !userLogin
{
visitorView?.setupVisitorInfo(false, imageName: "visitordiscover_image_message", message: "登录后,别人评论你的微博,发给你的消息,都会在这里收到通知")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
// #warning Incomplete implementation, return the number of sections
return 0
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return 0
}
/*
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath)
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {
if editingStyle == .delete {
// Delete the row from the data source
tableView.deleteRows(at: [indexPath], with: .fade)
} else if editingStyle == .insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(_ tableView: UITableView, moveRowAt fromIndexPath: IndexPath, to: IndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
// Return false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| e0932a0d8e4b912d0df76f4998dfb301 | 30.652632 | 136 | 0.658464 | false | false | false | false |
appcorn/cordova-plugin-siths-manager | refs/heads/master | src/ios/SITHSManager/Utilities.swift | mit | 1 | //
// Written by Martin Alléus, Appcorn AB, [email protected]
//
// Copyright 2017 Svensk e-identitet AB
//
// 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
extension Sequence where Iterator.Element == UInt8 {
/// Creates and returns a HEX string representation of the data in the byte array.
///
/// - Parameter byteSeparator: If set to true (the default value), the bytes will be separated with a space.
/// - Returns: An upper case HEX string represent of the byte array, for exampel "6D 61 72 74 69 6E" or "6D617274696E"
func hexString(byteSeparator: Bool = true) -> String {
var hexString = [String]()
for byte in self {
hexString.append(String(format: "%02X", byte))
}
return hexString.joined(separator: byteSeparator ? " " : "")
}
}
extension Data {
/// Creates and returns a HEX string representation of the data.
///
/// - Parameter byteSeparator: If set to true (the default value), the bytes will be separated with a space.
/// - Returns: An upper case HEX string represent of the data, for exampel "6D 61 72 74 69 6E" or "6D617274696E"
func hexString(byteSeparator: Bool = true) -> String {
var hexString = [String]()
for i in 0..<count {
hexString.append(String(format: "%02X", self[i]))
}
return hexString.joined(separator: byteSeparator ? " " : "")
}
/// Converts the byte array to a big endian signed integer. Note that byte arrays larger than 4 bytes will be truncated.
///
/// - Returns: The big endian signed integer representation of up to 4 bytes in the byte array.
func intValue() -> Int {
var data = self
switch count {
case 0:
return 0
case 1:
return Int(data[0])
case 2:
let value = data.withUnsafeBytes { (pointer: UnsafePointer<Int16>) in
return pointer.pointee
}
return Int(Int16(bigEndian: value))
case 3:
// Only three bytes, add 0x00 padding to result in four bytes and continue to next case
data = Data(bytes: [0x00]) + data
fallthrough
case 4..<Int.max:
let value = data.withUnsafeBytes { (pointer: UnsafePointer<Int32>) in
return pointer.pointee
}
return Int(Int32(bigEndian: value))
default:
fatalError()
}
}
/// Converts the byte array to a big endian unsigned integer. Note that byte arrays larger than 4 bytes will be truncated.
///
/// - Returns: The big endian unsigned integer representation of up to 4 bytes in the byte array.
func uintValue() -> UInt {
var data = self
switch count {
case 0:
return 0
case 1:
return UInt(data[0])
case 2:
let value = data.withUnsafeBytes { (pointer: UnsafePointer<UInt16>) in
return pointer.pointee
}
return UInt(UInt16(bigEndian: value))
case 3:
// Only three bytes, add 0x00 padding to result in four bytes and continue to next case
data = Data(bytes: [0x00]) + data
fallthrough
case 4..<Int.max:
let value = data.withUnsafeBytes { (pointer: UnsafePointer<UInt32>) in
return pointer.pointee
}
return UInt(UInt32(bigEndian: value))
default:
fatalError()
}
}
}
extension Collection {
/// Returns the element at the specified index if it is within bounds, otherwise nil.
subscript (safe index: Index) -> Generator.Element? {
return index <= endIndex ? self[index] : nil
}
}
extension UnsafeMutablePointer {
/// Creates an array containing the values at the pointer.
///
/// - Parameter count: Number of bytes to read from the pointer.
/// - Returns: An array, conatining the bytes of data at the pointer.
func valueArray(count: Int) -> [Pointee] {
let buffer = UnsafeBufferPointer(start: self, count: count)
return Array(buffer)
}
}
| 0187e6bd7e6197050165f19f01f8b8ec | 39.248062 | 139 | 0.634823 | false | false | false | false |
roambotics/swift | refs/heads/master | SwiftCompilerSources/Sources/Optimizer/TestPasses/EscapeInfoDumper.swift | apache-2.0 | 1 | //===--- EscapeInfoDumper.swift - Dumps escape information ----------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SIL
/// Dumps the results of escape analysis.
///
/// Dumps the EscapeInfo query results for all `alloc_stack` instructions in a function.
///
/// This pass is used for testing EscapeInfo.
let escapeInfoDumper = FunctionPass(name: "dump-escape-info", {
(function: Function, context: PassContext) in
print("Escape information for \(function.name):")
struct Visitor : EscapeVisitorWithResult {
var result: Set<String> = Set()
mutating func visitUse(operand: Operand, path: EscapePath) -> UseResult {
if operand.instruction is ReturnInst {
result.insert("return[\(path.projectionPath)]")
return .ignore
}
return .continueWalk
}
mutating func visitDef(def: Value, path: EscapePath) -> DefResult {
guard let arg = def as? FunctionArgument else {
return .continueWalkUp
}
result.insert("arg\(arg.index)[\(path.projectionPath)]")
return .walkDown
}
}
for inst in function.instructions {
if let allocRef = inst as? AllocRefInst {
let resultStr: String
if let result = allocRef.visit(using: Visitor(), context) {
if result.isEmpty {
resultStr = " - "
} else {
resultStr = Array(result).sorted().joined(separator: ",")
}
} else {
resultStr = "global"
}
print("\(resultStr): \(allocRef)")
}
}
print("End function \(function.name)\n")
})
/// Dumps the results of address-related escape analysis.
///
/// Dumps the EscapeInfo query results for addresses escaping to function calls.
/// The `fix_lifetime` instruction is used as marker for addresses and values to query.
///
/// This pass is used for testing EscapeInfo.
let addressEscapeInfoDumper = FunctionPass(name: "dump-addr-escape-info", {
(function: Function, context: PassContext) in
print("Address escape information for \(function.name):")
var valuesToCheck = [Value]()
var applies = [Instruction]()
for inst in function.instructions {
switch inst {
case let fli as FixLifetimeInst:
valuesToCheck.append(fli.operand)
case is FullApplySite:
applies.append(inst)
default:
break
}
}
struct Visitor : EscapeVisitor {
let apply: Instruction
mutating func visitUse(operand: Operand, path: EscapePath) -> UseResult {
let user = operand.instruction
if user == apply {
return .abort
}
if user is ReturnInst {
// Anything which is returned cannot escape to an instruction inside the function.
return .ignore
}
return .continueWalk
}
}
// test `isEscaping(addressesOf:)`
for value in valuesToCheck {
print("value:\(value)")
for apply in applies {
let path = AliasAnalysis.getPtrOrAddressPath(for: value)
if value.at(path).isAddressEscaping(using: Visitor(apply: apply), context) {
print(" ==> \(apply)")
} else {
print(" - \(apply)")
}
}
}
// test `canReferenceSameField` for each pair of `fix_lifetime`.
if !valuesToCheck.isEmpty {
for lhsIdx in 0..<(valuesToCheck.count - 1) {
for rhsIdx in (lhsIdx + 1) ..< valuesToCheck.count {
print("pair \(lhsIdx) - \(rhsIdx)")
let lhs = valuesToCheck[lhsIdx]
let rhs = valuesToCheck[rhsIdx]
print(lhs)
print(rhs)
let projLhs = lhs.at(AliasAnalysis.getPtrOrAddressPath(for: lhs))
let projRhs = rhs.at(AliasAnalysis.getPtrOrAddressPath(for: rhs))
let mayAlias = projLhs.canAddressAlias(with: projRhs, context)
assert(mayAlias == projRhs.canAddressAlias(with: projLhs, context),
"canAddressAlias(with:) must be symmetric")
if mayAlias {
print("may alias")
} else {
print("no alias")
}
}
}
}
print("End function \(function.name)\n")
})
| e97a92c630151617e2a14be4db2f1bf7 | 29.431507 | 90 | 0.620302 | false | false | false | false |
ermesup/RxDecodable | refs/heads/master | RxDecodableTests/RxDecodableTests.swift | mit | 1 | import RxSwift
import RxCocoa
import Decodable
import Quick
import Nimble
@testable import RxDecodable
struct God: RxDecodable {
let name: String
let parents: [God]
static func decode(j: AnyObject) throws -> God {
return try God(name: j => "name", parents: j => "parents")
}
}
class RxDecodableSpec: QuickSpec {
let disposableBag = DisposeBag()
let hermesDictionary = [
"name": "Hermes",
"parents": [
["name": "Zeus", "parents": []],
["name": "Maia", "parents": []]
]
]
let zeusDictionary = [
"name": "Zeus",
"parents": []
]
override func spec() {
describe("RxDecodable") {
it("decodes one item in a decodable object") {
God.rx_decode(self.hermesDictionary).subscribe { o in
expect(o.element?.name).to(equal("Hermes"))
}.addDisposableTo(self.disposableBag)
}
it("decodes multiple items in a array of decodable objects") {
let a = [God].rx_decode([self.hermesDictionary, self.zeusDictionary])
a.subscribeError { e in
print(e)
}.addDisposableTo(self.disposableBag)
a.subscribe { o in
expect(o.element?.first?.name).to(equal("Hermes"))
expect(o.element?.last?.name).to(equal("Zeus"))
}.addDisposableTo(self.disposableBag)
}
it("decodes embedded array") {
God.rx_decode(self.hermesDictionary).subscribe { o in
expect(o.element?.name).to(equal("Hermes"))
expect(o.element?.parents.first?.name).to(equal("Zeus"))
expect(o.element?.parents.last?.name).to(equal("Maia"))
}.addDisposableTo(self.disposableBag)
}
}
}
}
| e84e890743c664c96c0a635dd59d400d | 29.650794 | 85 | 0.525117 | false | false | false | false |
hunterknepshield/MIPSwift | refs/heads/master | MIPSwift/RegisterFile.swift | mit | 1 | //
// RegisterFile.swift
// MIPSwift
//
// Created by Hunter Knepshield on 12/10/15.
// Copyright © 2015 Hunter Knepshield. All rights reserved.
//
import Foundation
/// Representation of a register file inside a CPU.
class RegisterFile: CustomStringConvertible {
// User-accessible registers
/// $zero or $0, immutable.
var zero: Int32 { get { return Int32.allZeros } }
/// $at or $1, assembler temporary value.
var at: Int32 = 0
/// $v0 or $2, function return value.
var v0: Int32 = 0
/// $v1 or $3, function return value.
var v1: Int32 = 0
/// $a0 or $4, function argument value.
var a0: Int32 = 0
/// $a1 or $5, function argument value.
var a1: Int32 = 0
/// $a2 or $6, function argument value.
var a2: Int32 = 0
/// $a3 or $7, function argument value.
var a3: Int32 = 0
/// $t0 or $8, temporary value.
var t0: Int32 = 0
/// $t1 or $9, temporary value.
var t1: Int32 = 0
/// $t2 or $10, temporary value.
var t2: Int32 = 0
/// $t3 or $11, temporary value.
var t3: Int32 = 0
/// $t4 or $12, temporary value.
var t4: Int32 = 0
/// $t5 or $13, temporary value.
var t5: Int32 = 0
/// $t6 or $14, temporary value.
var t6: Int32 = 0
/// $t7 or $15, temporary value.
var t7: Int32 = 0
/// $s0 or $16, saved value.
var s0: Int32 = 0
/// $s1 or $17, saved value.
var s1: Int32 = 0
/// $s2 or $18, saved value.
var s2: Int32 = 0
/// $s3 or $19, saved value.
var s3: Int32 = 0
/// $s4 or $20, saved value.
var s4: Int32 = 0
/// $s5 or $21, saved value.
var s5: Int32 = 0
/// $s6 or $22, saved value.
var s6: Int32 = 0
/// $s7 or $23, saved value.
var s7: Int32 = 0
/// $t8 or $24, temporary value.
var t8: Int32 = 0
/// $t9 or $25, temporary value.
var t9: Int32 = 0
/// $k0 or $26, kernel reserved.
var k0: Int32 = 0
/// $k1 or $27, kernel reserved.
var k1: Int32 = 0
/// $gp or $28, global memory pointer.
var gp: Int32 = 0
/// $sp or $29, stack pointer.
var sp: Int32 = 0
/// $fp or $30, stack frame pointer.
var fp: Int32 = 0
/// $ra or $31, return address pointer.
var ra: Int32 = 0
// User-inaccessible registers
/// hi, upper 32 bits of large mathematical operations.
var hi: Int32 = 0
/// lo, lower 32 bits of large mathematical operations.
var lo: Int32 = 0
/// Program counter.
var pc: Int32 = 0
/// Get the value of a given register.
func get(register: Register) -> Int32 {
switch(register) {
case .zero:
return self.zero
case .at:
return self.at
case .v0:
return self.v0
case .v1:
return self.v1
case .a0:
return self.a0
case .a1:
return self.a1
case .a2:
return self.a2
case .a3:
return self.a3
case .t0:
return self.t0
case .t1:
return self.t1
case .t2:
return self.t2
case .t3:
return self.t3
case .t4:
return self.t4
case .t5:
return self.t5
case .t6:
return self.t6
case .t7:
return self.t7
case .s0:
return self.s0
case .s1:
return self.s1
case .s2:
return self.s2
case .s3:
return self.s3
case .s4:
return self.s4
case .s5:
return self.s5
case .s6:
return self.s6
case .s7:
return self.s7
case .t8:
return self.t8
case .t9:
return self.t9
case .k0:
return self.k0
case .k1:
return self.k1
case .gp:
return self.gp
case .sp:
return self.sp
case .fp:
return self.fp
case .ra:
return self.ra
case .hi:
return self.hi
case .lo:
return self.lo
case .pc:
return self.pc
}
}
/// Set the value of a given register.
func set(register: Register, _ value: Int32) {
switch(register) {
case .zero:
fatalError("Cannot modify immutable register: \(register.name)")
case .at:
self.at = value
case .v0:
self.v0 = value
case .v1:
self.v1 = value
case .a0:
self.a0 = value
case .a1:
self.a1 = value
case .a2:
self.a2 = value
case .a3:
self.a3 = value
case .t0:
self.t0 = value
case .t1:
self.t1 = value
case .t2:
self.t2 = value
case .t3:
self.t3 = value
case .t4:
self.t4 = value
case .t5:
self.t5 = value
case .t6:
self.t6 = value
case .t7:
self.t7 = value
case .s0:
self.s0 = value
case .s1:
self.s1 = value
case .s2:
self.s2 = value
case .s3:
self.s3 = value
case .s4:
self.s4 = value
case .s5:
self.s5 = value
case .s6:
self.s6 = value
case .s7:
self.s7 = value
case .t8:
self.t8 = value
case .t9:
self.t9 = value
case .k0:
self.k0 = value
case .k1:
self.k1 = value
case .gp:
self.gp = value
case .sp:
self.sp = value
case .fp:
self.fp = value
case .ra:
self.ra = value
case .hi:
self.hi = value
case .lo:
self.lo = value
case .pc:
self.pc = value
}
}
/// The current formatting setting used in self.description.
var printOption: PrintOption = .Hex
var description: String {
get {
let format = printOption.rawValue
var contents = "Register file contents:\n"
contents += "$zero: \(zero.format(format)) $at: \(at.format(format)) $v0: \(v0.format(format)) $v1: \(v1.format(format))\n"
contents += " $a0: \(a0.format(format)) $a1: \(a1.format(format)) $a2: \(a2.format(format)) $a3: \(a3.format(format))\n"
contents += " $t0: \(t0.format(format)) $t1: \(t1.format(format)) $t2: \(t2.format(format)) $t3: \(t3.format(format))\n"
contents += " $t4: \(t4.format(format)) $t5: \(t5.format(format)) $t6: \(t6.format(format)) $t7: \(t7.format(format))\n"
contents += " $s0: \(s0.format(format)) $s1: \(s1.format(format)) $s2: \(s2.format(format)) $s3: \(s3.format(format))\n"
contents += " $s4: \(s4.format(format)) $s5: \(s5.format(format)) $s6: \(s6.format(format)) $s7: \(s7.format(format))\n"
contents += " $t8: \(t8.format(format)) $t9: \(t9.format(format)) $k0: \(k0.format(format)) $k1: \(k1.format(format))\n"
contents += " $gp: \(gp.format(format)) $sp: \(sp.format(format)) $fp: \(fp.format(format)) $ra: \(ra.format(format))\n"
contents += " pc: \(pc.format(format)) hi: \(hi.format(format)) lo: \(lo.format(format))"
return contents
}
}
} | 7eb9ceab3074178a390cc9b81e9f4e7f | 23.644531 | 138 | 0.576728 | false | false | false | false |
bindlechat/ZenText | refs/heads/master | ZenText/Classes/Style.swift | mit | 1 | import Foundation
public class Style: ExpressibleByStringLiteral {
open var color: UIColor?
open var fontName: String?
open var fontSize: CGFloat?
open var underline: Bool?
open var alpha: CGFloat?
open var backgroundColor: UIColor?
public required init(stringLiteral value: String) {
for styleName in ZenText.manager.styleNamesFromStyleString(value) {
if let style = styleName.style() {
append(style)
}
}
}
public required init(extendedGraphemeClusterLiteral value: String) {
for styleName in ZenText.manager.styleNamesFromStyleString(value) {
if let style = styleName.style() {
append(style)
}
}
}
public required init(unicodeScalarLiteral value: String) {
for styleName in ZenText.manager.styleNamesFromStyleString(value) {
if let style = styleName.style() {
append(style)
}
}
}
public init(color: UIColor? = nil, fontName: String? = nil, fontSize: CGFloat? = nil, underline: Bool? = nil, alpha: CGFloat? = nil, backgroundColor: UIColor? = nil) {
self.color = color
self.fontName = fontName
self.fontSize = fontSize
self.underline = underline
self.alpha = alpha
self.backgroundColor = backgroundColor
}
public func append(_ style: Style?) {
guard let style = style else { return }
if let color = style.color { self.color = color }
if let fontName = style.fontName { self.fontName = fontName }
if let fontSize = style.fontSize { self.fontSize = fontSize }
if let alpha = style.alpha { self.alpha = alpha }
if let underline = style.underline { self.underline = underline }
if let backgroundColor = style.backgroundColor { self.backgroundColor = backgroundColor }
}
}
| 463b221ef8cc6208aeb635730a348f3b | 35.415094 | 171 | 0.619171 | false | false | false | false |
vulcancreative/chinwag-swift | refs/heads/master | Tests/GenerationTests.swift | mit | 1 | //
// GenerationTests.swift
// Chinwag
//
// Created by Chris Calo on 2/26/15.
// Copyright (c) 2015 Chris Calo. All rights reserved.
//
import Foundation
import Chinwag
import XCTest
class GenerationTests: XCTestCase {
var blank = Chinwag.open()
var seuss = Chinwag.open()
var latin = Chinwag.open()
override func setUp() {
super.setUp()
blank = Chinwag.open()
seuss = Chinwag.open(embedded: .Seuss)!
latin = Chinwag.open(embedded: .Latin)!
}
override func tearDown() {
super.tearDown()
blank.close()
seuss.close()
latin.close()
}
func testGenerateMinLessThanOneError() {
let result = Chinwag.generate(seuss, .Letters, 0, 10)
let raw = result.err!.rawValue
XCTAssertEqual(raw, CWError.MinLessThanOne.rawValue, "min is less than one, but no error was thrown")
}
func testGenerateMaxLessThanMinError() {
let result = Chinwag.generate(seuss, .Letters, 13, 12)
let raw = result.err!.rawValue
XCTAssertEqual(raw, CWError.MaxLessThanMin.rawValue, "max is less than min, but no error was thrown")
}
func testGenerateMaxTooHighError() {
let result = Chinwag.generate(seuss, .Letters, 5, 10001)
let raw = result.err!.rawValue
XCTAssertEqual(raw, CWError.MaxTooHigh.rawValue, "max exceeds 10.000, but no error was thrown")
}
func testGenerateDictionaryTooSmallError() {
let result = Chinwag.generate(blank, .Letters, 4, 50)
let raw = result.err!.rawValue
XCTAssertEqual(raw, CWError.DictTooSmall.rawValue, "dict should be too small, but no error was thrown")
}
}
| 93ec0100a70113d4dde936fcc9133557 | 27.918033 | 111 | 0.621882 | false | true | false | false |
openbuild-sheffield/jolt | refs/heads/master | Sources/OpenbuildExtensionPerfect/model.ResponseModel500Messages.swift | gpl-2.0 | 1 | import PerfectLib
public class ResponseModel500Messages: JSONConvertibleObject, DocumentationProtocol {
static let registerName = "responseModel500Messages"
public var error: Bool = true
public var message: String = "Internal server error. This has been logged."
public var messages: [String: Any] = [:]
public var descriptions = [
"error": "An error has occurred, will always be true",
"message": "Will always be 'Internal server error. This has been logged.'",
"messages": "Key pair of error messages."
]
public init(messages: [String : Any]) {
self.messages = messages
}
public override func setJSONValues(_ values: [String : Any]) {
self.error = getJSONValue(named: "error", from: values, defaultValue: true)
self.message = getJSONValue(named: "message", from: values, defaultValue: "Internal server error. This has been logged.")
self.messages = getJSONValue(named: "messages", from: values, defaultValue: [:])
}
public override func getJSONValues() -> [String : Any] {
return [
JSONDecoding.objectIdentifierKey:ResponseModel500Messages.registerName,
"error": error,
"message": message,
"messages":messages
]
}
public static func describeRAML() -> [String] {
if let docs = ResponseDocumentation.getRAML(key: "ResponseModel500Messages") {
return docs
} else {
let model = ResponseModel500Messages(messages: [
"message": "Failed to generate a successful response."
])
let aMirror = Mirror(reflecting: model)
let docs = ResponseDocumentation.genRAML(mirror: aMirror, descriptions: model.descriptions)
ResponseDocumentation.setRAML(key: "ResponseModel500Messages", lines: docs)
return docs
}
/*
var raml:[String] = ["error: boolean"]
raml.append("errors?:")
raml.append(" description: key/value pair describing the errors")
raml.append(" type: object")
raml.append("validated?:")
raml.append(" description: validated data with possible errors")
raml.append(" type: object")
raml.append(" properties:")
raml.append(" valid: boolean")
raml.append(" validated?: object")
raml.append(" description: key/pair of validated data")
raml.append(" errors?: object")
raml.append(" description: key/pair describing the errors")
raml.append(" raw: object")
raml.append(" description: the data sent to the server")
raml.append(" properties:")
raml.append(" uri?: object")
raml.append(" description: key/value pair data sent to the server in the uri")
raml.append(" body?: object")
raml.append(" description: key/value pair data sent to the server in the body")
return raml
*/
}
}
extension ResponseModel500Messages: CustomReflectable {
open var customMirror: Mirror {
return Mirror(
self,
children: [
"error": self.error,
"message": self.message,
"messages": self.messages
],
displayStyle: Mirror.DisplayStyle.class
)
}
} | 4cfef2569a416e94730812ca8f9b21cf | 31.961165 | 130 | 0.601355 | false | false | false | false |
BananosTeam/CreativeLab | refs/heads/master | Assistant/Trello/Models/List.swift | mit | 1 | //
// List.swift
// Assistant
//
// Created by Dmitrii Celpan on 5/14/16.
// Copyright © 2016 Bananos. All rights reserved.
//
import Foundation
final class List {
var id: String?
var name: String?
var closed: Bool?
var idBoard: String?
var subscribed: Bool?
}
final class ListParser {
func listsFromDictionaties(dictionaries: [NSDictionary]) -> [List] {
return dictionaries.map() { listFromDictionary($0) }
}
func listFromDictionary(dictionary: NSDictionary) -> List {
let list = List()
list.id = dictionary["id"] as? String
list.name = dictionary["name"] as? String
list.closed = dictionary["closed"] as? Bool
list.idBoard = dictionary["idBoard"] as? String
list.subscribed = dictionary["subscribed"] as? Bool
return list
}
}
| 4679dde6bb70fc5eac920d7ef37ae084 | 22.243243 | 72 | 0.616279 | false | false | false | false |
rudkx/swift | refs/heads/main | test/Concurrency/Runtime/async_initializer.swift | apache-2.0 | 1 | // RUN: %target-run-simple-swift(-parse-as-library -Xfrontend -disable-availability-checking %import-libdispatch) | %FileCheck %s
// REQUIRES: executable_test
// REQUIRES: concurrency
// REQUIRES: libdispatch
// rdar://76038845
// REQUIRES: concurrency_runtime
// UNSUPPORTED: back_deployment_runtime
@available(SwiftStdlib 5.1, *)
actor NameGenerator {
private var counter = 0
private var prefix : String
init(_ title: String) { self.prefix = title }
func getName() -> String {
counter += 1
return "\(prefix) \(counter)"
}
}
@available(SwiftStdlib 5.1, *)
protocol Person {
init() async
var name : String { get set }
}
@available(SwiftStdlib 5.1, *)
class EarthPerson : Person {
private static let oracle = NameGenerator("Earthling")
var name : String
required init() async {
self.name = await EarthPerson.oracle.getName()
}
init(name: String) async {
self.name = await (detach { name }).get()
}
}
@available(SwiftStdlib 5.1, *)
class NorthAmericaPerson : EarthPerson {
private static let oracle = NameGenerator("NorthAmerican")
required init() async {
await super.init()
self.name = await NorthAmericaPerson.oracle.getName()
}
override init(name: String) async {
await super.init(name: name)
}
}
@available(SwiftStdlib 5.1, *)
class PrecariousClass {
init?(nilIt : Int) async {
let _ : Optional<Int> = await (detach { nil }).get()
return nil
}
init(throwIt : Double) async throws {
if await (detach { 0 }).get() != 1 {
throw Something.bogus
}
}
init?(nilOrThrowIt shouldThrow: Bool) async throws {
let flag = await (detach { shouldThrow }).get()
if flag {
throw Something.bogus
}
return nil
}
init!(crashOrThrowIt shouldThrow: Bool) async throws {
let flag = await (detach { shouldThrow }).get()
if flag {
throw Something.bogus
}
return nil
}
}
enum Something : Error {
case bogus
}
@available(SwiftStdlib 5.1, *)
struct PrecariousStruct {
init?(nilIt : Int) async {
let _ : Optional<Int> = await (detach { nil }).get()
return nil
}
init(throwIt : Double) async throws {
if await (detach { 0 }).get() != 1 {
throw Something.bogus
}
}
}
// CHECK: Earthling 1
// CHECK-NEXT: Alice
// CHECK-NEXT: Earthling 2
// CHECK-NEXT: Bob
// CHECK-NEXT: Earthling 3
// CHECK-NEXT: Alex
// CHECK-NEXT: NorthAmerican 1
// CHECK-NEXT: NorthAmerican 2
// CHECK-NEXT: Earthling 6
// CHECK-NEXT: class was nil
// CHECK-NEXT: class threw
// CHECK-NEXT: nilOrThrowIt init was nil
// CHECK-NEXT: nilOrThrowIt init threw
// CHECK-NEXT: crashOrThrowIt init threw
// CHECK-NEXT: struct was nil
// CHECK-NEXT: struct threw
// CHECK: done
@available(SwiftStdlib 5.1, *)
@main struct RunIt {
static func main() async {
let people : [Person] = [
await EarthPerson(),
await NorthAmericaPerson(name: "Alice"),
await EarthPerson(),
await NorthAmericaPerson(name: "Bob"),
await EarthPerson(),
await NorthAmericaPerson(name: "Alex"),
await NorthAmericaPerson(),
await NorthAmericaPerson(),
await EarthPerson()
]
for p in people {
print(p.name)
}
// ----
if await PrecariousClass(nilIt: 0) == nil {
print("class was nil")
}
do { let _ = try await PrecariousClass(throwIt: 0.0) } catch {
print("class threw")
}
if try! await PrecariousClass(nilOrThrowIt: false) == nil {
print("nilOrThrowIt init was nil")
}
do { let _ = try await PrecariousClass(nilOrThrowIt: true) } catch {
print("nilOrThrowIt init threw")
}
do { let _ = try await PrecariousClass(crashOrThrowIt: true) } catch {
print("crashOrThrowIt init threw")
}
if await PrecariousStruct(nilIt: 0) == nil {
print("struct was nil")
}
do { let _ = try await PrecariousStruct(throwIt: 0.0) } catch {
print("struct threw")
}
print("done")
}
}
| 8bd151217ddf8c3b68c28f1dfcc0a69b | 21.494318 | 130 | 0.639808 | false | false | false | false |
trashkalmar/omim | refs/heads/master | iphone/Maps/UI/PlacePage/PlacePageLayout/Content/ViatorCells/ViatorElement.swift | apache-2.0 | 1 | @objc(MWMViatorElement)
final class ViatorElement: UICollectionViewCell {
@IBOutlet private weak var more: UIButton!
@IBOutlet private weak var priceView: UIView!
@IBOutlet private weak var image: UIImageView!
@IBOutlet private weak var title: UILabel! {
didSet {
title.font = UIFont.medium14()
title.textColor = UIColor.blackPrimaryText()
}
}
@IBOutlet private weak var duration: UILabel! {
didSet {
duration.font = UIFont.regular12()
duration.textColor = UIColor.blackSecondaryText()
}
}
@IBOutlet private weak var price: UILabel! {
didSet {
price.textColor = UIColor.linkBlue()
price.font = UIFont.medium14()
}
}
@IBOutlet private weak var rating: RatingSummaryView! {
didSet {
rating.defaultConfig()
rating.textFont = UIFont.bold12()
rating.textSize = 12
}
}
private var isLastCell = false {
didSet {
more.isHidden = !isLastCell
image.isHidden = isLastCell
title.isHidden = isLastCell
duration.isHidden = isLastCell
price.isHidden = isLastCell
rating.isHidden = isLastCell
priceView.isHidden = isLastCell
}
}
override var isHighlighted: Bool {
didSet {
guard model != nil else { return }
UIView.animate(withDuration: kDefaultAnimationDuration,
delay: 0,
options: [.allowUserInteraction, .beginFromCurrentState],
animations: { self.alpha = self.isHighlighted ? 0.3 : 1 },
completion: nil)
}
}
@IBAction
private func onMore() {
onMoreAction?()
}
@objc
var model: ViatorItemModel? {
didSet {
if let model = model {
image.af_setImage(withURL: model.imageURL, imageTransition: .crossDissolve(kDefaultAnimationDuration))
title.text = model.title
duration.text = model.duration
price.text = String(coreFormat: L("place_page_starting_from"), arguments: [model.price])
rating.value = model.ratingFormatted
rating.type = model.ratingType
backgroundColor = UIColor.white()
layer.cornerRadius = 6
layer.borderWidth = 1
layer.borderColor = UIColor.blackDividers().cgColor
isLastCell = false
} else {
more.setImage(UIColor.isNightMode() ? #imageLiteral(resourceName: "btn_float_more_dark") : #imageLiteral(resourceName: "btn_float_more_light"), for: .normal)
backgroundColor = UIColor.clear
layer.borderColor = UIColor.clear.cgColor
isLastCell = true
}
}
}
var onMoreAction: (() -> Void)?
}
| 2a82a1fc1e408828768ed356b4623d6f | 27.258065 | 165 | 0.638508 | false | false | false | false |
jeffreybergier/Hipstapaper | refs/heads/main | Hipstapaper/Packages/V3Errors/Sources/V3Errors/Errors/CPError+CodableError.swift | mit | 1 | //
// Created by Jeffrey Bergier on 2022/08/05.
//
// MIT License
//
// Copyright (c) 2021 Jeffrey Bergier
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
import Umbrella
extension CPError {
public var codableValue: CodableError {
let data: Data?
switch self {
case .accountStatus(let status):
data = try? PropertyListEncoder().encode(status.rawValue)
case .sync(let error):
// TODO: Enhance to save suberror kind
NSLog(String(describing: error))
data = nil
}
return CodableError(domain: type(of: self).errorDomain,
code: self.errorCode,
arbitraryData: data)
}
public init?(codableError: CodableError) {
guard type(of: self).errorDomain == codableError.errorDomain else { return nil }
switch codableError.errorCode {
case 1001:
let status: CPAccountStatus = {
guard
let data = codableError.arbitraryData,
let rawValue = try? PropertyListDecoder().decode(Int.self, from: data),
let status = CPAccountStatus(rawValue: rawValue)
else { return .couldNotDetermine }
return status
}()
self = .accountStatus(status)
case 1002:
self = .sync(nil)
default:
return nil
}
}
}
| e0e74a68f1dadf39264124da35a40c7e | 37.784615 | 91 | 0.638239 | false | false | false | false |
LearningSwift2/LearningApps | refs/heads/master | ReminderApp/ReminderApp/DateTableViewCell.swift | apache-2.0 | 1 | //
// DateTableViewCell.swift
// ReminderApp
//
// Created by Phil Wright on 4/8/16.
// Copyright © 2016 Touchopia, LLC. All rights reserved.
//
import UIKit
class DateTableViewCell: UITableViewCell {
@IBOutlet weak var datePicker: UIDatePicker!
var currentDate = NSDate()
var isDatePickerHidden = true
override func awakeFromNib() {
super.awakeFromNib()
}
func configureCell(currentDate: NSDate) {
datePicker.hidden = isDatePickerHidden
datePicker.date = currentDate
self.layoutIfNeeded()
}
func toggleDatePicker() {
self.isDatePickerHidden = !self.isDatePickerHidden
self.datePicker.hidden = self.isDatePickerHidden
}
@IBAction func datePickerValueChanged(sender: UIDatePicker) {
self.currentDate = sender.date
NSNotificationCenter.defaultCenter().postNotificationName("DateHasChanged", object: nil)
}
}
| e6219f2121da04d2364859fe67276162 | 19.470588 | 96 | 0.613985 | false | false | false | false |
younata/RSSClient | refs/heads/master | TethysKit/Services/FeedService/InoreaderFeedService.swift | mit | 1 | import Result
import CBGPromise
import FutureHTTP
struct InoreaderFeedService: FeedService {
private let httpClient: HTTPClient
let baseURL: URL
init(httpClient: HTTPClient, baseURL: URL) {
self.httpClient = httpClient
self.baseURL = baseURL
}
func feeds() -> Future<Result<AnyCollection<Feed>, TethysError>> {
let url = self.baseURL.appendingPathComponent("reader/api/0/subscription/list", isDirectory: false)
let request = URLRequest(url: url)
return self.httpClient.request(request).map { requestResult -> Result<[InoreaderFeed], NetworkError> in
switch requestResult {
case .success(let response):
return self.parse(response: response).map { (parsed: InoreaderSubscriptions) -> [InoreaderFeed] in
return parsed.subscriptions
}
case .failure(let clientError):
return .failure(NetworkError(httpClientError: clientError))
}
}.map { feedResult -> Future<Result<[Feed], TethysError>> in
return feedResult.mapError { return TethysError.network(url, $0) }.mapFuture(self.retrieveFeedDetails)
}.map { feedResult -> Future<Result<[Feed], TethysError>> in
return feedResult.mapFuture { feeds in
return self.requestUnreadCounts().map { unreadCountsResult -> Result<[Feed], TethysError> in
return unreadCountsResult.map { unreadCounts in
feeds.forEach { feed in
feed.unreadCount = unreadCounts[feed.identifier] ?? 0
}
return feeds
}
}
}
}.map { parseResult -> Result<AnyCollection<Feed>, TethysError> in
return parseResult.map { AnyCollection($0) }
}
}
private func requestUnreadCounts() -> Future<Result<[String: Int], TethysError>> {
let url = self.baseURL.appendingPathComponent("reader/api/0/unread-count", isDirectory: false)
let request = URLRequest(url: url)
return self.httpClient.request(request).map { requestResult -> Result<[String: Int], NetworkError> in
switch requestResult {
case .success(let response):
return self.parse(response: response).map { (parsed: InoreaderUnreadCounts) -> [String: Int] in
return parsed.unreadcounts.reduce(
into: [String: Int]()
) { (result: inout [String: Int], unreadCount: InoreaderUnreadCount) in
result[unreadCount.id] = Int(unreadCount.count) ?? 0
}
}
case .failure(let clientError):
return .failure(NetworkError(httpClientError: clientError))
}
}.map {
return $0.mapError { return TethysError.network(url, $0) }
}
}
func articles(of feed: Feed) -> Future<Result<AnyCollection<Article>, TethysError>> {
let encodedURL: String = feed.url.absoluteString.addingPercentEncoding(
withAllowedCharacters: .urlHostAllowed
) ?? ""
let apiUrl = self.baseURL.appendingPathComponent("reader/api/0/stream/contents/feed")
let url = URL(string: apiUrl.absoluteString + "%2F" + encodedURL)!
return self.httpClient.request(URLRequest(url: url))
.map { requestResult -> Result<[InoreaderArticle], NetworkError> in
switch requestResult {
case .success(let response):
return self.parse(response: response).map { (parsed: InoreaderArticles) -> [InoreaderArticle] in
return parsed.items
}
case .failure(let clientError):
return .failure(NetworkError(httpClientError: clientError))
}
}.map { articlesResult -> Result<AnyCollection<Article>, TethysError> in
return articlesResult.mapError { return TethysError.network(url, $0) }
.map { articles -> [Article] in
return articles.compactMap {
guard let url = $0.canonical.first?.href else { return nil }
return Article(
title: $0.title,
link: url,
summary: $0.summary.content,
authors: [Author(name: $0.author, email: nil)].filter { $0.name.isEmpty == false },
identifier: $0.id,
content: $0.summary.content,
read: InoreaderTags(tags: $0.categories.map { InoreaderTag(id: $0) }).containsRead,
published: $0.published,
updated: $0.updated
)
}
}.map { AnyCollection($0) }
}
}
func subscribe(to url: URL) -> Future<Result<Feed, TethysError>> {
var urlComponents = URLComponents(url: self.baseURL.appendingPathComponent(
"reader/api/0/subscription/quickadd"), resolvingAgainstBaseURL: false
)
urlComponents?.queryItems = [
URLQueryItem(name: "quickadd", value: "feed/" + url.absoluteString)
]
guard let apiUrl = urlComponents?.url else {
return Promise<Result<Feed, TethysError>>.resolved(.failure(TethysError.unknown))
}
let request = URLRequest(url: apiUrl, headers: [:], method: .post(Data()))
return self.httpClient.request(request).map { result -> Result<InoreaderSubscribeResponse, NetworkError> in
switch result {
case .success(let response):
return self.parse(response: response)
case .failure(let clientError):
return .failure(NetworkError(httpClientError: clientError))
}
}.map { result -> Result<Feed, TethysError> in
switch result {
case .success(let subscribeResponse):
let subscribedUrlString = String(subscribeResponse.query.split(
separator: "/",
maxSplits: 1,
omittingEmptySubsequences: true
)[1])
let subscribedUrl = URL(string: subscribedUrlString)!
return .success(Feed(
title: subscribeResponse.streamName,
url: subscribedUrl,
summary: "",
tags: []
))
case .failure(let networkError):
return .failure(.network(apiUrl, networkError))
}
}
}
func tags() -> Future<Result<AnyCollection<String>, TethysError>> {
let apiUrl = self.baseURL.appendingPathComponent("reader/api/0/tag/list")
let request = URLRequest(url: apiUrl)
return self.httpClient.request(request).map { requestResult -> Result<[String], NetworkError> in
switch requestResult {
case .success(let response):
return self.parse(response: response).map { (parsed: InoreaderTags) -> [String] in
return parsed.tags.compactMap { $0.tagName }
}
case .failure(let clientError):
return .failure(NetworkError(httpClientError: clientError))
}
}.map { result -> Result<AnyCollection<String>, TethysError> in
return result.mapError { return TethysError.network(apiUrl, $0) }.map { AnyCollection($0) }
}
}
func set(tags: [String], of feed: Feed) -> Future<Result<Feed, TethysError>> {
return Promise<Result<Feed, TethysError>>.resolved(.failure(.notSupported))
}
func set(url: URL, on feed: Feed) -> Future<Result<Feed, TethysError>> {
return Promise<Result<Feed, TethysError>>.resolved(.failure(.notSupported))
}
func readAll(of feed: Feed) -> Future<Result<Void, TethysError>> {
var urlComponents = URLComponents(url: self.baseURL.appendingPathComponent("reader/api/0/mark-all-as-read"),
resolvingAgainstBaseURL: false)!
urlComponents.queryItems = [
URLQueryItem(name: "s", value: "feed/\(feed.url.absoluteString)")
]
let url = urlComponents.url!
let request = URLRequest(url: url)
return self.httpClient.request(request).map { requestResult -> Result<Void, NetworkError> in
switch requestResult {
case .success(let response):
guard response.status == .ok else {
guard let receivedStatus = response.status, let status = HTTPError(status: receivedStatus) else {
return .failure(.unknown)
}
return .failure(.http(status, response.body))
}
return .success(Void())
case .failure(let error):
return .failure(NetworkError(httpClientError: error))
}
}.map { result -> Result<Void, TethysError> in
return result.mapError { return TethysError.network(url, $0) }
}
}
func remove(feed: Feed) -> Future<Result<Void, TethysError>> {
var urlComponents = URLComponents(url: self.baseURL.appendingPathComponent("reader/api/0/subscription/edit"),
resolvingAgainstBaseURL: false)!
urlComponents.queryItems = [
URLQueryItem(name: "ac", value: "unsubscribe"),
URLQueryItem(name: "s", value: "feed/\(feed.url.absoluteString)")
]
let url = urlComponents.url!
let request = URLRequest(url: url)
return self.httpClient.request(request).map { requestResult -> Result<Void, NetworkError> in
switch requestResult {
case .success(let response):
guard response.status == .ok else {
guard let receivedStatus = response.status, let status = HTTPError(status: receivedStatus) else {
return .failure(.unknown)
}
return .failure(.http(status, response.body))
}
return .success(Void())
case .failure(let error):
return .failure(NetworkError(httpClientError: error))
}
}.map { result -> Result<Void, TethysError> in
return result.mapError { return TethysError.network(url, $0) }
}
}
// MARK: Private
private func parse<T: Decodable>(response: HTTPResponse) -> Result<T, NetworkError> {
guard response.status == .ok else {
guard let receivedStatus = response.status, let status = HTTPError(status: receivedStatus) else {
return .failure(.unknown)
}
return .failure(.http(status, response.body))
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .secondsSince1970
do {
return .success(try decoder.decode(T.self, from: response.body))
} catch let error {
print("error decoding data: \(String(data: response.body, encoding: .utf8) ?? "")")
dump(error)
return .failure(.badResponse(response.body))
}
}
private func retrieveFeedDetails(feeds: [InoreaderFeed]) -> Future<Result<[Feed], TethysError>> {
return Promise<Result<[Feed], TethysError>>.resolved(.success(feeds.map {
return Feed(
title: $0.title,
url: $0.url,
summary: "",
tags: $0.categories.map { $0.label },
unreadCount: 0,
image: nil,
identifier: $0.id,
settings: nil
)
}))
}
}
private struct InoreaderSubscriptions: Codable {
let subscriptions: [InoreaderFeed]
}
private struct InoreaderFeed: Codable {
let id: String
let title: String
let categories: [InoreaderCategory]
let sortid: String
let firstitemmsec: Int
let url: URL
let htmlUrl: URL
let iconUrl: String
}
private struct InoreaderCategory: Codable {
let id: String
let label: String
}
private struct InoreaderArticles: Codable {
let id: String
let title: String
let updated: Date
let continuation: String
let items: [InoreaderArticle]
}
private struct InoreaderArticle: Codable {
let id: String
let title: String
let categories: [String]
let published: Date
let updated: Date?
let canonical: [InoreaderLink]
let alternate: [InoreaderLink]
let author: String
let summary: InoreaderSummary
}
private struct InoreaderLink: Codable {
let href: URL
let type: String?
}
private struct InoreaderSummary: Codable {
let content: String
}
private struct InoreaderSubscribeResponse: Codable {
let query: String
let numResults: Int
let streamId: String
let streamName: String
}
private struct InoreaderTags: Codable {
let tags: [InoreaderTag]
var containsRead: Bool {
return self.tags.contains(where: { $0.isRead })
}
}
private struct InoreaderTag: Codable {
let id: String
var tagName: String? {
// user/-/label/Tech, only if "label" in the preceeding.
let components = self.id.components(separatedBy: "/")
guard components.count >= 4 else { return nil }
guard components[2] == "label" else { return nil }
return components[3..<(components.count)].joined(separator: "/")
}
var state: String? {
let components = self.id.components(separatedBy: "/")
guard components.count >= 5 else { return nil }
guard components[2] == "state" else { return nil }
return components[3..<(components.count)].joined(separator: "/")
}
var isRead: Bool {
return self.state == "com.google/read"
}
}
private struct InoreaderUnreadCounts: Decodable {
let max: String
let unreadcounts: [InoreaderUnreadCount]
}
private struct InoreaderUnreadCount: Decodable {
let id: String
let count: String
let newestItemTimestampUsec: String
enum CodingKeys: String, CodingKey {
case id
case count
case newestItemTimestampUsec
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.id = try container.decode(String.self, forKey: .id)
do {
self.count = try container.decode(String.self, forKey: .count)
} catch DecodingError.typeMismatch {
self.count = "0"
}
self.newestItemTimestampUsec = try container.decode(String.self, forKey: .newestItemTimestampUsec)
}
}
| d9d839f9499ae360a9035616f616db62 | 39.194595 | 117 | 0.582033 | false | false | false | false |
gitdoapp/SoundCloudSwift | refs/heads/master | Carthage/Checkouts/Mockingjay/Mockingjay/Builders.swift | mit | 6 | //
// Builders.swift
// Mockingjay
//
// Created by Kyle Fuller on 01/03/2015.
// Copyright (c) 2015 Cocode. All rights reserved.
//
import Foundation
// Collection of generic builders
/// Generic builder for returning a failure
public func failure(error:NSError)(request:NSURLRequest) -> Response {
return .Failure(error)
}
public func http(status:Int = 200, headers:[String:String]? = nil, data:NSData? = nil)(request:NSURLRequest) -> Response {
if let response = NSHTTPURLResponse(URL: request.URL!, statusCode: status, HTTPVersion: nil, headerFields: headers) {
return Response.Success(response, data)
}
return .Failure(NSError(domain: NSInternalInconsistencyException, code: 0, userInfo: [NSLocalizedDescriptionKey: "Failed to construct response for stub."]))
}
public func json(body:AnyObject, status:Int = 200, headers:[String:String]? = nil)(request:NSURLRequest) -> Response {
do {
let data = try NSJSONSerialization.dataWithJSONObject(body, options: NSJSONWritingOptions())
return jsonData(data, status: status, headers: headers)(request: request)
} catch {
return .Failure(error as NSError)
}
}
public func jsonData(data: NSData, status: Int = 200, headers: [String:String]? = nil)(request:NSURLRequest) -> Response {
var headers = headers ?? [String:String]()
if headers["Content-Type"] == nil {
headers["Content-Type"] = "application/json; charset=utf-8"
}
return http(status, headers: headers, data: data)(request:request)
}
| 528f0eb7d26d91ae55dc5a8679826079 | 34.547619 | 158 | 0.720697 | false | false | false | false |
gali8/WhichFont | refs/heads/master | WhichFont/LaunchViewController.swift | mit | 1 | //
// LaunchViewController.swift
// WhichFont
//
// Created by Daniele on 25/07/17.
// Copyright © 2017 nexor. All rights reserved.
//
import UIKit
class DelayHelper {
class func delay(_ delay:Double, closure:@escaping ()->()) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
}
}
class LaunchViewController: UIViewController, UIViewControllerTransitioningDelegate {
private let presentationTransitioning = RevealAnimator()
override func viewDidLoad() {
super.viewDidLoad()
self.transitioningDelegate = self
DelayHelper.delay(0.2) {
let vc = self.storyboard!.instantiateViewController(withIdentifier: "MainScene")
vc.transitioningDelegate = self
self.present(vc, animated: true, completion: nil)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return presentationTransitioning
}
func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return nil
}
}
class RevealAnimator: NSObject, UIViewControllerAnimatedTransitioning, CAAnimationDelegate {
let animationDuration = 0.4
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return animationDuration
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)
//let from = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.from)
//let to = transitionContext.viewController(forKey: UITransitionContextViewControllerKey.to)
//let finalFrame = transitionContext.finalFrame(for: to!)
let containerView = transitionContext.containerView
//let bounds = UIScreen.main.bounds
toView?.alpha = 0.8
containerView.addSubview(toView!)
UIView.animate(withDuration: animationDuration, animations: {
fromView?.alpha = 0
toView?.alpha = 1
}) { (done) in
transitionContext.completeTransition(true)
fromView?.alpha = 1
}
}
}
| 9baaaeb192f464ce601988d917821d2e | 34.61039 | 170 | 0.690372 | false | false | false | false |
Ivacker/swift | refs/heads/master | test/Constraints/tuple.swift | apache-2.0 | 9 | // RUN: %target-parse-verify-swift
// Test various tuple constraints.
func f0(x x: Int, y: Float) {}
var i : Int
var j : Int
var f : Float
func f1(y y: Float, rest: Int...) {}
func f2(_: (x: Int, y: Int) -> Int) {}
func f2xy(x x: Int, y: Int) -> Int {}
func f2ab(a a: Int, b: Int) -> Int {}
func f2yx(y y: Int, x: Int) -> Int {}
func f3(x: (x: Int, y: Int) -> ()) {}
func f3a(x: Int, y: Int) {}
func f3b(_: Int) {}
func f4(rest: Int...) {}
func f5(x: (Int, Int)) {}
func f6(_: (i: Int, j: Int), k: Int = 15) {}
//===--------------------------------------------------------------------===//
// Conversions and shuffles
//===--------------------------------------------------------------------===//
// Variadic functions.
f4()
f4(1)
f4(1, 2, 3)
f2(f2xy)
f2(f2ab)
f2(f2yx) // expected-error{{cannot convert value of type '(y: Int, x: Int) -> Int' to expected argument type '(x: Int, y: Int) -> Int'}}
f3(f3a)
f3(f3b) // expected-error{{cannot convert value of type '(Int) -> ()' to expected argument type '(x: Int, y: Int) -> ()'}}
func getIntFloat() -> (int: Int, float: Float) {}
var values = getIntFloat()
func wantFloat(_: Float) {}
wantFloat(values.float)
var e : (x: Int..., y: Int) // expected-error{{cannot create a variadic tuple}}
typealias Interval = (a:Int, b:Int)
func takeInterval(x: Interval) {}
takeInterval(Interval(1, 2))
f5((1,1))
// Tuples with existentials
var any : Any = ()
any = (1, 2)
any = (label: 4)
// Scalars don't have .0/.1/etc
i = j.0 // expected-error{{value of type 'Int' has no member '0'}}
any.1 // expected-error{{value of type 'Any' (aka 'protocol<>') has no member '1'}}
// Fun with tuples
protocol PosixErrorReturn {
static func errorReturnValue() -> Self
}
extension Int : PosixErrorReturn {
static func errorReturnValue() -> Int { return -1 }
}
func posixCantFail<A, T : protocol<Comparable, PosixErrorReturn>>
(f:(A) -> T)(args:A) -> T // expected-warning{{curried function declaration syntax will be removed in a future version of Swift}}
{
let result = f(args)
assert(result != T.errorReturnValue())
return result
}
func open(name: String, oflag: Int) -> Int { }
var foo: Int = 0
var fd = posixCantFail(open)(args: ("foo", 0))
// Tuples and lvalues
class C {
init() {}
func f(_: C) {}
}
func testLValue(c: C) {
var c = c
c.f(c)
let x = c
c = x
}
// <rdar://problem/21444509> Crash in TypeChecker::coercePatternToType
func invalidPatternCrash(k : Int) {
switch k {
case (k, cph_: k) as UInt8: // expected-error {{tuple pattern cannot match values of the non-tuple type 'UInt8'}} expected-warning {{cast from 'Int' to unrelated type 'UInt8' always fails}}
break
}
}
// <rdar://problem/21875219> Tuple to tuple conversion with IdentityExpr / AnyTryExpr hang
class Paws {
init() throws {}
}
func scruff() -> (AnyObject?, ErrorType?) {
do {
return try (Paws(), nil)
} catch {
return (nil, error)
}
}
// Test variadics with trailing closures.
func variadicWithTrailingClosure(x: Int..., y: Int = 2, fn: (Int, Int) -> Int) {
}
variadicWithTrailingClosure(1, 2, 3) { $0 + $1 }
variadicWithTrailingClosure(1) { $0 + $1 }
variadicWithTrailingClosure() { $0 + $1 }
variadicWithTrailingClosure { $0 + $1 }
variadicWithTrailingClosure(1, 2, 3, y: 0) { $0 + $1 }
variadicWithTrailingClosure(1, y: 0) { $0 + $1 }
variadicWithTrailingClosure(y: 0) { $0 + $1 }
variadicWithTrailingClosure(1, 2, 3, y: 0, fn: +)
variadicWithTrailingClosure(1, y: 0, fn: +)
variadicWithTrailingClosure(y: 0, fn: +)
variadicWithTrailingClosure(1, 2, 3, fn: +)
variadicWithTrailingClosure(1, fn: +)
variadicWithTrailingClosure(fn: +)
// <rdar://problem/23700031> QoI: Terrible diagnostic in tuple assignment
func gcd_23700031<T>(a: T, b: T) {
var a = a
var b = b
(a, b) = (b, a % b) // expected-error {{binary operator '%' cannot be applied to two 'T' operands}}
// expected-note @-1 {{overloads for '%' exist with these partially matching parameter lists: (UInt8, UInt8), (Int8, Int8), (UInt16, UInt16), (Int16, Int16), (UInt32, UInt32), (Int32, Int32), (UInt64, UInt64), (Int64, Int64), (UInt, UInt), (Int, Int), (Float, Float)}}
}
| dddef09f67c6a8afaa3d0e7e3b92c4ba | 25.896104 | 270 | 0.614437 | false | false | false | false |
jamalping/XPUtil | refs/heads/master | XPUtil/QRCodeUtil.swift | mit | 1 | //
// QRCodeUtil.swift
// ML
//
// Created by midland on 2019/4/1.
// Copyright © 2019年 杨帅. All rights reserved.
//
import UIKit
import CoreImage
public class QRCodeUtil {
public static func setQRCodeToImageView(_ imageView: UIImageView?, _ url: String?, _ centerLogo: String?) {
if imageView == nil || url == nil {
return
}
// 创建二维码滤镜
let filter = CIFilter(name: "CIQRCodeGenerator")
// 恢复滤镜默认设置
filter?.setDefaults()
// 设置滤镜输入数据
let data = url!.data(using: String.Encoding.utf8)
filter?.setValue(data, forKey: "inputMessage")
// 设置二维码的纠错率
filter?.setValue("M", forKey: "inputCorrectionLevel")
// 从二维码滤镜里面, 获取结果图片
var image = filter?.outputImage
// 生成一个高清图片
let transform = CGAffineTransform.init(scaleX: 20, y: 20)
image = image?.transformed(by: transform)
// 图片处理
var resultImage = UIImage(ciImage: image!)
// 中间的logo
var center = UIImage(named: "log-logo.png")
if let url = URL(string: centerLogo ?? "") {
do {
let data = try Data(contentsOf: url)
center = UIImage(data: data)
} catch let error as NSError {
print(error)
}
}
// 设置二维码中心显示的小图标
resultImage = getClearImage(sourceImage: resultImage, center: center!)
// 显示图片
imageView?.image = resultImage
}
// 使图片放大也可以清晰
static func getClearImage(sourceImage: UIImage, center: UIImage) -> UIImage {
let size = sourceImage.size
// 开启图形上下文
UIGraphicsBeginImageContext(size)
// 绘制大图片
sourceImage.draw(in: CGRect(x: 0, y: 0, width: size.width, height: size.height))
// 绘制二维码中心小图片
let width: CGFloat = 120
let height: CGFloat = 120
let x: CGFloat = (size.width - width) * 0.5
let y: CGFloat = (size.height - height) * 0.5
// 方形
// center.draw(in: CGRect(x: x, y: y, width: width, height: height))
// 画圆
let path = UIBezierPath.init(ovalIn: CGRect.init(x: x, y: y, width: width, height: height))
//裁切
path.addClip()
//3.绘制图像
center.draw(in: CGRect.init(x: x, y: y, width: width, height: height))
// 取出结果图片
let resultImage = UIGraphicsGetImageFromCurrentImageContext()
// 关闭上下文
UIGraphicsEndImageContext()
return resultImage!
}
}
| eb5e1eb0f68745e536c90c8b185a2cff | 27.212766 | 111 | 0.535068 | false | false | false | false |
dbruzzone/wishing-tree | refs/heads/master | iOS/Measure/Microsoft-Band/Microsoft-Band/AppDelegate.swift | gpl-3.0 | 1 | //
// AppDelegate.swift
// Microsoft-Band
//
// Created by Davide Bruzzone on 11/4/15.
// Copyright © 2015 Bitwise Samurai. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> 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:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.bitwisesamurai.Microsoft_Band" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("Microsoft_Band", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| 84477c9d0605823cf6020eb29c8a755a | 54.162162 | 291 | 0.720398 | false | false | false | false |
andrewapperley/WEBD-204-IOS | refs/heads/master | IOS Helper/IOS Helper/Advanced/AdvancedHelp_VideoPlayer.swift | mit | 1 | //
// AdvancedHelp_VideoPlayer.swift
// IOS Helper
//
// Created by Andrew Apperley on 2016-12-06.
// Copyright © 2016 Humber College. All rights reserved.
//
import UIKit
import AVFoundation
class AdvancedHelp_VideoPlayer: HelperViewController {
var player: AVPlayer?
override func viewDidLoad() {
super.viewDidLoad()
let url = NSURL.fileURLWithPath(NSBundle.mainBundle().pathForResource("bunny", ofType: "mp4")!)
player = AVPlayer(URL: url)
player?.volume = 0.5
let playerView = UIView()
playerView.backgroundColor = UIColor.redColor()
playerView.translatesAutoresizingMaskIntoConstraints = false
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravityResizeAspect
playerView.layer.addSublayer(playerLayer)
let playButton = UIButton()
playButton.translatesAutoresizingMaskIntoConstraints = false
playButton.setImage(UIImage(named: "play"), forState: .Normal)
playButton.imageView?.contentMode = .ScaleAspectFit
playButton.addTarget(self, action: #selector(play), forControlEvents: .TouchUpInside)
let pauseButton = UIButton()
pauseButton.translatesAutoresizingMaskIntoConstraints = false
pauseButton.setImage(UIImage(named: "pause"), forState: .Normal)
pauseButton.imageView?.contentMode = .ScaleAspectFit
pauseButton.addTarget(self, action: #selector(pause), forControlEvents: .TouchUpInside)
let volumeSlider = UISlider()
volumeSlider.translatesAutoresizingMaskIntoConstraints = false
volumeSlider.maximumValue = 1.0
volumeSlider.minimumValue = 0.0
volumeSlider.setValue(0.5, animated: false)
volumeSlider.addTarget(self, action: #selector(volumeUpdated), forControlEvents: .ValueChanged)
let controls = UIView()
controls.addSubview(playButton)
controls.addSubview(pauseButton)
controls.addSubview(volumeSlider)
stack.addArrangedSubview(controls)
stack.addArrangedSubview(playerView)
controls.heightAnchor.constraintEqualToConstant(100).active = true
playButton.heightAnchor.constraintEqualToConstant(50).active = true
playButton.widthAnchor.constraintEqualToConstant(50).active = true
playButton.leftAnchor.constraintEqualToAnchor(controls.leftAnchor, constant: 10).active = true
playButton.topAnchor.constraintEqualToAnchor(controls.topAnchor).active = true
pauseButton.heightAnchor.constraintEqualToConstant(50).active = true
pauseButton.widthAnchor.constraintEqualToConstant(50).active = true
pauseButton.leftAnchor.constraintEqualToAnchor(playButton.rightAnchor, constant: 10).active = true
pauseButton.topAnchor.constraintEqualToAnchor(controls.topAnchor).active = true
volumeSlider.widthAnchor.constraintEqualToConstant(90).active = true
volumeSlider.leftAnchor.constraintEqualToAnchor(pauseButton.rightAnchor, constant: 10).active = true
volumeSlider.centerYAnchor.constraintEqualToAnchor(pauseButton.centerYAnchor).active = true
playerView.heightAnchor.constraintEqualToConstant(300).active = true
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
player!.pause()
}
@objc private func play() {
player!.play()
}
@objc private func pause() {
player!.pause()
}
@objc private func volumeUpdated(slider: UISlider) {
player!.volume = slider.value
}
}
| 3ec4042415681f1dbeb9cfe289cc41df | 35.322581 | 104 | 0.767318 | false | false | false | false |
osorioabel/checklist-app | refs/heads/master | checklist-app/checklist-app/Models/DataModel.swift | mit | 1 | //
// DataModel.swift
// checklist-app
//
// Created by Abel Osorio on 2/16/16.
// Copyright © 2016 Abel Osorio. All rights reserved.
//
import Foundation
class DataModel {
var lists = [Checklist]()
var indexOfSelectedChecklist: Int {
get {
return NSUserDefaults.standardUserDefaults().integerForKey( "ChecklistIndex")
}
set {
NSUserDefaults.standardUserDefaults().setInteger(newValue,forKey: "ChecklistIndex")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
init(){
loadChecklists()
registerDefaults()
handleFirstTime()
}
func documentsDirectory() -> String {
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
return paths[0]
}
func dataFilePath() -> String {
return (documentsDirectory() as NSString).stringByAppendingPathComponent("Checklists.plist")
}
func saveChecklists() {
let data = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: data)
archiver.encodeObject(lists, forKey: "Checklists")
archiver.finishEncoding()
data.writeToFile(dataFilePath(), atomically: true)
}
func loadChecklists() {
let path = dataFilePath()
if NSFileManager.defaultManager().fileExistsAtPath(path) {
if let data = NSData(contentsOfFile: path) {
let unarchiver = NSKeyedUnarchiver(forReadingWithData: data)
lists = unarchiver.decodeObjectForKey("Checklists") as! [Checklist]
sortChecklists()
unarchiver.finishDecoding()
}
}
}
func registerDefaults() {
let dictionary = [ "ChecklistIndex": -1,"FirstTime": true,"ChecklistItemID" :0]
NSUserDefaults.standardUserDefaults().registerDefaults(dictionary)
}
func handleFirstTime() {
let userDefaults = NSUserDefaults.standardUserDefaults()
let firstTime = userDefaults.boolForKey("FirstTime")
if firstTime {
let checklist = Checklist(name: "List")
lists.append(checklist)
indexOfSelectedChecklist = 0
userDefaults.setBool(false, forKey: "FirstTime")
userDefaults.synchronize()
}
}
func sortChecklists() {
lists.sortInPlace({ checklist1, checklist2 in return
checklist1.name.localizedStandardCompare(checklist2.name) == .OrderedAscending })
}
class func nextChecklistItemID() -> Int {
let userDefaults = NSUserDefaults.standardUserDefaults()
let itemID = userDefaults.integerForKey("ChecklistItemID")
userDefaults.setInteger(itemID + 1, forKey: "ChecklistItemID")
userDefaults.synchronize()
return itemID
}
} | 02c0f990b1fcb08cb66c75db7ea2796c | 32.011111 | 104 | 0.614815 | false | false | false | false |
imzyf/99-projects-of-swift | refs/heads/master | 004-login-animation/004-login-animation/LoginViewController.swift | mit | 1 | import UIKit
class LoginViewController: UIViewController {
@IBOutlet weak var userNameField: UITextField!
@IBOutlet weak var passwordField: UITextField!
@IBOutlet weak var loginButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
self.view.alpha = 0
}
override func viewWillAppear(_ animated: Bool) {
// 淡入的效果
UIView.animate(withDuration: 0.5) {
self.view.alpha = 1
}
// user name 效果
userNameField.frame = CGRect(x: -270, y: 50, width: 270, height: 40)
userNameField.borderStyle = .roundedRect
userNameField.placeholder = "UserName"
UIView.animate(withDuration: 0.5, delay: 0.6, usingSpringWithDamping: 0.9, initialSpringVelocity: 2, options: .allowAnimatedContent, animations: {
self.userNameField.center.x = self.view.center.x
}, completion: nil)
// password
passwordField.frame = CGRect(x: -270, y: 100, width: 270, height: 40)
passwordField.borderStyle = .roundedRect
passwordField.placeholder = "Password"
UIView.animate(withDuration: 0.5, delay: 0.8, usingSpringWithDamping: 0.9, initialSpringVelocity: 2, options: .allowAnimatedContent, animations: {
self.passwordField.center.x = self.view.center.x
}, completion: nil)
// login
loginButton.frame = CGRect(x: -125, y: 160, width: 125, height: 40)
loginButton.setTitle("Login", for: .normal)
loginButton.setTitleColor(UIColor.white, for: .normal)
loginButton.backgroundColor = UIColor(red: 22/255.0, green: 139/255.0, blue: 3/255.0, alpha: 1)
UIView.animate(withDuration: 0.5, delay: 1, options: .curveEaseIn, animations: {
self.loginButton.center.x = self.view.center.x
}) { (isComplete) in
// usingSpringWithDamping: 0-1, the less the more exaggerate
// initialSpringVelocity: the bigger the faster init speed
UIView.animate(withDuration: 1, delay: 0.5, usingSpringWithDamping: 0.1, initialSpringVelocity: 2, options:.allowAnimatedContent, animations: {
self.loginButton.frame.size.width = 180
self.loginButton.center.x = self.view.center.x
}, completion: nil)
}
}
@IBAction func loginAction() {
self.dismiss(animated: true, completion: nil)
}
}
| f6099f3477dd231a344de5908cabdb52 | 39.290323 | 155 | 0.618895 | false | false | false | false |
rsyncOSX/RsyncOSX | refs/heads/master | RsyncOSX/Alerts.swift | mit | 1 | //
// alerts.swift
// Rsync
//
// Created by Thomas Evensen on 01/02/16.
// Copyright © 2016 Thomas Evensen. All rights reserved.
//
import Cocoa
public struct Alerts {
public static func showInfo(info: String) {
let alert = NSAlert()
alert.messageText = info
alert.alertStyle = NSAlert.Style.warning
let close: String = NSLocalizedString("Close", comment: "Close NSAlert")
alert.addButton(withTitle: close)
alert.runModal()
}
public static func dialogOrCancel(question: String, text: String, dialog: String) -> Bool {
let myPopup = NSAlert()
myPopup.messageText = question
myPopup.informativeText = text
myPopup.alertStyle = NSAlert.Style.warning
myPopup.addButton(withTitle: dialog)
let cancel: String = NSLocalizedString("Cancel", comment: "Cancel NSAlert")
myPopup.addButton(withTitle: cancel)
let res = myPopup.runModal()
if res == NSApplication.ModalResponse.alertFirstButtonReturn {
return true
}
return false
}
}
| 733b01a6e50a95e9073f49fddf89d0fc | 30.2 | 95 | 0.647436 | false | false | false | false |
csontosgabor/Twitter_Post | refs/heads/master | Twitter_Post/PhotoViewController.swift | mit | 1 | //
// PhotoViewController.swift
// Twitter_Post
//
// Created by Gabor Csontos on 12/23/16.
// Copyright © 2016 GaborMajorszki. All rights reserved.
//
import UIKit
import Photos
protocol PhotoViewControllerDelegate: class {
//header button delegates
func openCameraView()
func openPhotoView()
func openLocationView()
func handlePostButton()
func openPhotoOrVideoEditor(_ mediaType: CustomAVAsset.MediaType?, assetIdentifier: String?)
}
class PhotoViewController: UIViewController {
//delegates
weak var delegate: PhotoViewControllerDelegate?
weak var postViewController: PostViewController?
//avAsset
var avAssetIdentifiers = [String]()
//selectedMediaType -> Fetching Camera Roll,Favoutires, Selfies or Videos
var selectedMediaType: MediaTypes = MediaTypes.CameraRoll {
didSet {
//by selectedMediaType
switch selectedMediaType {
case .CameraRoll: grabPhotosAndVideos(.smartAlbumUserLibrary)
case .Favourites: grabPhotosAndVideos(.smartAlbumFavorites)
case .Selfies: grabPhotosAndVideos(.smartAlbumSelfPortraits)
case .Videos: grabPhotosAndVideos(.smartAlbumVideos)
}
}
}
//titleView
var titleView: UIView!
//fullView
var fullView: UIView!
//navbarMenu
var dropDownTitle: DropdownTitleView!
var navigationBarMenu: DropDownMenu!
//closeButton
var closeButton: UIButton!
//closedView
var closedView: UIView!
var locationButton: UIButton!
var photoButton: UIButton!
var cameraButton: UIButton!
var postButton: UIButton!
//separatorView
var titleViewSeparator: UIView!
//emptyDataSet Strings
var emptyPhotos: Bool = false
var emptyImgName: String = "ic_enable_photo"
var emptyTitle: String = "Please enable your photo access"
var emptyDescription: String = "In iPhone settings tap \(Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String)\n and turn on Photo access."
var emptyBtnTitle: String = "Open settings."
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//
// MARK: Views .collectionView //
// CollectionView is responsible to show the photos and videos in its cells.
// After fetching AVAssets from phones memory it create an AVASset which is used to help indentified the mediaType for editing and adding to the CreatePostViewController
//
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
lazy var collectionView: UICollectionView = {
let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
layout.minimumLineSpacing = 1
layout.minimumInteritemSpacing = 1
layout.sectionInset = UIEdgeInsetsMake(1, 0, 0, 0)
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(AVAssetCollectionViewCell.self, forCellWithReuseIdentifier: "cell")
collectionView.backgroundColor = UIColor.white
collectionView.showsVerticalScrollIndicator = true
//setup emptyDataSource
collectionView.emptyDataSetSource = self
collectionView.emptyDataSetDelegate = self
collectionView.isScrollEnabled = false
return collectionView
}()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
if let nc = self.navigationController as? FeedNavigationController {
nc.si_delegate = self
nc.fullScreenSwipeUp = true
//setup the NavigationBar headers
titleView = UIView(frame: CGRect(x: 0, y: 0, width: nc.navigationBar.frame.width, height: nc.navigationBar.frame.height))
titleView.backgroundColor = .white
setupHeaders()
nc.navigationBar.addSubview(titleView)
view.center = nc.navigationBar.center
}
setupCollectionView()
//fast check and grabPhotos from CameraRoll(default value)
PHPhotoLibrary.requestAuthorization() { status in
switch status {
case .authorized: self.grabPhotosAndVideos(.smartAlbumUserLibrary)
default:
//set the PhotoViewController's view on the bottom of the Screen if the PhotoAccess check failed
DispatchQueue.main.async {
if let parentVC = self.navigationController?.parent?.childViewControllers.first as? PostViewController {
parentVC.reactOnScroll()
self.collectionView.reloadEmptyDataSet()
}
}
}
}
//setupDropDownMenuTitle -> Last view, because of the collectionView
setupDropDownMenuTitle()
}
fileprivate func setupButtons(_ withImage: String, selector: Selector) -> UIButton {
let button = UIButton(type: .system)
let imageView = UIImageView()
imageView.image = UIImage(named: withImage)!.withRenderingMode(.alwaysTemplate)
imageView.tintColor = UIColor.lightGray
button.setImage(imageView.image, for: .normal)
button.tintColor = UIColor.lightGray
button.translatesAutoresizingMaskIntoConstraints = false
button.addTarget(self, action: selector, for: .touchUpInside)
return button
}
func setupHeaders() {
setupClosedHeader()
setupFullHeader()
}
func setupClosedHeader(){
locationButton = setupButtons("ic_location", selector: #selector(handleLocationBtn))
photoButton = setupButtons("ic_photos", selector: #selector(handlePhotoBtn))
cameraButton = setupButtons("ic_photo_camera", selector: #selector(handleCameraBtn))
postButton = UIButton(type: .system)
postButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
postButton.setTitle("POST", for: UIControlState())
postButton.setTitle("POST", for: .disabled)
postButton.setTitleColor(.white, for: UIControlState())
postButton.setTitleColor(UIColor.lightGray, for: .disabled)
postButton.isEnabled = false
postButton.layer.cornerRadius = 4
postButton.layer.borderWidth = 1
postButton.translatesAutoresizingMaskIntoConstraints = false
postButton.addTarget(self, action: #selector(handlePostBtn), for: .touchUpInside)
//closedView x,y,w,h
closedView = UIView()
closedView.translatesAutoresizingMaskIntoConstraints = false
if !closedView.isDescendant(of: titleView) { titleView.addSubview(closedView) }
closedView.leftAnchor.constraint(equalTo: titleView.leftAnchor).isActive = true
closedView.widthAnchor.constraint(equalTo: titleView.widthAnchor).isActive = true
closedView.heightAnchor.constraint(equalTo: titleView.heightAnchor).isActive = true
closedView.backgroundColor = .white
//location btn x,y,w,h
if !locationButton.isDescendant(of: closedView) { closedView.addSubview(locationButton) }
locationButton.leftAnchor.constraint(equalTo: closedView.leftAnchor,constant: 12).isActive = true
locationButton.centerYAnchor.constraint(equalTo: closedView.centerYAnchor).isActive = true
locationButton.widthAnchor.constraint(equalToConstant: 20).isActive = true
locationButton.heightAnchor.constraint(equalToConstant: 20).isActive = true
//photo btn x,y,w,h
if !photoButton.isDescendant(of: closedView) { closedView.addSubview(photoButton) }
photoButton.leftAnchor.constraint(equalTo: locationButton.rightAnchor,constant: 22).isActive = true
photoButton.centerYAnchor.constraint(equalTo: closedView.centerYAnchor).isActive = true
photoButton.widthAnchor.constraint(equalToConstant: 20).isActive = true
photoButton.heightAnchor.constraint(equalToConstant: 20).isActive = true
//camera btn x,y,w.h
if !cameraButton.isDescendant(of: closedView) { closedView.addSubview(cameraButton) }
cameraButton.leftAnchor.constraint(equalTo: photoButton.rightAnchor,constant: 22).isActive = true
cameraButton.centerYAnchor.constraint(equalTo: closedView.centerYAnchor).isActive = true
cameraButton.widthAnchor.constraint(equalToConstant: 20).isActive = true
cameraButton.heightAnchor.constraint(equalToConstant: 20).isActive = true
//post btn x,y,w,h
if !postButton.isDescendant(of: closedView) { closedView.addSubview(postButton) }
postButton.leftAnchor.constraint(equalTo: closedView.rightAnchor,constant: -72).isActive = true
postButton.centerYAnchor.constraint(equalTo: closedView.centerYAnchor).isActive = true
postButton.widthAnchor.constraint(equalToConstant: 60).isActive = true
postButton.heightAnchor.constraint(equalToConstant: 26).isActive = true
enableDisablePostButton(enable: false)
//titleViewSeparator x,y,w,h
titleViewSeparator = UIView()
titleViewSeparator.translatesAutoresizingMaskIntoConstraints = false
closedView.addSubview(titleViewSeparator)
titleViewSeparator.leftAnchor.constraint(equalTo: closedView.leftAnchor).isActive = true
titleViewSeparator.centerXAnchor.constraint(equalTo: closedView.centerXAnchor).isActive = true
titleViewSeparator.widthAnchor.constraint(equalTo: closedView.widthAnchor).isActive = true
titleViewSeparator.heightAnchor.constraint(equalToConstant: 0.5).isActive = true
titleViewSeparator.topAnchor.constraint(equalTo: closedView.topAnchor).isActive = true
titleViewSeparator.backgroundColor = UIColor(white: 0.7, alpha: 0.8)
}
func setupFullHeader(){
//fullView x,y,w,h
fullView = UIView()
fullView.translatesAutoresizingMaskIntoConstraints = false
if !fullView.isDescendant(of: titleView) { titleView.addSubview(fullView) }
fullView.leftAnchor.constraint(equalTo: titleView.leftAnchor).isActive = true
fullView.widthAnchor.constraint(equalTo: titleView.widthAnchor).isActive = true
fullView.heightAnchor.constraint(equalTo: titleView.heightAnchor).isActive = true
fullView.backgroundColor = .white
fullView.alpha = 0
//closeHeaderView Dismiss btn x,y,w,h
closeButton = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: titleView.frame.height))
closeButton.addTarget(self, action: #selector(closeView), for: .touchUpInside)
closeButton.setTitle("Close", for: .normal)
closeButton.setTitleColor(.black, for: .normal)
fullView.addSubview(closeButton)
//closeHeaderView Title x,y,w,h
//dropDownTitle x,y,w,h
dropDownTitle = DropdownTitleView()
dropDownTitle.titleLabel.textAlignment = .center
dropDownTitle.addTarget(self,action: #selector(self.willToggleNavigationBarMenu),for: .touchUpInside)
dropDownTitle.title = MediaTypes.CameraRoll.rawValue //default title
dropDownTitle.translatesAutoresizingMaskIntoConstraints = false
if !dropDownTitle.isDescendant(of: fullView) { fullView.addSubview(dropDownTitle) }
dropDownTitle.centerXAnchor.constraint(equalTo: fullView.centerXAnchor).isActive = true
dropDownTitle.centerYAnchor.constraint(equalTo: fullView.centerYAnchor).isActive = true
dropDownTitle.widthAnchor.constraint(equalToConstant: 120).isActive = true
dropDownTitle.heightAnchor.constraint(equalToConstant: 20).isActive = true
}
func setupDropDownMenuTitle(){
//DropDownMenuBar setup
prepareNavigationBarMenu(MediaTypes.CameraRoll.rawValue)
updateMenuContentOffsets()
navigationBarMenu.container = view
}
func setupCollectionView() {
//collectionView x,y,w,h
if !collectionView.isDescendant(of: self.view) { self.view.addSubview(collectionView) }
self.collectionView.translatesAutoresizingMaskIntoConstraints = false
self.self.collectionView.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true
self.collectionView.widthAnchor.constraint(equalTo: self.view.widthAnchor).isActive = true
self.collectionView.topAnchor.constraint(equalTo: self.view.topAnchor).isActive = true
self.collectionView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor).isActive = true
self.collectionView.isScrollEnabled = false
}
//fetch photos or videos by PHAssetCollectionSubtype , setted by DropDownTitleView
func grabPhotosAndVideos(_ subType: PHAssetCollectionSubtype){
self.avAssetIdentifiers.removeAll()
let fetchOptions = PHFetchOptions()
let fetchResult = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: subType, options: fetchOptions)
fetchResult.enumerateObjects({ (collection, start, stop) in
let fetchOptions = PHFetchOptions()
fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: false)]
let assets = PHAsset.fetchAssets(in: collection, options: fetchOptions)
assets.enumerateObjects({ (object, count, stop) in
self.avAssetIdentifiers.append(object.localIdentifier)
DispatchQueue.main.async {
//reload collectionView
self.collectionView.reloadData()
if self.avAssetIdentifiers.count == 0 {
//if avAsset count is nil -> There is no Photos to load
//change emptyView for making selfies
self.emptyPhotos = true
self.emptyImgName = "ic_selfie_dribbble"
self.emptyTitle = "You don't have any photos"
self.emptyDescription = "Let's give a try, and make some selfies about you."
self.emptyBtnTitle = "Open camera."
//Here you can make more specific messages based on PHAssetCollectionSubtype
switch subType {
case .smartAlbumVideos:
self.emptyImgName = "ic_selfie_dribbble"
self.emptyTitle = "You don't have any videos"
self.emptyDescription = "Capture some moments to share."
case .smartAlbumFavorites:
self.emptyImgName = "ic_selfie_dribbble"
self.emptyTitle = "No favoutires:("
self.emptyDescription = "In Photos you can easily make your fav album."
case .smartAlbumSelfPortraits:
break //etc
case .smartAlbumUserLibrary:
break //etc
default: break
}
self.collectionView.reloadEmptyDataSet()
//set the view on the bottom
}
}
})
if self.avAssetIdentifiers.count == 0 {
DispatchQueue.main.async {
if let parentVC = self.navigationController?.parent?.childViewControllers.first as? PostViewController {
parentVC.reactOnScroll()
}
}
}
})
}
//Color indicator if the location is setted or not
func locationIsSetted(bool: Bool) {
if bool {
self.locationButton.tintColor = self.view.tintColor
} else {
self.locationButton.tintColor = UIColor.lightGray
}
}
func closeView(){
//set the dropDownTitle to false to avoid UI crash
if self.dropDownTitle.isUp {
self.dropDownTitle.toggleMenu()
self.navigationBarMenu.hide(withAnimation: false)
}
//set scrollView to default
self.collectionView.isScrollEnabled = false
self.collectionView.setContentOffset(self.collectionView.contentOffset, animated: false)
DispatchQueue.main.async {
self.parent?.navigationController?.si_dismissModalView(toViewController: self.parent!, completion: {
if let nc = self.navigationController as? FeedNavigationController {
nc.si_delegate?.navigationControllerDidClosed?(navigationController: nc)
}
})
}
}
}
extension PhotoViewController: FeedNavigationControllerDelegate {
// MARK: - FeedNavigationControllerDelegate
func navigationControllerDidSpreadToEntire(navigationController: UINavigationController) {
print("spread to the entire")
//set scrollView's scrolling
self.collectionView.isScrollEnabled = true
UIView.animate(withDuration: 0.2,
delay: 0.0,
options: .curveEaseIn,
animations: {
self.fullView.alpha = 1
}, completion: nil)
}
func navigationControllerDidClosed(navigationController: UINavigationController) {
print("decreased on the view")
//set the dropDownTitle to false to avoid UI crash
if self.dropDownTitle.isUp {
self.dropDownTitle.toggleMenu()
self.navigationBarMenu.hide(withAnimation: false)
}
//set scrollView to default
self.collectionView.isScrollEnabled = false
self.collectionView.setContentOffset(self.collectionView.contentOffset, animated: false)
UIView.animate(withDuration: 0.2,
delay: 0.0,
options: .curveEaseIn,
animations: {
self.fullView.alpha = 0
}, completion: nil)
}
}
//MARK: - UIBUTTON FUNCTIONS
extension PhotoViewController {
func handleLocationBtn(_ sender: UIButton){
delegate?.openLocationView()
}
func handlePhotoBtn(_ sender: UIButton){
delegate?.openPhotoView()
}
func handleCameraBtn(_ sender: UIButton){
delegate?.openCameraView()
}
func handlePostBtn(_ sender: UIButton){
delegate?.handlePostButton()
}
//setting the PostButton color if post contains text or content
func enableDisablePostButton(enable: Bool){
if enable {
postButton.isEnabled = true
postButton.layer.borderColor = self.view.tintColor.cgColor
postButton.backgroundColor = self.view.tintColor
} else {
postButton.isEnabled = false
postButton.layer.borderColor = UIColor.lightGray.cgColor
postButton.backgroundColor = .clear
}
}
}
extension PhotoViewController: UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return avAssetIdentifiers.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! AVAssetCollectionViewCell
cell.assetID = self.avAssetIdentifiers[indexPath.row]
cell.tag = (indexPath as NSIndexPath).row
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let cell = collectionView.cellForItem(at: indexPath) as! AVAssetCollectionViewCell
// recognize the assetType and send the localidentifier to open the VideoTrimmer of PhotoEditor
delegate?.openPhotoOrVideoEditor(cell.asset?.type, assetIdentifier: cell.asset?.identifier)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let width = collectionView.frame.width / 3 - 1
return CGSize(width: width, height: width)
}
}
extension PhotoViewController: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate {
func emptyDataSetShouldDisplay(_ scrollView: UIScrollView) -> Bool {
return true
}
func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
return UIImage(named: emptyImgName)
}
func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
let attribs = [
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 18),
NSForegroundColorAttributeName: UIColor.darkGray
]
return NSAttributedString(string: emptyTitle, attributes: attribs)
}
func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
let para = NSMutableParagraphStyle()
para.lineBreakMode = NSLineBreakMode.byWordWrapping
para.alignment = NSTextAlignment.center
let attribs = [
NSFontAttributeName: UIFont.systemFont(ofSize: 14),
NSForegroundColorAttributeName: UIColor.lightGray,
NSParagraphStyleAttributeName: para
]
return NSAttributedString(string: emptyDescription, attributes: attribs)
}
func buttonTitle(forEmptyDataSet scrollView: UIScrollView!, for state: UIControlState) -> NSAttributedString! {
let attribs = [
NSFontAttributeName: UIFont.boldSystemFont(ofSize: 16),
NSForegroundColorAttributeName: view.tintColor
]
return NSAttributedString(string: emptyBtnTitle, attributes: attribs)
}
func emptyDataSetDidTapButton(_ scrollView: UIScrollView!) {
if !emptyPhotos {
getAccessForSettings()
} else {
//shot some new pics
openCameraView()
}
}
func openCameraView(){
self.delegate?.openCameraView()
}
func getAccessForSettings(){
//Open App's settings
openApplicationSettings()
}
}
| 49e8bc15bda4fe9a5b6b4f20a3973a41 | 36.794712 | 175 | 0.624434 | false | false | false | false |
techgrains/TGFramework-iOS | refs/heads/master | TGFrameworkExample/TGFrameworkExample/Classes/Model/Request - Response/EmployeeCreateRequest.swift | apache-2.0 | 1 | import Foundation
import TGFramework
class EmployeeCreateRequest: TGRequest {
var serviceMethodName: String = ""
var name: String = ""
var designation = ""
var uniqueDeviceID: String = ""
override init() {
super.init()
// Initialization code here.
serverURL = LIVE_SERVICE_TG_RESTFUL
serviceMethodName = EMPLOYEE_CREATE
}
func url() -> String {
// Append Service Method Name
let urlString = serverURL + "/\(serviceMethodName)"
return urlString
}
}
| aa1c1f2c9900f690a34e6fe342ba4407 | 21.64 | 59 | 0.59364 | false | false | false | false |
bbktsk/LimeIzard-ios | refs/heads/master | LimeIzard/Services.swift | mit | 1 | //
// Services.swift
// LimeIzard
//
// Created by Martin Vytrhlík on 22/04/16.
// Copyright © 2016 LimeIzards. All rights reserved.
//
import Foundation
import KontaktSDK
import Alamofire
import SwiftyJSON
import FBSDKLoginKit
import SVProgressHUD
struct User {
var fbID: String
var fbName: String
var firstName: String?
var lastName: String?
var imgUrl: String?
var mood: String = ""
var message: String = ""
var signal: Float = 0
}
var BeaconManager: KTKBeaconManager!
let API = WebAPI._instance
var FBToken: FBSDKAccessToken?
var CurrentUser: User?
var UsersNearby = [User]()
let UsersNearbyChanged = "UsersNearbyChanged"
let MyRegion = KTKBeaconRegion(proximityUUID: NSUUID(UUIDString: "11f10af9-8ec0-4e88-bc27-3fb17effe8bf")!, identifier: "region1")
func startRangingBeacons() {
MyRegion.notifyEntryStateOnDisplay = true
// Start Ranging
BeaconManager.startMonitoringForRegion(MyRegion)
BeaconManager.requestStateForRegion(MyRegion)
}
func cropImageToSquare(image : UIImage?) -> UIImage? {
if (image != nil) {
let contextSize: CGSize = image!.size
if (contextSize.height == contextSize.width) {
return image
}
var posX: CGFloat = 0.0
var posY: CGFloat = 0.0
var cgwidth: CGFloat = CGFloat(contextSize.width)
var cgheight: CGFloat = CGFloat(contextSize.height)
// See what size is longer and create the center off of that
if contextSize.width > contextSize.height {
posX = ((contextSize.width - contextSize.height) / 2)
posY = 0
cgwidth = contextSize.height
cgheight = contextSize.height
} else {
posX = 0
posY = ((contextSize.height - contextSize.width) / 2)
cgwidth = contextSize.width
cgheight = contextSize.width
}
let rect: CGRect = CGRectMake(posX, posY, cgwidth, cgheight)
// Create bitmap image from context using the rect
let imageRef: CGImageRef = CGImageCreateWithImageInRect(image!.CGImage, rect)!
// Create a new image based on the imageRef and rotate back to the original orientation
let img: UIImage = UIImage(CGImage: imageRef, scale: image!.scale, orientation: image!.imageOrientation)
return img
}
return nil
}
func maskImageToCircle(image: UIImage) -> UIImage {
let img = cropImageToSquare(image)
let imageView: UIImageView = UIImageView(image: img)
var layer: CALayer = CALayer()
layer = imageView.layer
layer.masksToBounds = true
layer.cornerRadius = CGFloat(img!.size.height/2)
UIGraphicsBeginImageContext(imageView.bounds.size)
layer.renderInContext(UIGraphicsGetCurrentContext()!)
let roundedImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return roundedImage
}
func getFacebookProfileUrl(fbID: String) -> NSURL?{
return NSURL(string: "https://graph.facebook.com/\(fbID)/picture?type=large")
}
func getFBImage(fbID: String) -> UIImage?{
if let url = getFacebookProfileUrl(fbID) {
if let data = NSData(contentsOfURL: url) {
if let img = UIImage(data: data) {
return maskImageToCircle(img)
}
}
}
return nil
}
func sendPokeNotif(poker: String) {
dispatch_async(dispatch_get_main_queue(), {
let notif = UILocalNotification()
notif.category = "poke"
notif.alertTitle = ""
notif.fireDate = nil
notif.alertBody = "You where poked by \(poker)"
notif.soundName = UILocalNotificationDefaultSoundName
let app = UIApplication.sharedApplication()
if app.applicationState == UIApplicationState.Active {
app.delegate?.application?(app, handleActionWithIdentifier: nil, forLocalNotification: notif, completionHandler: {})
}
else {
UIApplication.sharedApplication().scheduleLocalNotification(notif)
}
})
}
class WebAPI {
static let _instance = WebAPI()
init() {
}
enum Router : URLRequestConvertible {
static let baseURL = "https://lime-izard.herokuapp.com/api/"
case UserInfo(userID: String)
case UserUpdate(userID: String)
case UserVisitBeacon(userID: String, beaconData: [String: AnyObject])
case UserCreate(user: [String: AnyObject])
case PokeUser(myID: String, hisID: String)
case GetPokes(myID: String)
var method : Alamofire.Method {
switch self {
case .UserInfo:
return .GET
case .UserUpdate:
return .PUT
case .UserCreate :
return .POST
case .UserVisitBeacon:
return .POST
case .PokeUser:
return .POST
case .GetPokes:
return .GET
}
}
var path : String {
switch self {
case .UserInfo(let userID):
return "users/\(userID)"
case .UserUpdate(let userID):
return "users/\(userID)"
case .UserCreate:
return "users"
case .UserVisitBeacon(let userID, _):
return "users/\(userID)/visit"
case .PokeUser(let myID, _):
return "users/\(myID)/poke"
case .GetPokes(let myID):
return "users/\(myID)/poke"
}
}
var URLRequest : NSMutableURLRequest {
let URL = NSURL(string: Router.baseURL)!
let mutableURLRequest = NSMutableURLRequest(URL: URL.URLByAppendingPathComponent(path))
mutableURLRequest.HTTPMethod = method.rawValue
mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
mutableURLRequest.setValue("no-cache", forHTTPHeaderField: "Cache-Control")
switch self {
case .UserCreate(let user):
return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: user).0
case .UserVisitBeacon(_, let beaconData):
return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: beaconData).0
case .PokeUser(_, let hisID):
return Alamofire.ParameterEncoding.JSON.encode(mutableURLRequest, parameters: ["target": hisID]).0
default:
return mutableURLRequest
}
}
}
func getUserInfo(userID: String, onComplete: ([String: AnyObject]?, NSError?) -> Void) {
Alamofire.request(Router.UserInfo(userID: userID))
.responseJSON { response in
print("---------------------------")
print(response.request) // original URL request
print(response.result) // result of response serialization
if let json = response.result.value as? [String: AnyObject] {
print(NSString(data: response.data!, encoding:NSUTF8StringEncoding)!)
onComplete(json, nil)
}
else {
print("no user data found")
onComplete(nil,nil)
}
}
}
func createUser(user: [String: AnyObject], onComplete: (JSON?, NSError?) -> Void) {
Alamofire.request(Router.UserCreate(user: user))
.responseJSON { response in
print("---------------------------")
print(response.request) // original URL request
print(NSString(data: response.request!.HTTPBody!, encoding:NSUTF8StringEncoding)!)
print(response.result) // result of response serialization
let json = response.result.value as? JSON
print(json)
onComplete(json, nil)
}
}
func updateUser(user: [String: AnyObject]) {
}
func sendUserVisitBeacon(userID: String, beaconData: [String: AnyObject]) {
Alamofire.request(Router.UserVisitBeacon(userID: userID, beaconData: beaconData))
.responseJSON { response in
print("---------------------------")
print(response.request) // original URL request
print(NSString(data: response.request!.HTTPBody!, encoding:NSUTF8StringEncoding)!)
UsersNearby.removeAll()
if let data = response.result.value as? [String: AnyObject] {
if let people = data["people"] as? [AnyObject] {
for p in people {
let fbID = p["fb_id"] as? String ?? ""
let name = p["first_name"] as? String ?? "---"
let signal = p["signal"] as? Float ?? 0
let mood = p["mood"] as? String ?? ""
let message = p["message"] as? String ?? ""
let imgUrl = p["photo_url"] as? String ?? ""
let usr = User(fbID: fbID, fbName: "", firstName: name, lastName: "", imgUrl: imgUrl, mood: mood, message: message, signal: signal)
UsersNearby.append(usr)
print("adding user \(name)")
}
}
}
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName(UsersNearbyChanged, object: nil)
}
}
func pokeUser(targetID: String) {
if let usr = CurrentUser {
SVProgressHUD.show()
Alamofire.request(Router.PokeUser(myID: usr.fbID, hisID: targetID))
.responseJSON { response in
SVProgressHUD.showSuccessWithStatus("")
}
}
else {
SVProgressHUD.showErrorWithStatus("There was problem sending the Poke")
}
}
func getPokes() {
if let usr = CurrentUser {
Alamofire.request(Router.GetPokes(myID: usr.fbID))
.responseJSON { response in
if let json = response.result.value as? [AnyObject] {
for poke in json {
if let poke = poke as? [String: AnyObject] {
// print(NSString(data: response.data!, encoding:NSUTF8StringEncoding)!)
// sendPokeNotif(poke["first_name"] as? String ?? "--" )
let nc = NSNotificationCenter.defaultCenter()
nc.postNotificationName("PokeReceived", object: nil, userInfo:["name": poke["first_name"] as? String ?? "--"])
}
}
}
}
}
}
} | 23653b91fdf581a456c459e5b97b63dd | 34.181538 | 159 | 0.539578 | false | false | false | false |
eridbardhaj/Weather | refs/heads/master | Weather WatchKit Extension/Classes/Controllers/Main/InterfaceController.swift | mit | 1 | //
// InterfaceController.swift
// Weather WatchKit Extension
//
// Created by Erid Bardhaj on 5/4/15.
// Copyright (c) 2015 STRV. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController
{
//Outlets
@IBOutlet weak var m_currenLocation: WKInterfaceLabel!
@IBOutlet weak var m_weatherIcon: WKInterfaceImage!
@IBOutlet weak var m_weatherCondition: WKInterfaceLabel!
@IBOutlet weak var m_weatherTemp: WKInterfaceLabel!
//Holder
var wModel: Weather?
override func awakeWithContext(context: AnyObject?) {
super.awakeWithContext(context)
// Configure interface objects here.
//Set the controller title
self.setTitle("Today")
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
//Load network request to download data
if wModel == nil
{
self.loadData()
}
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
//MARK: - Setups
func loadData()
{
//Make the call to API
WeatherNetwork.getCurrentWeatherByCoordinates(DataManager.shared.m_city_lat, lng: DataManager.shared.m_city_lng, responseHandler:
{
(error, object) -> (Void) in
//No Error just show content
if error == ErrorType.None
{
dispatch_async(dispatch_get_main_queue(),
{
() -> Void in
self.wModel = object
self.bindDataToViews(self.wModel!)
})
}
else
{
//Handle Error
println("Error")
}
})
}
func bindDataToViews(model: Weather)
{
let vModel = TodayViewModel(model: model)
self.m_currenLocation.setText(vModel.m_currentLocation)
self.m_weatherCondition.setText(vModel.m_weatherCondition)
self.m_weatherIcon.setImage(UIImage(named: vModel.m_weatherImageName))
self.m_weatherTemp.setText(vModel.m_temp)
}
//MARK: - Force Touch Actions
@IBAction func forceTouchRefreshContent()
{
//Reload data
loadData()
}
}
| 50dfacd930c0a3ad04179a92eee4d34a | 26.602151 | 137 | 0.562914 | false | false | false | false |
powerytg/Accented | refs/heads/master | Accented/UI/Home/HomeStreamViewController.swift | mit | 1 | //
// HomeStreamViewController.swift
// Accented
//
// Created by Tiangong You on 5/2/16.
// Copyright © 2016 Tiangong You. All rights reserved.
//
import UIKit
class HomeStreamViewController: StreamViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Events
NotificationCenter.default.addObserver(self, selector: #selector(appThemeDidChange(_:)), name: ThemeManagerEvents.appThemeDidChange, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func createViewModel() {
let viewModelClass = ThemeManager.sharedInstance.currentTheme.streamViewModelClass
viewModel = viewModelClass.init(stream: stream, collectionView: collectionView, flowLayoutDelegate: self)
}
// MARK: - UICollectionViewDelegateFlowLayout
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
if section == 0 {
// Section 0 is reserved for stream headers
return CGSize.zero
} else {
return CGSize(width: collectionView.bounds.width, height: 8)
}
}
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForFooterInSection section: Int) -> CGSize {
if section == 0 {
return CGSize.zero
}
return CGSize(width: collectionView.bounds.width, height: 26)
}
// MARK: - Events
func appThemeDidChange(_ notification : Notification) {
let viewModelClass = ThemeManager.sharedInstance.currentTheme.streamViewModelClass
viewModel = viewModelClass.init(stream: stream, collectionView: collectionView, flowLayoutDelegate: self)
viewModel?.delegate = self
collectionView.dataSource = viewModel
viewModel!.updateCollectionView(true)
}
}
| 0fb8c4c012f3f5de904e0b8f9a575ebe | 34.754098 | 179 | 0.690967 | false | false | false | false |
almazrafi/Metatron | refs/heads/master | Tests/MetatronTests/Tools/ExtensionsTest.swift | mit | 1 | //
// ExtensionsTest.swift
// Metatron
//
// Copyright (c) 2016 Almaz Ibragimov
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import XCTest
@testable import Metatron
class ExtensionsTest: XCTestCase {
// MARK: Instance Methods
func testStringPrefix() {
do {
let value = ""
XCTAssert(value.prefix(0) == "")
}
do {
let value = ""
XCTAssert(value.prefix(123) == "")
}
do {
let value = "Abc 123"
XCTAssert(value.prefix(0) == "")
}
do {
let value = "Abc 123"
XCTAssert(value.prefix(3) == "Abc")
}
do {
let value = "Abc 123"
XCTAssert(value.prefix(123) == "Abc 123")
}
}
func testStringListRevised() {
do {
let value: [String] = []
XCTAssert(value.revised == [])
}
do {
let value = [""]
XCTAssert(value.revised == [])
}
do {
let value = ["Abc 123"]
XCTAssert(value.revised == value)
}
do {
let value = ["Абв 123"]
XCTAssert(value.revised == value)
}
do {
let value = ["Abc 1", "Abc 2"]
XCTAssert(value.revised == value)
}
do {
let value = ["", "Abc 2"]
XCTAssert(value.revised == ["Abc 2"])
}
do {
let value = ["Abc 1", ""]
XCTAssert(value.revised == ["Abc 1"])
}
do {
let value = ["", ""]
XCTAssert(value.revised == [])
}
do {
let value = [Array<String>(repeating: "Abc", count: 123).joined(separator: "\n")]
XCTAssert(value.revised == value)
}
do {
let value = Array<String>(repeating: "Abc", count: 123)
XCTAssert(value.revised == value)
}
}
// MARK:
func testArrayLastIndex() {
do {
let value: [UInt8] = []
XCTAssert(value.lastIndex(of: 0) == nil)
XCTAssert(value.lastIndex(of: 123) == nil)
}
do {
let value: [UInt8] = [123]
XCTAssert(value.lastIndex(of: 0) == nil)
XCTAssert(value.lastIndex(of: 123) == 0)
}
do {
let value: [UInt8] = [1, 2, 3]
XCTAssert(value.lastIndex(of: 0) == nil)
XCTAssert(value.lastIndex(of: 2) == 1)
}
do {
let value: [UInt8] = [0, 0, 0]
XCTAssert(value.lastIndex(of: 0) == 2)
XCTAssert(value.lastIndex(of: 2) == nil)
}
}
func testArrayFirstOccurrence() {
do {
let value: [UInt8] = []
XCTAssert(value.firstOccurrence(of: []) == nil)
XCTAssert(value.firstOccurrence(of: [123]) == nil)
XCTAssert(value.firstOccurrence(of: [1, 2, 3]) == nil)
XCTAssert(value.firstOccurrence(of: [0, 0, 0]) == nil)
}
do {
let value: [UInt8] = [123]
XCTAssert(value.firstOccurrence(of: []) == nil)
XCTAssert(value.firstOccurrence(of: [123]) == 0)
XCTAssert(value.firstOccurrence(of: [1, 2, 3]) == nil)
XCTAssert(value.firstOccurrence(of: [0, 0, 0]) == nil)
}
do {
let value: [UInt8] = [1, 2, 3]
XCTAssert(value.firstOccurrence(of: []) == nil)
XCTAssert(value.firstOccurrence(of: [123]) == nil)
XCTAssert(value.firstOccurrence(of: [1, 2, 3]) == 0)
XCTAssert(value.firstOccurrence(of: [0, 0, 0]) == nil)
}
do {
let value: [UInt8] = [0, 0, 0]
XCTAssert(value.firstOccurrence(of: []) == nil)
XCTAssert(value.firstOccurrence(of: [123]) == nil)
XCTAssert(value.firstOccurrence(of: [1, 2, 3]) == nil)
XCTAssert(value.firstOccurrence(of: [0, 0, 0]) == 0)
}
do {
let value: [UInt8] = [123, 1, 2, 3, 0, 0, 0, 123, 1, 2, 3, 0, 0, 0]
XCTAssert(value.firstOccurrence(of: []) == nil)
XCTAssert(value.firstOccurrence(of: [123]) == 0)
XCTAssert(value.firstOccurrence(of: [1, 2, 3]) == 1)
XCTAssert(value.firstOccurrence(of: [0, 0, 0]) == 4)
}
}
func testArrayLastOccurrence() {
do {
let value: [UInt8] = []
XCTAssert(value.lastOccurrence(of: []) == nil)
XCTAssert(value.lastOccurrence(of: [123]) == nil)
XCTAssert(value.lastOccurrence(of: [1, 2, 3]) == nil)
XCTAssert(value.lastOccurrence(of: [0, 0, 0]) == nil)
}
do {
let value: [UInt8] = [123]
XCTAssert(value.lastOccurrence(of: []) == nil)
XCTAssert(value.lastOccurrence(of: [123]) == 0)
XCTAssert(value.lastOccurrence(of: [1, 2, 3]) == nil)
XCTAssert(value.lastOccurrence(of: [0, 0, 0]) == nil)
}
do {
let value: [UInt8] = [1, 2, 3]
XCTAssert(value.lastOccurrence(of: []) == nil)
XCTAssert(value.lastOccurrence(of: [123]) == nil)
XCTAssert(value.lastOccurrence(of: [1, 2, 3]) == 0)
XCTAssert(value.lastOccurrence(of: [0, 0, 0]) == nil)
}
do {
let value: [UInt8] = [0, 0, 0]
XCTAssert(value.lastOccurrence(of: []) == nil)
XCTAssert(value.lastOccurrence(of: [123]) == nil)
XCTAssert(value.lastOccurrence(of: [1, 2, 3]) == nil)
XCTAssert(value.lastOccurrence(of: [0, 0, 0]) == 0)
}
do {
let value: [UInt8] = [123, 1, 2, 3, 0, 0, 0, 123, 1, 2, 3, 0, 0, 0]
XCTAssert(value.lastOccurrence(of: []) == nil)
XCTAssert(value.lastOccurrence(of: [123]) == 7)
XCTAssert(value.lastOccurrence(of: [1, 2, 3]) == 8)
XCTAssert(value.lastOccurrence(of: [0, 0, 0]) == 11)
}
}
}
| d77e916a06034b7b20bbed5a4620d26e | 27.166008 | 93 | 0.510806 | false | false | false | false |
lkzhao/Hero | refs/heads/master | Sources/Parser/HeroStringConvertible.swift | mit | 1 | // The MIT License (MIT)
//
// Copyright (c) 2016 Luke Zhao <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public protocol HeroStringConvertible {
static func from(node: ExprNode) -> Self?
}
extension String {
func parse<T: HeroStringConvertible>() -> [T]? {
let lexer = Lexer(input: self)
let parser = Parser(tokens: lexer.tokenize())
do {
let nodes = try parser.parse()
var results = [T]()
for node in nodes {
if let modifier = T.from(node: node) {
results.append(modifier)
} else {
print("\(node.name) doesn't exist in \(T.self)")
}
}
return results
} catch let error {
print("failed to parse \"\(self)\", error: \(error)")
}
return nil
}
func parseOne<T: HeroStringConvertible>() -> T? {
return parse()?.last
}
}
| 5d12f9311e243bf217dcd665dd253c36 | 34.867925 | 80 | 0.687533 | false | false | false | false |
ArthurKK/Bond | refs/heads/master | Bond/Core/OptionalType.swift | apache-2.0 | 22 | //
// The MIT License (MIT)
//
// Copyright (c) 2015 Srdan Rasic (@srdanrasic)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
public protocol OptionalType {
typealias WrappedType
var isNil: Bool { get }
var value: WrappedType? { get }
init(optional: WrappedType?)
}
extension Optional: OptionalType {
public var isNil: Bool {
return self == nil
}
public var value: Wrapped? {
return self
}
public init(optional: Wrapped?) {
if let some = optional {
self = .Some(some)
} else {
self = .None
}
}
}
| 787f1706807604459496e48b0edbe430 | 31.795918 | 81 | 0.708774 | false | false | false | false |
joelklabo/bitcoin | refs/heads/master | bitcoin/ChartViewController.swift | mit | 1 | //
// ChartViewController.swift
// bitcoin
//
// Created by Joel Klabo on 12/3/16.
// Copyright © 2016 Joel Klabo. All rights reserved.
//
import UIKit
class ChartViewController: UIViewController {
let priceSource = BlockchainClient()
private var lastPrice: Double?
@IBOutlet weak var chartView: ChartView!
@IBOutlet weak var currentPrice: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var segmentedControl: UISegmentedControl!
override func viewDidLoad() {
super.viewDidLoad()
let becameActiveNotification = NSNotification.Name.UIApplicationDidBecomeActive
NotificationCenter.default.addObserver(self, selector: #selector(updatePrice), name: becameActiveNotification, object: nil)
activityIndicator.hidesWhenStopped = true
updateChart(.oneMonth)
// segmentedControl.selectedSegmentIndex = ChartRange.oneMonth.rawValue
}
@IBAction func chartRangeUpdate(_ sender: Any) {
// if let control = sender as? UISegmentedControl {
// updateChart(chartRange)
// }
}
private func updateChart(_ range: ChartRange) {
activityIndicator.startAnimating()
BlockchainChartClient().chartFor(range) { chart in
self.activityIndicator.stopAnimating()
self.chartView.chart = chart
}
}
@objc dynamic private func updatePrice() {
lastPrice = priceSource.lastPrice()
if let storedPrice = lastPrice {
self.currentPrice.text = formatPrice(storedPrice)
}
activityIndicator.startAnimating()
priceSource.currentPrice { price in
self.activityIndicator.stopAnimating()
self.priceSource.storePrice(price.last)
self.currentPrice.text = self.formatPrice(price.last)
}
}
private func formatPrice(_ price: Double) -> String {
return String(format: "%.02f", price)
}
}
| 7f3f842f2d03bff63a534ea745879aa4 | 30.793651 | 131 | 0.6665 | false | false | false | false |
cuappdev/tempo | refs/heads/master | Tempo/Controllers/FeedViewController.swift | mit | 1 | //
// FeedVC.swift
// Tempo
//
// Created by Joseph Antonakakis on 3/15/15.
// Copyright (c) 2015 Joseph Antonakakis. All rights reserved.
//
import UIKit
import MediaPlayer
class FeedViewController: PlayerTableViewController, SongSearchDelegate, FeedFollowSuggestionsControllerDelegate {
static let readPostsKey = "FeedViewController.readPostsKey"
lazy var customRefresh: ADRefreshControl = {
self.refreshControl = UIRefreshControl()
let customRefresh = ADRefreshControl(refreshControl: self.refreshControl!)
self.refreshControl?.addTarget(self, action: #selector(refreshFeed), for: .valueChanged)
return customRefresh
}()
lazy var searchTableViewController: SearchViewController = {
let vc = SearchViewController()
vc.delegate = self
return vc
}()
var refreshNeeded = false //set to true on logout
var activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .white)
var feedFollowSuggestionsController: FeedFollowSuggestionsController?
// MARK: - Lifecycle Methods
override func viewDidLoad() {
super.viewDidLoad()
title = "Feed"
view.backgroundColor = .readCellColor
tableView.register(UINib(nibName: "FeedTableViewCell", bundle: nil), forCellReuseIdentifier: "FeedCell")
playingPostType = .feed
//disable user interaction when first loading up feed
//user interaction gets enabled after refresh is done
//not very elegant solution, but fixes some UI issues
view.isUserInteractionEnabled = false
tableView.tableHeaderView = nil
tableView.rowHeight = 209
tableView.showsVerticalScrollIndicator = false
refreshControl = customRefresh.refreshControl
tableView.insertSubview(refreshControl, belowSubview: tableView.getScrollView()!)
tableView.alpha = 0.0
// Add follow suggestions controller to tableView
// Only shows if no posts in past 24 hours
feedFollowSuggestionsController = FeedFollowSuggestionsController(frame: view.frame)
feedFollowSuggestionsController?.delegate = self
refreshFeedWithDelay(0, timeout: 5.0)
activityIndicatorView.center = view.center
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
feedFollowSuggestionsController?.reload()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if refreshNeeded { //when user re-logged in
refreshNeeded = false
refreshFeed()
}
let _ = notConnected(true)
}
func refreshFeedWithDelay(_ delay: Double, timeout: Double) {
//finished refreshing gets set to true when the api returns
var finishedRefreshing = false
//minimum time passed gets set to true when minimum delay dispatch gets called
var minimumTimePassed = false
if tableView.alpha == 0.0 {
activityIndicatorView.startAnimating()
view.addSubview(activityIndicatorView)
}
feedFollowSuggestionsController?.reload()
API.sharedAPI.fetchFeedOfEveryone { [weak self] (posts: [Post]) in
DispatchQueue.main.async {
self?.posts = posts
//return even if we get data after a timeout
if finishedRefreshing {
self?.tableView.alpha = 1.0
self?.tableView.reloadData()
return
} else if minimumTimePassed {
self?.refreshControl?.endRefreshing()
self?.view.isUserInteractionEnabled = true
self?.tableView.reloadData()
}
finishedRefreshing = true
if let x = self {
if x.posts.count == 0 {
x.feedFollowSuggestionsController?.showNoMorePostsLabel()
x.tableView.tableFooterView = x.feedFollowSuggestionsController?.view
} else if x.posts.count < 3 {
x.feedFollowSuggestionsController?.hideNoMorePostsLabel()
x.tableView.tableFooterView = x.feedFollowSuggestionsController?.view
} else {
x.tableView.backgroundView = nil
x.tableView.tableFooterView = nil
}
x.preparePosts()
x.continueAnimatingAfterRefresh()
}
self?.tableView.alpha = 1.0
}
self?.activityIndicatorView.stopAnimating()
self?.activityIndicatorView.removeFromSuperview()
}
//fetch for a minimum of delay seconds
//if after delay seconds we finished fetching,
//then we reload the tableview, else we wait for the
//api to return to reload by setting minumum time passed
var popTime = DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: popTime) {
if finishedRefreshing {
Banner.hide()
self.tableView.reloadData()
self.refreshControl?.endRefreshing()
self.view.isUserInteractionEnabled = true
} else {
minimumTimePassed = true
}
}
//timeout for refresh taking too long
popTime = DispatchTime.now() + Double(Int64(timeout * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: popTime) {
if !finishedRefreshing {
self.refreshControl?.endRefreshing()
self.view.isUserInteractionEnabled = true
finishedRefreshing = true
}
}
}
func continueAnimatingAfterRefresh() {
//animate currently playing song
if let currentPost = self.playerCenter.getCurrentPost(), currentPost.postType == .feed {
for row in 0 ..< posts.count {
if posts[row].equals(other: currentPost) {
posts[row] = currentPost
let indexPath = IndexPath(row: row, section: 0)
if let cell = tableView.cellForRow(at: indexPath) as? FeedTableViewCell {
cell.feedPostView.post = currentPost
cell.feedPostView.updatePlayingStatus()
}
break
}
}
}
}
func refreshFeed() {
refreshFeedWithDelay(3.0, timeout: 10.0)
}
// MARK: - UITableViewDataSource
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "FeedCell", for: indexPath) as! FeedTableViewCell
let post = posts[indexPath.row]
cell.feedPostView.avatarImageView?.image = nil
cell.feedPostView.type = .feed
cell.feedPostView.post = posts[indexPath.row]
cell.feedPostView.postViewDelegate = self
cell.feedPostView.playerDelegate = self
if let listenedToPosts = UserDefaults.standard.dictionary(forKey: FeedViewController.readPostsKey) as? [String:Double], listenedToPosts[post.postID] != nil {
cell.feedPostView.post?.player.wasPlayed = true
}
cell.setUpFeedCell(firstName: post.user.firstName, lastName: post.user.lastName)
transplantPlayerAndPostViewIfNeeded(cell: cell)
return cell
}
// MARK: - UITableViewDelegate
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let post = posts[indexPath.row]
if var listenedToPosts = UserDefaults.standard.dictionary(forKey: FeedViewController.readPostsKey) as? [String:Double] {
// clear posts older than 24 hrs
for postID in listenedToPosts.keys {
if let timestamp = listenedToPosts[postID], Date().timeIntervalSince1970 - timestamp > 86400000 {
listenedToPosts[postID] = nil
}
}
listenedToPosts[post.postID] = Date().timeIntervalSince1970
UserDefaults.standard.set(listenedToPosts, forKey: FeedViewController.readPostsKey)
} else {
UserDefaults.standard.set([post.postID: Date().timeIntervalSince1970], forKey: FeedViewController.readPostsKey)
}
currentlyPlayingIndexPath = indexPath
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
customRefresh.scrollViewDidScroll(scrollView)
}
func dismissButtonTapped() {
searchTableViewController.dismiss()
}
// MARK: - SongSearchDelegate
func didSelectSong(_ song: Song) {
posts.insert(Post(song: song, user: User.currentUser, date: Date()), at: 0)
API.sharedAPI.updatePost(User.currentUser.id, song: song) { [weak self] _ in
self?.refreshFeed()
}
}
// MARK: - Navigation
func didTapImageForPostView(_ post: Post) {
let profileVC = ProfileViewController()
profileVC.title = "Profile"
profileVC.user = post.user
navigationController?.pushViewController(profileVC, animated: true)
}
func didToggleLike() {
//if there is a currentlyPlayingIndexPath, need to sync liked status of playerCells and post
if let currentlyPlayingIndexPath = currentlyPlayingIndexPath {
if let cell = tableView.cellForRow(at: currentlyPlayingIndexPath) as? FeedTableViewCell {
cell.feedPostView.updateLikedStatus()
playerCenter.updateLikeButton()
}
}
}
func didToggleAdd() {
if let currentlyPlayingIndexPath = currentlyPlayingIndexPath {
if let cell = tableView.cellForRow(at: currentlyPlayingIndexPath) as? FeedTableViewCell {
cell.feedPostView.updateAddStatus()
}
}
}
// MARK: - FeedFollowSuggestionsDelegate
func feedFollowSuggestionsController(controller: FeedFollowSuggestionsController, wantsToShowProfileForUser user: User) {
let profileVC = ProfileViewController()
profileVC.title = "Profile"
profileVC.user = user
navigationController?.pushViewController(profileVC, animated: true)
}
func feedFollowSuggestionsControllerWantsToShowMoreSuggestions() {
navigateToSuggestions()
}
func feedFollowSuggestionsUserFollowed() {
refreshFeed()
}
}
extension UITableView {
func getScrollView() -> UIScrollView? {
for subview in subviews {
if subview is UIScrollView {
return subview as? UIScrollView
}
}
return nil
}
}
| 255f630571579ea358049b2ac8a133a6 | 30.607509 | 159 | 0.741173 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/SILGen/reabstract_lvalue.swift | apache-2.0 | 3 | // RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -emit-silgen %s | %FileCheck %s
struct MyMetatypeIsThin {}
// CHECK-LABEL: sil hidden @_T017reabstract_lvalue19consumeGenericInOut{{[_0-9a-zA-Z]*}}F : $@convention(thin) <T> (@inout T) -> ()
func consumeGenericInOut<T>(_ x: inout T) {}
// CHECK-LABEL: sil hidden @_T017reabstract_lvalue9transformSdSiF : $@convention(thin) (Int) -> Double
func transform(_ i: Int) -> Double {
return Double(i)
}
// CHECK-LABEL: sil hidden @_T017reabstract_lvalue0A13FunctionInOutyyF : $@convention(thin) () -> ()
func reabstractFunctionInOut() {
// CHECK: [[BOX:%.*]] = alloc_box ${ var @callee_owned (Int) -> Double }
// CHECK: [[PB:%.*]] = project_box [[BOX]]
// CHECK: [[ARG:%.*]] = function_ref @_T017reabstract_lvalue9transformSdSiF
// CHECK: [[THICK_ARG:%.*]] = thin_to_thick_function [[ARG]]
// CHECK: store [[THICK_ARG:%.*]] to [init] [[PB]]
// CHECK: [[FUNC:%.*]] = function_ref @_T017reabstract_lvalue19consumeGenericInOut{{[_0-9a-zA-Z]*}}F
// CHECK: [[ABSTRACTED_BOX:%.*]] = alloc_stack $@callee_owned (@in Int) -> @out Double
// CHECK: [[THICK_ARG:%.*]] = load [copy] [[PB]]
// CHECK: [[THUNK1:%.*]] = function_ref @_T0SiSdIxyd_SiSdIxir_TR
// CHECK: [[ABSTRACTED_ARG:%.*]] = partial_apply [[THUNK1]]([[THICK_ARG]])
// CHECK: store [[ABSTRACTED_ARG]] to [init] [[ABSTRACTED_BOX]]
// CHECK: apply [[FUNC]]<(Int) -> Double>([[ABSTRACTED_BOX]])
// CHECK: [[NEW_ABSTRACTED_ARG:%.*]] = load [take] [[ABSTRACTED_BOX]]
// CHECK: [[THUNK2:%.*]] = function_ref @_T0SiSdIxir_SiSdIxyd_TR
// CHECK: [[NEW_ARG:%.*]] = partial_apply [[THUNK2]]([[NEW_ABSTRACTED_ARG]])
var minimallyAbstracted = transform
consumeGenericInOut(&minimallyAbstracted)
}
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0SiSdIxyd_SiSdIxir_TR : $@convention(thin) (@in Int, @owned @callee_owned (Int) -> Double) -> @out Double
// CHECK-LABEL: sil shared [transparent] [reabstraction_thunk] @_T0SiSdIxir_SiSdIxyd_TR : $@convention(thin) (Int, @owned @callee_owned (@in Int) -> @out Double) -> Double
// CHECK-LABEL: sil hidden @_T017reabstract_lvalue0A13MetatypeInOutyyF : $@convention(thin) () -> ()
func reabstractMetatypeInOut() {
var thinMetatype = MyMetatypeIsThin.self
// CHECK: [[FUNC:%.*]] = function_ref @_T017reabstract_lvalue19consumeGenericInOut{{[_0-9a-zA-Z]*}}F
// CHECK: [[BOX:%.*]] = alloc_stack $@thick MyMetatypeIsThin.Type
// CHECK: [[THICK:%.*]] = metatype $@thick MyMetatypeIsThin.Type
// CHECK: store [[THICK]] to [trivial] [[BOX]]
// CHECK: apply [[FUNC]]<MyMetatypeIsThin.Type>([[BOX]])
consumeGenericInOut(&thinMetatype)
}
| 41e03238b4138bf3abfb77ff9a3c7345 | 56.347826 | 171 | 0.654663 | false | false | false | false |
alecananian/osx-coin-ticker | refs/heads/develop | CoinTicker/Source/Exchanges/UPbitExchange.swift | mit | 1 | //
// UPbitExchange.swift
// CoinTicker
//
// Created by Alec Ananian on 6/25/17.
// Copyright © 2017 Alec Ananian.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
import SwiftyJSON
class UPbitExchange: Exchange {
private struct Constants {
static let ProductListAPIPath = "https://api.upbit.com/v1/market/all"
static let TickerAPIPathFormat = "https://api.upbit.com/v1/ticker?markets=%@"
}
init(delegate: ExchangeDelegate? = nil) {
super.init(site: .upbit, delegate: delegate)
}
override func load() {
super.load(from: Constants.ProductListAPIPath) {
$0.json.arrayValue.compactMap { data in
let productId = data["market"].stringValue
let customCodeParts = productId.split(separator: "-")
guard let quoteCurrency = customCodeParts.first, let baseCurrency = customCodeParts.last else {
return nil
}
return CurrencyPair(
baseCurrency: String(baseCurrency),
quoteCurrency: String(quoteCurrency),
customCode: productId
)
}
}
}
override internal func fetch() {
let productIds: [String] = selectedCurrencyPairs.map({ $0.customCode })
let apiPath = String(format: Constants.TickerAPIPathFormat, productIds.joined(separator: ","))
requestAPI(apiPath).map { [weak self] result in
result.json.arrayValue.forEach({ data in
if let currencyPair = self?.selectedCurrencyPair(withCustomCode: data["market"].stringValue) {
self?.setPrice(data["trade_price"].doubleValue, for: currencyPair)
}
})
self?.onFetchComplete()
}.catch { error in
print("Error fetching UPbit ticker: \(error)")
}
}
}
| bcac00b626d4872303ac1f8ee21ef750 | 38.506667 | 111 | 0.650354 | false | false | false | false |
danwaltin/SwiftSpec | refs/heads/master | Tests/SwiftSpecTests/TestExecutionTests/ExecuteStepBindingFunctionTests.swift | apache-2.0 | 1 | // ------------------------------------------------------------------------
// Copyright 2017 Dan Waltin
//
// 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.
// ------------------------------------------------------------------------
//
// ExecuteStepBindingFunctionTests.swift
// SwiftSpec
//
// Created by Dan Waltin on 2016-07-23.
//
// ------------------------------------------------------------------------
import XCTest
@testable import SwiftSpec
@testable import GherkinSwift
class ExecuteStepBindingFunctionTests : XCTestCase {
func test_functionIsExecuted() {
var hasBeenExecuted = false
let s = step {_ in
hasBeenExecuted = true
}
try! s.execute(BindingsParameters())
XCTAssertTrue(hasBeenExecuted)
}
func test_bindingsParametersAreSet() {
var parameters: BindingsParameters?
let s = step {
parameters = $0
}
try! s.execute(BindingsParameters(tableParameter: TableParameter(columns: ["c"])))
XCTAssertEqual(parameters, BindingsParameters(tableParameter: TableParameter(columns: ["c"])))
}
// MARK: - Factory methods
private func step(_ function: @escaping (BindingsParameters) -> ()) -> StepBindingImplementation {
return StepBindingImplementation(stepText: "text", function: function)
}
}
| c933243a485c375cd683f6fbe7bf4fbb | 31.444444 | 99 | 0.644406 | false | true | false | false |
Masteryyz/CSYMicroBlockSina | refs/heads/master | CSYMicroBlockSina/CSYMicroBlockSina/Classes/Module/Home/HomeTableViewCell/CSYHomeTableViewCell.swift | mit | 1 | //
// CSYHomeTableViewCell.swift
// CSYMicroBlockSina
//
// Created by 姚彦兆 on 15/11/14.
// Copyright © 2015年 姚彦兆. All rights reserved.
//
import UIKit
import SnapKit
import FFLabel
let cellMargin : CGFloat = 12
let iconWidth : CGFloat = 35
class CSYHomeTableViewCell: UITableViewCell {
private var bottomConstraint : Constraint?
var blogModel : CSYMyMicroBlogModel? {
didSet{
originView.messageModel = blogModel
self.bottomConstraint?.uninstall()
if let rModel = blogModel?.retweetedMessageModel{
retweetedView.retweetedModel = rModel
retweetedView.hidden = false
bottomView.snp_updateConstraints(closure: { (make) -> Void in
self.bottomConstraint = make.top.equalTo(retweetedView.snp_bottom).offset(1).constraint
})
}else{
retweetedView.hidden = true
bottomView.snp_updateConstraints(closure: { (make) -> Void in
self.bottomConstraint = make.top.equalTo(originView.snp_bottom).offset(1).constraint
})
}
}
}
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .None
setUpUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//设置UI
private func setUpUI(){
let separateView : UIView = getSeparateView()
contentView.addSubview(separateView)
separateView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(contentView.snp_left)
make.right.equalTo(contentView.snp_right)
make.height.equalTo(10)
make.top.equalTo(contentView.snp_top).offset(1)
}
let headView : UIView = getHeaderView()
contentView.addSubview(headView)
headView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(separateView.snp_bottom).offset(1)
make.centerX.equalTo(contentView.snp_centerX)
make.width.equalTo(snp_width).offset(-10.0)
make.height.equalTo(lineWidth)
}
contentView.addSubview(originView)
originView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(headView.snp_bottom).offset(0)
make.left.equalTo(contentView.snp_left).offset(0)
make.right.equalTo(contentView.snp_right).offset(0)
}
contentView.addSubview(retweetedView)
retweetedView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(originView.snp_bottom)
make.left.equalTo(contentView.snp_left)
make.right.equalTo(contentView.snp_right)
}
contentView.addSubview(bottomView)
bottomView.snp_makeConstraints { (make) -> Void in
self.bottomConstraint = make.top.equalTo(retweetedView.snp_bottom).constraint
make.left.equalTo(contentView.snp_left)
make.right.equalTo(contentView.snp_right)
make.height.equalTo(30)
}
contentView.snp_makeConstraints { (make) -> Void in
make.bottom.equalTo(bottomView.snp_bottom).offset(0)
make.top.equalTo(self.snp_top)
make.left.equalTo(self.snp_left)
make.right.equalTo(self.snp_right)
}
}
//懒加载公共子控件
lazy var originView : CSYOriginBlogView = CSYOriginBlogView()
lazy var bottomView : CSYBottomView = CSYBottomView()
lazy var retweetedView : CSYRetweetedView = CSYRetweetedView()
private func getSeparateView () -> UIView {
let view = UIView()
view.backgroundColor = UIColor(white: 0.97, alpha: 1)
return view
}
private func getHeaderView () -> UIView {
let view = UIView()
view.backgroundColor = UIColor(white: 0.8, alpha: 1)
return view
}
}
| 894ea02616fc78a98427bd9ca191c567 | 24.87766 | 107 | 0.512641 | false | false | false | false |
Tsukishita/CaveCommentViewer | refs/heads/master | CaveCommentViewer/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// RSSTable
//
// Created by 月下 on 2015/06/10.
// Copyright (c) 2015年 月下. All rights reserved.
//
/*
・プリセット名デフォルト表示
・上書き更新
・
*/
import UIKit
import SwiftyJSON
import KeychainAccess
@UIApplicationMain
/*
UserDefaults,KeyChainの保存内容について
first_launch: 初回起動時判定
auth_user: ユーザー名
auth_pass: パスワード
auth_api: APIキー
access_key:コメントサーバーへのアクセスキー
device_Key: デバイスキー(固定)
HTTPCookieKey: 認証の通ったクッキー
comment-date:コメント日付の表示形式
*/
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var api = CaveAPI()
let ud = NSUserDefaults.standardUserDefaults()
var HomeStream:Bool = false
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
UIApplication.sharedApplication().setMinimumBackgroundFetchInterval(UIApplicationBackgroundFetchIntervalMinimum)
//初回起動時に各種初期化する
if ud.objectForKey("first_launch") == nil {
ud.setObject(false, forKey: "first_launch")
api.initData()
print("初期化を行います")
}
CaveAPI().getAccessKey()
//認証クッキーの期限確認
if api.cookieKey != nil{
let coockies = api.cookieKey!
let date = NSDate()
if date.compare(coockies.first!.expiresDate!) == NSComparisonResult.OrderedDescending{
api.Login(user: api.auth_user, pass: api.auth_pass, regist:{res in})
}
}
return true
}
func application(application: UIApplication, performFetchWithCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
}
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) {
//print("applicationWillEnterForeground")
}
func applicationDidBecomeActive(application: UIApplication) {
//print("applicationDidBecomeActive")
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
}
//let statusBarHeight: CGFloat = UIApplication.sharedApplication().statusBarFrame.height
| 3980f75feeec7473ee3dde3812781f72 | 33.451613 | 285 | 0.682135 | false | false | false | false |
abertelrud/swift-package-manager | refs/heads/main | Sources/Commands/PackageTools/ToolsVersionCommand.swift | apache-2.0 | 2 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2014-2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import ArgumentParser
import CoreCommands
import PackageLoading
import PackageModel
import Workspace
// This is named as `ToolsVersionCommand` instead of `ToolsVersion` to avoid naming conflicts, as the latter already
// exists to denote the version itself.
struct ToolsVersionCommand: SwiftCommand {
static let configuration = CommandConfiguration(
commandName: "tools-version",
abstract: "Manipulate tools version of the current package")
@OptionGroup(_hiddenFromHelp: true)
var globalOptions: GlobalOptions
@Flag(help: "Set tools version of package to the current tools version in use")
var setCurrent: Bool = false
@Option(help: "Set tools version of package to the given value")
var set: String?
enum ToolsVersionMode {
case display
case set(String)
case setCurrent
}
var toolsVersionMode: ToolsVersionMode {
// TODO: enforce exclusivity
if let set = set {
return .set(set)
} else if setCurrent {
return .setCurrent
} else {
return .display
}
}
func run(_ swiftTool: SwiftTool) throws {
let pkg = try swiftTool.getPackageRoot()
switch toolsVersionMode {
case .display:
let manifestPath = try ManifestLoader.findManifest(packagePath: pkg, fileSystem: swiftTool.fileSystem, currentToolsVersion: .current)
let version = try ToolsVersionParser.parse(manifestPath: manifestPath, fileSystem: swiftTool.fileSystem)
print("\(version)")
case .set(let value):
guard let toolsVersion = ToolsVersion(string: value) else {
// FIXME: Probably lift this error definition to ToolsVersion.
throw ToolsVersionParser.Error.malformedToolsVersionSpecification(.versionSpecifier(.isMisspelt(value)))
}
try ToolsVersionSpecificationWriter.rewriteSpecification(
manifestDirectory: pkg,
toolsVersion: toolsVersion,
fileSystem: swiftTool.fileSystem
)
case .setCurrent:
// Write the tools version with current version but with patch set to zero.
// We do this to avoid adding unnecessary constraints to patch versions, if
// the package really needs it, they can do it using --set option.
try ToolsVersionSpecificationWriter.rewriteSpecification(
manifestDirectory: pkg,
toolsVersion: ToolsVersion.current.zeroedPatch,
fileSystem: swiftTool.fileSystem
)
}
}
}
| 77881e39c12ac58b54b7b88cb4cc51c7 | 36.927711 | 145 | 0.629924 | false | false | false | false |
ashfurrow/cornell-rx-materials | refs/heads/master | Carthage/Checkouts/Moya/Source/Plugins/NetworkLoggerPlugin.swift | apache-2.0 | 10 | import Foundation
/// Logs network activity (outgoing requests and incoming responses).
public class NetworkLoggerPlugin<Target: MoyaTarget>: Plugin<Target> {
private let loggerId = "Moya_Logger"
private let dateFormatString = "dd/MM/yyyy HH:mm:ss"
private let dateFormatter = NSDateFormatter()
/// If true, also logs response body data.
public let verbose: Bool
public init(verbose: Bool = false) {
self.verbose = verbose
}
public override func willSendRequest(request: MoyaRequest, provider: MoyaProvider<Target>, target: Target) {
logNetworkRequest(request.request)
}
public override func didReceiveResponse(data: NSData?, statusCode: Int?, response: NSURLResponse?, error: ErrorType?, provider: MoyaProvider<Target>, target: Target) {
logNetworkResponse(response, data: data, target: target)
}
}
private extension NetworkLoggerPlugin {
private var date: String {
dateFormatter.dateFormat = dateFormatString
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
return dateFormatter.stringFromDate(NSDate())
}
func logNetworkRequest(request: NSURLRequest?) {
var output = ""
output += String(format: "%@: [%@] Request: %@", loggerId, date, request?.description ?? "(invalid request)")
if let headers = request?.allHTTPHeaderFields {
output += String(format: "%@ [%@] Request Headers: %@", loggerId, date, headers)
}
if let bodyStream = request?.HTTPBodyStream {
output += String(format: "%@: [%@] Request Body Stream: %@", loggerId, date, bodyStream.description)
}
if let httpMethod = request?.HTTPMethod {
output += String(format: "%@: [%@] HTTP Request Method: %@", loggerId, date, httpMethod)
}
if let body = request?.HTTPBody where verbose == true {
if let stringOutput = NSString(data: body, encoding: NSUTF8StringEncoding) {
output += String(format: "%@: [%@] Request Body: %@", loggerId, date, stringOutput)
}
}
print(output)
}
func logNetworkResponse(response: NSURLResponse?, data: NSData?, target: Target) {
guard let response = response else {
print("Received empty network response for \(target).")
return
}
var output = ""
output += String(format: "%@: [%@] Response: %@", loggerId, date, response.description)
if let data = data,
let stringData = NSString(data: data, encoding: NSUTF8StringEncoding) as? String
where verbose == true {
output += stringData
}
print(output)
}
}
| eeed2b0a8938f541836c1aab1d8a2c99 | 33.518987 | 171 | 0.625229 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.