repo_name
stringlengths 6
91
| path
stringlengths 8
968
| copies
stringclasses 210
values | size
stringlengths 2
7
| content
stringlengths 61
1.01M
| license
stringclasses 15
values | hash
stringlengths 32
32
| line_mean
float64 6
99.8
| line_max
int64 12
1k
| alpha_frac
float64 0.3
0.91
| ratio
float64 2
9.89
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
avito-tech/Paparazzo
|
Paparazzo/Core/VIPER/PhotoLibrary/View/PhotoLibraryViewController.swift
|
1
|
4766
|
import UIKit
final class PhotoLibraryViewController: PaparazzoViewController, PhotoLibraryViewInput, ThemeConfigurable {
typealias ThemeType = PhotoLibraryUITheme
private let photoLibraryView = PhotoLibraryView()
// MARK: - UIViewController
override func loadView() {
view = photoLibraryView
}
override func viewDidLoad() {
super.viewDidLoad()
onViewDidLoad?()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.setNavigationBarHidden(true, animated: animated)
if !UIDevice.current.hasTopSafeAreaInset {
UIApplication.shared.setStatusBarHidden(true, with: animated ? .fade : .none)
}
}
override var prefersStatusBarHidden: Bool {
return !UIDevice.current.hasTopSafeAreaInset
}
// MARK: - ThemeConfigurable
func setTheme(_ theme: ThemeType) {
self.theme = theme
photoLibraryView.setTheme(theme)
}
// MARK: - PhotoLibraryViewInput
var onItemSelect: ((PhotoLibraryItem) -> ())?
var onViewDidLoad: (() -> ())?
var onTitleTap: (() -> ())? {
get { return photoLibraryView.onTitleTap }
set { photoLibraryView.onTitleTap = newValue }
}
var onPickButtonTap: (() -> ())? {
get { return photoLibraryView.onConfirmButtonTap }
set { photoLibraryView.onConfirmButtonTap = newValue }
}
var onCancelButtonTap: (() -> ())? {
get { return photoLibraryView.onDiscardButtonTap }
set { photoLibraryView.onDiscardButtonTap = newValue }
}
var onAccessDeniedButtonTap: (() -> ())? {
get { return photoLibraryView.onAccessDeniedButtonTap }
set { photoLibraryView.onAccessDeniedButtonTap = newValue }
}
var onDimViewTap: (() -> ())? {
get { return photoLibraryView.onDimViewTap }
set { photoLibraryView.onDimViewTap = newValue }
}
@nonobjc func setTitle(_ title: String) {
photoLibraryView.setTitle(title)
}
func setTitleVisible(_ visible: Bool) {
photoLibraryView.setTitleVisible(visible)
}
func setPlaceholderState(_ state: PhotoLibraryPlaceholderState) {
switch state {
case .hidden:
photoLibraryView.setPlaceholderVisible(false)
case .visible(let title):
photoLibraryView.setPlaceholderTitle(title)
photoLibraryView.setPlaceholderVisible(true)
}
}
func setItems(_ items: [PhotoLibraryItemCellData], scrollToBottom: Bool, completion: (() -> ())?) {
photoLibraryView.setItems(items, scrollToBottom: scrollToBottom, completion: completion)
}
func applyChanges(_ changes: PhotoLibraryViewChanges, completion: (() -> ())?) {
photoLibraryView.applyChanges(changes, completion: completion)
}
func setCanSelectMoreItems(_ canSelectMoreItems: Bool) {
photoLibraryView.canSelectMoreItems = canSelectMoreItems
}
func setDimsUnselectedItems(_ dimUnselectedItems: Bool) {
photoLibraryView.dimsUnselectedItems = dimUnselectedItems
}
func deselectAllItems() {
photoLibraryView.deselectAndAdjustAllCells()
}
func scrollToBottom() {
photoLibraryView.scrollToBottom()
}
func setAccessDeniedViewVisible(_ visible: Bool) {
photoLibraryView.setAccessDeniedViewVisible(visible)
}
func setAccessDeniedTitle(_ title: String) {
photoLibraryView.setAccessDeniedTitle(title)
}
func setAccessDeniedMessage(_ message: String) {
photoLibraryView.setAccessDeniedMessage(message)
}
func setAccessDeniedButtonTitle(_ title: String) {
photoLibraryView.setAccessDeniedButtonTitle(title)
}
func setProgressVisible(_ visible: Bool) {
photoLibraryView.setProgressVisible(visible)
}
func setAlbums(_ albums: [PhotoLibraryAlbumCellData]) {
photoLibraryView.setAlbums(albums)
}
func selectAlbum(withId id: String) {
photoLibraryView.selectAlbum(withId: id)
}
func showAlbumsList() {
photoLibraryView.showAlbumsList()
}
func hideAlbumsList() {
photoLibraryView.hideAlbumsList()
}
func toggleAlbumsList() {
photoLibraryView.toggleAlbumsList()
}
// MARK: - Private
private var theme: PhotoLibraryUITheme?
@objc private func onCancelButtonTap(_ sender: UIBarButtonItem) {
onCancelButtonTap?()
}
@objc private func onPickButtonTap(_ sender: UIBarButtonItem) {
onPickButtonTap?()
}
}
|
mit
|
b1e348539ef5db184d23110ba6f4366c
| 28.060976 | 107 | 0.643726 | 5.535424 | false | false | false | false |
micchyboy1023/Today
|
Today iOS App/TodayKit iOS/Setting.swift
|
1
|
2523
|
//
// Setting.swift
// Today
//
// Created by UetaMasamichi on 2016/01/10.
// Copyright © 2016年 Masamichi Ueta. All rights reserved.
//
import Foundation
public final class Setting {
private static let defaults = UserDefaults.standard
public static var shared = Setting()
//MARK: - Keys
public struct SettingKey {
public static let notificationEnabled = "NotificationEnabled"
public static let notificationHour = "NotificationHour"
public static let notificationMinute = "NotificationMinute"
public static let version = "CFBundleShortVersionString"
}
//MARK: - Values
public var notificationEnabled: Bool {
didSet {
Setting.defaults.set(notificationEnabled, forKey: SettingKey.notificationEnabled)
}
}
public var notificationHour: Int {
didSet {
Setting.defaults.set(notificationHour, forKey: SettingKey.notificationHour)
}
}
public var notificationMinute: Int {
didSet {
Setting.defaults.set(notificationMinute, forKey: SettingKey.notificationMinute)
}
}
public var version: String
public var notificationTime: Date {
var comps = DateComponents()
comps.hour = notificationHour
comps.minute = notificationMinute
let calendar = Calendar.current
return calendar.date(from: comps)!
}
//MARK: -
private init() {
Setting.setupDefaultSetting()
notificationEnabled = Setting.defaults.bool(forKey: SettingKey.notificationEnabled)
notificationHour = Setting.defaults.integer(forKey: SettingKey.notificationHour)
notificationMinute = Setting.defaults.integer(forKey: SettingKey.notificationMinute)
guard let settingVersion = Bundle.main.object(forInfoDictionaryKey: SettingKey.version) as? String else {
fatalError("Invalid setting")
}
version = settingVersion
}
private class func setupDefaultSetting() {
let settingBundle = Bundle(for: Today.self)
guard let fileURL = settingBundle.url(forResource: "Setting", withExtension: "plist") else {
fatalError("Wrong file name")
}
guard let defaultSettingDic = NSDictionary(contentsOf: fileURL) as? [String : AnyObject] else {
fatalError("File not exists")
}
Setting.defaults.register(defaults: defaultSettingDic)
}
}
|
mit
|
0f1624abeeb38741e4dfb0f0b63e57dc
| 30.5 | 113 | 0.65 | 5.060241 | false | false | false | false |
NyaaFinder/nyaacat-ios
|
BabyBluetoothExamples/BluetoothStubOnOSX/BluetoothStubOnOSX/ViewController.swift
|
1
|
6200
|
//
// ViewController.swift
// BluetoothStubOnOSX
//
// Created by ZTELiuyw on 15/9/30.
// Copyright © 2015年 liuyanwei. All rights reserved.
//
import Cocoa
import CoreBluetooth
class ViewController: NSViewController,CBPeripheralManagerDelegate{
//MARK:- static parameter
let localNameKey = "BabyBluetoothStubOnOSX";
let ServiceUUID = "FFF0";
let notiyCharacteristicUUID = "FFF1";
let readCharacteristicUUID = "FFF2";
let readwriteCharacteristicUUID = "FFE3";
var peripheralManager:CBPeripheralManager!
var timer:NSTimer!
override func viewDidLoad() {
super.viewDidLoad()
peripheralManager = CBPeripheralManager(delegate: self, queue: nil)
}
//publish service and characteristic
func publishService(){
let notiyCharacteristic = CBMutableCharacteristic(type: CBUUID(string: notiyCharacteristicUUID), properties: [CBCharacteristicProperties.Notify], value: nil, permissions: CBAttributePermissions.Readable)
let readCharacteristic = CBMutableCharacteristic(type: CBUUID(string: readCharacteristicUUID), properties: [CBCharacteristicProperties.Read], value: nil, permissions: CBAttributePermissions.Readable)
let writeCharacteristic = CBMutableCharacteristic(type: CBUUID(string: readwriteCharacteristicUUID), properties: [CBCharacteristicProperties.Write,CBCharacteristicProperties.Read], value: nil, permissions: [CBAttributePermissions.Readable,CBAttributePermissions.Writeable])
//设置description
let descriptionStringType = CBUUID(string: CBUUIDCharacteristicUserDescriptionString)
let description1 = CBMutableDescriptor(type: descriptionStringType, value: "canNotifyCharacteristic")
let description2 = CBMutableDescriptor(type: descriptionStringType, value: "canReadCharacteristic")
let description3 = CBMutableDescriptor(type: descriptionStringType, value: "canWriteAndWirteCharacteristic")
notiyCharacteristic.descriptors = [description1];
readCharacteristic.descriptors = [description2];
writeCharacteristic.descriptors = [description3];
//设置service
let service:CBMutableService = CBMutableService(type: CBUUID(string: ServiceUUID), primary: true)
service.characteristics = [notiyCharacteristic,readCharacteristic,writeCharacteristic]
peripheralManager.addService(service);
}
//发送数据,发送当前时间的秒数
func sendData(t:NSTimer)->Bool{
let characteristic = t.userInfo as! CBMutableCharacteristic;
let dft = NSDateFormatter();
dft.dateFormat = "ss";
NSLog("%@",dft.stringFromDate(NSDate()))
//执行回应Central通知数据
return peripheralManager.updateValue(dft.stringFromDate(NSDate()).dataUsingEncoding(NSUTF8StringEncoding)!, forCharacteristic: characteristic, onSubscribedCentrals: nil)
}
//MARK:- CBPeripheralManagerDelegate
func peripheralManagerDidUpdateState(peripheral: CBPeripheralManager) {
switch peripheral.state{
case CBPeripheralManagerState.PoweredOn:
NSLog("power on")
publishService();
case CBPeripheralManagerState.PoweredOff:
NSLog("power off")
default:break;
}
}
func peripheralManager(peripheral: CBPeripheralManager, didAddService service: CBService, error: NSError?) {
peripheralManager.startAdvertising(
[
CBAdvertisementDataServiceUUIDsKey : [CBUUID(string: ServiceUUID)]
,CBAdvertisementDataLocalNameKey : localNameKey
]
)
}
func peripheralManagerDidStartAdvertising(peripheral: CBPeripheralManager, error: NSError?) {
NSLog("in peripheralManagerDidStartAdvertisiong");
}
//订阅characteristics
func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didSubscribeToCharacteristic characteristic: CBCharacteristic) {
NSLog("订阅了 %@的数据",characteristic.UUID)
//每秒执行一次给主设备发送一个当前时间的秒数
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector:"sendData:" , userInfo: characteristic, repeats: true)
}
//取消订阅characteristics
func peripheralManager(peripheral: CBPeripheralManager, central: CBCentral, didUnsubscribeFromCharacteristic characteristic: CBCharacteristic) {
NSLog("取消订阅 %@的数据",characteristic.UUID)
//取消回应
timer.invalidate()
}
//读characteristics请求
func peripheralManager(peripheral: CBPeripheralManager, didReceiveReadRequest request: CBATTRequest) {
NSLog("didReceiveReadRequest")
//判断是否有读数据的权限
if(request.characteristic.properties.contains(CBCharacteristicProperties.Read))
{
request.value = request.characteristic.value;
peripheral .respondToRequest(request, withResult: CBATTError.Success);
}
else{
peripheral .respondToRequest(request, withResult: CBATTError.ReadNotPermitted);
}
}
func peripheralManager(peripheral: CBPeripheralManager, didReceiveWriteRequests requests: [CBATTRequest]) {
NSLog("didReceiveWriteRequests")
let request:CBATTRequest = requests[0];
//判断是否有写数据的权限
if (request.characteristic.properties.contains(CBCharacteristicProperties.Write)) {
//需要转换成CBMutableCharacteristic对象才能进行写值
let c:CBMutableCharacteristic = request.characteristic as! CBMutableCharacteristic
c.value = request.value;
peripheral .respondToRequest(request, withResult: CBATTError.Success);
}else{
peripheral .respondToRequest(request, withResult: CBATTError.ReadNotPermitted);
}
}
func peripheralManagerIsReadyToUpdateSubscribers(peripheral: CBPeripheralManager) {
NSLog("peripheralManagerIsReadyToUpdateSubscribers")
}
}
|
mit
|
45a25c56ab8f2903cd86b15a32d1b46d
| 39.412162 | 282 | 0.706571 | 5.563721 | false | false | false | false |
evering7/iSpeak8
|
Data_BasicTypes.swift
|
1
|
2365
|
//
// Data_BasicTypes.swift
// iSpeak8
//
// Created by JianFei Li on 15/08/2017.
// Copyright © 2017 JianFei Li. All rights reserved.
//
import Foundation
import CoreData
//import CoreStore
class String_TS: NSObject {
private var strValue_Unsafe: String = ""
private var accessQueue: DispatchQueue?
init(queueLabel: String, initialValue: String) {
let labelStr = UUID().uuidString + "com.blogspot.cnshoe.string.threadsafe.\(queueLabel)"
super.init()
// set access queue
self.accessQueue = DispatchQueue(
label: labelStr,
qos: DispatchQoS.default,
attributes: .concurrent,
autoreleaseFrequency: .inherit , target: nil)
// set value
self.setStrValue(value: initialValue)
}
public func getStrValue() -> String { // read-only, atomic
guard let q = self.accessQueue else {
sayFatal("can't unwrap accessQueue")
fatalError()
}
var value = ""
q.sync {
value = self.strValue_Unsafe
}
return value
}
public func setStrValue(value: String) { // atom, write,
guard let q = self.accessQueue else {
sayFatal("can't unwrap accessQueue")
fatalError()
}
q.async(flags:.barrier) {
self.strValue_Unsafe = value
}
} // public func setValue(value: String) 2017 July 15th
} // class String_TS: NSObject 2017.8.15
class Date_TS : NSObject {
private var dateValue_Unsafe : Date
private var accessQueue: DispatchQueue?
init(queueLabel: String, initialValue: Date) {
let labelStr = UUID().uuidString + "com.blogspot.cnshoe.iSpeak8.date.threadsafe" +
queueLabel
self.accessQueue = DispatchQueue(label: labelStr,
qos: .default,
attributes: .concurrent,
autoreleaseFrequency: .inherit,
target: nil)
self.dateValue_Unsafe = initialValue
super.init()
} // override init(queueLabel: String, initialValue: Date) 2017.9.19
} // class Date_TS : NSObject 2017.9.19
|
mit
|
99f7c1e97b8a17d4fa3d55fef8d7edab
| 28.55 | 96 | 0.549069 | 4.804878 | false | false | false | false |
KrishMunot/swift
|
test/SILGen/optional.swift
|
2
|
3519
|
// RUN: %target-swift-frontend -emit-silgen %s | FileCheck %s
func testCall(_ f: (() -> ())?) {
f?()
}
// CHECK: sil hidden @{{.*}}testCall{{.*}}
// CHECK: bb0([[T0:%.*]] : $Optional<() -> ()>):
// CHECK: [[T1:%.*]] = select_enum %0
// CHECK-NEXT: cond_br [[T1]], bb1, bb3
// If it does, project and load the value out of the implicitly unwrapped
// optional...
// CHECK: bb1:
// CHECK-NEXT: [[FN0:%.*]] = unchecked_enum_data %0 : $Optional<() -> ()>, #Optional.some!enumelt.1
// ...unnecessarily reabstract back to () -> ()...
// CHECK: [[T0:%.*]] = function_ref @_TTRXFo_iT__iT__XFo___ : $@convention(thin) (@owned @callee_owned (@in ()) -> @out ()) -> ()
// CHECK-NEXT: [[FN1:%.*]] = partial_apply [[T0]]([[FN0]])
// .... then call it
// CHECK-NEXT: apply [[FN1]]()
// CHECK: br bb2(
// (first nothing block)
// CHECK: bb3:
// CHECK-NEXT: enum $Optional<()>, #Optional.none!enumelt
// CHECK-NEXT: br bb2
func testAddrOnlyCallResult<T>(_ f: (()->T)?) {
var f = f
var x = f?()
}
// CHECK-LABEL: sil hidden @{{.*}}testAddrOnlyCallResult{{.*}} : $@convention(thin) <T> (@owned Optional<() -> T>) -> ()
// CHECK: bb0([[T0:%.*]] : $Optional<() -> T>):
// CHECK: [[F:%.*]] = alloc_box $Optional<() -> T>, var, name "f"
// CHECK-NEXT: [[PBF:%.*]] = project_box [[F]]
// CHECK: store [[T0]] to [[PBF]]
// CHECK-NEXT: [[X:%.*]] = alloc_box $Optional<T>, var, name "x"
// CHECK-NEXT: [[PBX:%.*]] = project_box [[X]]
// CHECK-NEXT: [[TEMP:%.*]] = init_enum_data_addr [[PBX]]
// Check whether 'f' holds a value.
// CHECK: [[T1:%.*]] = select_enum_addr [[PBF]]
// CHECK-NEXT: cond_br [[T1]], bb1, bb3
// If so, pull out the value...
// CHECK: bb1:
// CHECK-NEXT: [[T1:%.*]] = unchecked_take_enum_data_addr [[PBF]]
// CHECK-NEXT: [[T0:%.*]] = load [[T1]]
// CHECK-NEXT: strong_retain
// ...evaluate the rest of the suffix...
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[THUNK:%.*]] = function_ref @{{.*}} : $@convention(thin) <τ_0_0> (@owned @callee_owned (@in ()) -> @out τ_0_0) -> @out τ_0_0
// CHECK-NEXT: [[T1:%.*]] = partial_apply [[THUNK]]<T>([[T0]])
// CHECK-NEXT: apply [[T1]]([[TEMP]])
// ...and coerce to T?
// CHECK-NEXT: inject_enum_addr [[PBX]] {{.*}}some
// CHECK-NEXT: br bb2
// Continuation block.
// CHECK: bb2
// CHECK-NEXT: strong_release [[X]]
// CHECK-NEXT: strong_release [[F]]
// CHECK-NEXT: release_value %0
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return [[T0]] : $()
// Nothing block.
// CHECK: bb3:
// CHECK-NEXT: inject_enum_addr [[PBX]] {{.*}}none
// CHECK-NEXT: br bb2
// <rdar://problem/15180622>
func wrap<T>(_ x: T) -> T? { return x }
// CHECK-LABEL: sil hidden @_TF8optional16wrap_then_unwrap
func wrap_then_unwrap<T>(_ x: T) -> T {
// CHECK: [[FORCE:%.*]] = function_ref @_TFs26_stdlib_Optional_unwrappedurFGSqx_x
// CHECK: apply [[FORCE]]<{{.*}}>(%0, {{%.*}})
return wrap(x)!
}
// CHECK-LABEL: sil hidden @_TF8optional10tuple_bind
func tuple_bind(_ x: (Int, String)?) -> String? {
return x?.1
// CHECK: cond_br {{%.*}}, [[NONNULL:bb[0-9]+]], [[NULL:bb[0-9]+]]
// CHECK: [[NONNULL]]:
// CHECK: [[STRING:%.*]] = tuple_extract {{%.*}} : $(Int, String), 1
// CHECK-NOT: release_value [[STRING]]
}
// rdar://21883752 - We were crashing on this function because the deallocation happened
// out of scope.
// CHECK-LABEL: sil hidden @_TF8optional16crash_on_deallocFTGVs10DictionarySiGSaSi___T_
func crash_on_dealloc(_ dict : [Int : [Int]] = [:]) {
var dict = dict
dict[1]?.append(2)
}
|
apache-2.0
|
39ad0d74b4e18e09043ae602c8972843
| 36.404255 | 140 | 0.557167 | 2.982188 | false | false | false | false |
ip3r/Cart
|
Cart/Currencies/Model/InMemoryCurrency.swift
|
1
|
979
|
//
// InMemoryCurrency.swift
// Cart
//
// Created by Jens Meder on 12.06.17.
// Copyright © 2017 Jens Meder. All rights reserved.
//
import Foundation
internal final class InMemoryCurrency: Currency {
private let currencies: Memory<[String: Float]>
private let mapping: Memory<[String:String]>
private let current: Memory<String>
private let key: String
// MARK: Init
internal required init(currencies: Memory<[String: Float]>, key: String, current: Memory<String>, mapping: Memory<[String:String]>) {
self.currencies = currencies
self.key = key
self.current = current
self.mapping = mapping
}
// MARK: Currency
var sign: OOString {
return ConstString(key)
}
var name: OOString {
return ConstString(mapping.value[key]!)
}
var rate: Double {
get {
return Double(currencies.value[key]!)
}
set {
currencies.value[key]! = Float(newValue)
}
}
func makeCurrent() {
current.value = key
}
}
|
mit
|
fae4db69a4200c820f33d27b7d79cc2f
| 19.375 | 137 | 0.664622 | 3.543478 | false | false | false | false |
liuguya/TestKitchen_1606
|
TestKitchen/TestKitchen/classes/cookbook/recommend/view/CBRecommendView.swift
|
1
|
11144
|
//
// CBRecommendView.swift
// TestKitchen
//
// Created by 阳阳 on 16/8/17.
// Copyright © 2016年 liuguyang. All rights reserved.
//
import UIKit
//推荐显示
class CBRecommendView: UIView{
//表格
private var tbView:UITableView?
//点击事件
var clickClosure:CBCellClosure?
//显示数据
var model:CBRecommendModel?{
didSet{
//刷新表格
tbView?.reloadData()
}
}
init(){
super.init(frame:CGRectZero)
//创建表格视图
tbView = UITableView(frame: CGRectZero, style: .Plain)
tbView?.delegate = self
tbView?.dataSource = self
tbView?.separatorStyle = .None
self.addSubview(tbView!)
//约束
tbView?.snp_makeConstraints(closure: {
[weak self]
(make) in
make.edges.equalTo(self!)
})
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
//MARK:UITableView代理
extension CBRecommendView:UITableViewDataSource,UITableViewDelegate{
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
//广告的数据显示一个分组
var sectionNum = 1
if model?.data?.widgetList?.count > 0{
sectionNum += (model?.data?.widgetList?.count)!
}
return sectionNum
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
var rowNum = 0
if section == 0 {
//广告的数据
if model?.data?.banner?.count > 0{
rowNum = 1
}
}else{
//其他情况下面
let listModel = model?.data?.widgetList![section-1]
if listModel?.widget_type?.integerValue == WidgetType.GuessYouLike.rawValue{
//猜你喜欢
rowNum = 1
}else if listModel?.widget_type?.integerValue == WidgetType.RedPacket.rawValue{
//红包入口
rowNum = 1
}else if listModel?.widget_type?.integerValue == WidgetType.NewProduct.rawValue{
//今日新品
rowNum = 1
}else if listModel?.widget_type?.integerValue == WidgetType.Special.rawValue{
rowNum = 1
}else if listModel?.widget_type?.integerValue ==
WidgetType.Scene.rawValue{
//全部场景
rowNum = 1
}else if listModel?.widget_type?.integerValue == WidgetType.Talent.rawValue{
//推荐达人
rowNum = (listModel?.widget_data?.count)!/4
}else if listModel?.widget_type?.integerValue == WidgetType.Works.rawValue{
//精选作品
rowNum = 1
}else if listModel?.widget_type?.integerValue == WidgetType.Subject.rawValue{
//精选作品
rowNum = (listModel?.widget_data?.count)!/3
}
}
return rowNum
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
var height:CGFloat = 0.0
if indexPath.section == 0{
//广告高度
if model?.data?.banner?.count > 0{
height = 160
}
}else{
//其他情况下面
let listModel = model?.data?.widgetList![indexPath.section-1]
if listModel?.widget_type?.integerValue == WidgetType.GuessYouLike.rawValue{
//猜你喜欢
height = 80
}else if listModel?.widget_type?.integerValue == WidgetType.RedPacket.rawValue{
//红包入口
height = 100
}else if listModel?.widget_type?.integerValue == WidgetType.NewProduct.rawValue{
//今日新品
height = 300
}else if listModel?.widget_type?.integerValue == WidgetType.Special.rawValue{
height = 200
}else if listModel?.widget_type?.integerValue ==
WidgetType.Scene.rawValue{
//全部场景
height = 60
}else if listModel?.widget_type?.integerValue == WidgetType.Talent.rawValue{
//推荐达人
height = 80
}else if listModel?.widget_type?.integerValue == WidgetType.Works.rawValue{
//精选作品
height = 240
}else if listModel?.widget_type?.integerValue == WidgetType.Subject.rawValue{
//精选作品
height = 180
}
}
return height
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
if indexPath.section == 0{
//广告
if model?.data?.banner?.count > 0{
cell = CBRecommendADCell.createAdCellForTbView(tableView, atIndexPath: indexPath, withModel: model!, cellClosure: clickClosure)
}
return cell
}else{
//其他情况下面
let listModel = model?.data?.widgetList![indexPath.section-1]
if listModel?.widget_type?.integerValue == WidgetType.GuessYouLike.rawValue{
//猜你喜欢
cell = CBRecommendLikeCell.createLikeCellFor(tableView, atIndexPath: indexPath, withlistModel: listModel!)
}else if listModel?.widget_type?.integerValue == WidgetType.RedPacket.rawValue{
//红包入口
cell = CBRedPacketCell.createRedPackageCellFor(tableView, atIndexPath: indexPath, withlistModel: listModel!)
}else if listModel?.widget_type?.integerValue == WidgetType.NewProduct.rawValue{
//今日新品
cell = CBRecommendNewCell.createNewCellFor(tableView, atIndexPath: indexPath, withlistModel: listModel!)
}else if listModel?.widget_type?.integerValue == WidgetType.Special.rawValue{
//早餐日记
cell = CBSpecialCell.createSpecialCellFor(tableView, atIndexPath: indexPath, withlistModel: listModel!)
}else if listModel?.widget_type?.integerValue ==
WidgetType.Scene.rawValue{
//全部场景
cell = CBSceneCell.createSceneCellFor(tableView, atIndexPath: indexPath, withlistModel: listModel!)
}else if listModel?.widget_type?.integerValue == WidgetType.Talent.rawValue{
//推荐达人
cell = CBTalentCell.CBTalentCellFor(tableView, atIndexPath: indexPath, withlistModel: listModel!)
}else if listModel?.widget_type?.integerValue == WidgetType.Works.rawValue{
//精选作品
cell = CBWorksCell.createWorksCellFor(tableView, atIndexPath: indexPath, withListModel: listModel!)
}else if listModel?.widget_type?.integerValue == WidgetType.Subject.rawValue{
//专题
cell = CBSubjectCell.CBSubjectCellFor(tableView, atIndexPath: indexPath, withListModel: listModel!)
}
return cell
}
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
var headView:UIView? = nil
if section>0{
//其他情况下面
let listModel = model?.data?.widgetList![section-1]
if listModel?.widget_type?.integerValue == WidgetType.GuessYouLike.rawValue{
//猜你喜欢
headView = CBSearchHeaderView.init(frame: CGRectMake(0,0,kSreenWith,44))
}else if listModel?.widget_type?.integerValue == WidgetType.NewProduct.rawValue{
//今日新品
let headView1 = CBHeadView.init(frame: CGRectMake(0,0,kSreenWith,44))
headView1.configTitle((listModel?.title!)!)
headView = headView1
}else if listModel?.widget_type?.integerValue == WidgetType.Special.rawValue{
//早餐日记 健康100岁
let headView1 = CBHeadView.init(frame: CGRectMake(0,0,kSreenWith,44))
headView1.configTitle((listModel?.title!)!)
headView = headView1
}else if listModel?.widget_type?.integerValue == WidgetType.Talent.rawValue{
//推荐达人
let headView1 = CBHeadView.init(frame: CGRectMake(0,0,kSreenWith,44))
headView1.configTitle((listModel?.title!)!)
headView = headView1
}else if listModel?.widget_type?.integerValue == WidgetType.Works.rawValue{
//推荐达人
let headView1 = CBHeadView.init(frame: CGRectMake(0,0,kSreenWith,44))
headView1.configTitle((listModel?.title!)!)
headView = headView1
}else if listModel?.widget_type?.integerValue == WidgetType.Subject.rawValue{
//专题
let headView1 = CBHeadView.init(frame: CGRectMake(0,0,kSreenWith,44))
headView1.configTitle((listModel?.title!)!)
headView = headView1
}
}
return headView
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
var height:CGFloat = 0.0
if section > 0 {
//其他情况
let listModel = model?.data?.widgetList![section-1]
if listModel?.widget_type?.integerValue == WidgetType.GuessYouLike.rawValue{
//猜你喜欢
height = 44
}else if listModel?.widget_type?.integerValue == WidgetType.NewProduct.rawValue{
//今日新品
height = 44
}else if listModel?.widget_type?.integerValue == WidgetType.Special.rawValue{
//今日新品
height = 44
}else if listModel?.widget_type?.integerValue == WidgetType.Talent.rawValue{
//推荐达人
height = 44
}else if listModel?.widget_type?.integerValue == WidgetType.Works.rawValue{
//推荐达人
height = 44
}else if listModel?.widget_type?.integerValue == WidgetType.Subject.rawValue{
//专题
height = 44
}
}
return height
}
func scrollViewDidScroll(scrollView: UIScrollView) {
let h:CGFloat = 44
if scrollView.contentOffset.y > h{
scrollView.contentInset = UIEdgeInsetsMake(-h, 0, 0, 0)
}else if scrollView.contentOffset.y > 0{
scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0)
}
}
}
|
mit
|
b5d1bdba1a3c8c9c59335393aa7b9a8c
| 37.68231 | 143 | 0.555016 | 4.967548 | false | false | false | false |
XWebView/XWebView
|
XWebView/XWVObject.swift
|
2
|
4191
|
/*
Copyright 2015 XWebView
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
import WebKit
private let webViewInvalidated =
NSError(domain: WKErrorDomain, code: WKError.webViewInvalidated.rawValue, userInfo: nil)
public class XWVObject : NSObject {
public let namespace: String
private(set) public weak var webView: WKWebView?
private weak var origin: XWVObject?
private let reference: Int
// initializer for plugin object.
init(namespace: String, webView: WKWebView) {
self.namespace = namespace
self.webView = webView
reference = 0
super.init()
origin = self
}
// initializer for script object with global namespace.
init(namespace: String, origin: XWVObject) {
self.namespace = namespace
self.origin = origin
webView = origin.webView
reference = 0
super.init()
}
// initializer for script object which is retained on script side.
init(reference: Int, origin: XWVObject) {
self.reference = reference
self.origin = origin
webView = origin.webView
namespace = "\(origin.namespace).$references[\(reference)]"
super.init()
}
deinit {
guard let webView = webView else { return }
let script: String
if origin === self {
script = "delete \(namespace)"
} else if reference != 0, let origin = origin {
script = "\(origin.namespace).$releaseObject(\(reference))"
} else {
return
}
webView.asyncEvaluateJavaScript(script, completionHandler: nil)
}
// Evaluate JavaScript expression
public func evaluateExpression(_ expression: String) throws -> Any {
guard let webView = webView else {
throw webViewInvalidated
}
let result = try webView.syncEvaluateJavaScript(scriptForRetaining(expression))
return wrapScriptObject(result)
}
public typealias Handler = ((Any?, Error?) -> Void)?
public func evaluateExpression(_ expression: String, completionHandler: Handler) {
guard let webView = webView else {
completionHandler?(nil, webViewInvalidated)
return
}
guard let completionHandler = completionHandler else {
webView.asyncEvaluateJavaScript(expression, completionHandler: nil)
return
}
webView.asyncEvaluateJavaScript(scriptForRetaining(expression)) {
[weak self](result: Any?, error: Error?)->Void in
if let error = error {
completionHandler(nil, error)
} else if let result = result {
completionHandler(self?.wrapScriptObject(result) ?? result, nil)
} else {
completionHandler(undefined, error)
}
}
}
private func scriptForRetaining(_ script: String) -> String {
guard let origin = origin else { return script }
return "\(origin.namespace).$retainObject(\(script))"
}
func wrapScriptObject(_ object: Any) -> Any {
guard let origin = origin else { return object }
if let dict = object as? [String: Any], dict["$sig"] as? NSNumber == 0x5857574F {
if let num = dict["$ref"] as? NSNumber, num != 0 {
return XWVScriptObject(reference: num.intValue, origin: origin)
} else if let namespace = dict["$ns"] as? String {
return XWVScriptObject(namespace: namespace, origin: origin)
}
}
return object
}
}
extension XWVObject : CustomJSONStringable {
public var jsonString: String? {
return namespace
}
}
|
apache-2.0
|
fa9ba622a8a9b13bf8b429355d45fe3d
| 33.925 | 92 | 0.635409 | 4.948052 | false | false | false | false |
oleander/bitbar
|
Sources/Plugin/Tray.swift
|
1
|
2042
|
import Parser
class Tray: Trayable {
func has(child: Childable) -> Bool {
return false
}
func set(error: Bool) {
// TODO FIX
events.append(.error(["bool error"]))
}
var events: [Event] = []
typealias Tail = Parser.Menu.Tail
typealias Text = Plugin.Text
static let `default` = Tray(title: "…", isVisible: false)
required public init(title: String, isVisible: Bool = true) {
set(title: title)
if !isVisible { hide() }
}
func set(_ tails: [Tail]) {
events.append(.tail(tails))
}
public func set(error: String) {
events.append(.error([error]))
}
public func set(errors: [String]) {
events.append(.error(errors))
}
public func set(title: String) {
events.append(.title(title))
}
public func set(title: Text) {
switch title {
case let .normal(string, _):
events.append(.title(string))
}
}
public func show() {
events.append(.show)
}
public func hide() {
events.append(.hide)
}
public func set(errors: [MenuError]) {
events.append(.menuError(errors))
}
public enum Event: Equatable {
case show
case hide
case title(String)
case error([String])
case menuError([MenuError])
case tail([Tail])
public static func == (lhs: Event, rhs: Event) -> Bool {
switch (lhs, rhs) {
case (.show, show):
return true
case (.hide, .hide):
return true
case let (.title(t1), .title(t2)):
return t1 == t2
case let (.tail(t1), .tail(t2)):
return t1 == t2
default:
return false
}
}
}
enum Title: Equatable {
case string(String)
case text(Text)
case error([String])
public static func == (lhs: Title, rhs: Title) -> Bool {
switch (lhs, rhs) {
case let (.string(s1), .string(s2)):
return s1 == s2
case let (.text(t1), .text(t2)):
return t1 == t2
case let (.error(e1), .error(e2)):
return e1 == e2
default:
return false
}
}
}
}
|
mit
|
8dd56a24df0f4a1c41f08d539d0ebad4
| 19 | 63 | 0.564706 | 3.547826 | false | false | false | false |
danielgindi/Charts
|
Source/Charts/Charts/CombinedChartView.swift
|
2
|
7200
|
//
// CombinedChartView.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
/// This chart class allows the combination of lines, bars, scatter and candle data all displayed in one chart area.
open class CombinedChartView: BarLineChartViewBase, CombinedChartDataProvider
{
/// the fill-formatter used for determining the position of the fill-line
internal var _fillFormatter: FillFormatter!
/// enum that allows to specify the order in which the different data objects for the combined-chart are drawn
@objc(CombinedChartDrawOrder)
public enum DrawOrder: Int
{
case bar
case bubble
case line
case candle
case scatter
}
open override func initialize()
{
super.initialize()
self.highlighter = CombinedHighlighter(chart: self, barDataProvider: self)
// Old default behaviour
self.highlightFullBarEnabled = true
_fillFormatter = DefaultFillFormatter()
renderer = CombinedChartRenderer(chart: self, animator: chartAnimator, viewPortHandler: viewPortHandler)
}
open override var data: ChartData?
{
get
{
return super.data
}
set
{
super.data = newValue
self.highlighter = CombinedHighlighter(chart: self, barDataProvider: self)
(renderer as? CombinedChartRenderer)?.createRenderers()
renderer?.initBuffers()
}
}
@objc open var fillFormatter: FillFormatter
{
get
{
return _fillFormatter
}
set
{
_fillFormatter = newValue
if _fillFormatter == nil
{
_fillFormatter = DefaultFillFormatter()
}
}
}
/// - Returns: The Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the CombinedChart.
open override func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight?
{
if data === nil
{
Swift.print("Can't select by touch. No data set.")
return nil
}
guard let h = self.highlighter?.getHighlight(x: pt.x, y: pt.y)
else { return nil }
if !isHighlightFullBarEnabled { return h }
// For isHighlightFullBarEnabled, remove stackIndex
return Highlight(
x: h.x, y: h.y,
xPx: h.xPx, yPx: h.yPx,
dataIndex: h.dataIndex,
dataSetIndex: h.dataSetIndex,
stackIndex: -1,
axis: h.axis)
}
// MARK: - CombinedChartDataProvider
open var combinedData: CombinedChartData?
{
get
{
return data as? CombinedChartData
}
}
// MARK: - LineChartDataProvider
open var lineData: LineChartData?
{
get
{
return combinedData?.lineData
}
}
// MARK: - BarChartDataProvider
open var barData: BarChartData?
{
get
{
return combinedData?.barData
}
}
// MARK: - ScatterChartDataProvider
open var scatterData: ScatterChartData?
{
get
{
return combinedData?.scatterData
}
}
// MARK: - CandleChartDataProvider
open var candleData: CandleChartData?
{
get
{
return combinedData?.candleData
}
}
// MARK: - BubbleChartDataProvider
open var bubbleData: BubbleChartData?
{
get
{
return combinedData?.bubbleData
}
}
// MARK: - Accessors
/// if set to true, all values are drawn above their bars, instead of below their top
@objc open var drawValueAboveBarEnabled: Bool
{
get { return (renderer as! CombinedChartRenderer).drawValueAboveBarEnabled }
set { (renderer as! CombinedChartRenderer).drawValueAboveBarEnabled = newValue }
}
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
@objc open var drawBarShadowEnabled: Bool
{
get { return (renderer as! CombinedChartRenderer).drawBarShadowEnabled }
set { (renderer as! CombinedChartRenderer).drawBarShadowEnabled = newValue }
}
/// `true` if drawing values above bars is enabled, `false` ifnot
open var isDrawValueAboveBarEnabled: Bool { return (renderer as! CombinedChartRenderer).drawValueAboveBarEnabled }
/// `true` if drawing shadows (maxvalue) for each bar is enabled, `false` ifnot
open var isDrawBarShadowEnabled: Bool { return (renderer as! CombinedChartRenderer).drawBarShadowEnabled }
/// the order in which the provided data objects should be drawn.
/// The earlier you place them in the provided array, the further they will be in the background.
/// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines.
@objc open var drawOrder: [Int]
{
get
{
return (renderer as! CombinedChartRenderer).drawOrder.map { $0.rawValue }
}
set
{
(renderer as! CombinedChartRenderer).drawOrder = newValue.map { DrawOrder(rawValue: $0)! }
}
}
/// Set this to `true` to make the highlight operation full-bar oriented, `false` to make it highlight single values
@objc open var highlightFullBarEnabled: Bool = false
/// `true` the highlight is be full-bar oriented, `false` ifsingle-value
open var isHighlightFullBarEnabled: Bool { return highlightFullBarEnabled }
// MARK: - ChartViewBase
/// draws all MarkerViews on the highlighted positions
override func drawMarkers(context: CGContext)
{
guard
let marker = marker,
isDrawMarkersEnabled && valuesToHighlight()
else { return }
for i in highlighted.indices
{
let highlight = highlighted[i]
guard
let set = combinedData?.getDataSetByHighlight(highlight),
let e = data?.entry(for: highlight)
else { continue }
let entryIndex = set.entryIndex(entry: e)
if entryIndex > Int(Double(set.entryCount) * chartAnimator.phaseX)
{
continue
}
let pos = getMarkerPosition(highlight: highlight)
// check bounds
if !viewPortHandler.isInBounds(x: pos.x, y: pos.y)
{
continue
}
// callbacks to update the content
marker.refreshContent(entry: e, highlight: highlight)
// draw the marker
marker.draw(context: context, point: pos)
}
}
}
|
apache-2.0
|
a61fbb9e33d0c817eb9b9f827575779c
| 28.268293 | 149 | 0.583056 | 5.313653 | false | false | false | false |
tomlokhorst/CoreDataKit
|
CoreDataKit/Importing/NSEntityDescription+Importing.swift
|
1
|
1389
|
//
// NSEntityDescription+Importing.swift
// CoreDataKit
//
// Created by Mathijs Kadijk on 16-10-14.
// Copyright (c) 2014 Mathijs Kadijk. All rights reserved.
//
import CoreData
extension NSEntityDescription
{
/**
Get the attribute description of this entity description that is marked as identifier in the model
- returns: Result with the identifying attribute description
*/
func identifyingAttribute() throws -> NSAttributeDescription {
if let identifyingAttributeName = userInfo?[IdentifierUserInfoKey] as? String {
if let identifyingAttribute = self.attributesByName[identifyingAttributeName] {
return identifyingAttribute
}
let error = NSError(domain: CoreDataKitErrorDomain, code: CoreDataKitErrorCode.IdentifyingAttributeNotFound.rawValue, userInfo: [NSLocalizedDescriptionKey: "Found \(IdentifierUserInfoKey) with value '\(identifyingAttributeName)' but that isn't a valid attribute name"])
throw error
} else if let superEntity = self.superentity {
return try superEntity.identifyingAttribute()
}
let error = NSError(domain: CoreDataKitErrorDomain, code: CoreDataKitErrorCode.IdentifyingAttributeNotFound.rawValue, userInfo: [NSLocalizedDescriptionKey: "No \(IdentifierUserInfoKey) value found on \(name)"])
throw error
}
}
|
mit
|
5ebff1cd976da0c84ac25f3724373a6e
| 41.090909 | 281 | 0.721382 | 5.383721 | false | false | false | false |
PedroTrujilloV/TIY-Assignments
|
19--Keep-On-The-Sunny-Side/Forecaster/GitHub Friends/CityData.swift
|
1
|
3232
|
//
// GitHubFriend.swift
// GitHub Friends
//
// Created by Pedro Trujillo on 10/27/15.
// Copyright © 2015 Pedro Trujillo. All rights reserved.
//
import Foundation
struct CityData
{
let name: String
let login: String
let thumbnailImageURL: String
let largeImageURL: String
let email:String
let company: String
let location: String
init(name:String, login:String, thumbnailImageURL:String, largeImageURL:String, company: String, location: String, email: String)
{
self.name = name
self.login = login
self.thumbnailImageURL = thumbnailImageURL+"&s=96"
self.largeImageURL = largeImageURL
self.email = email
self.company = company
self.location = location
print("name: \(self.name )")
print("self.login: \(self.login)")
print("self.thumbnailImageURL: \(self.thumbnailImageURL)")
print("self.location: \(self.location)")
}
static func CitiesDataWithJSON(results: NSArray) ->[CityData]
{
var CitiesData = [CityData]()
if results.count > 0
{
for result in results
{
print("hola! fetch fetch!!!!!!!!")
/*var emailUser = result["email"] as? String
if emailUser == nil
{
emailUser = result["blog"] as? String
if emailUser == nil
{
emailUser == " no public email :("
}
}*/
let emailUser = result["email"] as? String ?? ""
let nameUser = result["name"] as? String ?? ""
let loginUser = result["login"] as? String ?? ""
let thumbnailURL = result["avatar_url"] as? String ?? ""
let imageURL = result["avatar_url"] as? String ?? ""
let locationUser = result["location"] as? String ?? ""
let companyUser = result["company"] as? String ?? ""
CitiesData.append(CityData(name: nameUser, login: loginUser, thumbnailImageURL: thumbnailURL, largeImageURL: imageURL, company: companyUser, location: locationUser, email: emailUser))
}
}
return CitiesData
}
static func aCityDataWithJSON(results: NSArray) -> CityData
{
let aFriendData:NSDictionary = results[0] as! NSDictionary
let emailUser = aFriendData["email"] as? String ?? ""
let nameUser = aFriendData["name"] as? String ?? ""
let loginUser = aFriendData["login"] as? String ?? ""
let thumbnailURL = aFriendData["avatar_url"] as? String ?? ""
let imageURL = aFriendData["avatar_url"] as? String ?? ""
let locationUser = aFriendData["location"] as? String ?? ""
let companyUser = aFriendData["company"] as? String ?? ""
return CityData(name: nameUser, login: loginUser, thumbnailImageURL: thumbnailURL, largeImageURL: imageURL, company: companyUser, location: locationUser, email: emailUser)
}
}
|
cc0-1.0
|
184b530acc07dbfa857aa32c43f0b534
| 34.516484 | 199 | 0.547199 | 4.793769 | false | false | false | false |
lorentey/Attabench
|
BenchmarkModel/ClosedRangeVariable.swift
|
2
|
2141
|
// Copyright © 2017 Károly Lőrentey.
// This file is part of Attabench: https://github.com/attaswift/Attabench
// For licensing information, see the file LICENSE.md in the Git repository above.
import GlueKit
public class ClosedRangeVariable<Bounds: Comparable> : Variable<ClosedRange<Bounds>> {
let limits: Value?
init(_ value: Value, limits: Value? = nil) {
self.limits = limits
super.init(value)
}
public var lowerBound: AnyUpdatableValue<Bounds> {
return AnyUpdatableValue<Bounds>(
getter: { () -> Bounds in self.value.lowerBound },
apply: self.applyLowerBoundUpdate,
updates: self.updates.map { update in update.map { change in change.map { $0.lowerBound } } })
}
func applyLowerBoundUpdate(_ update: ValueUpdate<Bounds>) {
switch update {
case .beginTransaction:
self.apply(.beginTransaction)
case .change(let change):
let upper = Swift.max(change.new, self.value.upperBound)
var new = (change.new ... upper)
if let limits = limits { new = new.clamped(to: limits) }
self.apply(.change(.init(from: self.value, to: new)))
case .endTransaction:
self.apply(.endTransaction)
}
}
public var upperBound: AnyUpdatableValue<Bounds> {
return AnyUpdatableValue<Bounds>(
getter: { () -> Bounds in self.value.upperBound },
apply: self.applyUpperBoundUpdate,
updates: self.updates.map { update in update.map { change in change.map { $0.upperBound } } })
}
func applyUpperBoundUpdate(_ update: ValueUpdate<Bounds>) {
switch update {
case .beginTransaction:
self.apply(.beginTransaction)
case .change(let change):
let lower = Swift.min(self.value.lowerBound, change.new)
var new = lower ... change.new
if let limits = limits { new = new.clamped(to: limits) }
self.apply(.change(.init(from: self.value, to: new)))
case .endTransaction:
self.apply(.endTransaction)
}
}
}
|
mit
|
607f9dd6de5947b9b635b4a4ec047f2e
| 37.178571 | 106 | 0.614125 | 4.381148 | false | false | false | false |
LKY769215561/KYHandMade
|
KYHandMade/Pods/DynamicColor/Sources/DynamicColor.swift
|
1
|
7384
|
/*
* DynamicColor
*
* Copyright 2015-present Yannick Loriot.
* http://yannickloriot.com
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#if os(iOS) || os(tvOS) || os(watchOS)
import UIKit
/**
Extension to manipulate colours easily.
It allows you to work hexadecimal strings and value, HSV and RGB components, derivating colours, and many more...
*/
public typealias DynamicColor = UIColor
#elseif os(OSX)
import AppKit
/**
Extension to manipulate colours easily.
It allows you to work hexadecimal strings and value, HSV and RGB components, derivating colours, and many more...
*/
public typealias DynamicColor = NSColor
#endif
public extension DynamicColor {
// MARK: - Manipulating Hexa-decimal Values and Strings
/**
Creates a color from an hex string (e.g. "#3498db").
If the given hex string is invalid the initialiser will create a black color.
- parameter hexString: A hexa-decimal color string representation.
*/
public convenience init(hexString: String) {
let hexString = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let scanner = Scanner(string: hexString)
if hexString.hasPrefix("#") {
scanner.scanLocation = 1
}
var color: UInt32 = 0
if scanner.scanHexInt32(&color) {
self.init(hex: color, useAlpha: hexString.characters.count > 7)
}
else {
self.init(hex: 0x000000)
}
}
/**
Creates a color from an hex integer (e.g. 0x3498db).
- parameter hex: A hexa-decimal UInt32 that represents a color.
- parameter alphaChannel: If true the given hex-decimal UInt32 includes the alpha channel (e.g. 0xFF0000FF).
*/
public convenience init(hex: UInt32, useAlpha alphaChannel: Bool = false) {
let mask = 0xFF
let r = Int(hex >> (alphaChannel ? 24 : 16)) & mask
let g = Int(hex >> (alphaChannel ? 16 : 8)) & mask
let b = Int(hex >> (alphaChannel ? 8 : 0)) & mask
let a = alphaChannel ? Int(hex) & mask : 255
let red = CGFloat(r) / 255
let green = CGFloat(g) / 255
let blue = CGFloat(b) / 255
let alpha = CGFloat(a) / 255
self.init(red: red, green: green, blue: blue, alpha: alpha)
}
/**
Returns the color representation as hexadecimal string.
- returns: A string similar to this pattern "#f4003b".
*/
public final func toHexString() -> String {
return String(format:"#%06x", toHex())
}
/**
Returns the color representation as an integer.
- returns: A UInt32 that represents the hexa-decimal color.
*/
public final func toHex() -> UInt32 {
func roundToHex(_ x: CGFloat) -> UInt32 {
return UInt32(roundf(Float(x) * 255.0))
}
let rgba = toRGBAComponents()
let colorToInt = roundToHex(rgba.r) << 16 | roundToHex(rgba.g) << 8 | roundToHex(rgba.b)
return colorToInt
}
// MARK: - Identifying and Comparing Colors
/**
Returns a boolean value that indicates whether the receiver is equal to the given hexa-decimal string.
- parameter hexString: A hexa-decimal color number representation to be compared to the receiver.
- returns: true if the receiver and the string are equals, otherwise false.
*/
public func isEqual(toHexString hexString: String) -> Bool {
return self.toHexString() == hexString
}
/**
Returns a boolean value that indicates whether the receiver is equal to the given hexa-decimal integer.
- parameter hex: A UInt32 that represents the hexa-decimal color.
- returns: true if the receiver and the integer are equals, otherwise false.
*/
public func isEqual(toHex hex: UInt32) -> Bool {
return self.toHex() == hex
}
// MARK: - Querying Colors
/**
Determines if the color object is dark or light.
It is useful when you need to know whether you should display the text in black or white.
- returns: A boolean value to know whether the color is light. If true the color is light, dark otherwise.
*/
public func isLight() -> Bool {
let components = toRGBAComponents()
let brightness = ((components.r * 299) + (components.g * 587) + (components.b * 114)) / 1000
return brightness >= 0.5
}
/**
A float value representing the luminance of the current color. May vary from 0 to 1.0.
We use the formula described by W3C in WCAG 2.0. You can read more here: https://www.w3.org/TR/WCAG20/#relativeluminancedef
*/
public var luminance: CGFloat {
let components = toRGBAComponents()
let componentsArray = [components.r, components.g, components.b].map { (val) -> CGFloat in
guard val <= 0.03928 else { return pow((val + 0.055) / 1.055, 2.4) }
return val / 12.92
}
return (0.2126 * componentsArray[0]) + (0.7152 * componentsArray[1]) + (0.0722 * componentsArray[2])
}
/**
Returns a float value representing the contrast ratio between 2 colors.
We use the formula described by W3C in WCAG 2.0. You can read more here: https://www.w3.org/TR/WCAG20-TECHS/G18.html
NB: the contrast ratio is a relative value. So the contrast between Color1 and Color2 is exactly the same between Color2 and Color1.
- returns: A CGFloat representing contrast value
*/
public func contrastRatio(with otherColor: DynamicColor) -> CGFloat {
let otherLuminance = otherColor.luminance
let l1 = max(luminance, otherLuminance)
let l2 = min(luminance, otherLuminance)
return (l1 + 0.05) / (l2 + 0.05)
}
/**
Indicates if two colors are contrasting, regarding W3C's WCAG 2.0 recommendations.
You can read it here: https://www.w3.org/TR/2008/REC-WCAG20-20081211/#visual-audio-contrast-contrast
The acceptable contrast ratio depends on the context of display. Most of the time, the default context (.Standard) is enough.
You can look at ContrastDisplayContext for more options.
- parameter otherColor: The other color to compare with.
- parameter context: An optional context to determine the minimum acceptable contrast ratio. Default value is .Standard.
- returns: true is the contrast ratio between 2 colors exceed the minimum acceptable ratio.
*/
public func isContrasting(with otherColor: DynamicColor, inContext context: ContrastDisplayContext = .standard) -> Bool {
return self.contrastRatio(with: otherColor) > context.minimumContrastRatio
}
}
|
apache-2.0
|
511b92e4c02d6d853ee50ca92ef90b0e
| 33.995261 | 137 | 0.697183 | 4.145985 | false | false | false | false |
glorybird/KeepReading2
|
kr/Pods/DKChainableAnimationKit/DKChainableAnimationKit/Classes/UIView+AnimationKit.swift
|
4
|
1051
|
//
// UIView+AnimationKit.swift
// DKChainableAnimationKit
//
// Created by Draveness on 15/5/13.
// Copyright (c) 2015年 Draveness. All rights reserved.
//
import UIKit
private var animationKitAssociationKey = "animationKitAssociationKey"
public extension UIView {
final public var animation: DKChainableAnimationKit {
get {
var animation: DKChainableAnimationKit! = objc_getAssociatedObject(self, &animationKitAssociationKey) as? DKChainableAnimationKit
if let animation = animation {
return animation
} else {
animation = DKChainableAnimationKit()
animation.view = self
objc_setAssociatedObject(self, &animationKitAssociationKey, animation, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN)
return animation
}
}
}
final public func bezierPathForAnimation() -> UIBezierPath {
let path = UIBezierPath()
path.moveToPoint(self.layer.position)
return path
}
}
|
apache-2.0
|
d34c84673102474f63112176f5dcc611
| 28.971429 | 141 | 0.655863 | 4.995238 | false | false | false | false |
pantuspavel/PPEventRegistryAPI
|
PPEventRegistryAPI/Classes/API/Operations/PPLoginOperation.swift
|
1
|
1535
|
//
// PPLoginOperation.swift
// PPEventRegistryAPI
//
// Created by Pavel Pantus on 6/19/16.
// Copyright © 2016 Pavel Pantus. All rights reserved.
//
import Foundation
/// Operation that logs in user.
final class PPLoginOperation: PPAsyncOperation {
/**
Operation initializer.
- Parameters:
- email: Email to log in user with.
- password: Password to log in user with.
- completionHandler: Completion handler that is executed upon operation completion.
- error: Error in case something went wrong.
*/
init(email: String, password: String, completionHandler: @escaping (_ error: PPError?) -> ()) {
let parameters = ["email": email, "pass": password]
super.init(controller: .Login, method: .Post, parameters: parameters)
self.completionHandler = { result in
switch result {
case let .Failure(error):
DispatchQueue.main.async {
completionHandler(error)
}
case let .Success(response):
var error: PPError?
switch response["action"] as? String ?? "" {
case "unknownUser":
error = .UnknownUser
case "missingData":
error = .MissingData
default:
error = nil
}
DispatchQueue.main.async {
completionHandler(error)
}
}
}
}
}
|
mit
|
62eb6322fcc689dd6a58c640ba358e52
| 30.306122 | 99 | 0.537158 | 5.113333 | false | false | false | false |
PopcornTimeTV/PopcornTimeTV
|
PopcornTime/Extensions/CGImage+IsDark.swift
|
1
|
806
|
import Foundation
extension CGImage {
var isDark: Bool {
guard let imageData = self.dataProvider?.data else { return false }
guard let ptr = CFDataGetBytePtr(imageData) else { return false }
let length = CFDataGetLength(imageData)
let threshold = Int(Double(self.width * self.height) * 0.45)
var darkPixels = 0
for i in stride(from: 0, to: length, by: 4) {
let r = ptr[i]
let g = ptr[i + 1]
let b = ptr[i + 2]
let luminance = (0.299 * Double(r) + 0.587 * Double(g) + 0.114 * Double(b))
if luminance < 150 {
darkPixels += 1
if darkPixels > threshold {
return true
}
}
}
return false
}
}
|
gpl-3.0
|
9714e1d9f34bbd12b59e01aa2813362e
| 28.851852 | 87 | 0.501241 | 4.176166 | false | false | false | false |
rajeejones/SavingPennies
|
Pods/IBAnimatable/IBAnimatable/ActivityIndicatorAnimationBallPulse.swift
|
5
|
1893
|
//
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallPulse: ActivityIndicatorAnimating {
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSpacing: CGFloat = 2
let circleSize: CGFloat = (size.width - 2 * circleSpacing) / 3
let x: CGFloat = (layer.bounds.size.width - size.width) / 2
let y: CGFloat = (layer.bounds.size.height - circleSize) / 2
let beginTime = CACurrentMediaTime()
let beginTimes: [CFTimeInterval] = [0.12, 0.24, 0.36]
let animation = self.animation
// Draw circles
for i in 0 ..< 3 {
let circle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color)
let frame = CGRect(x: x + circleSize * CGFloat(i) + circleSpacing * CGFloat(i),
y: y,
width: circleSize,
height: circleSize)
animation.beginTime = beginTime + beginTimes[i]
circle.frame = frame
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallPulse {
var animation: CAKeyframeAnimation {
let duration: CFTimeInterval = 0.75
let timingFunction = CAMediaTimingFunction(controlPoints: 0.2, 0.68, 0.18, 1.08)
let animation = CAKeyframeAnimation(keyPath: "transform.scale")
animation.keyTimes = [0, 0.3, 1]
animation.timingFunctions = [timingFunction, timingFunction]
animation.values = [1, 0.3, 1]
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
}
|
gpl-3.0
|
ad35328a96513ba23a8a4b0db1beed9e
| 33.418182 | 131 | 0.650291 | 4.550481 | false | false | false | false |
iOS-Swift-Developers/Swift
|
实战前技术点/3.JQPageView/JQPageView/JQPageView/JQPageView.swift
|
1
|
2503
|
//
// JQPageView.swift
// JQPageView
//
// Created by 韩俊强 on 2017/7/18.
// Copyright © 2017年 HaRi. All rights reserved.
//
import UIKit
class JQPageView: UIView {
// MARK: 定义属性
fileprivate var titles : [String]!
fileprivate var childVcs : [UIViewController]!
fileprivate weak var parentVc : UIViewController!
fileprivate var style : JQTitleStyle!
fileprivate var titleView : JQTitleView!
fileprivate var contentView : JQContentView!
// MARK: 自定义构造函数
init(frame : CGRect, titles : [String], style : JQTitleStyle, childVCs : [UIViewController], parentVc : UIViewController) {
super.init(frame: frame)
// assert(titles.count == childVcs.count, "标题和控制前个数不同!") // 测试
self.style = style
self.titles = titles
self.childVcs = childVCs
self.parentVc = parentVc
parentVc.automaticallyAdjustsScrollViewInsets = false
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK:- 设置UI界面内容
extension JQPageView {
fileprivate func setupUI() {
let titleH : CGFloat = style.titleHeight
let titleFrame = CGRect(x: 0, y: 0, width: frame.width, height: titleH)
titleView = JQTitleView(frame: titleFrame, titles: titles, style: style)
titleView.delegate = self
addSubview(titleView)
let contentFrame = CGRect(x: 0, y: titleH, width: frame.width, height: frame.height - titleH)
contentView = JQContentView(frame: contentFrame, childVcs: childVcs, parentViewController: parentVc)
contentView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
contentView.delegate = self
addSubview(contentView)
}
}
// MARK:- 设置JQContentView的代理
extension JQPageView : JQContentViewDelegate {
func contentView(_ contentView: JQContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
titleView.setTitleWithProgress(progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
func contentViewEndScroll(_ contentView: JQContentView) {
titleView.contentViewDidEndScroll()
}
}
// MARK:- 设置JQTitleView的代理
extension JQPageView : JQTitleViewDelegate {
func titleView(_ titleView: JQTitleView, selectedIndex index: Int) {
contentView.setCurrentIndex(index)
}
}
|
mit
|
3beb8bc6f1033ad7626e8bf5438a369a
| 31.213333 | 127 | 0.671772 | 4.727984 | false | false | false | false |
nthegedus/NHPageView
|
NHPageView/ViewController.swift
|
1
|
1963
|
//
// ViewController.swift
// NHPageView
//
// Created by Nathan Hegedus on 4/2/15.
// Copyright (c) 2015 Nathan Hegedus. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var pageRightView: NHPageView!
@IBOutlet weak var pageCenterView: NHPageView!
@IBOutlet weak var pageLeftView: NHPageView!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var rightArray: Array <UIView> = Array()
for var i = 0; i < 10; i++ {
var view: UIView = UIView (frame: CGRectMake(0, 0, 200, 100))
view.backgroundColor = UIColor.lightGrayColor()
rightArray.insert(view, atIndex: i)
}
self.pageRightView.alignment = .Right
self.pageRightView.insertSubviews(rightArray)
var centerArray: Array <UIView> = Array()
for var i = 0; i < 10; i++ {
var view: UIView = UIView (frame: CGRectMake(0, 0, 200, 100))
view.backgroundColor = UIColor.lightGrayColor()
centerArray.insert(view, atIndex: i)
}
self.pageCenterView.alignment = .Center
self.pageCenterView.insertSubviews(centerArray)
var leftArray: Array <UIView> = Array()
for var i = 0; i < 10; i++ {
var view: UIView = UIView (frame: CGRectMake(0, 0, 200, 100))
view.backgroundColor = UIColor.lightGrayColor()
leftArray.insert(view, atIndex: i)
}
self.pageLeftView.alignment = .Left
self.pageLeftView.insertSubviews(leftArray)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
b6f90a30cade072f217fa6c01678ddbf
| 27.042857 | 80 | 0.574121 | 4.651659 | false | false | false | false |
onekiloparsec/siesta
|
Source/Request/ProgressTracker.swift
|
2
|
1835
|
//
// ProgressTracker.swift
// Siesta
//
// Created by Paul on 2015/12/15.
// Copyright © 2016 Bust Out Solutions. All rights reserved.
//
import Foundation
internal class ProgressTracker
{
var progress: Double
{ return progressComputation.fractionDone }
var callbacks = CallbackGroup<Double>()
private var networking: RequestNetworking?
private var lastProgressBroadcast: Double?
private var progressComputation: RequestProgressComputation
private var progressUpdateTimer: NSTimer?
init(isGet: Bool)
{
progressComputation = RequestProgressComputation(isGet: isGet)
}
func start(networking: RequestNetworking, reportingInterval: NSTimeInterval)
{
precondition(self.networking == nil, "already started")
self.networking = networking
progressUpdateTimer =
CFRunLoopTimerCreateWithHandler(
kCFAllocatorDefault,
CFAbsoluteTimeGetCurrent(),
reportingInterval, 0, 0)
{ [weak self] _ in self?.updateProgress() }
CFRunLoopAddTimer(CFRunLoopGetCurrent(), progressUpdateTimer, kCFRunLoopCommonModes)
}
deinit
{
progressUpdateTimer?.invalidate()
}
private func updateProgress()
{
guard let networking = networking else
{ return }
progressComputation.update(networking.transferMetrics)
let progress = self.progress
if lastProgressBroadcast != progress
{
lastProgressBroadcast = progress
callbacks.notify(progress)
}
}
func complete()
{
progressUpdateTimer?.invalidate()
progressComputation.complete()
callbacks.notifyOfCompletion(1)
}
}
|
mit
|
1d6ac11b2bbe8c48a87ca773b23be514
| 25.57971 | 92 | 0.630862 | 5.859425 | false | false | false | false |
sohda/auth-swift
|
Source/RicohAPIAuth.swift
|
1
|
9126
|
//
// Copyright (c) 2016 Ricoh Company, Ltd. All Rights Reserved.
// See LICENSE for more information
//
import Foundation
public struct AuthResult {
public var accessToken: String? = nil
}
public struct AuthError {
public let statusCode: Int?
public let message: String?
public func isEmpty() -> Bool {
return (statusCode == nil) && (message == nil)
}
}
public class AuthClient {
let clientId: String?
let clientSecret: String?
var userId = ""
var userPass = ""
var accessToken: String? = nil
var refreshToken: String? = nil
var expire: NSDate? = nil
let expireMargin: Double = -10
public init(clientId: String, clientSecret: String) {
self.clientId = clientId
self.clientSecret = clientSecret
}
public func setResourceOwnerCreds(userId userId: String, userPass: String) {
self.userId = userId
self.userPass = userPass
}
public func session(completionHandler: (AuthResult, AuthError) -> Void) {
token(){(data, resp, err) in
if err != nil {
completionHandler(
AuthResult(accessToken: nil),
AuthError(statusCode: nil, message: "request failed: \(err!.code): \(err!.domain)"))
return
}
let httpresp = resp as! NSHTTPURLResponse
let statusCode = httpresp.statusCode
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
if !httpresp.isSucceeded() {
completionHandler(
AuthResult(accessToken: nil),
AuthError(statusCode: statusCode, message: "received error: \(dataString)"))
return
}
do {
let dataDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
let authToken = dataDictionary["access_token"]!
if authToken != nil {
self.discovery(authToken: authToken as! String, completionHandler: completionHandler)
} else {
completionHandler(
AuthResult(accessToken: nil),
AuthError(statusCode: statusCode, message: "invalid response: \(dataString)"))
}
} catch {
completionHandler(
AuthResult(accessToken: nil),
AuthError(statusCode: statusCode, message: "invalid response: \(dataString)"))
}
}
}
public func getAccessToken(completionHandler: (AuthResult, AuthError) -> Void) -> Void {
if accessToken == nil {
completionHandler(
AuthResult(accessToken: nil),
AuthError(statusCode: nil, message: "wrong usage: use the session method to get an access token."))
return
}
if NSDate().compare(expire!.dateByAddingTimeInterval(expireMargin)) == NSComparisonResult.OrderedAscending {
completionHandler(
AuthResult(accessToken: accessToken!),
AuthError(statusCode: nil, message: nil))
return
}
refresh(completionHandler)
}
func token(completionHandler completionHandler: (NSData?, NSURLResponse?, NSError?) -> Void) -> Void {
RicohAPIAuthRequest.post(
url: "https://auth.beta2.ucs.ricoh.com/auth/token",
header: [
"content-type" : "application/x-www-form-urlencoded"
],
params: [
"client_id" : clientId!,
"client_secret" : clientSecret!,
"username" : userId,
"password" : userPass,
"scope" : "https://ucs.ricoh.com/scope/api/auth https://ucs.ricoh.com/scope/api/discovery https://ucs.ricoh.com/scope/api/udc2",
"grant_type" : "password"
],
completionHandler: completionHandler
)
}
func discovery(authToken authToken: String, completionHandler: (AuthResult, AuthError) -> Void) -> Void {
RicohAPIAuthRequest.post(
url: "https://auth.beta2.ucs.ricoh.com/auth/discovery",
header: [
"content-type" : "application/x-www-form-urlencoded",
"Authorization" : "Bearer \(authToken)"
],
params: [
"scope" : "https://ucs.ricoh.com/scope/api/udc2"
]
){(data, resp, err) in
if err != nil {
completionHandler(
AuthResult(accessToken: nil),
AuthError(statusCode: nil, message: "request failed: \(err!.code): \(err!.domain)"))
return
}
let httpresp = resp as! NSHTTPURLResponse
let statusCode = httpresp.statusCode
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
if !httpresp.isSucceeded() {
completionHandler(
AuthResult(accessToken: nil),
AuthError(statusCode: statusCode, message: "received error: \(dataString)"))
return
}
do {
let dataDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
let udc2Dictionary = dataDictionary["https://ucs.ricoh.com/scope/api/udc2"]!!
let accessToken = udc2Dictionary["access_token"]!
if accessToken != nil {
self.accessToken = (accessToken as! String)
self.expire = NSDate().dateByAddingTimeInterval(Double(udc2Dictionary["expires_in"] as! Int))
self.refreshToken = (udc2Dictionary["refresh_token"] as! String)
completionHandler(
AuthResult(accessToken: (accessToken as! String)),
AuthError(statusCode: nil, message: nil))
} else {
completionHandler(
AuthResult(accessToken: nil),
AuthError(statusCode: statusCode, message: "invalid response: \(dataString)"))
}
} catch {
completionHandler(
AuthResult(accessToken: nil),
AuthError(statusCode: statusCode, message: "invalid response: \(dataString)"))
}
}
}
func refresh(completionHandler: (AuthResult, AuthError) -> Void) -> Void {
RicohAPIAuthRequest.post(
url: "https://auth.beta2.ucs.ricoh.com/auth/token",
header: [
"content-type" : "application/x-www-form-urlencoded"
],
params: [
"client_id" : clientId!,
"client_secret" : clientSecret!,
"refresh_token" : refreshToken!,
"grant_type" : "refresh_token"
]
){(data, resp, err) in
if err != nil {
completionHandler(
AuthResult(accessToken: nil),
AuthError(statusCode: nil, message: "request failed: \(err!.code): \(err!.domain)"))
return
}
let httpresp = resp as! NSHTTPURLResponse
let statusCode = httpresp.statusCode
let dataString = NSString(data: data!, encoding: NSUTF8StringEncoding) as! String
if !httpresp.isSucceeded() {
completionHandler(
AuthResult(accessToken: nil),
AuthError(statusCode: statusCode, message: "received error: \(dataString)"))
return
}
do {
let dataDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.AllowFragments)
let accessToken = dataDictionary["access_token"]!
if accessToken != nil {
self.accessToken = (accessToken as! String)
self.expire = NSDate().dateByAddingTimeInterval(Double(dataDictionary["expires_in"] as! Int))
self.refreshToken = (dataDictionary["refresh_token"] as! String)
completionHandler(
AuthResult(accessToken: (accessToken as! String)),
AuthError(statusCode: nil, message: nil))
} else {
completionHandler(
AuthResult(accessToken: nil),
AuthError(statusCode: statusCode, message: "invalid response: \(dataString)"))
}
} catch {
completionHandler(
AuthResult(accessToken: nil),
AuthError(statusCode: statusCode, message: "invalid response: \(dataString)"))
}
}
}
}
|
mit
|
dc9c0efcf506c431945ebdfb5e28390c
| 40.294118 | 144 | 0.535174 | 5.346221 | false | false | false | false |
Stitch7/Vaporizer
|
App/Models/Form.swift
|
1
|
1697
|
//
// Form.swift
// Vaporizer
//
// Created by Christopher Reitz on 29.10.16.
// Copyright © 2016 Christopher Reitz. All rights reserved.
//
import Vapor
import HTTP
import Fluent
final class Form: Model {
// MARK: - Properties
var id: Node?
var exists = false
var userId: Node
var question1: String
var question2: String
var question3: String
// MARK: - Initializers
init(node: Node, in context: Context) throws {
guard
let question1 = node["question1"]?.string,
let question2 = node["question2"]?.string,
let question3 = node["question3"]?.string
else {
throw TypeSafeRoutingError.missingParameter
}
self.id = try node.extract("id")
self.userId = try node.extract("user_id")
self.question1 = question1
self.question2 = question2
self.question3 = question3
}
}
// MARK: - NodeRepresentable
extension Form {
func makeNode(context: Context) throws -> Node {
return try Node(node: [
"id": id,
"user_id": userId,
"question1": question1,
"question2": question2,
"question3": question3
])
}
}
// MARK: - JSONRepresentable
extension Form {
func makeJSON() throws -> JSON {
return JSON([
"id": id!,
"user": try user().get()?.makeJSON().node ?? nil,
"question1": Node(question1),
"question2": Node(question2),
"question3": Node(question3)
])
}
}
// MARK: - Relations
extension Form {
func user() throws -> Parent<User> {
return try parent(userId)
}
}
|
mit
|
d5434d21d0df5d5d3e284ffbb7f3b490
| 21.025974 | 61 | 0.564269 | 4.067146 | false | false | false | false |
venticake/RetricaImglyKit-iOS
|
RetricaImglyKit/Classes/Frontend/Editor/Tools/CropToolController.swift
|
1
|
30583
|
// This file is part of the PhotoEditor Software Development Kit.
// Copyright (C) 2016 9elements GmbH <[email protected]>
// All rights reserved.
// Redistribution and use in source and binary forms, without
// modification, are permitted provided that the following license agreement
// is approved and a legal/financial contract was signed by the user.
// The license agreement can be found under the following link:
// https://www.photoeditorsdk.com/LICENSE.txt
import UIKit
/**
* A `CropToolController` is reponsible for displaying the UI to crop an image.
*/
@available(iOS 8, *)
@objc(IMGLYCropToolController) public class CropToolController: PhotoEditToolController {
// MARK: - Statics
private static let IconCaptionCollectionViewCellReuseIdentifier = "IconCaptionCollectionViewCellReuseIdentifier"
private static let IconCaptionCollectionViewCellSize = CGSize(width: 64, height: 80)
private static let MinimumCropSize = CGFloat(50)
// MARK: - Properties
private lazy var collectionView: UICollectionView = {
let flowLayout = UICollectionViewFlowLayout()
flowLayout.itemSize = CropToolController.IconCaptionCollectionViewCellSize
flowLayout.scrollDirection = .Horizontal
flowLayout.minimumLineSpacing = 8
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.showsVerticalScrollIndicator = false
collectionView.registerClass(IconCaptionCollectionViewCell.self, forCellWithReuseIdentifier: CropToolController.IconCaptionCollectionViewCellReuseIdentifier)
collectionView.backgroundColor = UIColor.clearColor()
collectionView.delegate = self
collectionView.dataSource = self
return collectionView
}()
private var clipView = UIView()
private let cropRectComponent = InstanceFactory.cropRectComponent()
/// The currently active selection mode.
public var selectionMode: CropRatio?
private var cropRectLeftBound = CGFloat(0)
private var cropRectRightBound = CGFloat(0)
private var cropRectTopBound = CGFloat(0)
private var cropRectBottomBound = CGFloat(0)
private var dragOffset = CGPoint.zero
private var didPresentCropRect = false
// MARK: - UIViewController
/**
:nodoc:
*/
public override func viewDidLoad() {
super.viewDidLoad()
if let firstCropAction = options.allowedCropRatios.first {
selectionMode = firstCropAction
}
collectionView.selectItemAtIndexPath(NSIndexPath(forItem: 0, inSection: 0), animated: false, scrollPosition: .None)
preferredRenderMode = [.AutoEnhancement, .Orientation, .Focus, .PhotoEffect, .ColorAdjustments, .RetricaFilter]
toolStackItem.performChanges {
toolStackItem.mainToolbarView = collectionView
toolStackItem.titleLabel?.text = options.title
if let applyButton = toolStackItem.applyButton {
applyButton.addTarget(self, action: #selector(CropToolController.apply(_:)), forControlEvents: .TouchUpInside)
applyButton.accessibilityLabel = Localize("Apply changes")
options.applyButtonConfigurationClosure?(applyButton)
}
if let discardButton = toolStackItem.discardButton {
discardButton.addTarget(self, action: #selector(CropToolController.discard(_:)), forControlEvents: .TouchUpInside)
discardButton.accessibilityLabel = Localize("Discard changes")
options.discardButtonConfigurationClosure?(discardButton)
}
}
clipView.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.8)
view.addSubview(clipView)
configureCropRect()
}
/**
:nodoc:
*/
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
clipView.alpha = 0
UIView.animateWithDuration(0.25) {
self.delegate?.photoEditToolControllerFrameController(self)?.imageView?.alpha = 0
}
}
/**
:nodoc:
*/
public override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if let previewView = delegate?.photoEditToolControllerPreviewView(self) {
clipView.frame = view.convertRect(previewView.bounds, fromView: previewView).integral
UIView.animateWithDuration(animated ? 0.25 : 0) {
self.clipView.alpha = 1
}
}
reCalculateCropRectBounds()
if !didPresentCropRect {
setCropRectForSelectionRatio()
cropRectComponent.present()
didPresentCropRect = true
} else {
resetCropRectToMatchActiveCropRect()
}
}
/**
:nodoc:
*/
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
UIView.animateWithDuration(0.25) {
self.delegate?.photoEditToolControllerFrameController(self)?.imageView?.alpha = 1
}
}
// MARK: - PhotoEditToolController
/// :nodoc:
public override var preferredDefaultPreviewViewScale: CGFloat {
return 0.9
}
/**
:nodoc:
*/
public override func didBecomeActiveTool() {
super.didBecomeActiveTool()
calculateNewOverlayPlacementWithCropEnabled(false)
options.didEnterToolClosure?()
}
/**
:nodoc:
*/
public override func willResignActiveTool() {
super.willResignActiveTool()
calculateNewOverlayPlacementWithCropEnabled(true)
options.willLeaveToolClosure?()
}
// MARK: - Helpers
private func denormalizePoint(point: CGPoint, inView view: UIView, baseImageSize: CGSize, containerSize: CGSize, normalizedCropRect: CGRect) -> CGPoint {
if normalizedCropRect == IMGLYPhotoEditModel.identityNormalizedCropRect() {
return CGPoint(x: point.x * view.bounds.width, y: point.y * view.bounds.height)
}
let convertedNormalizedCropRect = CGRect(x: normalizedCropRect.origin.x, y: 1 - normalizedCropRect.origin.y - normalizedCropRect.size.height, width: normalizedCropRect.size.width, height: normalizedCropRect.size.height)
let denormalizedCropRect = CGRect(
x: convertedNormalizedCropRect.origin.x * baseImageSize.width,
y: convertedNormalizedCropRect.origin.y * baseImageSize.height,
width: convertedNormalizedCropRect.size.width * baseImageSize.width,
height: convertedNormalizedCropRect.size.height * baseImageSize.height
)
let viewToCroppedImageScale = min(containerSize.width / denormalizedCropRect.width, containerSize.height / denormalizedCropRect.height)
let denormalizedPoint = CGPoint(x: point.x * baseImageSize.width, y: point.y * baseImageSize.height)
let pointInCropRect = CGPoint(x: denormalizedPoint.x - denormalizedCropRect.origin.x, y: denormalizedPoint.y - denormalizedCropRect.origin.y)
return CGPoint(x: pointInCropRect.x * viewToCroppedImageScale, y: pointInCropRect.y * viewToCroppedImageScale)
}
private func calculateNewOverlayPlacementWithCropEnabled(cropEnabled: Bool) {
guard let mainPreviewView = delegate?.photoEditToolControllerPreviewView(self), previewViewScrollingContainer = delegate?.photoEditToolControllerPreviewViewScrollingContainer(self), overlays = delegate?.photoEditToolControllerOverlayViews(self), photoEditRenderer = delegate?.photoEditToolControllerMainRenderer(self) else {
return
}
let cachedRenderMode = photoEditRenderer.renderMode
photoEditRenderer.renderMode = photoEditRenderer.renderMode.subtract(.Crop)
let outputImageSize = photoEditRenderer.outputImageSize
photoEditRenderer.renderMode = cachedRenderMode
let previewBounds = mainPreviewView.bounds
let containerBounds = previewViewScrollingContainer.bounds
let normalizedCropRect = photoEditModel.normalizedCropRect
let convertedNormalizedCropRect = CGRect(
x: normalizedCropRect.origin.x,
y: 1 - normalizedCropRect.origin.y - normalizedCropRect.size.height,
width: normalizedCropRect.size.width,
height: normalizedCropRect.size.height
)
let denormalizedCropRect = CGRect(
x: convertedNormalizedCropRect.origin.x * previewBounds.size.width,
y: convertedNormalizedCropRect.origin.y * previewBounds.size.height,
width: convertedNormalizedCropRect.size.width * previewBounds.size.width,
height: convertedNormalizedCropRect.size.height * previewBounds.size.height
)
let baseScale = min(containerBounds.width / denormalizedCropRect.width, containerBounds.height / denormalizedCropRect.height)
let scale = cropEnabled ? baseScale : 1 / baseScale
for overlay in overlays ?? [] {
overlay.transform = CGAffineTransformScale(overlay.transform, scale, scale)
if let stickerImageView = overlay as? StickerImageView {
stickerImageView.center = denormalizePoint(stickerImageView.normalizedCenterInImage, inView: mainPreviewView, baseImageSize: outputImageSize, containerSize: containerBounds.size, normalizedCropRect: cropEnabled ? normalizedCropRect : IMGLYPhotoEditModel.identityNormalizedCropRect())
} else if let textLabel = overlay as? TextLabel {
textLabel.center = denormalizePoint(textLabel.normalizedCenterInImage, inView: mainPreviewView, baseImageSize: outputImageSize, containerSize: containerBounds.size, normalizedCropRect: cropEnabled ? normalizedCropRect : IMGLYPhotoEditModel.identityNormalizedCropRect())
}
}
}
private func configureCropRect() {
cropRectComponent.cropRect = photoEditModel.normalizedCropRect
cropRectComponent.setup(clipView, parentView: view, showAnchors: true)
addGestureRecognizerToTransparentView()
addGestureRecognizerToAnchors()
}
// MARK: - Actions
@objc private func apply(sender: UIButton) {
photoEditModel.normalizedCropRect = normalizedCropRect()
if let frameController = delegate?.photoEditToolControllerFrameController(self), indexPath = collectionView.indexPathsForSelectedItems()?.last {
let cropRatio = options.allowedCropRatios[indexPath.item]
frameController.unlock()
frameController.imageRatio = Float(cropRatio.ratio ?? (cropRectComponent.cropRect.size.width / cropRectComponent.cropRect.size.height))
}
delegate?.photoEditToolControllerDidFinish(self)
}
@objc private func discard(sender: UIButton) {
delegate?.photoEditToolController(self, didDiscardChangesInFavorOfPhotoEditModel: uneditedPhotoEditModel)
}
// MARK: - Helpers
private var options: CropToolControllerOptions {
return self.configuration.cropToolControllerOptions
}
// MARK: - Crop Rect Related Methods
private func addGestureRecognizerToTransparentView() {
clipView.userInteractionEnabled = true
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(CropToolController.handlePan(_:)))
clipView.addGestureRecognizer(panGestureRecognizer)
}
private func addGestureRecognizerToAnchors() {
addGestureRecognizerToAnchor(cropRectComponent.topLeftAnchor!)
addGestureRecognizerToAnchor(cropRectComponent.topRightAnchor!)
addGestureRecognizerToAnchor(cropRectComponent.bottomRightAnchor!)
addGestureRecognizerToAnchor(cropRectComponent.bottomLeftAnchor!)
}
private func addGestureRecognizerToAnchor(anchor: UIImageView) {
anchor.userInteractionEnabled = true
let panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(CropToolController.handlePan(_:)))
anchor.addGestureRecognizer(panGestureRecognizer)
}
@objc private func handlePan(recognizer: UIPanGestureRecognizer) {
if recognizer.view!.isEqual(cropRectComponent.topRightAnchor) {
handlePanOnTopRight(recognizer)
} else if recognizer.view!.isEqual(cropRectComponent.topLeftAnchor) {
handlePanOnTopLeft(recognizer)
} else if recognizer.view!.isEqual(cropRectComponent.bottomLeftAnchor) {
handlePanOnBottomLeft(recognizer)
} else if recognizer.view!.isEqual(cropRectComponent.bottomRightAnchor) {
handlePanOnBottomRight(recognizer)
} else if recognizer.view!.isEqual(clipView) {
handlePanOnTransparentView(recognizer)
}
UIAccessibilityPostNotification(UIAccessibilityLayoutChangedNotification, nil)
}
@objc private func handlePanOnTopLeft(recognizer: UIPanGestureRecognizer) {
let location = recognizer.locationInView(clipView)
var sizeX = cropRectComponent.bottomRightAnchor!.center.x - location.x
var sizeY = cropRectComponent.bottomRightAnchor!.center.y - location.y
sizeX = CGFloat(Int(sizeX))
sizeY = CGFloat(Int(sizeY))
var size = CGSize(width: sizeX, height: sizeY)
size = applyMinimumAreaRuleToSize(size)
size = reCalulateSizeForTopLeftAnchor(size)
var center = cropRectComponent.topLeftAnchor!.center
center.x += (cropRectComponent.cropRect.size.width - size.width)
center.y += (cropRectComponent.cropRect.size.height - size.height)
cropRectComponent.topLeftAnchor!.center = center
recalculateCropRectFromTopLeftAnchor()
cropRectComponent.layoutViewsForCropRect()
}
private func reCalulateSizeForTopLeftAnchor(size: CGSize) -> CGSize {
var newSize = size
if let selectionRatio = selectionMode?.ratio {
newSize.height = newSize.height * CGFloat(selectionRatio)
if newSize.height > newSize.width {
newSize.width = newSize.height
}
newSize.height = newSize.width / CGFloat(selectionRatio)
if (cropRectComponent.bottomRightAnchor!.center.x - newSize.width) < cropRectLeftBound {
newSize.width = cropRectComponent.bottomRightAnchor!.center.x - cropRectLeftBound
newSize.height = newSize.width / CGFloat(selectionRatio)
}
if (cropRectComponent.bottomRightAnchor!.center.y - newSize.height) < cropRectTopBound {
newSize.height = cropRectComponent.bottomRightAnchor!.center.y - cropRectTopBound
newSize.width = newSize.height * CGFloat(selectionRatio)
}
} else {
if (cropRectComponent.bottomRightAnchor!.center.x - newSize.width) < cropRectLeftBound {
newSize.width = cropRectComponent.bottomRightAnchor!.center.x - cropRectLeftBound
}
if (cropRectComponent.bottomRightAnchor!.center.y - newSize.height) < cropRectTopBound {
newSize.height = cropRectComponent.bottomRightAnchor!.center.y - cropRectTopBound
}
}
return newSize
}
private func recalculateCropRectFromTopLeftAnchor() {
cropRectComponent.cropRect = CGRect(x: cropRectComponent.topLeftAnchor!.center.x,
y: cropRectComponent.topLeftAnchor!.center.y,
width: cropRectComponent.bottomRightAnchor!.center.x - cropRectComponent.topLeftAnchor!.center.x,
height: cropRectComponent.bottomRightAnchor!.center.y - cropRectComponent.topLeftAnchor!.center.y)
}
private func handlePanOnTopRight(recognizer: UIPanGestureRecognizer) {
let location = recognizer.locationInView(clipView)
var sizeX = cropRectComponent.bottomLeftAnchor!.center.x - location.x
var sizeY = cropRectComponent.bottomLeftAnchor!.center.y - location.y
sizeX = CGFloat(abs(Int(sizeX)))
sizeY = CGFloat(abs(Int(sizeY)))
var size = CGSize(width: sizeX, height: sizeY)
size = applyMinimumAreaRuleToSize(size)
size = reCalulateSizeForTopRightAnchor(size)
var center = cropRectComponent.topRightAnchor!.center
center.x = (cropRectComponent.bottomLeftAnchor!.center.x + size.width)
center.y = (cropRectComponent.bottomLeftAnchor!.center.y - size.height)
cropRectComponent.topRightAnchor!.center = center
recalculateCropRectFromTopRightAnchor()
cropRectComponent.layoutViewsForCropRect()
}
private func reCalulateSizeForTopRightAnchor(size: CGSize) -> CGSize {
var newSize = size
if let selectionRatio = selectionMode?.ratio {
newSize.height = newSize.height * CGFloat(selectionRatio)
if newSize.height > newSize.width {
newSize.width = newSize.height
}
if (cropRectComponent.topLeftAnchor!.center.x + newSize.width) > cropRectRightBound {
newSize.width = cropRectRightBound - cropRectComponent.topLeftAnchor!.center.x
}
newSize.height = newSize.width / CGFloat(selectionRatio)
if (cropRectComponent.bottomRightAnchor!.center.y - newSize.height) < cropRectTopBound {
newSize.height = cropRectComponent.bottomRightAnchor!.center.y - cropRectTopBound
newSize.width = newSize.height * CGFloat(selectionRatio)
}
} else {
if (cropRectComponent.topLeftAnchor!.center.x + newSize.width) > cropRectRightBound {
newSize.width = cropRectRightBound - cropRectComponent.topLeftAnchor!.center.x
}
if (cropRectComponent.bottomRightAnchor!.center.y - newSize.height) < cropRectTopBound {
newSize.height = cropRectComponent.bottomRightAnchor!.center.y - cropRectTopBound
}
}
return newSize
}
private func recalculateCropRectFromTopRightAnchor() {
cropRectComponent.cropRect = CGRect(x: cropRectComponent.bottomLeftAnchor!.center.x,
y: cropRectComponent.topRightAnchor!.center.y,
width: cropRectComponent.topRightAnchor!.center.x - cropRectComponent.bottomLeftAnchor!.center.x,
height: cropRectComponent.bottomLeftAnchor!.center.y - cropRectComponent.topRightAnchor!.center.y)
}
private func handlePanOnBottomLeft(recognizer: UIPanGestureRecognizer) {
let location = recognizer.locationInView(clipView)
var sizeX = cropRectComponent.topRightAnchor!.center.x - location.x
var sizeY = cropRectComponent.topRightAnchor!.center.y - location.y
sizeX = CGFloat(abs(Int(sizeX)))
sizeY = CGFloat(abs(Int(sizeY)))
var size = CGSize(width: sizeX, height: sizeY)
size = applyMinimumAreaRuleToSize(size)
size = reCalulateSizeForBottomLeftAnchor(size)
var center = cropRectComponent.bottomLeftAnchor!.center
center.x = (cropRectComponent.topRightAnchor!.center.x - size.width)
center.y = (cropRectComponent.topRightAnchor!.center.y + size.height)
cropRectComponent.bottomLeftAnchor!.center = center
recalculateCropRectFromTopRightAnchor()
cropRectComponent.layoutViewsForCropRect()
}
private func reCalulateSizeForBottomLeftAnchor(size: CGSize) -> CGSize {
var newSize = size
if let selectionRatio = selectionMode?.ratio {
newSize.height = newSize.height * CGFloat(selectionRatio)
if newSize.height > newSize.width {
newSize.width = newSize.height
}
newSize.height = newSize.width / CGFloat(selectionRatio)
if (cropRectComponent.topRightAnchor!.center.x - newSize.width) < cropRectLeftBound {
newSize.width = cropRectComponent.topRightAnchor!.center.x - cropRectLeftBound
newSize.height = newSize.width / CGFloat(selectionRatio)
}
if (cropRectComponent.topRightAnchor!.center.y + newSize.height) > cropRectBottomBound {
newSize.height = cropRectBottomBound - cropRectComponent.topRightAnchor!.center.y
newSize.width = newSize.height * CGFloat(selectionRatio)
}
} else {
if (cropRectComponent.topRightAnchor!.center.x - newSize.width) < cropRectLeftBound {
newSize.width = cropRectComponent.topRightAnchor!.center.x - cropRectLeftBound
}
if (cropRectComponent.topRightAnchor!.center.y + newSize.height) > cropRectBottomBound {
newSize.height = cropRectBottomBound - cropRectComponent.topRightAnchor!.center.y
}
}
return newSize
}
private func handlePanOnBottomRight(recognizer: UIPanGestureRecognizer) {
let location = recognizer.locationInView(clipView)
var sizeX = cropRectComponent.topLeftAnchor!.center.x - location.x
var sizeY = cropRectComponent.topLeftAnchor!.center.y - location.y
sizeX = CGFloat(abs(Int(sizeX)))
sizeY = CGFloat(abs(Int(sizeY)))
var size = CGSize(width: sizeX, height: sizeY)
size = applyMinimumAreaRuleToSize(size)
size = reCalulateSizeForBottomRightAnchor(size)
var center = cropRectComponent.bottomRightAnchor!.center
center.x -= (cropRectComponent.cropRect.size.width - size.width)
center.y -= (cropRectComponent.cropRect.size.height - size.height)
cropRectComponent.bottomRightAnchor!.center = center
recalculateCropRectFromTopLeftAnchor()
cropRectComponent.layoutViewsForCropRect()
}
private func reCalulateSizeForBottomRightAnchor(size: CGSize) -> CGSize {
var newSize = size
if let selectionRatio = selectionMode?.ratio {
newSize.height = newSize.height * CGFloat(selectionRatio)
if newSize.height > newSize.width {
newSize.width = newSize.height
}
if (cropRectComponent.topLeftAnchor!.center.x + newSize.width) > cropRectRightBound {
newSize.width = cropRectRightBound - cropRectComponent.topLeftAnchor!.center.x
}
newSize.height = newSize.width / CGFloat(selectionRatio)
if (cropRectComponent.topLeftAnchor!.center.y + newSize.height) > cropRectBottomBound {
newSize.height = cropRectBottomBound - cropRectComponent.topLeftAnchor!.center.y
newSize.width = newSize.height * CGFloat(selectionRatio)
}
} else {
if (cropRectComponent.topLeftAnchor!.center.x + newSize.width) > cropRectRightBound {
newSize.width = cropRectRightBound - cropRectComponent.topLeftAnchor!.center.x
}
if (cropRectComponent.topLeftAnchor!.center.y + newSize.height) > cropRectBottomBound {
newSize.height = cropRectBottomBound - cropRectComponent.topLeftAnchor!.center.y
}
}
return newSize
}
private func handlePanOnTransparentView(recognizer: UIPanGestureRecognizer) {
let location = recognizer.locationInView(clipView)
if cropRectComponent.cropRect.contains(location) {
calculateDragOffsetOnNewDrag(recognizer:recognizer)
let newLocation = clampedLocationToBounds(location)
var rect = cropRectComponent.cropRect
rect.origin.x = newLocation.x - dragOffset.x
rect.origin.y = newLocation.y - dragOffset.y
cropRectComponent.cropRect = rect
cropRectComponent.layoutViewsForCropRect()
}
}
private func calculateDragOffsetOnNewDrag(recognizer recognizer: UIPanGestureRecognizer) {
let location = recognizer.locationInView(clipView)
if recognizer.state == UIGestureRecognizerState.Began {
dragOffset = CGPoint(x: location.x - cropRectComponent.cropRect.origin.x, y: location.y - cropRectComponent.cropRect.origin.y)
}
}
private func clampedLocationToBounds(location: CGPoint) -> CGPoint {
let rect = cropRectComponent.cropRect
var locationX = location.x
var locationY = location.y
let left = locationX - dragOffset.x
let right = left + rect.size.width
let top = locationY - dragOffset.y
let bottom = top + rect.size.height
if left < cropRectLeftBound {
locationX = cropRectLeftBound + dragOffset.x
}
if right > cropRectRightBound {
locationX = cropRectRightBound - cropRectComponent.cropRect.size.width + dragOffset.x
}
if top < cropRectTopBound {
locationY = cropRectTopBound + dragOffset.y
}
if bottom > cropRectBottomBound {
locationY = cropRectBottomBound - cropRectComponent.cropRect.size.height + dragOffset.y
}
return CGPoint(x: locationX, y: locationY)
}
private func normalizedCropRect() -> CGRect {
reCalculateCropRectBounds()
let boundWidth = cropRectRightBound - cropRectLeftBound
let boundHeight = cropRectBottomBound - cropRectTopBound
let x = (cropRectComponent.cropRect.origin.x - cropRectLeftBound) / boundWidth
let y = (cropRectComponent.cropRect.origin.y - cropRectTopBound) / boundHeight
let normalizedRect = CGRect(x: x, y: 1 - y - cropRectComponent.cropRect.size.height / boundHeight, width: cropRectComponent.cropRect.size.width / boundWidth, height: cropRectComponent.cropRect.size.height / boundHeight)
return normalizedRect
}
private func reCalculateCropRectBounds() {
let width = clipView.frame.size.width
let height = clipView.frame.size.height
cropRectLeftBound = (width - clipView.bounds.width) / 2.0
cropRectRightBound = width - cropRectLeftBound
cropRectTopBound = (height - clipView.bounds.height) / 2.0
cropRectBottomBound = height - cropRectTopBound
}
private func applyMinimumAreaRuleToSize(size: CGSize) -> CGSize {
var newSize = size
if newSize.width < CropToolController.MinimumCropSize {
newSize.width = CropToolController.MinimumCropSize
}
if newSize.height < CropToolController.MinimumCropSize {
newSize.height = CropToolController.MinimumCropSize
}
return newSize
}
private func setCropRectForSelectionRatio() {
let size = CGSize(width: cropRectRightBound - cropRectLeftBound,
height: cropRectBottomBound - cropRectTopBound)
var rectWidth = size.width
var rectHeight = rectWidth
if size.width > size.height {
rectHeight = size.height
rectWidth = rectHeight
}
let selectionRatio = selectionMode?.ratio ?? 1
if selectionRatio >= 1 {
rectHeight /= CGFloat(selectionRatio)
} else {
rectWidth *= CGFloat(selectionRatio)
}
let sizeDeltaX = (size.width - rectWidth) / 2.0
let sizeDeltaY = (size.height - rectHeight) / 2.0
cropRectComponent.cropRect = CGRect(
x: cropRectLeftBound + sizeDeltaX,
y: cropRectTopBound + sizeDeltaY,
width: rectWidth,
height: rectHeight)
}
private func resetCropRectToMatchActiveCropRect() {
var cropRect = photoEditModel.normalizedCropRect
cropRect = CGRect(x: cropRect.origin.x, y: 1 - cropRect.origin.y - cropRect.height, width: cropRect.width, height: cropRect.height)
cropRect = CGRect(x: cropRect.origin.x * clipView.bounds.width, y: cropRect.origin.y * clipView.bounds.height, width: cropRect.width * clipView.bounds.width, height: cropRect.height * clipView.bounds.height)
cropRectComponent.cropRect = cropRect
cropRectComponent.layoutViewsForCropRect()
}
private func updateCropRectForSelectionMode() {
if let _ = selectionMode?.ratio {
setCropRectForSelectionRatio()
cropRectComponent.layoutViewsForCropRect()
}
}
}
@available(iOS 8, *)
extension CropToolController: UICollectionViewDelegate {
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let cropRatio = options.allowedCropRatios[indexPath.item]
options.cropRatioSelectedClosure?(cropRatio)
selectionMode = cropRatio
updateCropRectForSelectionMode()
}
}
@available(iOS 8, *)
extension CropToolController: UICollectionViewDataSource {
/**
:nodoc:
*/
public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return options.allowedCropRatios.count
}
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CropToolController.IconCaptionCollectionViewCellReuseIdentifier, forIndexPath: indexPath)
if let iconCaptionCell = cell as? IconCaptionCollectionViewCell {
let cropRatio = options.allowedCropRatios[indexPath.item]
iconCaptionCell.imageView.image = cropRatio.icon
iconCaptionCell.captionLabel.text = cropRatio.title
iconCaptionCell.accessibilityLabel = cropRatio.accessibilityLabel
options.cropRatioButtonConfigurationClosure?(iconCaptionCell, cropRatio)
}
return cell
}
}
@available(iOS 8, *)
extension CropToolController: UICollectionViewDelegateFlowLayout {
/**
:nodoc:
*/
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
guard let flowLayout = collectionViewLayout as? UICollectionViewFlowLayout else {
return UIEdgeInsetsZero
}
let cellSpacing = flowLayout.minimumLineSpacing
let cellWidth = flowLayout.itemSize.width
let cellCount = collectionView.numberOfItemsInSection(section)
let inset = max((collectionView.bounds.width - (CGFloat(cellCount) * (cellWidth + cellSpacing))) * 0.5, 0)
return UIEdgeInsets(top: 0, left: inset, bottom: 0, right: 0)
}
}
|
mit
|
7469919d9ac507dca2e6c030e55fdaa4
| 43.195087 | 332 | 0.692084 | 5.078545 | false | false | false | false |
koutalou/iOS-CleanArchitecture
|
iOSCleanArchitectureTwitterSample/Data/Network/RestSLRequest.swift
|
1
|
2791
|
//
// RestSLRequest.swift
// iOSCleanArchitectureTwitterSample
//
// Created by Kodama.Kotaro on 2015/12/21.
// Copyright © 2015年 koutalou. All rights reserved.
//
import Foundation
import Accounts
import Social
import RxSwift
import ObjectMapper
import RealmSwift
struct Context: MapContext {
}
struct RestSLRequest {
func getUserTimeline(_ account: ACAccount, screenName: String) -> Observable<[TimelineEntity]> {
let url: String = "https://api.twitter.com/1.1/statuses/user_timeline.json"
let request: SLRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.GET, url: URL(string: url), parameters: ["screen_name": screenName])
request.account = account
return fetchTimelines(request)
}
func getHomeTimeline(_ account: ACAccount) -> Observable<[TimelineEntity]> {
// let realm = try! Realm()
// let preloadRowTimelineModels: Array<TimelineEntity>? = realm.objects(TimelineEntity) as? Array<TimelineEntity>
// if (preloadRowTimelineModels != nil && preloadRowTimelineModels!.count > 0) {
// callback(preloadRowTimelineModels, AppError.noError)
// }
let url: String = "https://api.twitter.com/1.1/statuses/home_timeline.json"
let request: SLRequest = SLRequest(forServiceType: SLServiceTypeTwitter, requestMethod: SLRequestMethod.GET, url: URL(string: url), parameters: nil)
request.account = account
return fetchTimelines(request)
}
func fetchTimelines(_ request: SLRequest) -> Observable<[TimelineEntity]> {
return Observable.create({ (observer) -> Disposable in
request.perform(handler: { (responseData, urlResponse, error) in
guard
let responseData = responseData,
let optionalJsonResponse = try? JSONSerialization.jsonObject(with: responseData,
options: JSONSerialization.ReadingOptions.mutableContainers) as? Array<[String: Any]>,
let jsonResponse = optionalJsonResponse else {
observer.onError(AppError.generic)
return
}
let context = Context()
let mapper = Mapper<TimelineEntity>(context: context)
guard let rowTimelines = mapper.mapArray(JSONArray: jsonResponse) else {
observer.onError(AppError.generic)
return
}
observer.onNext(rowTimelines)
observer.onCompleted()
})
return Disposables.create()
})
}
}
|
mit
|
d48820fbd28fbcf4d925c0c8e7605992
| 38.267606 | 180 | 0.605811 | 5.125 | false | false | false | false |
RevenueCat/purchases-ios
|
Sources/Attribution/AfficheClientProxy.swift
|
1
|
2631
|
//
// Copyright RevenueCat Inc. All Rights Reserved.
//
// Licensed under the MIT License (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://opensource.org/licenses/MIT
//
// AfficheClientProxy.swift
//
// Created by Juanpe Catalán on 14/7/21.
//
import Foundation
typealias AttributionDetailsBlock = ([String: NSObject]?, Error?) -> Void
// We need this class to avoid Kid apps being rejected for getting idfa. It seems like App
// Review uses some grep to find the class names, so we ended up creating a fake class that
// exposes the same methods we're looking for in ADClient to call the same methods and mangling
// the class names. So that Apple can't find them during the review, but we can still access them on runtime.
// You can see the class here: https://rev.cat/fake-affiche-client
class FakeAfficheClient: NSObject {
// We need this method to be available as an optional implicitly unwrapped method for `AnyClass`.
@objc static func sharedClient() -> FakeAfficheClient {
FakeAfficheClient()
}
// We need this method to be available as an optional implicitly unwrapped method for `AnyClass`.
@objc(requestAttributionDetailsWithBlock:)
func requestAttributionDetails(_ completionHandler: @escaping AttributionDetailsBlock) {
Logger.warn(Strings.attribution.apple_affiche_framework_present_but_couldnt_call_request_attribution_details)
}
}
class AfficheClientProxy {
private static let mangledClassName = "NQPyvrag"
static var afficheClientClass: AnyClass? {
NSClassFromString(Self.mangledClassName.rot13())
}
func requestAttributionDetails(_ completionHandler: @escaping AttributionDetailsBlock) {
let client: AnyObject
if let klass = Self.afficheClientClass, let clientClass = klass as AnyObject as? NSObjectProtocol {
// This looks strange, but #selector() does fun things to create a selector. If the selector for the given
// function matches the selector on another class, it can be used in place. Results:
// If ADClient class is instantiated above, then +sharedClient selector is performed even though you can see
// that we're using #selector(FakeAfficheClient.sharedClient) to instantiate a Selector object.
client = clientClass.perform(#selector(FakeAfficheClient.sharedClient)).takeUnretainedValue()
} else {
client = FakeAfficheClient.sharedClient()
}
client.requestAttributionDetails(completionHandler)
}
}
|
mit
|
91888309906ef68afad26a06c758d7af
| 41.419355 | 120 | 0.724715 | 4.442568 | false | false | false | false |
apple/swift-syntax
|
Examples/AddOneToIntegerLiterals.swift
|
1
|
1382
|
import SwiftSyntax
import SwiftParser
import Foundation
/// AddOneToIntegerLiterals will visit each token in the Syntax tree, and
/// (if it is an integer literal token) add 1 to the integer and return the
/// new integer literal token.
///
/// For example, it will turn
/// ```
/// let x = 2
/// let y = 3_000
/// ```
/// into
/// ```
/// let x = 3
/// let y = 3001
/// ```
///
private class AddOneToIntegerLiterals: SyntaxRewriter {
override func visit(_ token: TokenSyntax) -> TokenSyntax {
// Only transform integer literals.
guard case .integerLiteral(let text) = token.tokenKind else {
return token
}
// Remove underscores from the original text.
let integerText = String(text.filter { ("0"..."9").contains($0) })
// Parse out the integer.
let int = Int(integerText)!
// Create a new integer literal token with `int + 1` as its text.
let newIntegerLiteralToken = token.withKind(.integerLiteral("\(int + 1)"))
// Return the new integer literal.
return newIntegerLiteralToken
}
}
@main
struct Main {
static func main() throws {
let file = CommandLine.arguments[1]
let url = URL(fileURLWithPath: file)
let source = try String(contentsOf: url, encoding: .utf8)
let sourceFile = Parser.parse(source: source)
let incremented = AddOneToIntegerLiterals().visit(sourceFile)
print(incremented)
}
}
|
apache-2.0
|
4e99b1ab394f49f73da580d6a0575a62
| 26.098039 | 78 | 0.668596 | 4.064706 | false | false | false | false |
wscqs/FMDemo-
|
FMDemo/Classes/Model/GetMaterialsData.swift
|
1
|
1734
|
//
// Data.swift
//
// Created by mba on 17/2/23
// Copyright (c) . All rights reserved.
//
import Foundation
import ObjectMapper
public class GetMaterialsData: Mappable {
// MARK: Declaration for string constants to be used to decode and also serialize.
private let kDataTimeKey: String = "time"
private let kDataMidKey: String = "mid"
private let kDataTitleKey: String = "title"
private let kDataStateKey: String = "state"
private let kDataURLKey: String = "url"
// MARK: Properties
public var time: String?
public var mid: String?
public var title: String?
public var state: String?
public var url: String?
// MARK: ObjectMapper Initalizers
/**
Map a JSON object to this class using ObjectMapper
- parameter map: A mapping from ObjectMapper
*/
required public init?(map: Map){
}
/**
Map a JSON object to this class using ObjectMapper
- parameter map: A mapping from ObjectMapper
*/
public func mapping(map: Map) {
time <- map[kDataTimeKey]
mid <- map[kDataMidKey]
title <- map[kDataTitleKey]
state <- map[kDataStateKey]
url <- map[kDataURLKey]
}
/**
Generates description of the object in the form of a NSDictionary.
- returns: A Key value pair containing all valid values in the object.
*/
public func dictionaryRepresentation() -> [String: Any] {
var dictionary: [String: Any] = [:]
if let value = time { dictionary[kDataTimeKey] = value }
if let value = mid { dictionary[kDataMidKey] = value }
if let value = title { dictionary[kDataTitleKey] = value }
if let value = state { dictionary[kDataStateKey] = value }
if let value = url { dictionary[kDataURLKey] = value }
return dictionary
}
}
|
apache-2.0
|
924477b12d45f9cce5609f309a605a39
| 26.967742 | 84 | 0.679931 | 3.949886 | false | false | false | false |
sseitov/WD-Content
|
WD Content TV/ShareCell.swift
|
1
|
1600
|
//
// ShareCell.swift
// WD Content
//
// Created by Сергей Сейтов on 29.12.16.
// Copyright © 2016 Sergey Seitov. All rights reserved.
//
import UIKit
class ShareCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var textView: UILabel!
@IBOutlet weak var textConstraint: NSLayoutConstraint!
var node:Node? {
didSet {
if node!.isFile {
if node!.info == nil {
textView.text = node!.name!
imageView.image = UIImage(named: "movie")
} else {
textView.text = node!.info!.title!
if node!.info!.poster != nil {
let url = URL(string: node!.info!.poster!)
imageView.sd_setImage(with: url, placeholderImage: UIImage(named: "movie"))
} else {
imageView.image = UIImage(named: "movie")
}
}
} else {
textView.text = node!.name!
imageView.image = UIImage(named: "sharedFolder")
}
}
}
override func awakeFromNib() {
super.awakeFromNib()
imageView.adjustsImageWhenAncestorFocused = false
imageView.clipsToBounds = false
textView.clipsToBounds = false
textView.alpha = 0.3
}
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
coordinator.addCoordinatedAnimations({
if self.isFocused {
self.textView.alpha = 1.0
self.textConstraint.constant = -40
self.imageView.adjustsImageWhenAncestorFocused = true
}
else {
self.textView.alpha = 0.3
self.textConstraint.constant = 0
self.imageView.adjustsImageWhenAncestorFocused = false
}
}, completion: nil)
}
}
|
gpl-2.0
|
c50fc36949f2cefb03aceb597be0ba38
| 24.190476 | 112 | 0.68368 | 3.582393 | false | false | false | false |
roambotics/swift
|
test/SILOptimizer/Inputs/specialize_opaque_type_archetypes_3.swift
|
2
|
1543
|
public protocol ExternalP2 {
func myValue3() -> Int64
}
extension Int64 : ExternalP2 {
public func myValue3() -> Int64 {
return self + 3
}
}
public func externalResilient() -> some ExternalP2 {
return Int64(6)
}
@inlinable
@inline(never)
public func inlinableExternalResilient() -> some ExternalP2 {
return Int64(6)
}
public struct ResilientContainer {
@usableFromInline
var x = Int64(0)
public init() {}
public var computedProperty : some ExternalP2 {
return x
}
@inlinable
@inline(never)
public var inlineableProperty : some ExternalP2 {
return x
}
@_alwaysEmitIntoClient
@inline(never)
public var inlineableProperty2 : some ExternalP2 {
return x
}
@inlinable
public func inlineableContext() {
let x = computedProperty
print(x)
}
@inlinable
@_eagerMove
@_specialize(where T == Int)
public func genericEagerMoveInlineableContext<T>(_ t: T) {
let x = computedProperty
print(x)
print(t)
}
@inlinable
@_eagerMove
public func eagerMoveInlineableContext() {
let x = computedProperty
print(x)
}
}
public struct WrapperP2<Wrapped: ExternalP2>: ExternalP2 {
public init(_ wrapped: Wrapped) {}
public func myValue3() -> Int64 { 0 }
}
public func externalResilientWrapper<Wrapped: ExternalP2>(_ wrapped: Wrapped) -> some ExternalP2 {
return WrapperP2(wrapped)
}
@inlinable
@inline(never)
public func inlinableExternalResilientWrapper<Wrapped: ExternalP2>(_ wrapped: Wrapped) -> some ExternalP2 {
return WrapperP2(wrapped)
}
|
apache-2.0
|
dd4995d1e2464ef805ab81dc4583220a
| 18.049383 | 107 | 0.698639 | 3.946292 | false | false | false | false |
Weebly/Cereal
|
Example/EditCarViewController.swift
|
2
|
1628
|
//
// EditCarViewController.swift
// Cereal
//
// Created by James Richard on 9/30/15.
// Copyright © 2015 Weebly. All rights reserved.
//
import UIKit
protocol EditCarViewControllerDelegate: class {
func editCarViewController(_ editCarViewController: EditCarViewController, didSaveCar car: Car)
}
class EditCarViewController: UIViewController {
var car: Car!
weak var delegate: EditCarViewControllerDelegate?
@IBOutlet var makeTextField: UITextField!
@IBOutlet var modelTextField: UITextField!
@IBOutlet var cylindersLabel: UILabel!
@IBOutlet var stepperView: UIStepper!
override func viewDidLoad() {
super.viewDidLoad()
makeTextField.text = car.make
modelTextField.text = car.model
cylindersLabel.text = String(car.cylinders)
stepperView.value = Double(car.cylinders)
}
@IBAction func savePressed() {
delegate?.editCarViewController(self, didSaveCar: car)
performSegue(withIdentifier: "UnwindToVehicleList", sender: self)
}
@IBAction func textValueChanged(_ textField: UITextField) {
switch textField {
case makeTextField: car = Car(make: textField.text ?? "", model: car.model, cylinders: car.cylinders)
case modelTextField: car = Car(make: car.make, model: textField.text ?? "", cylinders: car.cylinders)
default: break
}
}
@IBAction func cylindersStepperChanged(_ stepper: UIStepper) {
let cylinders = Int(stepper.value)
car = Car(make: car.make, model: car.model, cylinders: cylinders)
cylindersLabel.text = String(cylinders)
}
}
|
bsd-3-clause
|
410990150fdfcd280068f89f8d1bdc6e
| 32.204082 | 109 | 0.692071 | 4.182519 | false | false | false | false |
IAskWind/IAWExtensionTool
|
IAWExtensionTool/IAWExtensionTool/Classes/Tool/IAW_PhotoTool.swift
|
1
|
3337
|
//
// IAW_ImageTool.swift
// IAWExtensionTool
//
// Created by winston on 17/1/5.
// Copyright © 2017年 winston. All rights reserved.
//
import Foundation
import SKPhotoBrowser
open class IAW_PhotoTool{
/**
*利用 https://github.com/suzuki-0000/SKPhotoBrowser 做个简单的图片预览工具
*any的类型可以 UIImage、[UIImage]、
*/
open class func show(_ target: UIViewController,any:Any){
weak var weakSelf = target
var images = [SKPhoto]()
if let photoImg = any as? UIImage{
let photo = SKPhoto.photoWithImage(photoImg)// add some UIImage
images.append(photo)
}else if let photoStr = any as? String{
let photo = SKPhoto.photoWithImageURL(photoStr)
photo.shouldCachePhotoURLImage = true // you can use image cache by true(NSCache)
images.append(photo)
}else if let photoImgs = any as? [UIImage]{
for photoImg in photoImgs{
let photo = SKPhoto.photoWithImage(photoImg)// add some UIImage
images.append(photo)
}
}else if let photoStrs = any as? [String]{
for photoStr in photoStrs{
let photo = SKPhoto.photoWithImageURL(photoStr)// add some UIImage
images.append(photo)
}
}else{
print("传入类型错误")
}
// 2. create PhotoBrowser Instance, and present from your viewController.
SKPhotoBrowserOptions.displayStatusbar = false
let browser = SKPhotoBrowser(photos: images)
browser.initializePageIndex(0)
weakSelf?.present(browser, animated: true, completion: {})
}
/**
*调用相册拍照功能的弹出框
*/
open class func showPhotoSheet<T: UIViewController>(_ target:T) where T: UIImagePickerControllerDelegate,T:UINavigationControllerDelegate{
weak var weakSelf = target
let actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
let cameraAction = UIAlertAction(title: "拍照", style: .default) { action in
self.showCamera(weakSelf!)
}
actionSheet.addAction(cameraAction)
let albumAction = UIAlertAction(title: "从相册选择", style: .default) { action in
self.openPhotoAlbum(weakSelf!)
}
actionSheet.addAction(albumAction)
let cancelAction = UIAlertAction(title: "取消", style: .cancel) { action in }
actionSheet.addAction(cancelAction)
weakSelf?.present(actionSheet, animated: true, completion: nil)
}
open class func showCamera<T: UIViewController>(_ target:T) where T: UIImagePickerControllerDelegate,T:UINavigationControllerDelegate{
let controller = UIImagePickerController()
controller.delegate = target
controller.sourceType = .camera
target.present(controller, animated: true, completion: nil)
}
open class func openPhotoAlbum<T: UIViewController>(_ target:T) where T: UIImagePickerControllerDelegate,T:UINavigationControllerDelegate {
let controller = UIImagePickerController()
controller.delegate = target
controller.sourceType = .photoLibrary
target.present(controller, animated: true, completion: nil)
}
}
|
mit
|
5bc95c18db75330dab72a35f598dbf4e
| 39.5 | 143 | 0.650309 | 4.695652 | false | false | false | false |
i-schuetz/SwiftCharts
|
SwiftCharts/Views/ChartAreasView.swift
|
1
|
4265
|
//
// ChartAreasView.swift
// swift_charts
//
// Created by ischuetz on 18/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
open class ChartAreasView: UIView {
fileprivate let animDuration: Float
fileprivate let animDelay: Float
fileprivate let addContainerPoints: Bool
public init(points: [CGPoint], frame: CGRect, colors: [UIColor], animDuration: Float, animDelay: Float, addContainerPoints: Bool, pathGenerator: ChartLinesViewPathGenerator) {
self.animDuration = animDuration
self.animDelay = animDelay
self.addContainerPoints = addContainerPoints
super.init(frame: frame)
backgroundColor = UIColor.clear
show(path: generateAreaPath(points: points, pathGenerator: pathGenerator), colors: colors)
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
fileprivate func generateAreaPath(points: [CGPoint], pathGenerator: ChartLinesViewPathGenerator) -> UIBezierPath {
return pathGenerator.generateAreaPath(points: points, lineWidth: 1.0)
}
fileprivate func show(path: UIBezierPath, colors: [UIColor]) {
var gradientColors = colors
guard let firstColor = gradientColors.first else {
print("WARNING: No color(s) used for ChartAreasView")
return
}
/*
* There is always the possibility to draw a single-color gradient.
* Since we're adding the gradient layer anyway we must ensure that there are at least 2 colors present.
* To handle this case we're adding the same color twice to the colors array to make sure we have at least 2 colors to fill the gradient layer with.
*/
if gradientColors.count == 1 {
gradientColors.append(gradientColors[0])
}
let shape = CAShapeLayer()
shape.frame = CGRect(x: bounds.origin.x, y: bounds.origin.y, width: path.bounds.width, height: bounds.height)
shape.path = path.cgPath
shape.strokeColor = firstColor.cgColor
shape.lineWidth = 2
shape.fillColor = nil
let gradient = CAGradientLayer()
gradient.frame = shape.bounds
gradient.colors = gradientColors.map{$0.cgColor}
let mask = CAShapeLayer()
mask.frame = self.bounds
if addContainerPoints {
path.addLine(to: CGPoint(x: shape.frame.size.width, y: shape.frame.size.height))
path.addLine(to: CGPoint(x: 0, y: shape.frame.size.height))
path.close()
}
mask.path = path.cgPath
mask.fillColor = UIColor.black.cgColor
gradient.mask = mask
layer.addSublayer(gradient)
layer.addSublayer(shape)
if animDuration > 0 {
let maskLayer = CAGradientLayer()
maskLayer.anchorPoint = CGPoint.zero
let colors = [
UIColor(white: 0, alpha: 0).cgColor,
UIColor(white: 0, alpha: 1).cgColor]
maskLayer.colors = colors
maskLayer.bounds = CGRect(x: 0, y: 0, width: 0, height: layer.bounds.size.height)
maskLayer.startPoint = CGPoint(x: 1, y: 0)
maskLayer.endPoint = CGPoint(x: 0, y: 0)
layer.mask = maskLayer
let revealAnimation = CABasicAnimation(keyPath: "bounds")
revealAnimation.fromValue = NSValue(cgRect: CGRect(x: 0, y: 0, width: 0, height: layer.bounds.size.height))
let target = CGRect(x: layer.bounds.origin.x, y: layer.bounds.origin.y, width: layer.bounds.size.width + 2000, height: layer.bounds.size.height)
revealAnimation.toValue = NSValue(cgRect: target)
revealAnimation.duration = CFTimeInterval(animDuration)
revealAnimation.isRemovedOnCompletion = false
revealAnimation.fillMode = CAMediaTimingFillMode.forwards
revealAnimation.beginTime = CACurrentMediaTime() + CFTimeInterval(animDelay)
layer.mask?.add(revealAnimation, forKey: "revealAnimation")
}
}
}
|
apache-2.0
|
e332d7e4747a7453990b29446a9b1ef9
| 38.12844 | 179 | 0.623212 | 4.723145 | false | false | false | false |
Randoramma/ImageSearcher
|
ImageSearcher/Controllers/SearchBarTableViewController.swift
|
1
|
5626
|
//
// SearchBarTableViewController.swift
// ImageSearcher
//
// Created by Randy McLain on 10/10/17.
// Copyright © 2017 Randy McLain. All rights reserved.
//
import UIKit
class SearchBarTableViewController: UITableViewController, UISearchBarDelegate {
let reuseIdentifier:String = "tableCell"
var searchBarController: UISearchController! // will not be nil
var didMakeRequest: Bool! // ensures only 1 request is made per user scroll action.
var dataSourceOfPhotos = [Photo]() {
didSet {
self.tableView.reloadData()
}
}
var dataSourceOfSearch = [Photo]() {
didSet {
self.tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.didMakeRequest = false
searchBarControllerSetup()
requestDefaultPhotos()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - Table view data source
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.searchBarController.isActive ? self.dataSourceOfSearch.count : self.dataSourceOfPhotos.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier, for: indexPath) as! PhotoTableViewCell
if self.searchBarController.isActive {
cell.photoData = self.dataSourceOfSearch[indexPath.row]
} else {
cell.photoData = self.dataSourceOfPhotos[indexPath.row]
}
return cell
}
// MARK: SearchBar Delegate
func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
requestSearchedForPhotos(searchBar.text!)
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
self.dataSourceOfSearch = self.dataSourceOfPhotos
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
}
// MARK: - ScrollView
/*
Notifies when the user scrolls, when the reach the bottom so we can know when to load new requests
Note: scrollViewDidScroll may be called several times during a scroll event and thus the need for the
didMakeRequest variable.
*/
override func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offsetY = scrollView.contentOffset.y
let contentHeight = scrollView.contentSize.height
if offsetY > contentHeight - scrollView.frame.size.height {
if !self.didMakeRequest {
self.didMakeRequest = true
if (self.searchBarController.isActive) && (self.searchBarController.searchBar.text != "") {
requestSearchedForPhotos(self.searchBarController.searchBar.text!)
self.didMakeRequest = false
}
} else {
requestDefaultPhotos()
self.didMakeRequest = false
}
}
}
// 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?) {
let destinationVC = segue.destination as! DetailViewController
let _ = destinationVC.view // call to initialize view related properties of the destinationVC
guard let indexPath = self.tableView.indexPathForSelectedRow else {return}
let indexOfCellSelected = indexPath.row
let cell = self.tableView.cellForRow(at: indexPath) as! PhotoTableViewCell
/* Setup the detail view with DI */
destinationVC.detailVCSetup(withImageView: cell.mainImage.image!, likesCount: self.dataSourceOfPhotos[indexOfCellSelected].likes!, andFavoritesCount: self.dataSourceOfPhotos[indexOfCellSelected].favorites!)
}
// MARK: - Helper
fileprivate func searchBarControllerSetup() {
self.searchBarController = UISearchController(searchResultsController: nil)
self.searchBarController.searchBar.delegate = self as UISearchBarDelegate
self.searchBarController.hidesNavigationBarDuringPresentation = true
self.searchBarController.dimsBackgroundDuringPresentation = false
self.searchBarController.searchBar.searchBarStyle = .prominent
self.searchBarController.searchBar.sizeToFit()
self.tableView.tableHeaderView = self.searchBarController.searchBar
self.searchBarController.definesPresentationContext = true // avoiding search bar remaining after segue.
self.searchBarController.searchBar.text = "Search for Images"
}
fileprivate func requestSearchedForPhotos(_ textToFind: String) {
RequestManager.sharedInstance.getImagesByName(nameToSearch: textToFind) { (photos, error) in
if error == nil {
self.dataSourceOfSearch += photos!
}
}
}
fileprivate func requestDefaultPhotos() {
RequestManager.sharedInstance.getEditorChoiceImages {[weak self] (photos, error) in
if error == nil {
self?.dataSourceOfPhotos += photos!
}
}
}
}
/*
checkout https://developer.apple.com/library/ios/documentation/UIkit/Reference/UIScrollViewDelegate_Protocol/index.html
for will begin decelerating.
*/
|
mit
|
2bb52c5b79a578eb2cc954222bd7a981
| 37.006757 | 214 | 0.672356 | 5.408654 | false | false | false | false |
PlugForMac/HypeMachineAPI
|
Source/Dictionary.swift
|
1
|
571
|
//
// Dictionary+merge.swift
// HypeMachineAPI
//
// Created by Alex Marchant on 5/14/15.
// Copyright (c) 2015 Plug. All rights reserved.
//
import Foundation
extension Dictionary /* <KeyType, ValueType> */ {
func merge(_ dictionary: Dictionary<Key, Value>?) -> Dictionary {
if dictionary == nil { return self }
var newDictionary = self
for key in dictionary!.keys {
if newDictionary[key] != nil { continue }
newDictionary[key] = dictionary![key]
}
return newDictionary
}
}
|
mit
|
246ea9b22501c673798d9f272ba5b2ed
| 23.826087 | 69 | 0.593695 | 4.261194 | false | false | false | false |
lzamudio/swift-book
|
Basic Operators.playground/section-1.swift
|
2
|
2053
|
// Playground for Basic Operators section
// Assignment Operator
let (x,y) = (1,2)
x
y
// Arithmetic Operators
1 + 2 // equals 3
5 - 3 // equals 2
2 * 3 // equals 6
10.0 / 2.5 // equals 4.0
var a = 0
let b = ++a
let c = a++
let three = 3
let minusThree = -three
let plusThree = -minusThree
let minusSix = -6
let alsoMinusSix = +minusSix // alsoMinusSix equals -6
// Compound Assignment Operators
var a2 = 1
a2 += 2
1 == 1 // true, because 1 is equal to 1
2 != 1 // true, because 2 is not equal to 1
2 > 1 // true, because 2 is greater than 1
1 < 2 // true, because 1 is less than 2
1 >= 1 // true, because 1 is greater than or equal to 1
2 <= 1 // false, because 2 is not less than or equal to 1
let name = "world"
if name == "world" {
println("hello, world")
} else {
println("I'm sorry \(name) but I don't recognize you")
}
let contentHeight = 40
let hasHeader = true
let rowHeight = contentHeight + (hasHeader ? 50 : 20)
// Nil Coalescing Operator
let defaultColorName = "red"
var userDefinedColorName: String? // defaults to nil
var colorNameToUse = userDefinedColorName ?? defaultColorName
userDefinedColorName = "green"
colorNameToUse = userDefinedColorName ?? defaultColorName
// Range operators
for index in 1...5 {
println("\(index) times 5 is \(index * 5)")
}
let names = ["Anna", "Alex", "Brian", "Jack"]
let count = names.count
for i in 0..<count {
println("Person \(i + 1) is called \(names[i])")
}
// Logical Operators
let allowedEntry = false
if !allowedEntry {
println("ACCESS DENIED")
}
let enteredDoorCode = true
let passedRetinaScan = false
if enteredDoorCode && passedRetinaScan {
println("Welcome!")
} else {
println("ACCESS DENIED")
}
let hasDoorKey = false
let knowsOverridePassword = true
if hasDoorKey || knowsOverridePassword {
println("Welcome!")
} else {
println("ACCESS DENIED")
}
if (enteredDoorCode && passedRetinaScan) || hasDoorKey || knowsOverridePassword {
println("Welcome!")
} else {
println("ACCESS DENIED")
}
|
mit
|
d2c0eda50b2fe9246a5cd1de59fac936
| 19.127451 | 81 | 0.661471 | 3.415973 | false | false | false | false |
wikimedia/apps-ios-wikipedia
|
Wikipedia/Code/WMFWelcomeAnimationViewControllers.swift
|
1
|
2617
|
class WMFWelcomeAnimationViewController: UIViewController {
var welcomePageType:WMFWelcomePageType = .intro
private var hasAlreadyAnimated = false
private(set) var animationView: WMFWelcomeAnimationView? = nil
override func viewDidLoad() {
super.viewDidLoad()
guard let animationView = animationView else {
return
}
view.wmf_addSubviewWithConstraintsToEdges(animationView)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if (!hasAlreadyAnimated) {
guard let animationView = animationView else {
return
}
animationView.beginAnimations()
}
hasAlreadyAnimated = true
}
}
class WMFWelcomeAnimationForgroundViewController: WMFWelcomeAnimationViewController {
override var animationView: WMFWelcomeAnimationView? {
return animationViewForWelcomePageType
}
private lazy var animationViewForWelcomePageType: WMFWelcomeAnimationView? = {
switch welcomePageType {
case .intro:
return WMFWelcomeIntroductionAnimationView()
case .exploration:
return WMFWelcomeExplorationAnimationView()
case .languages:
return WMFWelcomeLanguagesAnimationView()
case .analytics:
return WMFWelcomeAnalyticsAnimationView()
}
}()
override func viewDidLoad() {
super.viewDidLoad()
guard let animationView = animationView else {
return
}
switch welcomePageType {
case .exploration:
fallthrough
case .languages:
fallthrough
case .analytics:
animationView.hasCircleBackground = true
default:
break
}
}
}
class WMFWelcomeAnimationBackgroundViewController: WMFWelcomeAnimationViewController {
override var animationView: WMFWelcomeAnimationView? {
return animationViewForWelcomePageType
}
private lazy var animationViewForWelcomePageType: WMFWelcomeAnimationView? = {
switch welcomePageType {
case .intro:
return nil
case .exploration:
return WMFWelcomeExplorationAnimationBackgroundView()
case .languages:
return WMFWelcomeLanguagesAnimationBackgroundView()
case .analytics:
return WMFWelcomeAnalyticsAnimationBackgroundView()
}
}()
override func viewDidLoad() {
super.viewDidLoad()
view.wmf_addHorizontalAndVerticalParallax(amount: 12)
}
}
|
mit
|
8b542a48645edc0f339a70af2f113738
| 30.154762 | 86 | 0.654184 | 6.275779 | false | false | false | false |
Andgfaria/MiniGitClient-iOS
|
MiniGitClient/MiniGitClientTests/Model/RepositoryOwnerSpec.swift
|
1
|
3374
|
/*
Copyright 2017 - André Gimenez Faria
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 Quick
import Nimble
@testable import MiniGitClient
class UserSpec: QuickSpec {
override func spec() {
describe("The Repository Owner") {
var repoUser = User()
let url = URL(string: "https://avatars0.githubusercontent.com/u/7774181?v=3")
beforeEach {
repoUser = User()
}
context("has", {
it("a name property") {
repoUser.name = "André"
expect(repoUser.name) == "André"
}
it("an avatar url property") {
repoUser.avatarURL = url
expect(repoUser.avatarURL) == url
}
})
context("can", {
let validJson : DataDict = ["login" : "André", "avatar_url" : "https://avatars0.githubusercontent.com/u/7774181?v=3"]
let emptyJson = DataDict()
it("be created from a valid JSON dictionary") {
repoUser = User(json: validJson)
expect(repoUser.name) == validJson["login"] as? String
expect(repoUser.avatarURL) == url
}
it("be created from an invalid JSON holding the default values") {
repoUser = User(json: emptyJson)
expect(repoUser.name).to(beEmpty())
expect(repoUser.avatarURL).to(beNil())
}
})
context("is", {
it("equatable") {
let secondRepoUser = User()
expect(repoUser) == secondRepoUser
}
it("printable") {
expect(repoUser.description).toNot(beEmpty())
}
it("debug printable") {
expect(repoUser.debugDescription).toNot(beEmpty())
}
})
}
}
}
|
mit
|
d1cfdc1cbd22d90c96a0d4508b9cde27
| 36.865169 | 461 | 0.517211 | 5.616667 | false | false | false | false |
nlefler/euclid
|
Euclid/Euclid/Interface/SegmentMachine.swift
|
1
|
1724
|
//
// SegmentMachine.swift
// Euclid
//
// Created by Nathan Lefler on 6/21/14.
// Copyright (c) 2014 nlefler. All rights reserved.
//
import Foundation
import UIKit
class SegmentMachine: TapStateMachine {
var tapState: TapStates
var points: CGPoint[]
init() {
tapState = .Possible
points = []
}
func touchAtPoint(point: CGPoint, geometryManager: GeometryManager) -> TapStates {
switch (tapState) {
case .Possible:
if !geometryManager.pointAtPoint(point) {
return tapState
}
points.append(point)
tapState = .InProgress
case .InProgress:
if !geometryManager.pointAtPoint(point) {
return tapState
}
points.append(point)
tapState = points.count == 2 ? .Finished : .InProgress
case .Finished:
return tapState
case .Cancelled:
points.removeAll(keepCapacity: false)
}
return tapState
}
func reset() {
tapState = .Possible
points = []
}
func createGeometryWithManager(geometryManager: GeometryManager) -> LabeledGeometry? {
if points.count != 2 {
return nil
}
var existingPointA = geometryManager.pointAtPoint(points[0])
if !existingPointA {
existingPointA = geometryManager.createGeometry(Point.self, solution: false, args: points[0])
}
var existingPointB = geometryManager.pointAtPoint(points[1])
if !existingPointB {
existingPointB = geometryManager.createGeometry(Point.self, solution: false, args: points[1])
}
if existingPointA? && existingPointB? {
return geometryManager.createGeometry(Segment.self, solution: false, args: existingPointA!, existingPointB!)
}
return nil
}
}
|
gpl-2.0
|
ba30a8956f0c9a283fd628b5b3817134
| 24 | 114 | 0.658933 | 4.046948 | false | false | false | false |
GianniCarlo/Audiobook-Player
|
BookPlayerWatch Extension/DataManager+WatchApp.swift
|
1
|
1116
|
//
// DataManager+WatchApp.swift
// BookPlayerWatch Extension
//
// Created by Gianni Carlo on 4/27/19.
// Copyright © 2019 Tortuga Power. All rights reserved.
//
import BookPlayerWatchKit
extension DataManager {
public static let dataUrl = FileManager.default
.urls(for: .documentDirectory, in: .userDomainMask).first!
.appendingPathComponent("library.data")
public class func loadLibrary() -> Library {
return self.decodeLibrary(FileManager.default.contents(atPath: self.dataUrl.path))
?? Library(context: self.getContext())
}
public class func decodeLibrary(_ data: Data?) -> Library? {
guard let data = data else { return nil }
try? data.write(to: DataManager.dataUrl)
let bgContext = DataManager.getBackgroundContext()
let decoder = JSONDecoder()
guard let context = CodingUserInfoKey.context else { return nil }
decoder.userInfo[context] = bgContext
guard let library = try? decoder.decode(Library.self, from: data) else {
return nil
}
return library
}
}
|
gpl-3.0
|
ca91ec2d5c2394f299fb7ed955516c48
| 27.589744 | 90 | 0.660987 | 4.51417 | false | false | false | false |
ovenbits/ModelRocket
|
Sources/Property.swift
|
1
|
4224
|
// Property.swift
//
// Copyright (c) 2015 Oven Bits, 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
final public class Property<T : JSONTransformable>: PropertyDescription {
public typealias PropertyType = T
/// Backing store for property data
public var value: PropertyType?
/// Post-processing closure.
public var postProcess: ((PropertyType?) -> Void)?
/// JSON parameter key
public var key: String
/// Type information
public var type: String {
return "\(PropertyType.self)"
}
/// Specify whether value is required
public var required = false
public subscript() -> PropertyType? {
set { value = newValue }
get { return value }
}
// MARK: Initialization
/// Initialize with JSON property key
public init(key: String, defaultValue: PropertyType? = nil, required: Bool = false, postProcess: ((PropertyType?) -> Void)? = nil) {
self.key = key
self.value = defaultValue
self.required = required
self.postProcess = postProcess
}
// MARK: Transform
/// Extract object from JSON and return whether or not the value was extracted
public func fromJSON(json: JSON) -> Bool {
var jsonValue = json
key.componentsSeparatedByString(".").forEach {
jsonValue = jsonValue[$0]
}
if let newValue = PropertyType.fromJSON(jsonValue) as? PropertyType {
value = newValue
}
return (value != nil)
}
/// Convert object to JSON
public func toJSON() -> AnyObject? {
return value?.toJSON()
}
/// Perform initialization post-processing
public func initPostProcess() {
postProcess?(value)
}
// MARK: Coding
/// Encode
public func encode(coder: NSCoder) {
if let object: AnyObject = value as? AnyObject {
coder.encodeObject(object, forKey: key)
}
}
public func decode(decoder: NSCoder) {
if let decodedValue = decoder.decodeObjectForKey(key) as? PropertyType {
value = decodedValue
}
}
}
// MARK:- CustomStringConvertible
extension Property: CustomStringConvertible {
public var description: String {
var string = "Property<\(type)> (key: \(key), value: "
if let value = value {
string += "\(value)"
}
else {
string += "nil"
}
string += ", required: \(required))"
return string
}
}
// MARK:- CustomDebugStringConvertible
extension Property: CustomDebugStringConvertible {
public var debugDescription: String {
return description
}
}
// MARK:- Hashable
extension Property: Hashable {
public var hashValue: Int {
return key.hashValue
}
}
// MARK:- Equatable
extension Property: Equatable {}
public func ==<T: Equatable>(lhs: Property<T>, rhs: Property<T>) -> Bool {
return lhs.key == rhs.key && lhs.value == rhs.value
}
public func ==<T>(lhs: Property<T>, rhs: Property<T>) -> Bool {
return lhs.key == rhs.key
}
|
mit
|
025b4bb7a6d5dab76e195b13e446c5a9
| 27.734694 | 136 | 0.63589 | 4.821918 | false | false | false | false |
mitchtreece/Spider
|
Spider/Classes/Core/Request/Builder/RequestBuilder.swift
|
1
|
2276
|
//
// RequestBuilder.swift
// Spider-Web
//
// Created by Mitch Treece on 8/24/18.
//
import Foundation
internal class RequestBuilder {
internal weak var spider: Spider!
internal init(spider: Spider) {
self.spider = spider
}
internal func url(for request: Request) -> URLRepresentable {
let path = request.queryEncodedPath ?? request.path
if let base = self.spider?.baseUrl,
let baseString = base.urlString {
return "\(baseString)\(path)"
}
return path
}
internal func urlRequest(for request: Request) -> URLRequest? {
guard let url = url(for: request).url else { return nil }
// Request
var urlRequest = URLRequest(url: url)
urlRequest.httpMethod = request.method.value
urlRequest.httpBody = request.body?.data
urlRequest.timeoutInterval = request.timeout
urlRequest.cachePolicy = request.cachePolicy
urlRequest.allowsCellularAccess = request.allowsCellularAccess
urlRequest.httpShouldHandleCookies = request.shouldHandleCookies
// Headers
let baseHeaders = self.spider.headers ?? Headers()
var headers = request.ignoreSharedHeaders ? request.headers : baseHeaders.merged(with: request.headers)
let jsonHeaders = headers.jsonifyAndPrepare(
for: request,
using: self.spider
)
for (key, value) in jsonHeaders {
urlRequest.setValue(value, forHTTPHeaderField: key)
}
// Set the request headers to our
// updated (merged) headers
request.headers = headers
// Set shared auth if needed
if let sharedAuth = self.spider.authorization,
!request.ignoreSharedAuthorization,
request.authorization == nil {
request.authorization = sharedAuth
}
// Set shared timeout if needed
if let sharedTimeout = self.spider.timeout,
!request.ignoreSharedTimeout {
request.timeout = sharedTimeout
}
return urlRequest
}
}
|
mit
|
33391da26333690b59bc6b0d89eb3012
| 26.421687 | 111 | 0.582162 | 5.305361 | false | false | false | false |
triassic-park/triassic-swift
|
Sources/Provider/Provider.swift
|
1
|
1504
|
//
// Provider.swift
// Triassic
//
// Created by Kilian Költzsch on 16/11/2016.
// Copyright © 2016 Triassic Park. All rights reserved.
//
import Foundation
import CoreLocation
public protocol Provider {
static var id: Common.OperatorCode { get }
static var baseURL: URL { get }
static var center: CLLocationCoordinate2D { get }
}
public extension Provider {
static func send(request: Request, completion: @escaping (TriassicError?, Data?) -> Void) {
// TODO: Use actual request xml data
// guard let data = request.xml.data(using: .utf8) else { return }
let data = "".data(using: .utf8)!
send(raw: data, completion: completion)
}
static func send(raw body: Data, completion: @escaping (TriassicError?, Data?) -> Void) {
var urlRequest = URLRequest(url: self.baseURL)
urlRequest.httpMethod = "POST"
urlRequest.httpBody = body
URLSession.shared.dataTask(with: urlRequest) { data, response, error in
guard let data = data, let response = response as? HTTPURLResponse else {
completion(.request(error), nil)
return
}
switch response.statusCode/100 {
case 4:
completion(.notFound, nil)
return
case 5:
completion(.server, nil)
return
default:
break
}
completion(nil, data)
}.resume()
}
}
|
mit
|
2207bef51f4ad4976ebb81348214de70
| 28.45098 | 95 | 0.581891 | 4.443787 | false | false | false | false |
RigaDevDay/RigaDevDays-Swift
|
RigaDevDays/DayViewController.swift
|
1
|
5018
|
// Copyright © 2017 RigaDevDays. All rights reserved.
import UIKit
import Firebase
class DayViewController: UITableViewController {
var selectedSession: Session?
var selectedDay: Day?
override func viewDidLoad() {
super.viewDidLoad()
tableView.estimatedRowHeight = tableView.rowHeight
tableView.rowHeight = UITableViewAutomaticDimension
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if traitCollection.forceTouchCapability == .available {
registerForPreviewing(with: self, sourceView: tableView)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showSession" {
if let sessionViewController = segue.destination as? SessionViewController {
sessionViewController.day = selectedDay
sessionViewController.session = selectedSession
}
}
}
// MARK: - UITableViewDataSource -
override func numberOfSections(in tableView: UITableView) -> Int {
return selectedDay?.timeslots.count ?? 0
}
override func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return selectedDay?.timeslots[section].startTime
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return selectedDay?.timeslots[section].sessions.count ?? 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: SessionCell = tableView.dequeueReusableCell(withIdentifier: "SessionCell", for: indexPath) as! SessionCell
cell.day = selectedDay
cell.session = selectedDay?.timeslots[indexPath.section].sessions[indexPath.row]
return cell
}
override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if (Auth.auth().currentUser?.uid) != nil {
return true
} else {
return false
}
}
// MARK: - UITableViewDelegate -
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
selectedSession = selectedDay?.timeslots[indexPath.section].sessions[indexPath.row]
performSegue(withIdentifier: "showSession", sender: nil)
tableView.deselectRow(at: indexPath, animated: true)
}
override func tableView(_ tableView: UITableView, editActionsForRowAt: IndexPath) -> [UITableViewRowAction]? {
if let session = selectedDay?.timeslots[editActionsForRowAt.section].sessions[editActionsForRowAt.row] {
var toggleFavourite: UITableViewRowAction
if session.isFavourite {
toggleFavourite = UITableViewRowAction(style: .normal, title: " ★ Remove") { action, index in
session.toggleFavourite(completionBlock: { (error, reference) in
// tableView.reloadRows(at: [editActionsForRowAt], with: .fade)
tableView.reloadData()
})
}
toggleFavourite.backgroundColor = .orange
} else {
toggleFavourite = UITableViewRowAction(style: .normal, title: " ★ Add") { action, index in
session.toggleFavourite(completionBlock: { (error, reference) in
// tableView.reloadRows(at: [editActionsForRowAt], with: .fade)
tableView.reloadData()
})
}
toggleFavourite.backgroundColor = Config.sharedInstance.themePrimaryColor
}
return [toggleFavourite]
}
return nil
}
}
extension DayViewController: UIViewControllerPreviewingDelegate {
func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = tableView.indexPathForRow(at: location) else { return nil }
let viewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "SessionViewController_ID")
guard let sessionViewController = viewController as? SessionViewController else { return nil }
sessionViewController.session = selectedDay?.timeslots[indexPath.section].sessions[indexPath.row]
let cellRect = tableView.rectForRow(at: indexPath)
previewingContext.sourceRect = previewingContext.sourceView.convert(cellRect, from: tableView)
return sessionViewController
}
func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
if let sessionViewController = viewControllerToCommit as? SessionViewController {
print(sessionViewController.title ?? "session")
}
show(viewControllerToCommit, sender: self)
}
}
|
mit
|
4fc79443bfe61b92e02d51869dfc1a0e
| 39.104 | 143 | 0.667066 | 5.716078 | false | false | false | false |
mihaicris/digi-cloud
|
Digi Cloud/Controller/Accounts/AccountSelectionViewController.swift
|
1
|
23530
|
//
// AccountSelectionViewController.swift
// Digi Cloud
//
// Created by Mihai Cristescu on 03/01/17.
// Copyright © 2017 Mihai Cristescu. All rights reserved.
//
import UIKit
final class AccountSelectionViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource,
UICollectionViewDelegateFlowLayout {
// MARK: - Properties
var cellWidth: CGFloat { return 200 * factor}
var cellHeight: CGFloat { return 100 * factor }
var spacingHoriz: CGFloat { return 100 * factor * 0.8 }
var spacingVert: CGFloat { return 100 * factor }
var factor: CGFloat {
if traitCollection.horizontalSizeClass == .compact && self.view.bounds.width < self.view.bounds.height {
return 0.7
} else {
return 1
}
}
private var isExecuting = false
var onSelect: (() -> Void)?
var accounts: [Account] = []
var users: [User] = []
private let spinner: UIActivityIndicatorView = {
let activityIndicator = UIActivityIndicatorView()
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = .white
activityIndicator.translatesAutoresizingMaskIntoConstraints = false
return activityIndicator
}()
var collectionView: UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = .vertical
let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = UIColor.init(white: 0.0, alpha: 0.05)
return collectionView
}()
private let noAccountsLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = UIColor(red: 161/255, green: 168/255, blue: 209/255, alpha: 1.0)
label.text = NSLocalizedString("No accounts", comment: "")
label.font = UIFont.fontHelveticaNeueLight(size: 30)
return label
}()
private let addAccountButton: UIButton = {
let button = UIButton(type: UIButtonType.system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(NSLocalizedString("Add Account", comment: ""), for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.fontHelveticaNeue(size: 14)
button.addTarget(self, action: #selector(handleShowLogin), for: .touchUpInside)
return button
}()
private let stackView: UIStackView = {
let stackView = UIStackView()
stackView.translatesAutoresizingMaskIntoConstraints = false
stackView.distribution = .fillEqually
return stackView
}()
private let loginToAnotherAccountButton: UIButton = {
let button = UIButton(type: UIButtonType.system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(NSLocalizedString("Log in to Another Account", comment: ""), for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.fontHelveticaNeue(size: 14)
button.addTarget(self, action: #selector(handleShowLogin), for: .touchUpInside)
return button
}()
private let logoBigLabel: UILabel = {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.textColor = .white
label.textAlignment = .center
label.numberOfLines = 3
let color = UIColor.init(red: 48/255, green: 133/255, blue: 243/255, alpha: 1.0)
let attributedText = NSMutableAttributedString(string: "Digi Cloud",
attributes: [NSAttributedStringKey.font: UIFont(name: "PingFangSC-Semibold", size: 34) as Any])
let word = NSLocalizedString("for", comment: "")
attributedText.append(NSAttributedString(string: "\n\(word) ",
attributes: [NSAttributedStringKey.font: UIFont(name: "Didot-Italic", size: 20) as Any]))
attributedText.append(NSAttributedString(string: "Digi Storage",
attributes: [NSAttributedStringKey.font: UIFont(name: "PingFangSC-Semibold", size: 20) as Any]))
let nsString = NSString(string: attributedText.string)
let nsRange = nsString.range(of: "Storage")
attributedText.addAttributes([NSAttributedStringKey.foregroundColor: color], range: nsRange)
label.attributedText = attributedText
return label
}()
private let manageAccountsButton: UIButton = {
let button = UIButton(type: UIButtonType.system)
button.translatesAutoresizingMaskIntoConstraints = false
button.setTitle(NSLocalizedString("Manage Accounts", comment: ""), for: .normal)
button.setTitleColor(.white, for: .normal)
button.titleLabel?.font = UIFont.fontHelveticaNeue(size: 14)
button.addTarget(self, action: #selector(handleManageAccounts), for: .touchUpInside)
return button
}()
// MARK: - Initializers and Deinitializers
deinit {
NotificationCenter.default.removeObserver(self)
}
// MARK: - Overridden Methods and Properties
override func viewDidLoad() {
super.viewDidLoad()
registerForNotificationCenter()
collectionView.register(AccountCollectionCell.self,
forCellWithReuseIdentifier: String(describing: AccountCollectionCell.self))
getPersistedUsers()
setupViews()
configureViews()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
updateStackViewAxis()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
getAccountsFromKeychain()
}
private func getPersistedUsers() {
users.removeAll()
do {
accounts = try Account.accountItems()
} catch {
AppSettings.showErrorMessageAndCrash(
title: NSLocalizedString("Error fetching accounts from Keychain", comment: ""),
subtitle: NSLocalizedString("The app will now close", comment: "")
)
}
for account in accounts {
if let user = AppSettings.getPersistedUserInfo(userID: account.userID) {
users.append(user)
} else {
account.revokeToken()
do {
try account.deleteItem()
} catch {
AppSettings.showErrorMessageAndCrash(
title: NSLocalizedString("Error deleting account from Keychain", comment: ""),
subtitle: NSLocalizedString("The app will now close", comment: "")
)
}
}
}
}
override var preferredStatusBarStyle: UIStatusBarStyle {
return .lightContent
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
changeStackViewAxis(for: size)
if let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout {
layout.invalidateLayout()
}
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return users.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: String(describing: AccountCollectionCell.self),
for: indexPath) as? AccountCollectionCell else {
return UICollectionViewCell()
}
let user = users[indexPath.item]
cell.accountNameLabel.text = "\(user.firstName) \(user.lastName)"
let cache = Cache()
if let data = cache.load(type: .profile, key: user.identifier + ".png") {
cell.profileImage.image = UIImage(data: data, scale: UIScreen.main.scale)
} else {
cell.profileImage.image = #imageLiteral(resourceName: "default_profile_image")
}
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: cellWidth, height: cellHeight)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout,
insetForSectionAt section: Int) -> UIEdgeInsets {
guard let layout = collectionViewLayout as? UICollectionViewFlowLayout else {
return UIEdgeInsets.zero
}
let colWidth = collectionView.bounds.width
let colHeight = collectionView.bounds.height
var topInset, leftInset, bottomInset, rightInset: CGFloat
let items = CGFloat(collectionView.numberOfItems(inSection: section))
layout.minimumInteritemSpacing = spacingHoriz
layout.minimumLineSpacing = spacingVert
switch items {
case 1:
topInset = (colHeight - cellHeight)/2
leftInset = (colWidth - cellWidth)/2
case 2:
topInset = (colHeight - cellHeight)/2
leftInset = (colWidth - (cellWidth * 2) - spacingHoriz)/2
case 3:
topInset = (colHeight - (cellHeight * 3) - (spacingVert * 2))/2
leftInset = (colWidth - cellWidth)/2
case 4:
topInset = (colHeight - (cellHeight * 2) - (spacingVert * 1))/2
leftInset = (colWidth - (cellWidth * 2) - (spacingHoriz * 1))/2
default:
topInset = (colHeight - (cellHeight * 3) - (spacingVert * 2))/2
leftInset = (colWidth - (cellWidth * 2) - (spacingHoriz * 1))/2
}
bottomInset = topInset
rightInset = leftInset
return UIEdgeInsets(top: topInset,
left: leftInset,
bottom: bottomInset,
right: rightInset)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// Prevents a second selection
guard !isExecuting else { return }
isExecuting = true
switchToAccount(indexPath)
}
// MARK: - Helper Functions
private func registerForNotificationCenter() {
NotificationCenter.default.addObserver(
self,
selector: #selector(updateStackViewAxis),
name: .UIApplicationWillResignActive,
object: nil)
}
private func setupViews() {
collectionView.delegate = self
collectionView.dataSource = self
setNeedsStatusBarAppearanceUpdate()
view.backgroundColor = UIColor.iconColor
view.addSubview(logoBigLabel)
view.addSubview(noAccountsLabel)
view.addSubview(collectionView)
view.addSubview(spinner)
view.addSubview(stackView)
NSLayoutConstraint.activate([
logoBigLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
NSLayoutConstraint(item: logoBigLabel, attribute: .centerY, relatedBy: .equal,
toItem: view, attribute: .bottom, multiplier: 0.13, constant: 0.0),
collectionView.leftAnchor.constraint(equalTo: view.leftAnchor),
collectionView.rightAnchor.constraint(equalTo: view.rightAnchor),
collectionView.centerYAnchor.constraint(equalTo: view.centerYAnchor),
NSLayoutConstraint(item: collectionView, attribute: .height, relatedBy: .equal,
toItem: view, attribute: .height, multiplier: 0.5, constant: 0.0),
spinner.centerXAnchor.constraint(equalTo: collectionView.centerXAnchor),
NSLayoutConstraint(item: spinner, attribute: .centerY, relatedBy: .equal,
toItem: collectionView, attribute: .centerY, multiplier: 1.25, constant: 0.0),
noAccountsLabel.centerXAnchor.constraint(equalTo: view.centerXAnchor),
noAccountsLabel.centerYAnchor.constraint(equalTo: view.centerYAnchor),
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor, constant: 0),
stackView.bottomAnchor.constraint(equalTo: view.layoutMarginsGuide.bottomAnchor, constant: -20)
])
}
func configureViews() {
if users.count == 0 {
loginToAnotherAccountButton.removeFromSuperview()
manageAccountsButton.removeFromSuperview()
stackView.insertArrangedSubview(addAccountButton, at: 0)
collectionView.isHidden = true
noAccountsLabel.isHidden = false
} else {
addAccountButton.removeFromSuperview()
stackView.insertArrangedSubview(loginToAnotherAccountButton, at: 0)
stackView.insertArrangedSubview(manageAccountsButton, at: 0)
collectionView.isHidden = false
noAccountsLabel.isHidden = true
loginToAnotherAccountButton.isHidden = false
}
collectionView.reloadData()
}
private func changeStackViewAxis(for size: CGSize) {
if self.traitCollection.horizontalSizeClass == .compact && size.width < size.height {
self.stackView.axis = .vertical
self.stackView.spacing = 10
} else {
self.stackView.axis = .horizontal
self.stackView.spacing = 40
}
}
@objc private func updateStackViewAxis() {
changeStackViewAxis(for: self.view.bounds.size)
}
@objc private func handleShowLogin() {
let controller = LoginViewController()
controller.modalPresentationStyle = .formSheet
controller.onSuccess = { [weak self] user in
self?.getPersistedUsers()
self?.configureViews()
}
present(controller, animated: true, completion: nil)
}
@objc private func handleManageAccounts() {
let controller = ManageAccountsViewController(controller: self)
controller.onAddAccount = { [weak self] in
self?.handleShowLogin()
}
let navController = UINavigationController(rootViewController: controller)
navController.modalPresentationStyle = .popover
navController.popoverPresentationController?.sourceView = manageAccountsButton
navController.popoverPresentationController?.sourceRect = manageAccountsButton.bounds
present(navController, animated: true, completion: nil)
}
func getAccountsFromKeychain() {
/*
Make sure the collection view is up-to-date by first reloading the
acocunts items from the keychain and then reloading the table view.
*/
do {
accounts = try Account.accountItems()
} catch {
AppSettings.showErrorMessageAndCrash(
title: NSLocalizedString("Error fetching accounts from Keychain", comment: ""),
subtitle: NSLocalizedString("The app will now close", comment: "")
)
}
updateUsers {
self.configureViews()
}
}
func updateUsers(completion: (() -> Void)?) {
var updateError = false
let dispatchGroup = DispatchGroup()
var updatedUsers: [User] = []
for account in accounts {
guard let token = try? account.readToken() else {
AppSettings.showErrorMessageAndCrash(
title: NSLocalizedString("Error reading account from Keychain", comment: ""),
subtitle: NSLocalizedString("The app will now close", comment: "")
)
return
}
dispatchGroup.enter()
AppSettings.saveUser(forToken: token) { user, error in
dispatchGroup.leave()
guard error == nil else {
updateError = true
return
}
if let user = user {
updatedUsers.append(user)
}
}
}
dispatchGroup.notify(queue: .main) {
if updateError {
// Shouwd we inform user about refresh failed?
// self.showError()
} else {
self.users = self.users.updating(from: updatedUsers)
completion?()
}
}
}
private func showError(message: String) {
let alert = UIAlertController(title: NSLocalizedString("Error", comment: ""),
message: message,
preferredStyle: .alert)
let actionOK = UIAlertAction(title: NSLocalizedString("OK", comment: ""), style: .default) { _ in
UIView.animate(withDuration: 0.5, animations: {
let indexPathOneElement = IndexPath(item: 0, section: 0)
if let cell = self.collectionView.cellForItem(at: indexPathOneElement) {
cell.transform = CGAffineTransform.identity
}
}, completion: { _ in
self.getPersistedUsers()
self.setupViews()
self.configureViews()
self.isExecuting = false
})
}
alert.addAction(actionOK)
self.present(alert, animated: false, completion: nil)
}
private func switchToAccount(_ userIndexPath: IndexPath) {
let user = users[userIndexPath.item]
// get indexPaths of all users except the one selected
let indexPaths = users.enumerated().compactMap({ (arg) -> IndexPath? in
let (offset, element) = arg
if element.identifier == user.identifier {
return nil
}
return IndexPath(item: offset, section: 0)
})
self.users.removeAll()
users.append(user)
let updatesClosure: () -> Void = {
self.collectionView.deleteItems(at: indexPaths)
}
let completionClosure: (Bool) -> Void = { _ in
let indexPathOneElement = IndexPath(item: 0, section: 0)
if let cell = self.collectionView.cellForItem(at: indexPathOneElement) {
let animationClosure = { cell.transform = CGAffineTransform(scaleX: 1.2, y: 1.2) }
let animationCompletionClosure: (Bool) -> Void = { _ in
self.spinner.startAnimating()
DispatchQueue.main.async {
let account = Account(userID: user.identifier)
guard let token = try? account.readToken() else {
AppSettings.showErrorMessageAndCrash(
title: NSLocalizedString("Error reading account from Keychain", comment: ""),
subtitle: NSLocalizedString("The app will now close", comment: "")
)
return
}
// Try to access network
DigiClient.shared.getUser(forToken: token) { _, error in
guard error == nil else {
self.spinner.stopAnimating()
var message: String
switch error! {
case NetworkingError.internetOffline(let errorMessage), NetworkingError.requestTimedOut(let errorMessage):
message = errorMessage
if !AppSettings.allowsCellularAccess {
let alert = UIAlertController(title: NSLocalizedString("Info", comment: ""),
message: NSLocalizedString("Would you like to use cellular data?", comment: ""),
preferredStyle: .alert)
let noAction = UIAlertAction(title: "No", style: .default) { _ in
self.showError(message: message)
}
let yesAction = UIAlertAction(title: "Yes", style: .default) { _ in
AppSettings.allowsCellularAccess = true
DigiClient.shared.renewSession()
self.switchToAccount(userIndexPath)
}
alert.addAction(noAction)
alert.addAction(yesAction)
self.present(alert, animated: true, completion: nil)
return
}
case AuthenticationError.login:
message = NSLocalizedString("Your session has expired, please log in again.", comment: "")
do {
try account.deleteItem()
} catch {
AppSettings.showErrorMessageAndCrash(
title: NSLocalizedString("Error deleting account from Keychain", comment: ""),
subtitle: NSLocalizedString("The app will now close", comment: "")
)
}
default:
message = NSLocalizedString("An error has occurred.\nPlease try again later!", comment: "")
}
self.showError(message: message)
return
}
// save the Token for current session
DigiClient.shared.loggedAccount = account
// Save in Userdefaults this user as logged in
AppSettings.loggedUserID = user.identifier
DigiClient.shared.getSecuritySettings()
// Show account locations
self.onSelect?()
}
}
}
UIView.animate(withDuration: 0.3, delay: 0,
usingSpringWithDamping: 0.3,
initialSpringVelocity: 0.5,
options: UIViewAnimationOptions.curveEaseInOut,
animations: animationClosure,
completion: animationCompletionClosure)
}
}
// Animate the selected account in the collection view
self.collectionView.performBatchUpdates(updatesClosure, completion: completionClosure)
}
}
|
mit
|
ebb4ee7388754e5f8ecd3c954209143a
| 37.826733 | 150 | 0.575205 | 5.929688 | false | false | false | false |
austinzheng/swift-compiler-crashes
|
crashes-fuzzing/26833-llvm-mapvector-swift-declcontext.swift
|
4
|
2335
|
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
struct c<h:d
class A:BooleanType}{class B<T where k:c<I : {
struct B:BooleanType}}enum S<T where g: Int = Swift.c {
let a {
class n{
var f=[1)let v: p
struct c:T: AnyObject.e :d{
var _=e:
struct B : e:
{
class B:d
struct Q{{
let :BooleanType}
class B<T where H:A
class A{
}
let , i {
class c:A{
class B<T
}
struct b{return"
struct b{
}
import CoreData
enum b<T where h:a
struct B<I : {
struct Q{
struct b{
}
struct A {{
class n{
var d func b<I :A<T where h: C {
}
{:
struct S<f=[1){
class B<T where H:BooleanType}class c<T {
func b{() {return"
func a<T where T: b { func a{
struct S<T where H : C {
{class
let a {:A{
let , i {class
struct A{}
func a:a{
class b<T where h: a{return"
struct c<T where h: p
class B<T where H:A{
[[]deinit{return"
struct B{
struct c:d{typealias f=e:A
class A:A{{
let a<T where T
}}
let f: e .c {
extension String {class d=e
}}
"[1
let v: b<T where h: c<T where k:a{{return"
}
class B<T where H:
let f: {}
class A{
(("
}
struct B
func b<T where g:AnyObject.c {struct S<T where T
{
struct Q{
struct c<T where h:A{
class B{
let f: {}enum a {
let c {
class b<T where h: AnyObject.c {
var f=e:A
struct D{
let d: B? = b
protocol c
enum B<d = "
import CoreData
enum b{func g: {
func b<T {
{
struct B : b<T where h:A{
protocol A {
import CoreData
var _=a{struct A:
class B<T where T{
}
}
let v: b
{{let f: e .T
let f: e = A:
}
e = A{
class A{
if true {
let a {
class C
var _=a{{class b{
func b
struct b{return""
var d = A{
}
struct S<I :A{
func g: C {
let start = true {
struct S<T where H:
func u([Void{{
class A{init(((i
let c {
{
struct Q{
class B<T where h:d<T where h:d<
func b{
{class
""[enum A<T w gb
struct c{
Void{{}
}
}enum b{
protocol A {{
class B<T where B<T where T{}
class B<T where T: C {
protocol A {var d = "[enum b<T where B{
var f: p
"
}
protocol c<T where B{
func u((e .Element
}
let start = A<T where g: d where k:a{var d{
struct b{
}
struct d
{struct b<T where h:A
func a{
}
}struct A<T where h:
}(i
class b<T where B
let
case c
struct b<T {
struct c{return"[1)let , i {
(i
class B:a:A
let a {return"[[[Void{
enum b{
let d<T where h:
e :c{
enum a {
var f: c<T where h:d: AnyObject.T
}
var = "[Void{
let a {
enum a {{
class
|
mit
|
036e79ff25b860b27ef891cd05f75987
| 13.503106 | 87 | 0.635118 | 2.342026 | false | false | false | false |
Stanbai/MultiThreadBasicDemo
|
ResumptionDemo/ResumptionDemo/ResumptionDemo/SBTableViewCell.swift
|
1
|
1563
|
//
// SBTableViewCell.swift
// ResumptionDemo
//
// Created by Stan on 2017-08-20.
// Copyright © 2017 stan. All rights reserved.
//
import UIKit
class SBTableViewCell: UITableViewCell {
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var downloadBtn: UIButton!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var sizeLabel: UILabel!
@IBOutlet weak var completeLabel: UILabel!
var downloadBlock: ((_ sender: UIButton?) -> Void)?
override func awakeFromNib() {
super.awakeFromNib()
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
func setupCellModel(model: SBDownloadModel) -> () {
nameLabel.text = model.name
// 判断文件夹中是否已经存在
let fileExist = FileManager.default.fileExists(atPath: model.cacheString)
if fileExist {
print("文件已经存在")
// 设置按钮的Btn
if progressView.progress == 1.0 {
downloadBtn.setTitle("完成", for: .normal)
} else {
downloadBtn.setTitle("恢复", for: .normal)
}
} else {
print("文件不存在")
downloadBtn.setTitle("开始", for: .normal)
progressView.progress = 0.0
}
}
@IBAction func downBtnClick(_ sender: Any) {
if downloadBlock != nil {
downloadBlock!(sender as? UIButton)
}
}
}
|
mit
|
c20c378f4c25b10904c938613eedd3ad
| 24.758621 | 81 | 0.58166 | 4.459701 | false | false | false | false |
mozilla-mobile/focus-ios
|
Blockzilla/Utilities/SearchSuggestClient.swift
|
5
|
2429
|
/* 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
let SearchSuggestClientErrorDomain = "org.mozilla.firefox.SearchSuggestClient"
let SearchSuggestClientErrorInvalidEngine = 0
let SearchSuggestClientErrorInvalidResponse = 1
class SearchSuggestClient {
private var request: NSMutableURLRequest?
func getSuggestions(_ query: String, callback: @escaping (_ response: [String]?, _ error: NSError?) -> Void) {
guard let url = SearchEngineManager(prefs: UserDefaults.standard).activeEngine.urlForSuggestions(query) else {
let error = NSError(domain: SearchSuggestClientErrorDomain, code: SearchSuggestClientErrorInvalidEngine, userInfo: nil)
callback(nil, error)
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { (data, response, error) in
do {
// The response will be of the following format:
// ["foobar",["foobar","foobar2000 mac","foobar skins",...]]
// That is, an array of at least two elements: the search term and an array of suggestions.
guard let myData = data, let array = try JSONSerialization.jsonObject(with: myData, options: []) as? [Any] else {
throw NSError(domain: SearchSuggestClientErrorDomain, code: SearchSuggestClientErrorInvalidResponse, userInfo: nil)
}
if array.count < 2 {
throw NSError(domain: SearchSuggestClientErrorDomain, code: SearchSuggestClientErrorInvalidResponse, userInfo: nil)
}
if var suggestions = array[1] as? [String] {
if let searchWord = array[0] as? String {
suggestions = suggestions.filter { $0 != searchWord }
suggestions.insert(searchWord, at: 0)
}
callback(suggestions, nil)
return
}
throw NSError(domain: SearchSuggestClientErrorDomain, code: SearchSuggestClientErrorInvalidResponse, userInfo: nil)
} catch let error as NSError {
callback(nil, error)
return
}
}.resume()
}
}
|
mpl-2.0
|
4d146492fc4dc90bdefb4d6c785f1216
| 47.58 | 135 | 0.616715 | 5.008247 | false | false | false | false |
blackbear/OpenHumansUpload
|
OpenHumansUpload/OpenHumansUpload/AppDelegate.swift
|
1
|
6362
|
//
// AppDelegate.swift
// OpenHumansUpload
//
// Created by James Turner on 4/28/16.
// Copyright © 2016 Open Humans. All rights reserved.
//
import UIKit
import CoreData
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(app: UIApplication, openURL url: NSURL, options: [String : AnyObject]) -> Bool {
if (OH_OAuth2.sharedInstance().parseLaunchURL(url)) {
return true;
}
return true;
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
Fabric.with([Crashlytics.self])
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 "biz.blackbear.OpenHumansUpload" 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("OpenHumansUpload", 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()
}
}
}
}
|
mit
|
e8a7c8653cabfef4c0bafff297593c93
| 51.139344 | 291 | 0.714353 | 5.79326 | false | false | false | false |
manavgabhawala/swift
|
test/SILGen/static-stored-properties-in-concrete-contexts.swift
|
1
|
540
|
// RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
struct Foo<T> {
static var foo: T { return (0 as Int) as! T }
}
extension Foo where T == Int {
// CHECK: sil_global private [[X_TOKEN:@.*]] : $Builtin.Word
// CHECK: sil_global hidden [let] @_TZve4mainRxzSirVS_3Foo1xSi : $Int
static let x = foo
// CHECK: sil_global private [[Y_TOKEN:@.*]] : $Builtin.Word
// CHECK: sil_global hidden @_TZve4mainRxzSirVS_3Foo1ySi : $Int
static var y = foo
}
print(Foo<Int>.x)
Foo<Int>.y = 2
Foo<Int>.y += 3
print(Foo<Int>.y)
|
apache-2.0
|
0c32a56a31dcaa80078c8bb97cf88231
| 24.714286 | 71 | 0.635185 | 2.741117 | false | false | false | false |
NorbertoVasconcelos/NVFileDownloader
|
NVFileDownloader/Progress.swift
|
1
|
1923
|
//
// Progress.swift
// NVFileDownloader
//
// Created by Norberto Vasconcelos on 02/05/2017.
// Copyright © 2017 Norberto Vasconcelos. All rights reserved.
//
import Foundation
public class Progress {
public var files: Dictionary<String, FileProgress>
public var currentFileUrl: String?
public var totalDownloadSize: Float = 0.0
public init() {
files = Dictionary<String, FileProgress>()
}
public func numberOfFiles() -> Int {
return files.count
}
public func downloadSpeed() -> Float {
var combinedDownloadSpeed: Float = 0.0
for key in files.keys {
let fp = files[key]
combinedDownloadSpeed += fp?.downloadSpeed ?? 0
}
return combinedDownloadSpeed
}
public func downloadedBytes() -> Float {
var combinedDownloaded: Float = 0.0
for key in files.keys {
let fp = files[key]
combinedDownloaded += fp?.downloadedBytes ?? 0
}
return combinedDownloaded
}
// File functions
public func addFile(_ file: FileProgress) {
let urlString = String(describing: file.url)
currentFileUrl = urlString
files[urlString] = file
}
public func removeFile(_ file: FileProgress) {
let urlString = String(describing: file.url)
files.removeValue(forKey: urlString)
}
public func updateFile(_ file: FileProgress) {
let urlString = String(describing: file.url)
let currentFile = files[urlString]
if let cf = currentFile, cf.fileSize == 0 {
totalDownloadSize += file.fileSize
}
files[urlString] = file
}
// Progress details
public func details() -> String {
return "Total Download Size: \(totalDownloadSize) \n Downloaded Bytes: \(downloadedBytes()) \n Download Speed: \(downloadSpeed())"
}
}
|
mit
|
0404972e83d982ba8114bbcf2936a3d4
| 27.686567 | 138 | 0.611863 | 4.554502 | false | false | false | false |
smartystreets/smartystreets-ios-sdk
|
Sources/SmartyStreets/USZipCode/USZipCode.swift
|
1
|
2829
|
import Foundation
@objcMembers public class USZipCode: NSObject, Codable {
// See "https://smartystreets.com/docs/cloud/us-zipcode-api#zipcodes"
public var zipCode:String?
public var zipCodeType:String?
public var defaultCity:String?
public var countyFips:String?
public var countyName:String?
public var stateAbbreviation:String?
public var state:String?
public var latitude:Double?
public var objcLatitude:NSNumber? {
get {
return latitude as NSNumber?
}
}
public var longitude:Double?
public var objcLongitude:NSNumber? {
get {
return longitude as NSNumber?
}
}
public var precision:String?
public var alternateCounties:[USAlternateCounties]?
enum CodingKeys: String, CodingKey {
case zipCode = "zipcode"
case zipCodeType = "zipcode_type"
case defaultCity = "default_city"
case countyFips = "county_fips"
case countyName = "county_name"
case stateAbbreviation = "state_abbreviation"
case state = "state"
case latitude = "latitude"
case longitude = "longitude"
case precision = "precision"
case alternateCounties = "alternate_counties"
}
public init(dictionary:NSDictionary) {
super.init()
self.zipCode = dictionary["zipcode"] as? String
self.zipCodeType = dictionary["zipcode_type"] as? String
self.defaultCity = dictionary["default_city"] as? String
self.countyFips = dictionary["county_fips"] as? String
self.countyName = dictionary["county_name"] as? String
self.stateAbbreviation = dictionary["state_abbreviation"] as? String
self.state = dictionary["state"] as? String
self.latitude = dictionary["latitude"] as? Double
self.longitude = dictionary["longitude"] as? Double
self.precision = dictionary["precision"] as? String
if let alternateCounties = dictionary["alternate_counties"] {
self.alternateCounties = convertToAlternateCountyObjects(alternateCounties as! [[String:String]])
} else {
self.alternateCounties = [USAlternateCounties]()
}
}
func convertToAlternateCountyObjects(_ object: [[String:String]]) -> [USAlternateCounties] {
var mutable = [USAlternateCounties]()
for alternateCity in object {
mutable.append(USAlternateCounties(dictionary: alternateCity as NSDictionary))
}
return mutable
}
func getAlternateCountiesAtIndex(index:Int) -> USAlternateCounties {
if let alternateCounty = self.alternateCounties?[index] {
return alternateCounty
} else {
return USAlternateCounties(dictionary: NSDictionary())
}
}
}
|
apache-2.0
|
a397e6e05255f65b3860e5bba9b5d5dd
| 36.223684 | 109 | 0.648993 | 4.622549 | false | false | false | false |
robpearson/BlueRing
|
BlueRing/AppDelegate.swift
|
1
|
1823
|
//
// AppDelegate.swift
// BlueRing
//
// Created by Robert Pearson on 9/2/17.
// Copyright © 2017 Rob Pearson. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {
var appEventMonitor: AppEventMonitor?
let appStatusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
let appPopover = NSPopover()
func applicationDidFinishLaunching(_ aNotification: Notification) {
if let button = appStatusItem.button {
button.image = NSImage(named: "statusIcon")
button.action = #selector(AppDelegate.togglePopover)
}
appPopover.behavior = .transient
appPopover.contentViewController = ProjectViewController(nibName: "ProjectViewController", bundle: nil)
appEventMonitor = AppEventMonitor(mask: [.leftMouseDown, .rightMouseDown]) { [unowned self] event in
if self.appPopover.isShown {
self.closePopover(sender: event)
}
}
appEventMonitor?.start()
}
func applicationWillTerminate(_ aNotification: Notification) {
// Insert code here to tear down your application
}
func showPopover(sender: AnyObject?) {
if let button = appStatusItem.button {
appPopover.show(relativeTo: button.bounds, of: button, preferredEdge: NSRectEdge.minY)
}
appEventMonitor?.start()
}
func closePopover(sender: AnyObject?) {
appPopover.performClose(sender)
appEventMonitor?.stop()
}
public func togglePopover(sender: AnyObject?) {
if appPopover.isShown {
closePopover(sender: sender)
} else {
showPopover(sender: sender)
}
}
}
|
apache-2.0
|
fe04138119c6caea85e4e361aa8994f6
| 28.387097 | 111 | 0.635565 | 5.075209 | false | false | false | false |
duliodenis/nostalgia
|
Nostalgia/Nostalgia/Controllers/PermissionViewController.swift
|
1
|
2116
|
//
// PermissionViewController.swift
// Nostalgia
//
// Created by Dulio Denis on 12/24/16.
// Copyright © 2016 ddApps. All rights reserved.
//
import UIKit
import AVFoundation // Microphone Access
import Photos // Photo Library Access
import Speech // Speech Transcription
class PermissionViewController: UIViewController {
@IBOutlet weak var helpLabel: UILabel!
@IBAction func requestPermissions(_ sender: Any) {
requestPhotoPermissions()
}
// MARK: - Individual Permissions Methods
func requestPhotoPermissions() {
PHPhotoLibrary.requestAuthorization { [unowned self]
authStatus in
DispatchQueue.main.async {
if authStatus == .authorized {
self.requestRecordPermissions()
} else {
self.helpLabel.text = "Photos permission was declined; please enable it in Settings then tap Continue again."
}
}
}
}
func requestRecordPermissions() {
AVAudioSession.sharedInstance().requestRecordPermission { [unowned self] allowed in
DispatchQueue.main.async {
if allowed {
self.requestTranscribePermissions()
} else {
self.helpLabel.text = "Recording permission was declined; please enable it in Settings then tap Continue again."
}
}
}
}
func requestTranscribePermissions() {
SFSpeechRecognizer.requestAuthorization { [unowned self] authStatus in
DispatchQueue.main.async {
if authStatus == .authorized {
self.authorizationComplete()
} else {
self.helpLabel.text = "Transcription permission was declined; please enable it in Settings then tap Continue again."
}
}
}
}
func authorizationComplete() {
dismiss(animated: true)
}
}
|
mit
|
2cd060b4eacc193b3b88e479028fae40
| 27.581081 | 136 | 0.561229 | 5.842541 | false | false | false | false |
SSU-CS-Department/ssumobile-ios
|
SSUMobile/Modules/Core/Moonlight/Builder/SSUJSONEntityBuilder.swift
|
1
|
5674
|
//
// SSUJSONEntityBuilder.swift
// SSUMobile
//
// Created by Eric Amorde on 7/8/18.
// Copyright © 2018 Sonoma State University Department of Computer Science. All rights reserved.
//
import Foundation
import CoreData
import SwiftyJSON
/**
A specialized builder that knows how to build entities which conform to `SSUJSONInitializable`
Subclasses should override `build(json:)` to perform their custom build logic
*/
class SSUJSONEntityBuilder<Entity: SSUJSONInitializable & SSUCoreDataEntity & NSManagedObject>: SSUMoonlightBuilder {
/**
The primary key of `Entity`
Default: `Entity.primaryKey`
*/
@objc
var idKey: String {
return Entity.identifierKey
}
/**
If `true`, data will be parsed as a single instance instead of an array of instances
*/
@objc
var shouldBuildSingleObject: Bool = false
/**
If `true`, entries that have a deletion date associated with them will trigger a deletion in the database
Default: `true`
*/
@objc
var autoDetectDeletion: Bool = true
/**
The most recent created, modified, or deleted date received in the JSON.
*/
var mostRecentModification: Date?
func id(fromJSON json: JSON) -> Entity.IdentifierType? {
return json[idKey].rawValue as? Entity.IdentifierType
}
func build(json: JSON, completion: (([Entity]) -> Void)? = nil) {
context.perform {
let results = self.build(json: json)
completion?(results)
}
}
override func buildJSON(_ json: JSON) {
self.build(json: json)
}
@discardableResult
func build(json: JSON) -> [Entity] {
SSULogging.logDebug("Building \(Entity.self)")
let startDate = Date()
var results = [Entity]()
let objectsToBuild: [JSON] = shouldBuildSingleObject ? [json] : json.arrayValue
// TODO: add error handling / logging for a non-array response
for entryData in objectsToBuild {
let id = self.id(fromJSON: entryData)
let instance: Entity = type(of: self).object(id: id, context: context)
let dates = self.dateInfo(from: entryData.dictionaryValue)
let mode = self.mode(from: dates)
mostRecentModification = maxValue(mostRecentModification, dates?.mostRecent)
if autoDetectDeletion {
if mode == .deleted {
context.delete(instance)
continue
}
}
do {
try instance.initializeWith(json: entryData)
results.append(instance)
} catch {
SSULogging.logError("Received an error while attempting to initialize \(instance) with data \(entryData): \(error)")
}
}
willFinishBuilding(objects: results)
saveContext()
didFinishBuilding(objects: results)
let buildTime = Date().timeIntervalSince(startDate)
let buildSeconds = String.init(format: "%.2f", buildTime)
SSULogging.logDebug("Finished building \(results.count) \(Entity.self) (\(buildSeconds)s)")
return results
}
/**
Called when `build(json:)` finishes, but before the context has been saved.
Override to perform any operations before saving the context
*/
func willFinishBuilding(objects: [Entity]) {
}
/**
Called when `build(json:)` finishes, after the context has been saved. Override to perform operations on the created/updated objects
*/
func didFinishBuilding(objects: [Entity]) {
}
// MARK: Static helpers
@objc
class var entityName: String {
return "\(Entity.self)"
}
class func idPredicate(_ id: Entity.IdentifierType?, key: String = Entity.identifierKey) -> NSPredicate? {
guard let id = id else { return nil }
return NSPredicate(format: "%K == %@", argumentArray: [key, id])
}
class func object(id: Entity.IdentifierType?, context: NSManagedObjectContext) -> Entity {
let predicate = idPredicate(id, key: Entity.identifierKey)
let result: Entity = object(matchingPredicate: predicate, context: context)
result.setValue(id, forKey: Entity.identifierKey)
return result
}
class func object(matchingPredicate predicate: NSPredicate?, context: NSManagedObjectContext) -> Entity {
guard let result = object(withEntityName: entityName, predicate: predicate, context: context) as? Entity else {
fatalError("Name of entity `\(Entity.self)` does not match any entites in provided context")
}
return result
}
class func allObjects(context: NSManagedObjectContext) -> [Entity] {
return allObjects(context: context, matching: nil)
}
class func allObjects(context: NSManagedObjectContext, matching predicate: NSPredicate?) -> [Entity] {
return allObjects(withEntityName: entityName, matchingPredicate: predicate, context: context).compactMap { $0 as? Entity }
}
/**
Load objects matching the provided predicate (or all, if predicate is nil) in to memory
*/
class func prefetch(context: NSManagedObjectContext, matching predicate: NSPredicate?) {
_ = allObjects(context: context, matching: predicate)
}
class func deleteObjects(matchingPredicate predicate: NSPredicate?, context: NSManagedObjectContext) {
deleteObjects(withEntityName: entityName, matchingPredicate: predicate, context: context)
}
}
|
apache-2.0
|
b4e1ac6b47393a144708afc2b5b41691
| 34.018519 | 137 | 0.634585 | 4.873711 | false | false | false | false |
leizh007/HiPDA
|
HiPDA/HiPDA/Sections/Home/Post/PostInfo.swift
|
1
|
2656
|
//
// PostRequestInfo.swift
// HiPDA
//
// Created by leizh007 on 2017/5/15.
// Copyright © 2017年 HiPDA. All rights reserved.
//
import Foundation
struct PostInfo {
let tid: Int
let page: Int
let pid: Int?
let authorid: Int?
init(tid: Int, page: Int = 1, pid: Int? = nil, authorid: Int? = nil) {
self.tid = tid
self.page = page
self.pid = pid
self.authorid = authorid
}
init?(urlString: String) {
enum PropertyKeys: String {
case tid
case page
case pid
case authorid
}
guard let index = urlString.range(of: "://www.hi-pda.com/forum/viewthread.php?")?.upperBound else { return nil }
var subString = urlString.substring(from: index)
var pid: Int?
if let sharpIndex = subString.range(of: "#pid")?.lowerBound {
subString = subString.substring(to: sharpIndex)
if let pidResult = try? Regex.firstMatch(in: urlString, of: "#pid(\\d+)"), pidResult.count == 2, let value = Int(pidResult[1]) {
pid = value
}
}
var dic = [String: Int]()
for string in subString.components(separatedBy: "&") {
let attribute = string.components(separatedBy: "=")
guard attribute.count == 2 else { continue }
let key = attribute[0]
guard let value = Int(attribute[1]) else { continue }
dic[key] = value
}
guard let tid = dic[PropertyKeys.tid.rawValue] else { return nil }
self.tid = tid
self.page = dic[PropertyKeys.page.rawValue] ?? 1
self.pid = pid ?? (dic[PropertyKeys.pid.rawValue] ?? dic["rpid"])
self.authorid = dic[PropertyKeys.authorid.rawValue]
}
}
// MARK: - Equatable
extension PostInfo: Equatable {
static func ==(lhs: PostInfo, rhs: PostInfo) -> Bool {
return lhs.tid == rhs.tid &&
lhs.page == rhs.page &&
lhs.pid == rhs.pid &&
lhs.authorid == rhs.authorid
}
}
// MARK: - Lens
extension PostInfo {
enum lens {
static let page = Lens<PostInfo, Int>(get: { $0.page }, set: { return PostInfo(tid: $1.tid, page: $0, pid: $1.pid, authorid: $1.authorid) })
}
}
// MARK: - Helper
/// 比较两个optional是否相等
///
/// - Parameters:
/// - lhs: 左值
/// - rhs: 右值
/// - Returns: 都不为nil且相等,或者都为nil时返回true
private func ==<T: Equatable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let(l?, r?):
return l == r
case (nil, nil):
return true
default:
return false
}
}
|
mit
|
8ddafe4a17990857428a2d4706e6cecb
| 27.271739 | 148 | 0.555556 | 3.622563 | false | false | false | false |
Minitour/AZTabBar
|
SnapKit/ConstraintDescription.swift
|
2
|
29726
|
//
// SnapKit
//
// Copyright (c) 2011-2015 SnapKit Team - https://github.com/SnapKit
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(iOS) || os(tvOS)
import UIKit
#else
import AppKit
#endif
/**
Used to expose the final API of a `ConstraintDescription` which allows getting a constraint from it
*/
public protocol ConstraintDescriptionFinalizable: class {
var constraint: Constraint { get }
func labeled(_ label: String) -> ConstraintDescriptionFinalizable
}
/**
Used to expose priority APIs
*/
public protocol ConstraintDescriptionPriortizable: ConstraintDescriptionFinalizable {
func priority(_ priority: Float) -> ConstraintDescriptionFinalizable
func priority(_ priority: Double) -> ConstraintDescriptionFinalizable
func priority(_ priority: CGFloat) -> ConstraintDescriptionFinalizable
func priority(_ priority: UInt) -> ConstraintDescriptionFinalizable
func priority(_ priority: Int) -> ConstraintDescriptionFinalizable
func priorityRequired() -> ConstraintDescriptionFinalizable
func priorityHigh() -> ConstraintDescriptionFinalizable
func priorityMedium() -> ConstraintDescriptionFinalizable
func priorityLow() -> ConstraintDescriptionFinalizable
}
/**
Used to expose multiplier & constant APIs
*/
public protocol ConstraintDescriptionEditable: ConstraintDescriptionPriortizable {
func multipliedBy(_ amount: Float) -> ConstraintDescriptionEditable
func multipliedBy(_ amount: Double) -> ConstraintDescriptionEditable
func multipliedBy(_ amount: CGFloat) -> ConstraintDescriptionEditable
func multipliedBy(_ amount: Int) -> ConstraintDescriptionEditable
func multipliedBy(_ amount: UInt) -> ConstraintDescriptionEditable
func dividedBy(_ amount: Float) -> ConstraintDescriptionEditable
func dividedBy(_ amount: Double) -> ConstraintDescriptionEditable
func dividedBy(_ amount: CGFloat) -> ConstraintDescriptionEditable
func dividedBy(_ amount: Int) -> ConstraintDescriptionEditable
func dividedBy(_ amount: UInt) -> ConstraintDescriptionEditable
func offset(_ amount: Float) -> ConstraintDescriptionEditable
func offset(_ amount: Double) -> ConstraintDescriptionEditable
func offset(_ amount: CGFloat) -> ConstraintDescriptionEditable
func offset(_ amount: Int) -> ConstraintDescriptionEditable
func offset(_ amount: UInt) -> ConstraintDescriptionEditable
func offset(_ amount: CGPoint) -> ConstraintDescriptionEditable
func offset(_ amount: CGSize) -> ConstraintDescriptionEditable
func offset(_ amount: EdgeInsets) -> ConstraintDescriptionEditable
func inset(_ amount: Float) -> ConstraintDescriptionEditable
func inset(_ amount: Double) -> ConstraintDescriptionEditable
func inset(_ amount: CGFloat) -> ConstraintDescriptionEditable
func inset(_ amount: Int) -> ConstraintDescriptionEditable
func inset(_ amount: UInt) -> ConstraintDescriptionEditable
func inset(_ amount: EdgeInsets) -> ConstraintDescriptionEditable
}
/**
Used to expose relation APIs
*/
public protocol ConstraintDescriptionRelatable: class {
func equalTo(_ other: ConstraintItem) -> ConstraintDescriptionEditable
func equalTo(_ other: View) -> ConstraintDescriptionEditable
func equalToSuperview() -> ConstraintDescriptionEditable
@available(iOS 7.0, *)
func equalTo(_ other: LayoutSupport) -> ConstraintDescriptionEditable
@available(iOS 9.0, OSX 10.11, *)
func equalTo(other: NSLayoutAnchor<AnyObject>) -> ConstraintDescriptionEditable
func equalTo(_ other: Float) -> ConstraintDescriptionEditable
func equalTo(_ other: Double) -> ConstraintDescriptionEditable
func equalTo(_ other: CGFloat) -> ConstraintDescriptionEditable
func equalTo(_ other: Int) -> ConstraintDescriptionEditable
func equalTo(_ other: UInt) -> ConstraintDescriptionEditable
func equalTo(_ other: CGSize) -> ConstraintDescriptionEditable
func equalTo(_ other: CGPoint) -> ConstraintDescriptionEditable
func equalTo(_ other: EdgeInsets) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(_ other: ConstraintItem) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(_ other: View) -> ConstraintDescriptionEditable
func lessThanOrEqualToSuperview() -> ConstraintDescriptionEditable
@available(iOS 7.0, *)
func lessThanOrEqualTo(_ other: LayoutSupport) -> ConstraintDescriptionEditable
@available(iOS 9.0, OSX 10.11, *)
func lessThanOrEqualTo(other: NSLayoutAnchor<AnyObject>) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(_ other: Float) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(_ other: Double) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(_ other: CGFloat) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(_ other: Int) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(_ other: UInt) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(_ other: CGSize) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(_ other: CGPoint) -> ConstraintDescriptionEditable
func lessThanOrEqualTo(_ other: EdgeInsets) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(_ other: ConstraintItem) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(_ other: View) -> ConstraintDescriptionEditable
func greaterThanOrEqualToSuperview() -> ConstraintDescriptionEditable
@available(iOS 7.0, *)
func greaterThanOrEqualTo(_ other: LayoutSupport) -> ConstraintDescriptionEditable
@available(iOS 9.0, OSX 10.11, *)
func greaterThanOrEqualTo(other: NSLayoutAnchor<AnyObject>) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(_ other: Float) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(_ other: Double) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(_ other: CGFloat) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(_ other: Int) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(_ other: UInt) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(_ other: CGSize) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(_ other: CGPoint) -> ConstraintDescriptionEditable
func greaterThanOrEqualTo(_ other: EdgeInsets) -> ConstraintDescriptionEditable
}
/**
Used to expose chaining APIs
*/
public protocol ConstraintDescriptionExtendable: ConstraintDescriptionRelatable {
var left: ConstraintDescriptionExtendable { get }
var top: ConstraintDescriptionExtendable { get }
var bottom: ConstraintDescriptionExtendable { get }
var right: ConstraintDescriptionExtendable { get }
var leading: ConstraintDescriptionExtendable { get }
var trailing: ConstraintDescriptionExtendable { get }
var width: ConstraintDescriptionExtendable { get }
var height: ConstraintDescriptionExtendable { get }
var centerX: ConstraintDescriptionExtendable { get }
var centerY: ConstraintDescriptionExtendable { get }
var baseline: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var firstBaseline: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var leftMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var rightMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var topMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var bottomMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var leadingMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var trailingMargin: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var centerXWithinMargins: ConstraintDescriptionExtendable { get }
@available(iOS 8.0, *)
var centerYWithinMargins: ConstraintDescriptionExtendable { get }
}
/**
Used to internally manage building constraint
*/
internal class ConstraintDescription: ConstraintDescriptionExtendable, ConstraintDescriptionEditable, ConstraintDescriptionFinalizable {
internal var left: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Left) }
internal var top: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Top) }
internal var right: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Right) }
internal var bottom: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Bottom) }
internal var leading: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Leading) }
internal var trailing: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Trailing) }
internal var width: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Width) }
internal var height: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Height) }
internal var centerX: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.CenterX) }
internal var centerY: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.CenterY) }
internal var baseline: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.Baseline) }
internal var label: String?
@available(iOS 8.0, *)
internal var firstBaseline: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.FirstBaseline) }
@available(iOS 8.0, *)
internal var leftMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.LeftMargin) }
@available(iOS 8.0, *)
internal var rightMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.RightMargin) }
@available(iOS 8.0, *)
internal var topMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.TopMargin) }
@available(iOS 8.0, *)
internal var bottomMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.BottomMargin) }
@available(iOS 8.0, *)
internal var leadingMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.LeadingMargin) }
@available(iOS 8.0, *)
internal var trailingMargin: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.TrailingMargin) }
@available(iOS 8.0, *)
internal var centerXWithinMargins: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.CenterXWithinMargins) }
@available(iOS 8.0, *)
internal var centerYWithinMargins: ConstraintDescriptionExtendable { return self.addConstraint(ConstraintAttributes.CenterYWithinMargins) }
// MARK: initializer
init(fromItem: ConstraintItem) {
self.fromItem = fromItem
self.toItem = ConstraintItem(object: nil, attributes: ConstraintAttributes.None)
}
// MARK: equalTo
internal func equalTo(_ other: ConstraintItem) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
internal func equalTo(_ other: View) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
internal func equalToSuperview() -> ConstraintDescriptionEditable {
guard let superview = fromItem.view?.superview else {
fatalError("equalToSuperview() requires the view have a superview before being set.")
}
return self.equalTo(superview)
}
@available(iOS 7.0, *)
internal func equalTo(_ other: LayoutSupport) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
@available(iOS 9.0, OSX 10.11, *)
internal func equalTo(other: NSLayoutAnchor<AnyObject>) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
internal func equalTo(_ other: Float) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
internal func equalTo(_ other: Double) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .equal)
}
internal func equalTo(_ other: CGFloat) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .equal)
}
internal func equalTo(_ other: Int) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .equal)
}
internal func equalTo(_ other: UInt) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .equal)
}
internal func equalTo(_ other: CGSize) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
internal func equalTo(_ other: CGPoint) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
internal func equalTo(_ other: EdgeInsets) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .equal)
}
// MARK: lessThanOrEqualTo
internal func lessThanOrEqualTo(_ other: ConstraintItem) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: View) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualToSuperview() -> ConstraintDescriptionEditable {
guard let superview = fromItem.view?.superview else {
fatalError("lessThanOrEqualToSuperview() requires the view have a superview before being set.")
}
return self.lessThanOrEqualTo(superview)
}
@available(iOS 7.0, *)
internal func lessThanOrEqualTo(_ other: LayoutSupport) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
@available(iOS 9.0, OSX 10.11, *)
internal func lessThanOrEqualTo(other: NSLayoutAnchor<AnyObject>) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: Float) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: Double) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: CGFloat) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: Int) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: UInt) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: CGSize) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: CGPoint) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func lessThanOrEqualTo(_ other: EdgeInsets) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
// MARK: greaterThanOrEqualTo
internal func greaterThanOrEqualTo(_ other: ConstraintItem) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: View) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualToSuperview() -> ConstraintDescriptionEditable {
guard let superview = fromItem.view?.superview else {
fatalError("greaterThanOrEqualToSuperview() requires the view have a superview before being set.")
}
return self.greaterThanOrEqualTo(superview)
}
@available(iOS 7.0, *)
internal func greaterThanOrEqualTo(_ other: LayoutSupport) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
@available(iOS 9.0, OSX 10.11, *)
internal func greaterThanOrEqualTo(other: NSLayoutAnchor<AnyObject>) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .lessThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: Float) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: Double) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: CGFloat) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: Int) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: UInt) -> ConstraintDescriptionEditable {
return self.constrainTo(Float(other), relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: CGSize) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: CGPoint) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
internal func greaterThanOrEqualTo(_ other: EdgeInsets) -> ConstraintDescriptionEditable {
return self.constrainTo(other, relation: .greaterThanOrEqualTo)
}
// MARK: multiplier
internal func multipliedBy(_ amount: Float) -> ConstraintDescriptionEditable {
self.multiplier = amount
return self
}
internal func multipliedBy(_ amount: Double) -> ConstraintDescriptionEditable {
return self.multipliedBy(Float(amount))
}
internal func multipliedBy(_ amount: CGFloat) -> ConstraintDescriptionEditable {
return self.multipliedBy(Float(amount))
}
internal func multipliedBy(_ amount: Int) -> ConstraintDescriptionEditable {
return self.multipliedBy(Float(amount))
}
internal func multipliedBy(_ amount: UInt) -> ConstraintDescriptionEditable {
return self.multipliedBy(Float(amount))
}
internal func dividedBy(_ amount: Float) -> ConstraintDescriptionEditable {
self.multiplier = 1.0 / amount;
return self
}
internal func dividedBy(_ amount: Double) -> ConstraintDescriptionEditable {
return self.dividedBy(Float(amount))
}
internal func dividedBy(_ amount: CGFloat) -> ConstraintDescriptionEditable {
return self.dividedBy(Float(amount))
}
internal func dividedBy(_ amount: Int) -> ConstraintDescriptionEditable {
return self.dividedBy(Float(amount))
}
internal func dividedBy(_ amount: UInt) -> ConstraintDescriptionEditable {
return self.dividedBy(Float(amount))
}
// MARK: offset
internal func offset(_ amount: Float) -> ConstraintDescriptionEditable {
self.constant = amount
return self
}
internal func offset(_ amount: Double) -> ConstraintDescriptionEditable {
return self.offset(Float(amount))
}
internal func offset(_ amount: CGFloat) -> ConstraintDescriptionEditable {
return self.offset(Float(amount))
}
internal func offset(_ amount: Int) -> ConstraintDescriptionEditable {
return self.offset(Float(amount))
}
internal func offset(_ amount: UInt) -> ConstraintDescriptionEditable {
return self.offset(Float(amount))
}
internal func offset(_ amount: CGPoint) -> ConstraintDescriptionEditable {
self.constant = amount
return self
}
internal func offset(_ amount: CGSize) -> ConstraintDescriptionEditable {
self.constant = amount
return self
}
internal func offset(_ amount: EdgeInsets) -> ConstraintDescriptionEditable {
self.constant = amount
return self
}
// MARK: inset
internal func inset(_ amount: Float) -> ConstraintDescriptionEditable {
let value = CGFloat(amount)
self.constant = EdgeInsets(top: value, left: value, bottom: -value, right: -value)
return self
}
internal func inset(_ amount: Double) -> ConstraintDescriptionEditable {
let value = CGFloat(amount)
self.constant = EdgeInsets(top: value, left: value, bottom: -value, right: -value)
return self
}
internal func inset(_ amount: CGFloat) -> ConstraintDescriptionEditable {
self.constant = EdgeInsets(top: amount, left: amount, bottom: -amount, right: -amount)
return self
}
internal func inset(_ amount: Int) -> ConstraintDescriptionEditable {
let value = CGFloat(amount)
self.constant = EdgeInsets(top: value, left: value, bottom: -value, right: -value)
return self
}
internal func inset(_ amount: UInt) -> ConstraintDescriptionEditable {
let value = CGFloat(amount)
self.constant = EdgeInsets(top: value, left: value, bottom: -value, right: -value)
return self
}
internal func inset(_ amount: EdgeInsets) -> ConstraintDescriptionEditable {
self.constant = EdgeInsets(top: amount.top, left: amount.left, bottom: -amount.bottom, right: -amount.right)
return self
}
// MARK: priority
internal func priority(_ priority: Float) -> ConstraintDescriptionFinalizable {
self.priority = priority
return self
}
internal func priority(_ priority: Double) -> ConstraintDescriptionFinalizable {
return self.priority(Float(priority))
}
internal func priority(_ priority: CGFloat) -> ConstraintDescriptionFinalizable {
return self.priority(Float(priority))
}
func priority(_ priority: UInt) -> ConstraintDescriptionFinalizable {
return self.priority(Float(priority))
}
internal func priority(_ priority: Int) -> ConstraintDescriptionFinalizable {
return self.priority(Float(priority))
}
internal func priorityRequired() -> ConstraintDescriptionFinalizable {
return self.priority(1000.0)
}
internal func priorityHigh() -> ConstraintDescriptionFinalizable {
return self.priority(750.0)
}
internal func priorityMedium() -> ConstraintDescriptionFinalizable {
#if os(iOS) || os(tvOS)
return self.priority(500.0)
#else
return self.priority(501.0)
#endif
}
internal func priorityLow() -> ConstraintDescriptionFinalizable {
return self.priority(250.0)
}
// MARK: Constraint
internal var constraint: Constraint {
if self.concreteConstraint == nil {
if self.relation == nil {
fatalError("Attempting to create a constraint from a ConstraintDescription before it has been fully chained.")
}
self.concreteConstraint = ConcreteConstraint(
fromItem: self.fromItem,
toItem: self.toItem,
relation: self.relation!,
constant: self.constant,
multiplier: self.multiplier,
priority: self.priority,
label: self.label)
}
return self.concreteConstraint!
}
func labeled(_ label: String) -> ConstraintDescriptionFinalizable {
self.label = label
return self
}
// MARK: Private
fileprivate let fromItem: ConstraintItem
fileprivate var toItem: ConstraintItem {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
fileprivate var relation: ConstraintRelation? {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
fileprivate var constant: Any = Float(0.0) {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
fileprivate var multiplier: Float = 1.0 {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
fileprivate var priority: Float = 1000.0 {
willSet {
if self.concreteConstraint != nil {
fatalError("Attempting to modify a ConstraintDescription after its constraint has been created.")
}
}
}
fileprivate var concreteConstraint: ConcreteConstraint? = nil
fileprivate func addConstraint(_ attributes: ConstraintAttributes) -> ConstraintDescription {
if self.relation == nil {
self.fromItem.attributes += attributes
}
return self
}
fileprivate func constrainTo(_ other: ConstraintItem, relation: ConstraintRelation) -> ConstraintDescription {
if other.attributes != ConstraintAttributes.None {
let toLayoutAttributes = other.attributes.layoutAttributes
if toLayoutAttributes.count > 1 {
let fromLayoutAttributes = self.fromItem.attributes.layoutAttributes
if toLayoutAttributes != fromLayoutAttributes {
NSException(name: NSExceptionName(rawValue: "Invalid Constraint"), reason: "Cannot constrain to multiple non identical attributes", userInfo: nil).raise()
return self
}
other.attributes = ConstraintAttributes.None
}
}
self.toItem = other
self.relation = relation
return self
}
fileprivate func constrainTo(_ other: View, relation: ConstraintRelation) -> ConstraintDescription {
return constrainTo(ConstraintItem(object: other, attributes: ConstraintAttributes.None), relation: relation)
}
@available(iOS 7.0, *)
fileprivate func constrainTo(_ other: LayoutSupport, relation: ConstraintRelation) -> ConstraintDescription {
return constrainTo(ConstraintItem(object: other, attributes: ConstraintAttributes.None), relation: relation)
}
@available(iOS 9.0, OSX 10.11, *)
fileprivate func constrainTo(_ other: NSLayoutAnchor<AnyObject>, relation: ConstraintRelation) -> ConstraintDescription {
return constrainTo(ConstraintItem(object: other, attributes: ConstraintAttributes.None), relation: relation)
}
fileprivate func constrainTo(_ other: Float, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
fileprivate func constrainTo(_ other: Double, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
fileprivate func constrainTo(_ other: CGSize, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
fileprivate func constrainTo(_ other: CGPoint, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
fileprivate func constrainTo(_ other: EdgeInsets, relation: ConstraintRelation) -> ConstraintDescription {
self.constant = other
return constrainTo(ConstraintItem(object: nil, attributes: ConstraintAttributes.None), relation: relation)
}
}
|
mit
|
bcf29a2a389babcc958a4b552e9cd207
| 46.184127 | 174 | 0.716679 | 5.567709 | false | false | false | false |
anatoliyv/AssistantKit
|
AssistantKit/Classes/OS.swift
|
1
|
3130
|
//
// Version.swift
// Pods
//
// Created by Anatoliy Voropay on 6/8/16.
// Copyright © 2016 Anatoliy Voropay. All rights reserved.
//
import Foundation
/// Detecting iOS version
extension Device {
/// Current iOS version as string
public static var osVersion: OSVersion {
return OSVersion(UIDevice.current.systemVersion)
}
public static var os8 = OSVersion("8")
public static var os9 = OSVersion("9")
public static var os10 = OSVersion("10")
public static var os11 = OSVersion("11")
public static var os12 = OSVersion("12")
public static var os13 = OSVersion("13")
public static var os14 = OSVersion("14")
/// Struct to work with OS version
public struct OSVersion {
fileprivate(set) var version: String
public init(_ version: String) {
let characters = CharacterSet(charactersIn: "01234567890.")
let string = version.trimmingCharacters(in: characters.inverted)
let clearedString = version.trimmingCharacters(in: characters)
if clearedString.count > 0 {
print("WARNING: Wrong delimiter used for AppVersion: \(version). Will remove it.")
}
self.version = string
}
fileprivate var versionNumbers: [String] {
let characters = CharacterSet(charactersIn: ".")
var components = version.components(separatedBy: characters)
while true {
if let last = components.last,
last == "0"
{
components.removeLast()
continue
}
break
}
return components
}
}
}
/// `Equatable` protocol implementation
extension Device.OSVersion: Equatable {
public static func == (lhs: Device.OSVersion, rhs: Device.OSVersion) -> Bool {
let lComponents = lhs.versionNumbers
let rComponents = rhs.versionNumbers
guard lComponents.count == rComponents.count else { return false }
let maxIndex = lComponents.count
for index in 0..<maxIndex {
if let lInt = Int(lComponents[index]),
let rInt = Int(rComponents[index]),
lInt != rInt
{
return false
}
}
return true
}
}
/// `Comparable` protocol implementation
extension Device.OSVersion: Comparable {
public static func < (lhs: Device.OSVersion, rhs: Device.OSVersion) -> Bool {
let lComponents = lhs.versionNumbers
let rComponents = rhs.versionNumbers
let maxIndex = max(lComponents.count, rComponents.count)
for index in 0..<maxIndex {
guard lComponents.count != index else { return true }
guard rComponents.count != index else { return false }
if let lInt = Int(lComponents[index]),
let rInt = Int(rComponents[index])
{
if lInt < rInt { return true }
if lInt > rInt { return false }
}
}
return false
}
}
|
mit
|
bc9d7617fdcd9fd49a3e99ceae1444c8
| 27.445455 | 98 | 0.57814 | 4.762557 | false | false | false | false |
away4m/Vendors
|
Vendors/trace/trace.swift
|
1
|
8101
|
//
// Created by ALI KIRAN on 2/7/16.
// Copyright (c) 2016 ALI KIRAN. All rights reserved.
//
import Darwin
import Foundation
public func platform() -> String {
var size: Int = 0 // as Ben Stahl noticed in his answer
sysctlbyname("hw.machine", nil, &size, nil, 0)
var machine = [CChar](repeating: 0, count: Int(size))
sysctlbyname("hw.machine", &machine, &size, nil, 0)
return String(cString: machine)
}
public struct Boot {
public static var time = mach_absolute_time()
}
let ESCAPE = "\u{001b}["
let RESET_FG = ESCAPE + "fg;" // Clear any foreground color
let RESET_BG = ESCAPE + "bg;" // Clear any background color
let RESET = ESCAPE + ";" // Clear any foreground or background color
let colorEnabled = false
public func white<T>(_ object: T) -> String {
guard colorEnabled else {
return "\(object)"
}
return "\(ESCAPE)fg255,255,255;\(object)\(RESET)"
}
public func red<T>(_ object: T) -> String {
guard colorEnabled else {
return "\(object)"
}
return "\(ESCAPE)fg240,19,52;\(object)\(RESET)"
}
public func green<T>(_ object: T) -> String {
guard colorEnabled else {
return "\(object)"
}
return "\(ESCAPE)fg0,174,124;\(object)\(RESET)"
}
public func blue<T>(_ object: T) -> String {
guard colorEnabled else {
return "\(object)"
}
return "\(ESCAPE)fg27,183,195;\(object)\(RESET)"
}
public func yellow<T>(_ object: T) -> String {
guard colorEnabled else {
return "\(object)"
}
return "\(ESCAPE)fg255,252,25;\(object)\(RESET)"
}
public func purple<T>(_ object: T) -> String {
guard colorEnabled else {
return "\(object)"
}
return "\(ESCAPE)fg133,91,126;\(object)\(RESET)"
}
public func gray<T>(_ object: T) -> String {
guard colorEnabled else {
return "\(object)"
}
return "\(ESCAPE)fg0,255,255;\(object)\(RESET)"
}
public func padTo<T>(_ str: T, length: Int = 10, blank: String = " ") -> String {
let out = NSString(string: "\(str)")
return out.padding(toLength: max(length, out.length), withPad: blank, startingAt: 0)
}
@inline(__always) public func trace(_ file: String = #file, _ functionName: String = #function, _ lineNum: Int = #line) {
trace("", file, functionName, lineNum)
}
public enum TraceLevel: Int {
case trace, warning, error
}
public var logLevel = TraceLevel.trace
@inline(__always) public func traceWarning<Template>(_ object: @autoclosure () -> Template, _ file: String = #file, _ functionName: String = #function, _ lineNum: Int = #line) {
guard logLevel.rawValue <= TraceLevel.warning.rawValue else {
return
}
let threadSign = Thread.current.isMainThread ? "*" : ""
if let url = URL(string: file) {
let path = url.lastPathComponent
let first = Boot.time
let now = mach_absolute_time()
let elapsed = now - first
var info: mach_timebase_info = mach_timebase_info(numer: 0, denom: 0)
let status = mach_timebase_info(&info)
var total: UInt64 = 0
if status == KERN_SUCCESS {
total = (elapsed * UInt64(info.numer) / UInt64(info.denom)) / 1_000_000
}
let totalStr = "[\(total) ms]"
let threadSignStr = "\(threadSign)\(Unmanaged.passUnretained(Thread.current).toOpaque())"
let clickableLine = " \(path):\(lineNum)"
print("⚠️ \(yellow(padTo(totalStr))) \(yellow(padTo(threadSignStr, length: 20))) \(yellow(padTo(clickableLine, length: 40)))\n\t►\(green(padTo(functionName)))\n\t\t→\(purple(object()))\n\n", terminator: "")
} else {
print("⚠️ \n\(threadSign)\(functionName)\n\t \(object())\n", terminator: "")
}
}
@inline(__always) public func traceFocus<Template>(_ object: @autoclosure () -> Template, _ file: String = #file, _ functionName: String = #function, _ lineNum: Int = #line) {
guard logLevel.rawValue <= TraceLevel.error.rawValue else {
return
}
let threadSign = Thread.current.isMainThread ? "*" : ""
if let url = URL(string: file) {
let path = url.lastPathComponent
let first = Boot.time
let now = mach_absolute_time()
let elapsed = now - first
var info: mach_timebase_info = mach_timebase_info(numer: 0, denom: 0)
let status = mach_timebase_info(&info)
var total: UInt64 = 0
if status == KERN_SUCCESS {
total = (elapsed * UInt64(info.numer) / UInt64(info.denom)) / 1_000_000
}
let totalStr = "[\(total) ms]"
let threadSignStr = "\(threadSign)\(Unmanaged.passUnretained(Thread.current).toOpaque())"
let clickableLine = " \(path):\(lineNum)"
print("\n =================== ᕦ(ò_óˇ)ᕤ ===================\n")
print("🔥 \(red(padTo(totalStr))) \(red(padTo(threadSignStr, length: 20))) \(red(padTo(clickableLine, length: 40)))\n\t►\(green(padTo(functionName)))\n\t\t→\(purple(object()))\n\n", terminator: "")
print("==============================================================\n\n")
} else {
print("\n =================== ᕦ(ò_óˇ)ᕤ ===================\n")
print("🔥 \n\(threadSign)\(functionName)\n\t \(object())\n", terminator: "")
print("==============================================================\n\n")
}
}
@inline(__always) public func traceError<Template>(_ object: @autoclosure () -> Template, _ file: String = #file, _ functionName: String = #function, _ lineNum: Int = #line) {
guard logLevel.rawValue <= TraceLevel.error.rawValue else {
return
}
let threadSign = Thread.current.isMainThread ? "*" : ""
if let url = URL(string: file) {
let path = url.lastPathComponent
let first = Boot.time
let now = mach_absolute_time()
let elapsed = now - first
var info: mach_timebase_info = mach_timebase_info(numer: 0, denom: 0)
let status = mach_timebase_info(&info)
var total: UInt64 = 0
if status == KERN_SUCCESS {
total = (elapsed * UInt64(info.numer) / UInt64(info.denom)) / 1_000_000
}
let totalStr = "[\(total) ms]"
let threadSignStr = "\(threadSign)\(Unmanaged.passUnretained(Thread.current).toOpaque())"
let clickableLine = " \(path):\(lineNum)"
print("💥 \(red(padTo(totalStr))) \(red(padTo(threadSignStr, length: 20))) \(red(padTo(clickableLine, length: 40)))\n\t►\(green(padTo(functionName)))\n\t\t→\(purple(object()))\n\n", terminator: "")
} else {
print("💥 \n\(threadSign)\(functionName)\n\t \(object())\n", terminator: "")
}
}
@inline(__always) public func trace<Template>(_ object: @autoclosure () -> Template, _ file: String = #file, _ functionName: String = #function, _ lineNum: Int = #line) {
guard logLevel.rawValue >= TraceLevel.trace.rawValue else {
return
}
let threadSign = Thread.current.isMainThread ? "*" : ""
if let url = URL(string: file) {
let path = url.lastPathComponent
let first = Boot.time
let now = mach_absolute_time()
let elapsed = now - first
var info: mach_timebase_info = mach_timebase_info(numer: 0, denom: 0)
let status = mach_timebase_info(&info)
var total: UInt64 = 0
if status == KERN_SUCCESS {
total = (elapsed * UInt64(info.numer) / UInt64(info.denom)) / 1_000_000
}
let totalStr = "[\(total) ms]"
let threadSignStr = "\(threadSign)\(Unmanaged.passUnretained(Thread.current).toOpaque())"
let clickableLine = " \(path):\(lineNum)"
print("💡 \(white(padTo(totalStr))) \(white(padTo(threadSignStr, length: 20))) \(white(padTo(clickableLine, length: 40)))\n\t►\(green(padTo(functionName)))\n\t\t→\(purple(object()))\n\n", terminator: "")
} else {
print("💡 \n\(threadSign)\(functionName)\n\t \(object())\n", terminator: "")
}
}
@objc public class Console: NSObject {
override init() {
}
@inline(__always) public class func log() {
trace()
}
}
|
mit
|
42e4e8f0d3185d93c70dfb7e81a809cd
| 33.527897 | 214 | 0.585084 | 3.697151 | false | false | false | false |
crewshin/GasLog
|
Pods/RealmSwift/RealmSwift/Realm.swift
|
3
|
24787
|
////////////////////////////////////////////////////////////////////////////
//
// Copyright 2014 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
import Realm
import Realm.Private
/**
A Realm instance (also referred to as "a realm") represents a Realm
database.
Realms can either be stored on disk (see `init(path:)`) or in
memory (see `Configuration`).
Realm instances are cached internally, and constructing equivalent Realm
objects (with the same path or identifier) produces limited overhead.
If you specifically want to ensure a Realm object is
destroyed (for example, if you wish to open a realm, check some property, and
then possibly delete the realm file and re-open it), place the code which uses
the realm within an `autoreleasepool {}` and ensure you have no other
strong references to it.
- warning: Realm instances are not thread safe and can not be shared across
threads or dispatch queues. You must construct a new instance on each thread you want
to interact with the realm on. For dispatch queues, this means that you must
call it in each block which is dispatched, as a queue is not guaranteed to run
on a consistent thread.
*/
public final class Realm {
// MARK: Properties
/// Path to the file where this Realm is persisted.
public var path: String { return rlmRealm.path }
/// Indicates if this Realm was opened in read-only mode.
public var readOnly: Bool { return rlmRealm.readOnly }
/// The Schema used by this realm.
public var schema: Schema { return Schema(rlmRealm.schema) }
/// Returns the `Configuration` that was used to create this `Realm` instance.
public var configuration: Configuration { return Configuration.fromRLMRealmConfiguration(rlmRealm.configuration) }
/// Indicates if this Realm contains any objects.
public var isEmpty: Bool { return rlmRealm.isEmpty }
// MARK: Initializers
/**
Obtains a Realm instance with the given configuration. Defaults to the default Realm configuration,
which can be changed by setting `Realm.Configuration.defaultConfiguration`.
- parameter configuration: The configuration to use when creating the Realm instance.
- throws: An NSError if the Realm could not be initialized.
*/
public convenience init(configuration: Configuration = Configuration.defaultConfiguration) throws {
let rlmRealm = try RLMRealm(configuration: configuration.rlmConfiguration)
self.init(rlmRealm)
}
/**
Obtains a Realm instance persisted at the specified file path.
- parameter path: Path to the realm file.
- throws: An NSError if the Realm could not be initialized.
*/
public convenience init(path: String) throws {
let rlmRealm = try RLMRealm(path: path, key: nil, readOnly: false, inMemory: false, dynamic: false, schema: nil)
self.init(rlmRealm)
}
// MARK: Transactions
/**
Performs actions contained within the given block inside a write transation.
Write transactions cannot be nested, and trying to execute a write transaction
on a `Realm` which is already in a write transaction will throw an exception.
Calls to `write` from `Realm` instances in other threads will block
until the current write transaction completes.
Before executing the write transaction, `write` updates the `Realm` to the
latest Realm version, as if `refresh()` was called, and generates notifications
if applicable. This has no effect if the `Realm` was already up to date.
- parameter block: The block to be executed inside a write transaction.
- throws: An NSError if the transaction could not be written.
*/
public func write(@noescape block: (() -> Void)) throws {
try rlmRealm.transactionWithBlock(block)
}
/**
Begins a write transaction in a `Realm`.
Only one write transaction can be open at a time. Write transactions cannot be
nested, and trying to begin a write transaction on a `Realm` which is
already in a write transaction will throw an exception. Calls to
`beginWrite` from `Realm` instances in other threads will block
until the current write transaction completes.
Before beginning the write transaction, `beginWrite` updates the
`Realm` to the latest Realm version, as if `refresh()` was called, and
generates notifications if applicable. This has no effect if the `Realm`
was already up to date.
It is rarely a good idea to have write transactions span multiple cycles of
the run loop, but if you do wish to do so you will need to ensure that the
`Realm` in the write transaction is kept alive until the write transaction
is committed.
*/
public func beginWrite() {
rlmRealm.beginWriteTransaction()
}
/**
Commits all writes operations in the current write transaction, and ends
the transaction.
Calling this when not in a write transaction will throw an exception.
- throws: An NSError if the transaction could not be written.
*/
public func commitWrite() throws {
try rlmRealm.commitWriteTransaction()
}
/**
Reverts all writes made in the current write transaction and end the transaction.
This rolls back all objects in the Realm to the state they were in at the
beginning of the write transaction, and then ends the transaction.
This restores the data for deleted objects, but does not revive invalidated
object instances. Any `Object`s which were added to the Realm will be
invalidated rather than switching back to standalone objects.
Given the following code:
```swift
let oldObject = objects(ObjectType).first!
let newObject = ObjectType()
realm.beginWrite()
realm.add(newObject)
realm.delete(oldObject)
realm.cancelWrite()
```
Both `oldObject` and `newObject` will return `true` for `invalidated`,
but re-running the query which provided `oldObject` will once again return
the valid object.
Calling this when not in a write transaction will throw an exception.
*/
public func cancelWrite() {
rlmRealm.cancelWriteTransaction()
}
/**
Indicates if this Realm is currently in a write transaction.
- warning: Wrapping mutating operations in a write transaction if this property returns `false`
may cause a large number of write transactions to be created, which could negatively
impact Realm's performance. Always prefer performing multiple mutations in a single
transaction when possible.
*/
public var inWriteTransaction: Bool {
return rlmRealm.inWriteTransaction
}
// MARK: Adding and Creating objects
/**
Adds or updates an object to be persisted it in this Realm.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
When added, all (child) relationships referenced by this object will also be
added to the Realm if they are not already in it. If the object or any related
objects already belong to a different Realm an exception will be thrown. Use one
of the `create` functions to insert a copy of a persisted object into a different
Realm.
The object to be added must be valid and cannot have been previously deleted
from a Realm (i.e. `invalidated` must be false).
- parameter object: Object to be added to this Realm.
- parameter update: If true will try to update existing objects with the same primary key.
*/
public func add(object: Object, update: Bool = false) {
if update && object.objectSchema.primaryKeyProperty == nil {
throwRealmException("'\(object.objectSchema.className)' does not have a primary key and can not be updated")
}
RLMAddObjectToRealm(object, rlmRealm, update)
}
/**
Adds or updates objects in the given sequence to be persisted it in this Realm.
- see: add(_:update:)
- warning: This method can only be called during a write transaction.
- parameter objects: A sequence which contains objects to be added to this Realm.
- parameter update: If true will try to update existing objects with the same primary key.
*/
public func add<S: SequenceType where S.Generator.Element: Object>(objects: S, update: Bool = false) {
for obj in objects {
add(obj, update: update)
}
}
/**
Create an `Object` with the given value.
Creates or updates an instance of this object and adds it to the `Realm` populating
the object with the given value.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
- warning: This method can only be called during a write transaction.
- parameter type: The object type to create.
- parameter value: The value used to populate the object. This can be any key/value coding compliant
object, or a JSON dictionary such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
When passing in an `Array`, all properties must be present,
valid and in the same order as the properties defined in the model.
- parameter update: If true will try to update existing objects with the same primary key.
- returns: The created object.
*/
public func create<T: Object>(type: T.Type, value: AnyObject = [:], update: Bool = false) -> T {
let className = (type as Object.Type).className()
if update && schema[className]?.primaryKeyProperty == nil {
throwRealmException("'\(className)' does not have a primary key and can not be updated")
}
return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, className, value, update), T.self)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `create(_:value:update:)`.
Creates or updates an object with the given class name and adds it to the `Realm`, populating
the object with the given value.
When 'update' is 'true', the object must have a primary key. If no objects exist in
the Realm instance with the same primary key value, the object is inserted. Otherwise,
the existing object is updated with any changed values.
- warning: This method can only be called during a write transaction.
- parameter className: The class name of the object to create.
- parameter value: The value used to populate the object. This can be any key/value coding compliant
object, or a JSON dictionary such as those returned from the methods in `NSJSONSerialization`,
or an `Array` with one object for each persisted property. An exception will be
thrown if any required properties are not present and no default is set.
When passing in an `Array`, all properties must be present,
valid and in the same order as the properties defined in the model.
- parameter update: If true will try to update existing objects with the same primary key.
- returns: The created object.
:nodoc:
*/
public func dynamicCreate(className: String, value: AnyObject = [:], update: Bool = false) -> DynamicObject {
if update && schema[className]?.primaryKeyProperty == nil {
throwRealmException("'\(className)' does not have a primary key and can not be updated")
}
return unsafeBitCast(RLMCreateObjectInRealmWithValue(rlmRealm, className, value, update), DynamicObject.self)
}
// MARK: Deleting objects
/**
Deletes the given object from this Realm.
- warning: This method can only be called during a write transaction.
- parameter object: The object to be deleted.
*/
public func delete(object: Object) {
RLMDeleteObjectFromRealm(object, rlmRealm)
}
/**
Deletes the given objects from this Realm.
- warning: This method can only be called during a write transaction.
- parameter objects: The objects to be deleted. This can be a `List<Object>`, `Results<Object>`,
or any other enumerable SequenceType which generates Object.
*/
public func delete<S: SequenceType where S.Generator.Element: Object>(objects: S) {
for obj in objects {
delete(obj)
}
}
/**
Deletes the given objects from this Realm.
- warning: This method can only be called during a write transaction.
- parameter objects: The objects to be deleted. Must be `List<Object>`.
:nodoc:
*/
public func delete<T: Object>(objects: List<T>) {
rlmRealm.deleteObjects(objects._rlmArray)
}
/**
Deletes the given objects from this Realm.
- warning: This method can only be called during a write transaction.
- parameter objects: The objects to be deleted. Must be `Results<Object>`.
:nodoc:
*/
public func delete<T: Object>(objects: Results<T>) {
rlmRealm.deleteObjects(objects.rlmResults)
}
/**
Deletes all objects from this Realm.
- warning: This method can only be called during a write transaction.
*/
public func deleteAll() {
RLMDeleteAllObjectsFromRealm(rlmRealm)
}
// MARK: Object Retrieval
/**
Returns all objects of the given type in the Realm.
- parameter type: The type of the objects to be returned.
- returns: All objects of the given type in Realm.
*/
public func objects<T: Object>(type: T.Type) -> Results<T> {
return Results<T>(RLMGetObjects(rlmRealm, (type as Object.Type).className(), nil))
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objects(type:)`.
Returns all objects for a given class name in the Realm.
- warning: This method is useful only in specialized circumstances.
- parameter className: The class name of the objects to be returned.
- returns: All objects for the given class name as dynamic objects
:nodoc:
*/
public func dynamicObjects(className: String) -> Results<DynamicObject> {
return Results<DynamicObject>(RLMGetObjects(rlmRealm, className, nil))
}
/**
Get an object with the given primary key.
Returns `nil` if no object exists with the given primary key.
This method requires that `primaryKey()` be overridden on the given subclass.
- see: Object.primaryKey()
- parameter type: The type of the objects to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `type` or `nil` if an object with the given primary key does not exist.
*/
public func objectForPrimaryKey<T: Object>(type: T.Type, key: AnyObject) -> T? {
return unsafeBitCast(RLMGetObject(rlmRealm, (type as Object.Type).className(), key), Optional<T>.self)
}
/**
This method is useful only in specialized circumstances, for example, when building
components that integrate with Realm. If you are simply building an app on Realm, it is
recommended to use the typed method `objectForPrimaryKey(_:key:)`.
Get a dynamic object with the given class name and primary key.
Returns `nil` if no object exists with the given class name and primary key.
This method requires that `primaryKey()` be overridden on the given subclass.
- see: Object.primaryKey()
- warning: This method is useful only in specialized circumstances.
- parameter className: The class name of the object to be returned.
- parameter key: The primary key of the desired object.
- returns: An object of type `DynamicObject` or `nil` if an object with the given primary key does not exist.
:nodoc:
*/
public func dynamicObjectForPrimaryKey(className: String, key: AnyObject) -> DynamicObject? {
return unsafeBitCast(RLMGetObject(rlmRealm, className, key), Optional<DynamicObject>.self)
}
// MARK: Notifications
/**
Add a notification handler for changes in this Realm.
Notification handlers are called after each write transaction is committed,
either on the current thread or other threads. The block is called on the
same thread as they were added on, and can only be added on threads which
are currently within a run loop. Unless you are specifically creating and
running a run loop on a background thread, this normally will only be the
main thread.
- parameter block: A block which is called to process Realm notifications.
It receives the following parameters:
- `Notification`: The incoming notification.
- `Realm`: The realm for which this notification occurred.
- returns: A notification token which can later be passed to `removeNotification(_:)`
to remove this notification.
*/
public func addNotificationBlock(block: NotificationBlock) -> NotificationToken {
return rlmRealm.addNotificationBlock(rlmNotificationBlockFromNotificationBlock(block))
}
/**
Remove a previously registered notification handler using the token returned
from `addNotificationBlock(_:)`
- parameter notificationToken: The token returned from `addNotificationBlock(_:)`
corresponding to the notification block to remove.
*/
public func removeNotification(notificationToken: NotificationToken) {
rlmRealm.removeNotification(notificationToken)
}
// MARK: Autorefresh and Refresh
/**
Whether this Realm automatically updates when changes happen in other threads.
If set to `true` (the default), changes made on other threads will be reflected
in this Realm on the next cycle of the run loop after the changes are
committed. If set to `false`, you must manually call `refresh()` on the Realm to
update it to get the latest version.
Note that by default, background threads do not have an active run loop and you
will need to manually call `refresh()` in order to update to the latest version,
even if `autorefresh` is set to `true`.
Even with this enabled, you can still call `refresh()` at any time to update the
Realm before the automatic refresh would occur.
Notifications are sent when a write transaction is committed whether or not
this is enabled.
Disabling this on a `Realm` without any strong references to it will not
have any effect, and it will switch back to YES the next time the `Realm`
object is created. This is normally irrelevant as it means that there is
nothing to refresh (as persisted `Object`s, `List`s, and `Results` have strong
references to the containing `Realm`), but it means that setting
`Realm().autorefresh = false` in
`application(_:didFinishLaunchingWithOptions:)` and only later storing Realm
objects will not work.
Defaults to true.
*/
public var autorefresh: Bool {
get {
return rlmRealm.autorefresh
}
set {
rlmRealm.autorefresh = newValue
}
}
/**
Update a `Realm` and outstanding objects to point to the most recent
data for this `Realm`.
- returns: Whether the realm had any updates.
Note that this may return true even if no data has actually changed.
*/
public func refresh() -> Bool {
return rlmRealm.refresh()
}
// MARK: Invalidation
/**
Invalidate all `Object`s and `Results` read from this Realm.
A Realm holds a read lock on the version of the data accessed by it, so
that changes made to the Realm on different threads do not modify or delete the
data seen by this Realm. Calling this method releases the read lock,
allowing the space used on disk to be reused by later write transactions rather
than growing the file. This method should be called before performing long
blocking operations on a background thread on which you previously read data
from the Realm which you no longer need.
All `Object`, `Results` and `List` instances obtained from this
`Realm` on the current thread are invalidated, and can not longer be used.
The `Realm` itself remains valid, and a new read transaction is implicitly
begun the next time data is read from the Realm.
Calling this method multiple times in a row without reading any data from the
Realm, or before ever reading any data from the Realm is a no-op. This method
cannot be called on a read-only Realm.
*/
public func invalidate() {
rlmRealm.invalidate()
}
// MARK: Writing a Copy
/**
Write an encrypted and compacted copy of the Realm to the given path.
The destination file cannot already exist.
Note that if this is called from within a write transaction it writes the
*current* data, and not data when the last write transaction was committed.
- parameter path: Path to save the Realm to.
- parameter encryptionKey: Optional 64-byte encryption key to encrypt the new file with.
- throws: An NSError if the copy could not be written.
*/
public func writeCopyToPath(path: String, encryptionKey: NSData? = nil) throws {
if let encryptionKey = encryptionKey {
try rlmRealm.writeCopyToPath(path, encryptionKey: encryptionKey)
} else {
try rlmRealm.writeCopyToPath(path)
}
}
// MARK: Internal
internal var rlmRealm: RLMRealm
internal init(_ rlmRealm: RLMRealm) {
self.rlmRealm = rlmRealm
}
}
// MARK: Equatable
extension Realm: Equatable { }
// swiftlint:disable valid_docs
/// Returns whether the two realms are equal.
public func == (lhs: Realm, rhs: Realm) -> Bool {
return lhs.rlmRealm == rhs.rlmRealm
}
// swiftlint:enable valid_docs
// MARK: Notifications
/// A notification due to changes to a realm.
public enum Notification: String {
/**
Posted when the data in a realm has changed.
DidChange is posted after a realm has been refreshed to reflect a write transaction, i.e. when
an autorefresh occurs, `refresh()` is called, after an implicit refresh from
`write(_:)`/`beginWrite()`, and after a local write transaction is committed.
*/
case DidChange = "RLMRealmDidChangeNotification"
/**
Posted when a write transaction has been committed to a Realm on a different thread for the same
file. This is not posted if `autorefresh` is enabled or if the Realm is refreshed before the
notification has a chance to run.
Realms with autorefresh disabled should normally have a handler for this notification which
calls `refresh()` after doing some work.
While not refreshing is allowed, it may lead to large Realm files as Realm has to keep an extra
copy of the data for the un-refreshed Realm.
*/
case RefreshRequired = "RLMRealmRefreshRequiredNotification"
}
/// Closure to run when the data in a Realm was modified.
public typealias NotificationBlock = (notification: Notification, realm: Realm) -> Void
internal func rlmNotificationBlockFromNotificationBlock(notificationBlock: NotificationBlock) -> RLMNotificationBlock {
return { rlmNotification, rlmRealm in
return notificationBlock(notification: Notification(rawValue: rlmNotification)!, realm: Realm(rlmRealm))
}
}
|
mit
|
50c8b67e19fc51df10102a5a923fb32f
| 38.344444 | 120 | 0.697059 | 4.918056 | false | false | false | false |
BalestraPatrick/ValueStepper
|
Example/ValueStepper/ViewController.swift
|
3
|
1953
|
//
// ViewController.swift
// ValueStepper
//
// Created by Patrick Balestra on 02/18/2016.
// Copyright (c) 2016 Patrick Balestra. All rights reserved.
//
import UIKit
import ValueStepper
class ViewController: UIViewController {
@IBOutlet weak var stepper1: ValueStepper!
@IBOutlet weak var stepper2: ValueStepper!
@IBOutlet weak var stepper3: ValueStepper!
@IBOutlet weak var stepper4: ValueStepper!
override func viewDidLoad() {
super.viewDidLoad()
// Enabled a tap on the label to manually modify the value in a UIAlertController.
stepper1.enableManualEditing = true
// Set up currency number formatter.
let moneyFormatter = NumberFormatter()
moneyFormatter.numberStyle = .currency
moneyFormatter.maximumFractionDigits = 0
stepper3.numberFormatter = moneyFormatter
stepper3.addTarget(self, action: #selector(ViewController.valueChanged3), for: .valueChanged)
stepper4.tintColor = .white
stepper4.disabledIconButtonColor = .white
stepper4.disabledBackgroundButtonColor = UIColor(red: 43 / 255, green: 145 / 255, blue: 154 / 255, alpha: 1)
stepper4.backgroundButtonColor = UIColor(red: 57 / 255, green: 193 / 255, blue: 204 / 255, alpha: 1)
stepper4.highlightedBackgroundColor = UIColor(red: 43 / 255, green: 145 / 255, blue: 154 / 255, alpha: 1)
stepper4.backgroundLabelColor = .clear
stepper4.enableManualEditing = true
}
@IBAction func valueChanged1(_ sender: ValueStepper) {
print("Stepper 1: \(sender.value)")
}
@IBAction func valueChanged2(_ sender: ValueStepper) {
print("Stepper 2: \(sender.value)")
}
@objc func valueChanged3(_ sender: ValueStepper) {
print("Stepper 3: \(sender.value)")
}
@IBAction func valueChanged4(_ sender: ValueStepper) {
print("Stepper 4: \(sender.value)")
}
}
|
mit
|
613ab7dc9af7e26f2a80c7a21b9bb253
| 32.672414 | 116 | 0.668203 | 4.428571 | false | false | false | false |
myTargetSDK/mytarget-ios
|
myTargetDemoSwift/myTargetDemo/Extensions/CGSize+Resize.swift
|
1
|
642
|
//
// CGSize+Resize.swift
// myTargetDemo
//
// Created by igor.sorokin on 05.10.2022.
// Copyright © 2022 Mail.ru Group. All rights reserved.
//
import UIKit
extension CGSize {
func resize(targetSize: CGSize) -> CGSize {
guard
width != 0, height != 0,
targetSize.width != 0, targetSize.height != 0
else {
return .zero
}
let widthRatio = targetSize.width / width
let heightRatio = targetSize.height / height
if widthRatio > heightRatio {
return CGSize(width: width * heightRatio, height: height * heightRatio)
} else {
return CGSize(width: width * widthRatio, height: height * widthRatio)
}
}
}
|
lgpl-3.0
|
ec1d42be4d875000ff9164a3a5367714
| 19.677419 | 74 | 0.669267 | 3.391534 | false | false | false | false |
sin2/SwiftTiles
|
SwiftTiles/AppConstants.swift
|
1
|
297
|
//
// AppConstants.swift
// SwiftTiles
//
// Created by Sin2 on 2014-06-05.
// Copyright (c) 2014 Sin2. All rights reserved.
//
import Foundation
let defaultTileHeight = 50
let defaultGameSize = 4
let defaultGameHeight = 4
let defaultGameLength = 25
let kGameTimeLabelHeight: CGFloat = 50
|
mit
|
eb272cbfa92700c2565e1aac2d1789bc
| 15.555556 | 49 | 0.73064 | 3.3 | false | false | false | false |
Nyx0uf/MPDRemote
|
src/common/extensions/UIDevice+Extensions.swift
|
1
|
1408
|
// UIDevice+Extensions.swift
// Copyright (c) 2017 Nyx0uf
//
// 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
extension UIDevice
{
func isPad() -> Bool
{
return userInterfaceIdiom == .pad
}
func isPhone() -> Bool
{
return userInterfaceIdiom == .phone
}
func isiPhoneX() -> Bool
{
return isPhone() && Int(UIScreen.main.nativeBounds.height) == 2436
}
}
|
mit
|
81de625f0dccf890052e0dc355a11d45
| 32.52381 | 80 | 0.744318 | 4.240964 | false | false | false | false |
stephentyrone/swift
|
test/SourceKit/CodeComplete/complete_checkdeps_clangmodule.swift
|
6
|
2491
|
import ClangFW
import SwiftFW
func foo() {
/*HERE*/
}
// REQUIRES: shell
// RUN: %empty-directory(%t/Frameworks)
// RUN: %empty-directory(%t/MyProject)
// RUN: COMPILER_ARGS=( \
// RUN: -target %target-triple \
// RUN: -module-name MyProject \
// RUN: -F %t/Frameworks \
// RUN: -I %t/MyProject \
// RUN: -import-objc-header %t/MyProject/Bridging.h \
// RUN: %t/MyProject/Library.swift \
// RUN: %s \
// RUN: )
// RUN: INPUT_DIR=%S/Inputs/checkdeps
// RUN: DEPCHECK_INTERVAL=1
// RUN: SLEEP_TIME=2
// RUN: cp -R $INPUT_DIR/MyProject %t/
// RUN: cp -R $INPUT_DIR/ClangFW.framework %t/Frameworks/
// RUN: %empty-directory(%t/Frameworks/SwiftFW.framework/Modules/SwiftFW.swiftmodule)
// RUN: %target-swift-frontend -emit-module -module-name SwiftFW -o %t/Frameworks/SwiftFW.framework/Modules/SwiftFW.swiftmodule/%target-swiftmodule-name $INPUT_DIR/SwiftFW_src/Funcs.swift
// RUN: %sourcekitd-test \
// RUN: -req=global-config -completion-check-dependency-interval ${DEPCHECK_INTERVAL} == \
// RUN: -shell -- echo "### Initial" == \
// RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} == \
// RUN: -shell -- echo '### Modify framework (c)' == \
// RUN: -shell -- sleep $SLEEP_TIME == \
// RUN: -shell -- cp -R $INPUT_DIR/ClangFW.framework_mod/* %t/Frameworks/ClangFW.framework/ == \
// RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} == \
// RUN: -shell -- echo '### Fast completion' == \
// RUN: -shell -- sleep $SLEEP_TIME == \
// RUN: -req=complete -pos=5:3 %s -- ${COMPILER_ARGS[@]} \
// RUN: | %FileCheck %s
// CHECK-LABEL: ### Initial
// CHECK: key.results: [
// CHECK-DAG: key.description: "clangFWFunc()"
// CHECK-DAG: key.description: "swiftFWFunc()"
// CHECK-DAG: key.description: "localClangFunc()"
// CHECK-DAG: key.description: "localSwiftFunc()"
// CHECK: ]
// CHECK-NOT: key.reusingastcontext: 1
// CHECK-LABEL: ### Modify framework (c)
// CHECK: key.results: [
// CHECK-DAG: key.description: "clangFWFunc_mod()"
// CHECK-DAG: key.description: "swiftFWFunc()"
// CHECK-DAG: key.description: "localClangFunc()"
// CHECK-DAG: key.description: "localSwiftFunc()"
// CHECK: ]
// CHECK-NOT: key.reusingastcontext: 1
// CHECK-LABEL: ### Fast completion
// CHECK: key.results: [
// CHECK-DAG: key.description: "clangFWFunc_mod()"
// CHECK-DAG: key.description: "swiftFWFunc()"
// CHECK-DAG: key.description: "localClangFunc()"
// CHECK-DAG: key.description: "localSwiftFunc()"
// CHECK: ]
// CHECK: key.reusingastcontext: 1
|
apache-2.0
|
3e11c022674dd2fd1b9c4d419bc75524
| 32.662162 | 187 | 0.647531 | 3.067734 | false | false | false | false |
benlangmuir/swift
|
test/IDE/comment_brief.swift
|
23
|
2701
|
// RUN: %target-swift-ide-test -print-comments -source-filename %s | %FileCheck %s
// REQUIRES: no_asan
///
func briefLine1() {}
/// Aaa.
func briefLine2() {}
/// Aaa.
/// Bbb.
func briefLine3() {}
/// Aaa.
///
/// Bbb.
func briefLine4() {}
/***/
func briefBlock1() {}
/**
*/
func briefBlock2() {}
/**
Aaa.
*/
func briefBlock3() {}
/**
Aaa.
*/
func briefBlock4() {}
/**
Aaa.
Bbb.
*/
func briefBlock5() {}
/**
Aaa.
Bbb.
*/
func briefBlock6() {}
/** Aaa.
* Bbb.
*/
func briefBlock7() {}
/** Aaa.
* Bbb.
* Ccc.
*/
func briefBlock8() {}
/** Aaa.
* Bbb.
Ccc.
*/
func briefBlock9() {}
/**
* Aaa.
*/
func briefBlockWithASCIIArt1() {}
/**
*
*/
func briefBlockWithASCIIArt2() {}
/**
* Aaa.
* Bbb.
*/
func briefBlockWithASCIIArt3() {}
/**
*Aaa.
*/
func briefBlockWithASCIIArt4() {}
/**
* Aaa.
Bbb.
*Ccc.
*/
func briefBlockWithASCIIArt5() {}
/**
* Aaa.
* Bbb.
*/
func briefBlockWithASCIIArt6() {}
/// Aaa.
/** Bbb. */
func briefMixed1() {}
/// Aaa.
/**
Bbb.
*/
func briefMixed2() {}
/**
Aaa.
*/
/**
Bbb.
*/
func briefMixed3() {}
struct Indentation {
/**
* Aaa.
*/
func briefBlockWithASCIIArt1() {}
}
// CHECK: Func/briefLine1 {{.*}} BriefComment=none
// CHECK-NEXT: Func/briefLine2 {{.*}} BriefComment=[Aaa.]
// CHECK-NEXT: Func/briefLine3 {{.*}} BriefComment=[Aaa. Bbb.]
// CHECK-NEXT: Func/briefLine4 {{.*}} BriefComment=[Aaa.]
// CHECK-NEXT: Func/briefBlock1 {{.*}} BriefComment=none
// CHECK-NEXT: Func/briefBlock2 {{.*}} BriefComment=none
// CHECK-NEXT: Func/briefBlock3 {{.*}} BriefComment=[Aaa.]
// CHECK-NEXT: Func/briefBlock4 {{.*}} BriefComment=[Aaa.]
// CHECK-NEXT: Func/briefBlock5 {{.*}} BriefComment=[Aaa. Bbb.]
// CHECK-NEXT: Func/briefBlock6 {{.*}} BriefComment=[Aaa.]
// CHECK-NEXT: Func/briefBlock7 {{.*}} BriefComment=[Aaa.]
// CHECK-NEXT: Func/briefBlock8 {{.*}} BriefComment=[Aaa.]
// CHECK-NEXT: Func/briefBlock9 {{.*}} BriefComment=[Aaa.]
// CHECK-NEXT: Func/briefBlockWithASCIIArt1 {{.*}} BriefComment=[Aaa.]
// CHECK-NEXT: Func/briefBlockWithASCIIArt2 {{.*}} BriefComment=none
// CHECK-NEXT: Func/briefBlockWithASCIIArt3 {{.*}} BriefComment=[Aaa. Bbb.]
// CHECK-NEXT: Func/briefBlockWithASCIIArt4 {{.*}} BriefComment=[*Aaa.]
// CHECK-NEXT: Func/briefBlockWithASCIIArt5 {{.*}} BriefComment=[Aaa. Bbb. *Ccc.]
// CHECK-NEXT: Func/briefBlockWithASCIIArt6 {{.*}} BriefComment=[Aaa.]
// CHECK-NEXT: Func/briefMixed1 {{.*}} BriefComment=[Aaa. Bbb.]
// CHECK-NEXT: Func/briefMixed2 {{.*}} BriefComment=[Aaa. Bbb.]
// CHECK-NEXT: Func/briefMixed3 {{.*}} BriefComment=[Aaa. Bbb.]
// CHECK-NEXT: Struct/Indentation RawComment=none
// CHECK-NEXT: Func/Indentation.briefBlockWithASCIIArt1 {{.*}} BriefComment=[Aaa.]
|
apache-2.0
|
477422a6a80d6964bbac6a010ed1efde
| 16.769737 | 82 | 0.61903 | 3.028027 | false | false | false | false |
aichamorro/fitness-tracker
|
Clients/Apple/FitnessTracker/FitnessTracker/Foundation/Interactor.swift
|
1
|
1783
|
//
// Interactor.swift
// FitnessTracker
//
// Created by Alberto Chamorro - Personal on 07/07/2017.
// Copyright © 2017 OnsetBits. All rights reserved.
//
import Foundation
import RxSwift
public protocol InteractorType {
associatedtype InputType
associatedtype OutputTpe
var rx_input: AnyObserver<InputType> { get }
var rx_output: Observable<OutputTpe> { get }
}
public extension InteractorType {
func send(value: InputType) {
rx_input.onNext(value)
}
}
public class AnyInteractor<InElementType, OutElementType>: InteractorType {
public typealias OutputTpe = OutElementType
public typealias InputType = InElementType
public typealias UseCaseImpl = (InElementType) -> Observable<OutElementType>
private let rx_outputSubject = PublishSubject<OutElementType>()
private let disposeBag = DisposeBag()
public var rx_output: Observable<OutElementType> {
return rx_outputSubject.asObservable().observeOn(MainScheduler.instance)
}
public var rx_input: AnyObserver<InElementType> {
return AnyObserver { event in
switch event {
case .next(let element):
self.executeUseCaseWithInput(element)
.subscribe(onNext: { result in
self.rx_outputSubject.onNext(result)
}, onError: { error in
self.rx_outputSubject.onError(error)
}).addDisposableTo(self.disposeBag)
default:
// NOTE: Interactors shouldn't receive onCompleted or onError
break
}
}
}
let executeUseCaseWithInput: UseCaseImpl
init(_ useCase: @escaping UseCaseImpl) {
self.executeUseCaseWithInput = useCase
}
}
|
gpl-3.0
|
ea8143b20b638e326f8c146f490a9225
| 29.20339 | 80 | 0.648709 | 4.829268 | false | false | false | false |
ipmobiletech/firefox-ios
|
Storage/Bookmarks.swift
|
13
|
11571
|
/* 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 UIKit
import Shared
/// Small structure to encapsulate all the possible data that we can get
// from an application sharing a web page or a URL.
public struct ShareItem {
public let url: String
public let title: String?
public let favicon: Favicon?
public init(url: String, title: String?, favicon: Favicon?) {
self.url = url
self.title = title
self.favicon = favicon
}
}
public protocol ShareToDestination {
func shareItem(item: ShareItem)
}
public protocol SearchableBookmarks {
func bookmarksByURL(url: NSURL) -> Deferred<Maybe<Cursor<BookmarkItem>>>
}
public struct BookmarkRoots {
// These match Places on desktop.
public static let RootGUID = "root________"
public static let MobileFolderGUID = "mobile______"
public static let MenuFolderGUID = "menu________"
public static let ToolbarFolderGUID = "toolbar_____"
public static let UnfiledFolderGUID = "unfiled_____"
/*
public static let TagsFolderGUID = "tags________"
public static let PinnedFolderGUID = "pinned______"
public static let FakeDesktopFolderGUID = "desktop_____"
*/
static let RootID = 0
static let MobileID = 1
static let MenuID = 2
static let ToolbarID = 3
static let UnfiledID = 4
}
/**
* This matches Places's nsINavBookmarksService, just for sanity.
* These are only used at the DB layer.
*/
public enum BookmarkNodeType: Int {
case Bookmark = 1
case Folder = 2
case Separator = 3
case DynamicContainer = 4
}
/**
* The immutable base interface for bookmarks and folders.
*/
public class BookmarkNode {
public var id: Int? = nil
public var guid: String
public var title: String
public var favicon: Favicon? = nil
init(guid: String, title: String) {
self.guid = guid
self.title = title
}
}
/**
* An immutable item representing a bookmark.
*
* To modify this, issue changes against the backing store and get an updated model.
*/
public class BookmarkItem: BookmarkNode {
public let url: String!
public init(guid: String, title: String, url: String) {
self.url = url
super.init(guid: guid, title: title)
}
}
/**
* A folder is an immutable abstraction over a named
* thing that can return its child nodes by index.
*/
public class BookmarkFolder: BookmarkNode {
public var count: Int { return 0 }
public subscript(index: Int) -> BookmarkNode? { return nil }
public func itemIsEditableAtIndex(index: Int) -> Bool {
return false
}
}
/**
* A model is a snapshot of the bookmarks store, suitable for backing a table view.
*
* Navigation through the folder hierarchy produces a sequence of models.
*
* Changes to the backing store implicitly invalidates a subset of models.
*
* 'Refresh' means requesting a new model from the store.
*/
public class BookmarksModel {
let modelFactory: BookmarksModelFactory
public let current: BookmarkFolder
public init(modelFactory: BookmarksModelFactory, root: BookmarkFolder) {
self.modelFactory = modelFactory
self.current = root
}
/**
* Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist.
*/
public func selectFolder(folder: BookmarkFolder, success: BookmarksModel -> (), failure: Any -> ()) {
modelFactory.modelForFolder(folder, success: success, failure: failure)
}
/**
* Produce a new model rooted at the appropriate folder. Fails if the folder doesn't exist.
*/
public func selectFolder(guid: String, success: BookmarksModel -> (), failure: Any -> ()) {
modelFactory.modelForFolder(guid, success: success, failure: failure)
}
/**
* Produce a new model rooted at the base of the hierarchy. Should never fail.
*/
public func selectRoot(success: BookmarksModel -> (), failure: Any -> ()) {
modelFactory.modelForRoot(success, failure: failure)
}
/**
* Produce a new model rooted at the same place as this model. Can fail if
* the folder has been deleted from the backing store.
*/
public func reloadData(success: BookmarksModel -> (), failure: Any -> ()) {
modelFactory.modelForFolder(current, success: success, failure: failure)
}
}
public protocol BookmarksModelFactory {
func modelForFolder(folder: BookmarkFolder, success: BookmarksModel -> (), failure: Any -> ())
func modelForFolder(guid: String, success: BookmarksModel -> (), failure: Any -> ())
func modelForRoot(success: BookmarksModel -> (), failure: Any -> ())
// Whenever async construction is necessary, we fall into a pattern of needing
// a placeholder that behaves correctly for the period between kickoff and set.
var nullModel: BookmarksModel { get }
func isBookmarked(url: String, success: Bool -> (), failure: Any -> ())
func remove(bookmark: BookmarkNode) -> Success
func removeByURL(url: String) -> Success
func clearBookmarks() -> Success
}
/*
* A folder that contains an array of children.
*/
public class MemoryBookmarkFolder: BookmarkFolder, SequenceType {
let children: [BookmarkNode]
public init(guid: String, title: String, children: [BookmarkNode]) {
self.children = children
super.init(guid: guid, title: title)
}
public struct BookmarkNodeGenerator: GeneratorType {
public typealias Element = BookmarkNode
let children: [BookmarkNode]
var index: Int = 0
init(children: [BookmarkNode]) {
self.children = children
}
public mutating func next() -> BookmarkNode? {
return index < children.count ? children[index++] : nil
}
}
override public var favicon: Favicon? {
get {
if let path = NSBundle.mainBundle().pathForResource("bookmark_folder_closed", ofType: "png") {
let url = NSURL(fileURLWithPath: path)
return Favicon(url: url.absoluteString, date: NSDate(), type: IconType.Local)
}
return nil
}
set {
}
}
override public var count: Int {
return children.count
}
override public subscript(index: Int) -> BookmarkNode {
get {
return children[index]
}
}
override public func itemIsEditableAtIndex(index: Int) -> Bool {
return true
}
public func generate() -> BookmarkNodeGenerator {
return BookmarkNodeGenerator(children: self.children)
}
/**
* Return a new immutable folder that's just like this one,
* but also contains the new items.
*/
func append(items: [BookmarkNode]) -> MemoryBookmarkFolder {
if (items.isEmpty) {
return self
}
return MemoryBookmarkFolder(guid: self.guid, title: self.title, children: self.children + items)
}
}
public class MemoryBookmarksSink: ShareToDestination {
var queue: [BookmarkNode] = []
public init() { }
public func shareItem(item: ShareItem) {
let title = item.title == nil ? "Untitled" : item.title!
func exists(e: BookmarkNode) -> Bool {
if let bookmark = e as? BookmarkItem {
return bookmark.url == item.url;
}
return false;
}
// Don't create duplicates.
if (!queue.contains(exists)) {
queue.append(BookmarkItem(guid: Bytes.generateGUID(), title: title, url: item.url))
}
}
}
private extension SuggestedSite {
func asBookmark() -> BookmarkNode {
let b = BookmarkItem(guid: self.guid ?? Bytes.generateGUID(), title: self.title, url: self.url)
b.favicon = self.icon
return b
}
}
public class BookmarkFolderWithDefaults: BookmarkFolder {
private let folder: BookmarkFolder
private let sites: SuggestedSitesData<SuggestedSite>
init(folder: BookmarkFolder, sites: SuggestedSitesData<SuggestedSite>) {
self.folder = folder
self.sites = sites
super.init(guid: folder.guid, title: folder.title)
}
override public var count: Int {
return self.folder.count + self.sites.count
}
override public subscript(index: Int) -> BookmarkNode? {
if index < self.folder.count {
return self.folder[index]
}
if let site = self.sites[index - self.folder.count] {
return site.asBookmark()
}
return nil
}
override public func itemIsEditableAtIndex(index: Int) -> Bool {
return index < self.folder.count
}
}
/**
* A trivial offline model factory that represents a simple hierarchy.
*/
public class MockMemoryBookmarksStore: BookmarksModelFactory, ShareToDestination {
let mobile: MemoryBookmarkFolder
let root: MemoryBookmarkFolder
var unsorted: MemoryBookmarkFolder
let sink: MemoryBookmarksSink
public init() {
let res = [BookmarkItem]()
mobile = MemoryBookmarkFolder(guid: BookmarkRoots.MobileFolderGUID, title: "Mobile Bookmarks", children: res)
unsorted = MemoryBookmarkFolder(guid: BookmarkRoots.UnfiledFolderGUID, title: "Unsorted Bookmarks", children: [])
sink = MemoryBookmarksSink()
root = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: [mobile, unsorted])
}
public func modelForFolder(folder: BookmarkFolder, success: (BookmarksModel) -> (), failure: (Any) -> ()) {
self.modelForFolder(folder.guid, success: success, failure: failure)
}
public func modelForFolder(guid: String, success: (BookmarksModel) -> (), failure: (Any) -> ()) {
var m: BookmarkFolder
switch (guid) {
case BookmarkRoots.MobileFolderGUID:
// Transparently merges in any queued items.
m = self.mobile.append(self.sink.queue)
break;
case BookmarkRoots.RootGUID:
m = self.root
break;
case BookmarkRoots.UnfiledFolderGUID:
m = self.unsorted
break;
default:
failure("No such folder.")
return
}
success(BookmarksModel(modelFactory: self, root: m))
}
public func modelForRoot(success: (BookmarksModel) -> (), failure: (Any) -> ()) {
success(BookmarksModel(modelFactory: self, root: self.root))
}
/**
* This class could return the full data immediately. We don't, because real DB-backed code won't.
*/
public var nullModel: BookmarksModel {
let f = MemoryBookmarkFolder(guid: BookmarkRoots.RootGUID, title: "Root", children: [])
return BookmarksModel(modelFactory: self, root: f)
}
public func shareItem(item: ShareItem) {
self.sink.shareItem(item)
}
public func isBookmarked(url: String, success: (Bool) -> (), failure: (Any) -> ()) {
failure("Not implemented")
}
public func remove(bookmark: BookmarkNode) -> Success {
return deferMaybe(DatabaseError(description: "Not implemented"))
}
public func removeByURL(url: String) -> Success {
return deferMaybe(DatabaseError(description: "Not implemented"))
}
public func clearBookmarks() -> Success {
return succeed()
}
}
|
mpl-2.0
|
5e3f980a35daf22043fef9564426c82d
| 30.024129 | 121 | 0.6429 | 4.557306 | false | false | false | false |
frootloops/swift
|
stdlib/public/core/UnicodeEncoding.swift
|
4
|
4760
|
//===--- UnicodeEncoding.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public protocol _UnicodeEncoding {
/// The basic unit of encoding
associatedtype CodeUnit : UnsignedInteger, FixedWidthInteger
/// A valid scalar value as represented in this encoding
associatedtype EncodedScalar : BidirectionalCollection
where EncodedScalar.Iterator.Element == CodeUnit
/// A unicode scalar value to be used when repairing
/// encoding/decoding errors, as represented in this encoding.
///
/// If the Unicode replacement character U+FFFD is representable in this
/// encoding, `encodedReplacementCharacter` encodes that scalar value.
static var encodedReplacementCharacter : EncodedScalar { get }
/// Converts from encoded to encoding-independent representation
static func decode(_ content: EncodedScalar) -> Unicode.Scalar
/// Converts from encoding-independent to encoded representation, returning
/// `nil` if the scalar can't be represented in this encoding.
static func encode(_ content: Unicode.Scalar) -> EncodedScalar?
/// Converts a scalar from another encoding's representation, returning
/// `nil` if the scalar can't be represented in this encoding.
///
/// A default implementation of this method will be provided
/// automatically for any conforming type that does not implement one.
static func transcode<FromEncoding : Unicode.Encoding>(
_ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type
) -> EncodedScalar?
/// A type that can be used to parse `CodeUnits` into
/// `EncodedScalar`s.
associatedtype ForwardParser : Unicode.Parser
where ForwardParser.Encoding == Self
/// A type that can be used to parse a reversed sequence of
/// `CodeUnits` into `EncodedScalar`s.
associatedtype ReverseParser : Unicode.Parser
where ReverseParser.Encoding == Self
//===--------------------------------------------------------------------===//
// FIXME: this requirement shouldn't be here and is mitigated by the default
// implementation below. Compiler bugs prevent it from being expressed in an
// intermediate, underscored protocol.
/// Returns true if `x` only appears in this encoding as the representation of
/// a complete scalar value.
static func _isScalar(_ x: CodeUnit) -> Bool
}
extension _UnicodeEncoding {
// See note on declaration of requirement, above
@_inlineable // FIXME(sil-serialize-all)
public static func _isScalar(_ x: CodeUnit) -> Bool { return false }
@_inlineable // FIXME(sil-serialize-all)
public static func transcode<FromEncoding : Unicode.Encoding>(
_ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type
) -> EncodedScalar? {
return encode(FromEncoding.decode(content))
}
/// Converts from encoding-independent to encoded representation, returning
/// `encodedReplacementCharacter` if the scalar can't be represented in this
/// encoding.
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal static func _encode(_ content: Unicode.Scalar) -> EncodedScalar {
return encode(content) ?? encodedReplacementCharacter
}
/// Converts a scalar from another encoding's representation, returning
/// `encodedReplacementCharacter` if the scalar can't be represented in this
/// encoding.
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal static func _transcode<FromEncoding : Unicode.Encoding>(
_ content: FromEncoding.EncodedScalar, from _: FromEncoding.Type
) -> EncodedScalar {
return transcode(content, from: FromEncoding.self)
?? encodedReplacementCharacter
}
@_inlineable // FIXME(sil-serialize-all)
@_versioned
internal static func _transcode<
Source: Sequence, SourceEncoding: Unicode.Encoding>(
_ source: Source,
from sourceEncoding: SourceEncoding.Type,
into processScalar: (EncodedScalar)->Void)
where Source.Element == SourceEncoding.CodeUnit {
var p = SourceEncoding.ForwardParser()
var i = source.makeIterator()
while true {
switch p.parseScalar(from: &i) {
case .valid(let e): processScalar(_transcode(e, from: sourceEncoding))
case .error(_): processScalar(encodedReplacementCharacter)
case .emptyInput: return
}
}
}
}
extension Unicode {
public typealias Encoding = _UnicodeEncoding
}
|
apache-2.0
|
bcdca7a5fe895379ee188ea3d1251674
| 39 | 80 | 0.7 | 5.134844 | false | false | false | false |
ephread/Instructions
|
Sources/Instructions/Extra/Internal/CoachMarkBodyBackgroundView.swift
|
2
|
2895
|
// Copyright (c) 2020-present Frédéric Maquin <[email protected]> and contributors.
// Licensed under the terms of the MIT License.
import UIKit
class CoachMarkBodyBackgroundView: UIView,
CoachMarkBodyBackgroundStyle,
CoachMarkComponent {
// MARK: Private Constants
private let minimumWidth: CGFloat = 17
private let minimumHeight: CGFloat = 18
private let foregroundLayer = CAShapeLayer()
private let backgroundLayer = CAShapeLayer()
// MARK: Public Properties
public var isHighlighted: Bool = false {
didSet {
setNeedsLayout()
}
}
public var cornerRadius: CGFloat = 8
public lazy var innerColor = InstructionsColor.coachMarkInner
public lazy var borderColor = InstructionsColor.coachMarkOuter
public lazy var highlightedInnerColor = InstructionsColor.coachMarkHighlightedInner
public lazy var highlightedBorderColor = InstructionsColor.coachMarkOuter
// MARK: - Initialization
override public init(frame: CGRect) {
super.init(frame: frame)
isUserInteractionEnabled = false
layer.addSublayer(backgroundLayer)
layer.addSublayer(foregroundLayer)
initializeConstraints()
}
convenience public init() {
self.init(frame: CGRect.zero)
}
required public init?(coder aDecoder: NSCoder) {
fatalError(ErrorMessage.Fatal.doesNotSupportNSCoding)
}
// MARK: - Layout
public override func layoutSubviews() {
super.layoutSubviews()
foregroundLayer.frame = bounds
backgroundLayer.frame = bounds
if isHighlighted {
foregroundLayer.fillColor = highlightedInnerColor.cgColor
backgroundLayer.fillColor = highlightedBorderColor.cgColor
} else {
foregroundLayer.fillColor = innerColor.cgColor
backgroundLayer.fillColor = borderColor.cgColor
}
foregroundLayer.path = makeInnerRoundedPath(cornerRadius: cornerRadius - 0.5)
backgroundLayer.path = makeOuterRoundedPath(cornerRadius: cornerRadius)
}
// MARK: Internal Methods
func updateValues(from bodyBackground: CoachMarkBodyBackgroundStyle) {
borderColor = bodyBackground.borderColor
innerColor = bodyBackground.innerColor
highlightedBorderColor = bodyBackground.highlightedBorderColor
highlightedInnerColor = bodyBackground.highlightedInnerColor
isHighlighted = bodyBackground.isHighlighted
cornerRadius = bodyBackground.cornerRadius
}
// MARK: - Private Methods
private func initializeConstraints() {
NSLayoutConstraint.activate([
widthAnchor.constraint(greaterThanOrEqualToConstant: minimumWidth),
heightAnchor.constraint(greaterThanOrEqualToConstant: minimumHeight)
])
}
}
|
mit
|
2051fb9aa4e2037ca0ed7a3b589c65fb
| 31.875 | 87 | 0.692361 | 5.868154 | false | false | false | false |
mrdepth/Neocom
|
Legacy/Neocom/Neocom/NCSkillTableViewCell.swift
|
2
|
3781
|
//
// NCSkillTableViewCell.swift
// Neocom
//
// Created by Artem Shimanski on 15.12.16.
// Copyright © 2016 Artem Shimanski. All rights reserved.
//
import UIKit
class NCSkillTableViewCell: NCTableViewCell {
@IBOutlet weak var iconView: UIImageView?
@IBOutlet weak var titleLabel: UILabel?
@IBOutlet weak var levelLabel: UILabel?
@IBOutlet weak var spLabel: UILabel?
@IBOutlet weak var trainingTimeLabel: UILabel?
@IBOutlet weak var progressView: UIProgressView?
@IBOutlet weak var skillLevelView: NCSkillLevelView?
}
extension Prototype {
enum NCSkillTableViewCell {
static let `default` = Prototype(nib: UINib(nibName: "NCSkillTableViewCell", bundle: nil), reuseIdentifier: "NCSkillTableViewCell")
}
}
class NCSkillRow: TreeRow {
let skill: NCSkill
let character: NCCharacter
init(prototype: Prototype = Prototype.NCSkillTableViewCell.default, skill: NCSkill, character: NCCharacter) {
self.skill = skill
self.character = character
super.init(prototype: prototype, route: Router.Database.TypeInfo(skill.typeID))
}
lazy var image: UIImage? = {
let typeID = Int32(self.skill.typeID)
return NCAccount.current?.activeSkillPlan?.skills?.first(where: { ($0 as? NCSkillPlanSkill)?.typeID == typeID }) != nil ? #imageLiteral(resourceName: "skillRequirementQueued") : nil
}()
var trainingTime: String?
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCSkillTableViewCell else {return}
cell.object = skill
cell.titleLabel?.text = "\(skill.typeName) (x\(Int(skill.rank)))"
if var level = skill.level {
if skill.isActive {
level = min(level + 1, 5)
}
// cell.levelLabel?.text = NSLocalizedString("LEVEL", comment: "") + " " + String(romanNumber:level)
cell.levelLabel?.text = NSLocalizedString("LEVEL", comment: "") + " " + String(romanNumber:level)
cell.skillLevelView?.level = level
cell.skillLevelView?.isActive = skill.isActive
}
else {
cell.levelLabel?.text = NSLocalizedString("N/A", comment: "")
cell.skillLevelView?.level = 0
cell.skillLevelView?.isActive = false
}
let sph = Int((character.attributes.skillpointsPerSecond(forSkill: skill) * 3600).rounded())
cell.spLabel?.text = "\(NCUnitFormatter.localizedString(from: sph, unit: .custom(NSLocalizedString("SP/h", comment: ""), false), style: .full))"
cell.progressView?.progress = 0
if let trainingTime = trainingTime {
cell.trainingTimeLabel?.text = trainingTime
}
else {
let level = (skill.level ?? 0)
if level < 5 {
cell.trainingTimeLabel?.text = " "
NCDatabase.sharedDatabase?.performBackgroundTask { managedObjectContext in
let trainingQueue = NCTrainingQueue(character: self.character)
if let type = NCDBInvType.invTypes(managedObjectContext: managedObjectContext)[self.skill.typeID] {
trainingQueue.add(skill: type, level: level + 1)
}
let t = trainingQueue.trainingTime(characterAttributes: self.character.attributes)
let s = String(format: NSLocalizedString("%@ ", comment: ""),
NCTimeIntervalFormatter.localizedString(from: t, precision: .seconds))
DispatchQueue.main.async {
self.trainingTime = s
if cell.object as? NCSkill === self.skill {
cell.trainingTimeLabel?.text = s
}
}
}
}
else {
trainingTime = NSLocalizedString("COMPLETED", comment: "")
cell.trainingTimeLabel?.text = trainingTime
}
}
cell.iconView?.image = image
}
override var hash: Int {
return skill.hashValue
}
override func isEqual(_ object: Any?) -> Bool {
return (object as? NCSkillRow)?.hashValue == hashValue
}
}
|
lgpl-2.1
|
c5a14566d9f4db31673d3455d7002896
| 33.678899 | 189 | 0.677778 | 3.921162 | false | false | false | false |
ti-gars/BugTracker
|
iOS/BugTracker/AddIssueViewController.swift
|
1
|
5426
|
//
// AddIssueViewController.swift
// BugTracker
//
// Created by Charles-Olivier Demers on 2015-09-20.
// Copyright (c) 2015 Charles-Olivier Demers. All rights reserved.
//
import UIKit
import Parse
class AddIssueViewController: UIViewController, UIPickerViewDelegate, UIPickerViewDataSource {
private var titleTextField: UITextField!
private var descriptionTextView: UITextView!
private var typePickerView: UIPickerView!
private var assignedToPickerView: UIPickerView!
private var saveIssueButton: UIButton!
private var typePicker = ["Bug", "Features", "To Try"]
private var typeValue = 0
private var userValue = 0
private var typeTag = 0
private var assignedToTag = 1
override func viewDidLoad() {
super.viewDidLoad()
self.navigationController?.tabBarController?.tabBar.hidden = true
setupView()
}
func setupView() {
let width = self.view.frame.width
let height = self.view.frame.height
titleTextField = UITextField()
titleTextField.frame = CGRectMake(width / 30, height / 8, width - (width / 30) * 2, height / 20)
titleTextField.borderStyle = UITextBorderStyle.RoundedRect
titleTextField.placeholder = "Title"
self.view.addSubview(titleTextField)
descriptionTextView = UITextView()
descriptionTextView.frame = CGRectMake(titleTextField.frame.origin.x, titleTextField.frame.origin.y * 2.4, titleTextField.frame.width, height / 10)
descriptionTextView.layer.borderColor = UIColor.grayColor().CGColor
self.view.addSubview(descriptionTextView)
typePickerView = UIPickerView()
typePickerView.frame = CGRectMake(descriptionTextView.frame.origin.x, descriptionTextView.frame.origin.y * 1.4, descriptionTextView.frame.width, descriptionTextView.frame.height)
typePickerView.delegate = self
typePickerView.tag = typeTag
self.view.addSubview(typePickerView)
assignedToPickerView = UIPickerView()
assignedToPickerView.frame = CGRectMake(descriptionTextView.frame.origin.x, typePickerView.frame.origin.y * 1.4, descriptionTextView.frame.width, descriptionTextView.frame.height)
assignedToPickerView.delegate = self
assignedToPickerView.tag = assignedToTag
self.view.addSubview(assignedToPickerView)
saveIssueButton = UIButton()
saveIssueButton.frame = CGRectMake(descriptionTextView.frame.origin.x, self.view.frame.height - self.navigationController!.tabBarController!.tabBar.frame.height * 2 + 10, descriptionTextView.frame.width, descriptionTextView.frame.height)
saveIssueButton.backgroundColor = UIColor.blueColor()
saveIssueButton.setTitle("Save", forState: UIControlState.Normal)
saveIssueButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
saveIssueButton.addTarget(self, action: "saveIssue", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(saveIssueButton)
}
func saveIssue() {
let issue = PFObject(className: "Issue")
issue["Title"] = titleTextField.text!
issue["Description"] = descriptionTextView.text
issue["Type"] = typeValue
let pointer = PFObject(withoutDataWithClassName: "_User", objectId: globalUsers[userValue].getObjectId())
issue["AssignedTo"] = pointer
issue["Resolved"] = false
do {
try issue.save()
} catch {
gblAlert("Veuillez rééssayer!")
}
let query = PFQuery(className: "Issue")
query.getObjectInBackgroundWithId(issue.objectId!, block: {
(object: PFObject?, error: NSError?) -> Void in
object?.setValue(issue.objectId!, forKey: "CustomObjectId")
do {
try object!.save()
} catch {
gblAlert("Veuillez rééssayer!")
}
})
// PFCloud.callFunction("createIssue", withParameters: ["title": titleTextField.text, "description": descriptionTextField.text, "type" : typeValue, "assignedTo" : "M04HyM4nmJ"])
}
// Picker View
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
if(pickerView.tag == typeTag) {
return typePicker.count
}
return globalUsers.count
}
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
if(pickerView.tag == typeTag) {
typeValue = row
} else {
userValue = row
}
}
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String! {
if(pickerView.tag == typeTag) {
return typePicker[row]
}
return globalUsers[row].getName()
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
self.view.endEditing(true)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
mit
|
64a8c5050ebf31a6bc096e8d29db8c84
| 37.728571 | 245 | 0.652342 | 4.997235 | false | false | false | false |
achimk/Swift-UIKit-Extensions
|
Controllers/UIViewController+Containment.swift
|
1
|
4279
|
//
// UIViewController+Containment.swift
//
// Created by Joachim Kret on 06.10.2015.
// Copyright © 2015 Joachim Kret. All rights reserved.
//
import UIKit
// MARK: Containment Methods
extension UIViewController {
func addViewController(viewController: UIViewController, toContainer viewContainer: UIView) -> Bool {
return replaceFromViewController(nil, toViewController: viewController, inContainer: viewContainer)
}
func removeViewController(viewController: UIViewController) -> Bool {
return replaceFromViewController(viewController, toViewController: nil, inContainer: view)
}
func replaceFromViewController(fromVC: UIViewController?, toViewController toVC: UIViewController?, inContainer viewContainer: UIView) -> Bool {
if fromVC != toVC, let fromVC = fromVC, let toVC = toVC {
// Replace existing view controller with new view controller
addChildViewController(toVC)
toVC.willMoveToParentViewController(self)
fromVC.willMoveToParentViewController(nil)
fromVC.view.removeFromSuperview()
fromVC.removeFromParentViewController()
fromVC.didMoveToParentViewController(nil)
setupContainer(viewContainer, withViewController: toVC)
toVC.didMoveToParentViewController(self)
return true
} else if fromVC == nil, let toVC = toVC {
// add new view controller
addChildViewController(toVC)
toVC.willMoveToParentViewController(self)
setupContainer(viewContainer, withViewController: toVC)
toVC.didMoveToParentViewController(self)
return true
} else if toVC == nil, let fromVC = fromVC {
// remove existing view controller
fromVC.willMoveToParentViewController(nil)
fromVC.view.removeFromSuperview()
fromVC.didMoveToParentViewController(nil)
fromVC.removeFromParentViewController()
return true
}
return false
}
func replaceFromViewController(fromVC: UIViewController?, toViewController toVC: UIViewController?, inContainer viewContainer: UIView, duration animationDuration: NSTimeInterval, options animationOptions: UIViewAnimationOptions, completion completionBlock: ((Bool) -> Void)?) {
let isAnimated = animationDuration > 0 && self.childViewControllers.count > 0
let completion: (Bool) -> (Void) = { isFinished in
if let completionBlock = completionBlock {
completionBlock(isFinished)
}
}
if fromVC != toVC && isAnimated, let fromVC = fromVC, let toVC = toVC {
// Animated transition between view controllers
self.addChildViewController(toVC)
toVC.willMoveToParentViewController(self)
fromVC.willMoveToParentViewController(nil)
transitionFromViewController(fromVC, toViewController: toVC, duration: animationDuration, options: animationOptions, animations: nil, completion: { isFinished in
fromVC.view.removeFromSuperview()
fromVC.didMoveToParentViewController(nil)
fromVC.removeFromParentViewController()
self.setupContainer(viewContainer, withViewController: toVC)
toVC.didMoveToParentViewController(self)
completion(isFinished)
})
} else {
// Non-animated transition
let isCompleted = replaceFromViewController(fromVC, toViewController: toVC, inContainer: viewContainer)
completion(isCompleted)
}
}
}
// MARK: Private Methods
extension UIViewController {
private func setupContainer(viewContainer: UIView, withViewController viewController: UIViewController) {
viewController.view.translatesAutoresizingMaskIntoConstraints = true
viewController.view.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
viewController.view.frame = viewContainer.bounds
viewContainer.addSubview(viewController.view)
viewContainer.setNeedsLayout()
}
}
|
mit
|
40b652de0d859756eade898f16ae3846
| 43.5625 | 281 | 0.664797 | 6.442771 | false | false | false | false |
slavapestov/swift
|
validation-test/compiler_crashers_fixed/27369-swift-type-transform.swift
|
4
|
739
|
// RUN: not %target-swift-frontend %s -parse
// Distributed under the terms of the MIT license
// Test case submitted to project by https://github.com/practicalswift (practicalswift)
// Test case found by fuzzing
if true {{} k. "
if true{
class d<T {let:a{}
g {class B<T B:C{let f=e()
typealias e
enum S<T> : A?
func a== f=Dictionary<T.E
}
class c{struct B<T{
class b<T{struct Q<T B : T{
class c<a
typealias ()
struct B<a:a{
}
class A{let a{} k. "
}
class A<T{}
class B<T {
struct B
class A{var f
"
class B<T{
class A{{
func f
}struct c<T B:C{let f=e()
}
func g:a{
import a:a{
}
enum S<T a{
class A{
func p{
class B<H : T.E
struct c<T B :a{
class B< E {}
class A{let ad{}
let T h.h =b()
1
typealias ()
let T B :b: AsB
class A? f{
typeal
|
apache-2.0
|
c4cfffeb790cd6b9f85fc10f7f0a5761
| 14.395833 | 87 | 0.64276 | 2.361022 | false | false | false | false |
csnu17/My-Swift-learning
|
HitListCoreDataLearning/HitListCoreDataLearning/CoreDataService.swift
|
1
|
3292
|
//
// CoreDataService.swift
// HitListCoreDataLearning
//
// Created by Phetrungnapha, K. on 6/18/2560 BE.
// Copyright © 2560 iTopStory. All rights reserved.
//
import Foundation
import CoreData
class CoreDataService {
static let shared = CoreDataService()
// Prevent a developer creates instance of this class.
private init() {}
// MARK: - Core Data stack
fileprivate lazy var persistentContainer: NSPersistentContainer = {
let container = NSPersistentContainer(name: "HitListCoreDataLearning")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - My Core Data support
fileprivate var managedContext: NSManagedObjectContext {
return persistentContainer.viewContext
}
// MARK: - Core Data Saving support
func saveContext() {
if managedContext.hasChanges {
do {
try managedContext.save()
} catch {
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
// MARK: - select, insert, update, delete functions for Core Data
extension CoreDataService {
func prepareManagedObject(entityName: String) -> NSManagedObject? {
guard let entity = NSEntityDescription.entity(forEntityName: entityName, in: managedContext) else {
return nil
}
return NSManagedObject(entity: entity, insertInto: managedContext)
}
func fetchObjects(entityName: String) -> [NSManagedObject]? {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)
do {
return try managedContext.fetch(fetchRequest)
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
return nil
}
}
func deleteObject(entityName: String, identifier: String) {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)
fetchRequest.predicate = NSPredicate(format: "identifier == %@", identifier)
do {
let objects = try managedContext.fetch(fetchRequest)
objects.forEach { managedContext.delete($0) }
saveContext()
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
func updateObject(entityName: String, identifier: String, valuesForUpdate: [String: Any]) {
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: entityName)
fetchRequest.predicate = NSPredicate(format: "identifier == %@", identifier)
do {
if let object = try managedContext.fetch(fetchRequest).first {
valuesForUpdate.forEach {
object.setValue($1, forKey: $0)
}
saveContext()
}
} catch let error as NSError {
print("Could not fetch. \(error), \(error.userInfo)")
}
}
}
|
mit
|
7f472efbd19a44f21a295b6edaf7df6e
| 30.644231 | 107 | 0.602249 | 5.439669 | false | false | false | false |
aiaio/DesignStudioExpress
|
Pods/AcknowList/Source/AcknowViewController.swift
|
1
|
3076
|
//
// AcknowViewController.swift
//
// Copyright (c) 2015 Vincent Tourraine (http://www.vtourraine.net)
//
// 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
/**
Subclass of `UIViewController` that displays a single acknowledgement.
*/
public class AcknowViewController: UIViewController {
/**
The main text view.
*/
public var textView: UITextView?
/**
The represented acknowledgement.
*/
var acknowledgement: Acknow?
/**
Initializes the `AcknowViewController` instance with an acknowledgement.
- parameter acknowledgement: The represented acknowledgement.
- returns: The new `AcknowViewController` instance.
*/
public init(acknowledgement: Acknow) {
super.init(nibName: nil, bundle: nil)
self.title = acknowledgement.title
self.acknowledgement = acknowledgement
}
/**
Initializes the `AcknowViewController` instance with a coder.
- parameter aDecoder: The archive coder.
- returns: The new `AcknowViewController` instance.
*/
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.acknowledgement = Acknow(title: "", text: "")
}
// MARK: - View lifecycle
override public func loadView() {
let textView = UITextView(frame: CGRectZero)
textView.alwaysBounceVertical = true;
textView.font = UIFont.systemFontOfSize(17)
textView.editable = false
textView.dataDetectorTypes = UIDataDetectorTypes.Link
textView.textContainerInset = UIEdgeInsetsMake(12, 10, 12, 10)
if let acknowledgement = self.acknowledgement {
textView.text = acknowledgement.text
}
self.view = textView
self.textView = textView
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let textView = self.textView {
textView.contentOffset = CGPointMake(textView.contentInset.top, 0)
}
}
}
|
mit
|
33c96bec15f6f5704bf1ef78efc34ce5
| 32.434783 | 80 | 0.694408 | 4.828885 | false | false | false | false |
nodes-vapor/admin-panel-provider
|
Sources/AdminPanelProvider/Tags/Leaf/PasswordGroup.swift
|
1
|
2607
|
import Leaf
import Vapor
public final class PasswordGroup: BasicTag {
public init(){}
public let name = "form:passwordgroup"
public func run(arguments: ArgumentList) throws -> Node? {
guard
arguments.count >= 2,
case .variable(let fieldsetPathNodes, value: let fieldset) = arguments.list[0],
let fieldsetPath = fieldsetPathNodes.last
else {
throw Abort(.internalServerError, reason: "FormTextGroup parse error, expecting: #form:textgroup(\"name\", \"default\", fieldset)")
}
// Retrieve input value, value from fieldset else passed default value
let inputValue = this(fieldset?["value"]?.string, or: arguments[1]?.string)
let label = fieldset?["label"]?.string ?? fieldsetPath
// This is not a required property
let errors = fieldset?["errors"]?.array
let hasErrors = !(errors?.isEmpty ?? true)
// Start constructing the template
var template = [String]()
var classes = "form-control "
if let customClasses = arguments[2]?.string {
classes.append(customClasses)
}
template.append("<div class='form-group action-wrapper \(hasErrors ? "has-error" : "")'>")
template.append("<label class='control-label' for='\(fieldsetPath)'>\(label)</label>")
template.append("<input class='\(classes)' type='password' id='\(fieldsetPath)' name='\(fieldsetPath)' value='\(inputValue)' ")
if let attributesNode = arguments[3] {
let attributes: [String]
if let attrArray = attributesNode.array {
attributes = attrArray.flatMap {
$0.string
}
} else if let attrStr = attributesNode.string {
attributes = attrStr.components(separatedBy: ",")
} else {
throw Abort(.internalServerError, reason: "FormTextGroup parse error, expecting: an array or comma separated list of custom attributes")
}
template.append(contentsOf: attributes)
}
template.append("/>")
// If Fieldset has errors then loop through them and add help-blocks
if let errors = errors {
for e in errors {
guard let errorString = e.string else {
continue
}
template.append("<span class='help-block'>\(errorString)</span>")
}
}
template.append("</div>")
// Return template
return .bytes(template.joined().bytes)
}
}
|
mit
|
8a31094932ca258512ad15b42ef309d9
| 35.71831 | 152 | 0.580361 | 4.845725 | false | false | false | false |
thankmelater23/relliK
|
Pods/SwiftyBeaver/Sources/SwiftyBeaver.swift
|
2
|
7301
|
//
// SwiftyBeaver.swift
// SwiftyBeaver
//
// Created by Sebastian Kreutzberger (Twitter @skreutzb) on 28.11.15.
// Copyright © 2015 Sebastian Kreutzberger
// Some rights reserved: http://opensource.org/licenses/MIT
//
import Foundation
open class SwiftyBeaver {
/// version string of framework
public static let version = "1.5.1" // UPDATE ON RELEASE!
/// build number of framework
public static let build = 1510 // version 0.7.1 -> 710, UPDATE ON RELEASE!
public enum Level: Int {
case verbose = 0
case debug = 1
case info = 2
case warning = 3
case error = 4
}
// a set of active destinations
open private(set) static var destinations = Set<BaseDestination>()
// MARK: Destination Handling
/// returns boolean about success
@discardableResult
open class func addDestination(_ destination: BaseDestination) -> Bool {
if destinations.contains(destination) {
return false
}
destinations.insert(destination)
return true
}
/// returns boolean about success
@discardableResult
open class func removeDestination(_ destination: BaseDestination) -> Bool {
if destinations.contains(destination) == false {
return false
}
destinations.remove(destination)
return true
}
/// if you need to start fresh
open class func removeAllDestinations() {
destinations.removeAll()
}
/// returns the amount of destinations
open class func countDestinations() -> Int {
return destinations.count
}
/// returns the current thread name
class func threadName() -> String {
#if os(Linux)
// on 9/30/2016 not yet implemented in server-side Swift:
// > import Foundation
// > Thread.isMainThread
return ""
#else
if Thread.isMainThread {
return ""
} else {
let threadName = Thread.current.name
if let threadName = threadName, !threadName.isEmpty {
return threadName
} else {
return String(format: "%p", Thread.current)
}
}
#endif
}
// MARK: Levels
/// log something generally unimportant (lowest priority)
open class func verbose(_ message: @autoclosure () -> Any, _
file: String = #file, _ function: String = #function, line: Int = #line, context: Any? = nil) {
custom(level: .verbose, message: message, file: file, function: function, line: line, context: context)
}
/// log something which help during debugging (low priority)
open class func debug(_ message: @autoclosure () -> Any, _
file: String = #file, _ function: String = #function, line: Int = #line, context: Any? = nil) {
custom(level: .debug, message: message, file: file, function: function, line: line, context: context)
}
/// log something which you are really interested but which is not an issue or error (normal priority)
open class func info(_ message: @autoclosure () -> Any, _
file: String = #file, _ function: String = #function, line: Int = #line, context: Any? = nil) {
custom(level: .info, message: message, file: file, function: function, line: line, context: context)
}
/// log something which may cause big trouble soon (high priority)
open class func warning(_ message: @autoclosure () -> Any, _
file: String = #file, _ function: String = #function, line: Int = #line, context: Any? = nil) {
custom(level: .warning, message: message, file: file, function: function, line: line, context: context)
}
/// log something which will keep you awake at night (highest priority)
open class func error(_ message: @autoclosure () -> Any, _
file: String = #file, _ function: String = #function, line: Int = #line, context: Any? = nil) {
custom(level: .error, message: message, file: file, function: function, line: line, context: context)
}
/// custom logging to manually adjust values, should just be used by other frameworks
public class func custom(level: SwiftyBeaver.Level, message: @autoclosure () -> Any,
file: String = #file, function: String = #function, line: Int = #line, context: Any? = nil) {
dispatch_send(level: level, message: message, thread: threadName(),
file: file, function: function, line: line, context: context)
}
/// internal helper which dispatches send to dedicated queue if minLevel is ok
class func dispatch_send(level: SwiftyBeaver.Level, message: @autoclosure () -> Any,
thread: String, file: String, function: String, line: Int, context: Any?) {
var resolvedMessage: String?
for dest in destinations {
guard let queue = dest.queue else {
continue
}
resolvedMessage = resolvedMessage == nil && dest.hasMessageFilters() ? "\(message())" : resolvedMessage
if dest.shouldLevelBeLogged(level, path: file, function: function, message: resolvedMessage) {
// try to convert msg object to String and put it on queue
let msgStr = resolvedMessage == nil ? "\(message())" : resolvedMessage!
let f = stripParams(function: function)
if dest.asynchronously {
queue.async {
_ = dest.send(level, msg: msgStr, thread: thread, file: file, function: f, line: line, context: context)
}
} else {
queue.sync {
_ = dest.send(level, msg: msgStr, thread: thread, file: file, function: f, line: line, context: context)
}
}
}
}
}
/**
DEPRECATED & NEEDS COMPLETE REWRITE DUE TO SWIFT 3 AND GENERAL INCORRECT LOGIC
Flush all destinations to make sure all logging messages have been written out
Returns after all messages flushed or timeout seconds
- returns: true if all messages flushed, false if timeout or error occurred
*/
public class func flush(secondTimeout: Int64) -> Bool {
/*
guard let grp = dispatch_group_create() else { return false }
for dest in destinations {
if let queue = dest.queue {
dispatch_group_enter(grp)
queue.asynchronously(execute: {
dest.flush()
grp.leave()
})
}
}
let waitUntil = DispatchTime.now(dispatch_time_t(DISPATCH_TIME_NOW), secondTimeout * 1000000000)
return dispatch_group_wait(grp, waitUntil) == 0
*/
return true
}
/// removes the parameters from a function because it looks weird with a single param
class func stripParams(function: String) -> String {
var f = function
if let indexOfBrace = f.find("(") {
#if swift(>=4.0)
f = String(f[..<indexOfBrace])
#else
f = f.substring(to: indexOfBrace)
#endif
}
f += "()"
return f
}
}
|
unlicense
|
b20c3def07ed3eb1e7671ceb1dc38abb
| 37.219895 | 128 | 0.589041 | 4.626109 | false | false | false | false |
skylib/SnapImagePicker
|
SnapImagePicker_Unit_Tests/TestDoubles/PhotoLoaderSpy.swift
|
1
|
3548
|
import Photos
@testable import SnapImagePicker
class PhotoLoaderSpy: ImageLoaderProtocol, AlbumLoaderProtocol {
var loadImageFromAssetCount = 0
var loadImageFromAssetAsset: PHAsset?
var loadImageFromAssetIsPreview: Bool?
var loadImageFromAssetPreviewSize: CGSize?
var loadImageFromAssetHandler: ((SnapImagePickerImage) -> ())?
var loadImagesFromAssetsCount = 0
var loadImagesFromAssetsAssets: [Int: PHAsset]?
var loadImagesFromAssetsSize: CGSize?
var loadImagesFromAssetsHandler: (([Int: SnapImagePickerImage]) -> ())?
var fetchAssetsFromCollectionWithTypeCount = 0
var fetchAssetsFromCollectionWithTypeType: AlbumType?
var fetchAllPhotosPreviewsCount = 0
var fetchAllPhotosPreviewsTargetSize: CGSize?
var fetchAllPhotosPreviewsHandler: ((Album) -> Void)?
var fetchFavoritesPreviewsCount = 0
var fetchFavoritesPreviewsTargetSize: CGSize?
var fetchFavoritesPreviewsHandler: ((Album) -> Void)?
var fetchUserAlbumPreviewsCount = 0
var fetchUserAlbumPreviewsTargetSize: CGSize?
var fetchUserAlbumPreviewsHandler: ((Album) -> Void)?
var fetchSmartAlbumPreviewsCount = 0
var fetchSmartAlbumPreviewsTargetSize: CGSize?
var fetchSmartAlbumPreviewsHandler: ((Album) -> Void)?
func loadImageFromAsset(_ asset: PHAsset, isPreview: Bool, withPreviewSize previewSize: CGSize , handler: @escaping (SnapImagePickerImage) -> ()) -> PHImageRequestID {
loadImageFromAssetCount += 1
loadImageFromAssetAsset = asset
loadImageFromAssetIsPreview = isPreview
loadImageFromAssetPreviewSize = previewSize
loadImageFromAssetHandler = handler
return PHImageRequestID()
}
func loadImagesFromAssets(_ assets: [Int: PHAsset], withTargetSize targetSize: CGSize, handler: @escaping ([Int: SnapImagePickerImage]) -> ()) -> [Int: PHImageRequestID] {
loadImagesFromAssetsCount += 1
loadImagesFromAssetsAssets = assets
loadImagesFromAssetsSize = targetSize
loadImagesFromAssetsHandler = handler
return [Int: PHImageRequestID]()
}
func fetchAssetsFromCollectionWithType(_ type: AlbumType) -> PHFetchResult<PHAsset>? {
fetchAssetsFromCollectionWithTypeCount += 1
fetchAssetsFromCollectionWithTypeType = type
return nil
}
func fetchAllPhotosPreview(_ targetSize: CGSize, handler: @escaping (Album) -> Void) {
fetchAllPhotosPreviewsCount += 1
fetchAllPhotosPreviewsTargetSize = targetSize
fetchAllPhotosPreviewsHandler = handler
}
func fetchFavoritesPreview(_ targetSize: CGSize, handler: @escaping (Album) -> Void) {
fetchFavoritesPreviewsCount += 1
fetchFavoritesPreviewsTargetSize = targetSize
fetchFavoritesPreviewsHandler = handler
}
func fetchAllUserAlbumPreviews(_ targetSize: CGSize, handler: @escaping (Album) -> Void) {
fetchUserAlbumPreviewsCount += 1
fetchUserAlbumPreviewsTargetSize = targetSize
fetchUserAlbumPreviewsHandler = handler
}
func fetchAllSmartAlbumPreviews(_ targetSize: CGSize, handler: @escaping (Album) -> Void) {
fetchSmartAlbumPreviewsCount += 1
fetchSmartAlbumPreviewsTargetSize = targetSize
fetchSmartAlbumPreviewsHandler = handler
}
func loadImageWithLocalIdentifier(_ identifier: String, handler: @escaping ((SnapImagePickerImage) -> Void)) {}
func deleteRequests(_ requestIds: [PHImageRequestID]) {}
}
|
bsd-3-clause
|
054d453edcd7b0bdc320d9a901c4bc59
| 39.781609 | 175 | 0.719842 | 5.400304 | false | false | false | false |
iOSWizards/AwesomeMedia
|
AwesomeMedia/Classes/Fetcher/AwesomeMediaCacheManager.swift
|
1
|
2290
|
//
// AwesomeMediaCacheManager.swift
// AwesomeMedia
//
// Created by Evandro Harrison Hoffmann on 01/09/2016.
// Copyright © 2016 Mindvalley. All rights reserved.
//
import UIKit
enum CacheType {
case urlCache
case nsCache
}
class AwesomeMediaCacheManager: NSObject {
let nsCache: NSCache<NSString, AnyObject>
override init() {
self.nsCache = NSCache()
}
/*
* Sets the cache size for the application
* @param memorySize: Size of cache in memory
* @param diskSize: Size of cache in disk
*/
open static func configureCache(withMemorySize memorySize: Int = 20, diskSize: Int = 200){
let cacheSizeMemory = memorySize*1024*1024
let cacheSizeDisk = diskSize*1024*1024
let cache = URLCache(memoryCapacity: cacheSizeMemory, diskCapacity: cacheSizeDisk, diskPath: nil)
URLCache.shared = cache
}
/*
* Clears cache
*/
open static func clearCache(){
URLCache.shared.removeAllCachedResponses()
}
/*
* Get cached object for urlRequest
* @param urlRequest: Request for cached data
*/
open static func getCachedObject(_ urlRequest: URLRequest) -> Data?{
if let cachedObject = URLCache.shared.cachedResponse(for: urlRequest) {
return cachedObject.data
}
return nil
}
/*
* Set object to cache
* @param data: data to cache
*/
open static func cacheObject(_ urlRequest: URLRequest?, response: URLResponse?, data: Data?){
guard let urlRequest = urlRequest else{
return
}
guard let response = response else{
return
}
guard let data = data else{
return
}
let cachedResponse = CachedURLResponse(response: response, data: data)
URLCache.shared.storeCachedResponse(cachedResponse, for: urlRequest)
}
// MARK: - Instance methods
func cacheObject(_ object: Any, forKey: String) {
nsCache.setObject(object as AnyObject, forKey: NSString(string: forKey))
}
func objectForKey(_ forKey: String) -> AnyObject? {
return nsCache.object(forKey: NSString(string: forKey))
}
}
|
mit
|
46f665eba7cc163df7c2d1994a487867
| 25.616279 | 105 | 0.613805 | 4.818947 | false | false | false | false |
austinzheng/swift
|
test/SourceKit/InterfaceGen/Inputs/swift_mod_syn.swift
|
34
|
753
|
public protocol P1{
associatedtype T1
associatedtype T2
func f1(t : T1) -> T1
func f2(t : T2) -> T2
}
public protocol P2 {
associatedtype P2T1
}
public extension P2 where P2T1 : P2{
public func p2member() {}
}
public protocol P3 {}
public extension P1 where T1 : P2 {
public func ef1(t : T1) {}
public func ef2(t : T2) {}
}
public extension P1 where T1 == P3, T2 : P3 {
public func ef3(t : T1) {}
public func ef4(t : T1) {}
}
public extension P1 where T2 : P3 {
public func ef5(t : T2) {}
}
public struct S2 {}
public struct S1<T> : P1, P2 {
public typealias T1 = T
public typealias T2 = S2
public typealias P2T1 = T
public func f1(t : T1) -> T1 {
return t
}
public func f2(t : T2) -> T2 {
return t
}
}
|
apache-2.0
|
dc6b8557274b4ed2f100524cce4b23be
| 15.733333 | 45 | 0.618858 | 2.569966 | false | false | false | false |
Swift3Home/TLSwiftCommon
|
001-图像的优化/001-图像的优化/ViewController.swift
|
1
|
2451
|
//
// ViewController.swift
// 001-图像的优化
//
// Created by lichuanjun on 2017/7/19.
// Copyright © 2017年 lichuanjun. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var label: TLLabel!
@IBOutlet weak var label: TLLabel!
@IBOutlet weak var tableView: UITableView!
// 如何设置圆角,不要用圆角半径
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let rect = CGRect(x: 0, y: 0, width: 160, height: 160)
let iv = UIImageView(frame: rect)
iv.center = view.center
view.addSubview(iv)
// 设置图像
// - PNG 图片是支持透明的
// - JPG 图片不支持透明
// let image = #imageLiteral(resourceName: "avatar_default_big.png")
// iv.image = avatarImage(image: image, size: rect.size, backColor: view.backgroundColor)
let image = UIImage(named: "shali.jpg")//#imageLiteral(resourceName: "shali.jpg")
iv.image = avatarImage(image: image!, size: rect.size, backColor: view.backgroundColor)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func avatarImage(image: UIImage, size: CGSize, backColor: UIColor?) -> UIImage? {
let rect = CGRect(origin: CGPoint(), size: size)
// 1. 图像的上下文 - 内存中开辟一个地址,跟屏幕无关
UIGraphicsBeginImageContextWithOptions(rect.size, true, 0)
// 0> 背景填充
backColor?.setFill()
UIRectFill(rect)
// 1> 实例化一个圆形的路径
let path = UIBezierPath(ovalIn: rect)
// 2> 进行路径裁切 - 后续的绘图,都会出现在圆形路径内部,外部的全部干掉
path.addClip()
// 2. 绘图 drawInRect 就是在指定区域内拉伸屏幕
image.draw(in: rect)
// 3. 绘制内切的圆形
UIColor.darkGray.setStroke()
path.lineWidth = 2
path.stroke()
// 4.取得结果
let result = UIGraphicsGetImageFromCurrentImageContext()
// 5. 关闭上下文
UIGraphicsEndImageContext()
// 6. 返回结果
return result
}
}
|
mit
|
202ac334ed1eb6328612ae4b20777b07
| 27.96 | 96 | 0.592541 | 4.044693 | false | false | false | false |
LuAndreCast/iOS_WatchProjects
|
watchOS2/Heart Rate/v3 Heart Rate Stream/Error.swift
|
1
|
2257
|
//
// Error.swift
// HealthWatchExample
//
// Created by Luis Castillo on 8/5/16.
// Copyright © 2016 LC. All rights reserved.
//
import Foundation
/* Debugging? */
let verbose = true //debug
struct Errors {
//MARK: - HealthStore
struct healthStore
{
static let domain:String = "healthkit.healthStore"
struct avaliableData
{
static let code = 101
static let description = [NSLocalizedDescriptionKey : "Health Store Data is Not avaliable"]
}
}//eo
struct heartRate
{
static let domain:String = "healthkit.heartRate"
struct quantity
{
static let code = 201
static let description = [NSLocalizedDescriptionKey : "un-able to create Heart rate quantity type"]
}
}//eo
struct workOut
{
static let domain:String = "healthkit.workout"
struct start
{
static let code = 301
static let description = [NSLocalizedDescriptionKey : "un-able to start workout"]
}
struct end
{
static let code = 302
static let description = [NSLocalizedDescriptionKey : "un-able to end workout"]
}
}//eo
//MARK: - Monitoring
struct monitoring
{
static let domain:String = ""
struct type
{
static let code = 401
static let description = [ NSLocalizedDescriptionKey: "un-able to init type"]
}
struct query
{
static let code = 402
static let description = [ NSLocalizedDescriptionKey: "un-able to query sample"]
}
}
//MARK: - WCSESSION
struct wcSession
{
static let domain:String = "watchconnectivity.wcession"
struct supported
{
static let code = 501
static let description = [NSLocalizedDescriptionKey : "wcsession is not supported"]
}
struct reachable
{
static let code = 502
static let description = [NSLocalizedDescriptionKey : "wcsession is not reachable"]
}
}//eo
}
|
mit
|
aa676bb476d03d394bb117cc2d9f36a8
| 23.532609 | 112 | 0.544326 | 5.127273 | false | false | false | false |
hughbe/swift
|
stdlib/public/SDK/ARKit/ARKit.swift
|
3
|
1789
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@_exported import ARKit
@available(iOS, introduced: 11.0)
extension ARCamera {
/**
A value describing the camera's tracking state.
*/
public enum TrackingState {
public enum Reason {
/** Tracking is limited due to a excessive motion of the camera. */
case excessiveMotion
/** Tracking is limited due to a lack of features visible to the camera. */
case insufficientFeatures
}
/** Tracking is not available. */
case notAvailable
/** Tracking is limited. See tracking reason for details. */
case limited(Reason)
/** Tracking is normal. */
case normal
}
/**
The tracking state of the camera.
*/
public var trackingState: TrackingState {
switch __trackingState {
case .notAvailable: return .notAvailable
case .normal: return .normal
case .limited:
let reason: TrackingState.Reason
switch __trackingStateReason {
case .excessiveMotion: reason = .excessiveMotion
default: reason = .insufficientFeatures
}
return .limited(reason)
}
}
}
|
apache-2.0
|
45285964e40020864141f267988928b5
| 30.385965 | 87 | 0.542202 | 5.573209 | false | false | false | false |
milseman/swift
|
test/IRGen/swift3-metadata-coff.swift
|
17
|
1041
|
// RUN: %swift -target thumbv7--windows-itanium -parse-stdlib -parse-as-library -module-name Swift -O -emit-ir %s -o - | %FileCheck %s
// REQUIRES: CODEGENERATOR=ARM
precedencegroup AssignmentPrecedence {
assignment: true
}
public enum Optional<Wrapped> {
case none
case some(Wrapped)
}
public protocol P {
associatedtype T
}
public struct S : P {
public typealias T = Optional<S>
}
var gg = S()
public func f(s : S) -> (() -> ()) {
return { gg = s }
}
// CHECK-DAG: @"\01l__swift3_reflection_descriptor" = private constant {{.*}}, section ".sw3cptr"
// CHECK-DAG: @{{[0-9]+}} = private constant [3 x i8] c"Sq\00", section ".sw3tyrf"
// CHECK-DAG: @{{[0-9]+}} = private constant [5 x i8] c"none\00", section ".sw3rfst"
// CHECK-DAG: @{{[0-9]+}} = private constant [5 x i8] c"some\00", section ".sw3rfst"
// CHECK-DAG: @_T0SqMF = internal constant {{.*}}, section ".sw3flmd"
// CHECK-DAG: @_T0s1SVs1PsMA = internal constant {{.*}}, section ".sw3asty"
// CHECK-DAG: @_T0BoMB = internal constant {{.*}}, section ".sw3bltn"
|
apache-2.0
|
97805cdaab5abc1848149a73fc90121c
| 28.742857 | 134 | 0.637848 | 3.008671 | false | false | false | false |
neonichu/emoji-search-keyboard
|
Keyboard/KeyboardKeyBackground.swift
|
1
|
10587
|
//
// KeyboardKeyBackground.swift
// TransliteratingKeyboard
//
// Created by Alexei Baboulevitch on 7/19/14.
// Copyright (c) 2014 Apple. All rights reserved.
//
import UIKit
// This class does not actually draw its contents; rather, it generates bezier curves for others to use.
// (You can still move it around, resize it, and add subviews to it. It just won't display the curve assigned to it.)
class KeyboardKeyBackground: UIView, Connectable {
var fillPath: UIBezierPath?
var underPath: UIBezierPath?
var edgePaths: [UIBezierPath]?
// do not set this manually
var cornerRadius: CGFloat
var underOffset: CGFloat
var startingPoints: [CGPoint]
var segmentPoints: [(CGPoint, CGPoint)]
var arcCenters: [CGPoint]
var arcStartingAngles: [CGFloat]
var dirty: Bool
var attached: Direction? {
didSet {
self.dirty = true
self.setNeedsLayout()
}
}
var hideDirectionIsOpposite: Bool {
didSet {
self.dirty = true
self.setNeedsLayout()
}
}
init(cornerRadius: CGFloat, underOffset: CGFloat) {
attached = nil
hideDirectionIsOpposite = false
dirty = false
startingPoints = []
segmentPoints = []
arcCenters = []
arcStartingAngles = []
startingPoints.reserveCapacity(4)
segmentPoints.reserveCapacity(4)
arcCenters.reserveCapacity(4)
arcStartingAngles.reserveCapacity(4)
for _ in 0..<4 {
startingPoints.append(CGPointZero)
segmentPoints.append((CGPointZero, CGPointZero))
arcCenters.append(CGPointZero)
arcStartingAngles.append(0)
}
self.cornerRadius = cornerRadius
self.underOffset = underOffset
super.init(frame: CGRectZero)
self.userInteractionEnabled = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var oldBounds: CGRect?
override func layoutSubviews() {
if !self.dirty {
if self.bounds.width == 0 || self.bounds.height == 0 {
return
}
if oldBounds != nil && CGRectEqualToRect(self.bounds, oldBounds!) {
return
}
}
oldBounds = self.bounds
super.layoutSubviews()
self.generatePointsForDrawing(self.bounds)
self.dirty = false
}
let floatPi = CGFloat(M_PI)
let floatPiDiv2 = CGFloat(M_PI/2.0)
let floatPiDivNeg2 = -CGFloat(M_PI/2.0)
func generatePointsForDrawing(bounds: CGRect) {
let segmentWidth = bounds.width
let segmentHeight = bounds.height - CGFloat(underOffset)
// base, untranslated corner points
self.startingPoints[0] = CGPointMake(0, segmentHeight)
self.startingPoints[1] = CGPointMake(0, 0)
self.startingPoints[2] = CGPointMake(segmentWidth, 0)
self.startingPoints[3] = CGPointMake(segmentWidth, segmentHeight)
self.arcStartingAngles[0] = floatPiDiv2
self.arcStartingAngles[2] = floatPiDivNeg2
self.arcStartingAngles[1] = floatPi
self.arcStartingAngles[3] = 0
//// actual coordinates for each edge, including translation
//self.segmentPoints.removeAll(keepCapacity: true)
//
//// actual coordinates for arc centers for each corner
//self.arcCenters.removeAll(keepCapacity: true)
//
//self.arcStartingAngles.removeAll(keepCapacity: true)
for i in 0 ..< self.startingPoints.count {
let currentPoint = self.startingPoints[i]
let nextPoint = self.startingPoints[(i + 1) % self.startingPoints.count]
var floatXCorner: CGFloat = 0
var floatYCorner: CGFloat = 0
if (i == 1) {
floatXCorner = cornerRadius
}
else if (i == 3) {
floatXCorner = -cornerRadius
}
if (i == 0) {
floatYCorner = -cornerRadius
}
else if (i == 2) {
floatYCorner = cornerRadius
}
let p0 = CGPointMake(
currentPoint.x + (floatXCorner),
currentPoint.y + underOffset + (floatYCorner))
let p1 = CGPointMake(
nextPoint.x - (floatXCorner),
nextPoint.y + underOffset - (floatYCorner))
self.segmentPoints[i] = (p0, p1)
let c = CGPointMake(
p0.x - (floatYCorner),
p0.y + (floatXCorner))
self.arcCenters[i] = c
}
// order of edge drawing: left edge, down edge, right edge, up edge
// We need to have separate paths for all the edges so we can toggle them as needed.
// Unfortunately, it doesn't seem possible to assemble the connected fill path
// by simply using CGPathAddPath, since it closes all the subpaths, so we have to
// duplicate the code a little bit.
let fillPath = UIBezierPath()
var edgePaths: [UIBezierPath] = []
var prevPoint: CGPoint?
for i in 0..<4 {
var edgePath: UIBezierPath?
let segmentPoint = self.segmentPoints[i]
if self.attached != nil && (self.hideDirectionIsOpposite ? self.attached!.rawValue != i : self.attached!.rawValue == i) {
// do nothing
// TODO: quick hack
if !self.hideDirectionIsOpposite {
continue
}
}
else {
edgePath = UIBezierPath()
// TODO: figure out if this is ncessary
if prevPoint == nil {
prevPoint = segmentPoint.0
fillPath.moveToPoint(prevPoint!)
}
fillPath.addLineToPoint(segmentPoint.0)
fillPath.addLineToPoint(segmentPoint.1)
edgePath!.moveToPoint(segmentPoint.0)
edgePath!.addLineToPoint(segmentPoint.1)
prevPoint = segmentPoint.1
}
let shouldDrawArcInOppositeMode = (self.attached != nil ? (self.attached!.rawValue == i) || (self.attached!.rawValue == ((i + 1) % 4)) : false)
if (self.attached != nil && (self.hideDirectionIsOpposite ? !shouldDrawArcInOppositeMode : self.attached!.rawValue == ((i + 1) % 4))) {
// do nothing
} else {
edgePath = (edgePath == nil ? UIBezierPath() : edgePath)
if prevPoint == nil {
prevPoint = segmentPoint.1
fillPath.moveToPoint(prevPoint!)
}
let startAngle = self.arcStartingAngles[(i + 1) % 4]
let endAngle = startAngle + floatPiDiv2
let arcCenter = self.arcCenters[(i + 1) % 4]
fillPath.addLineToPoint(prevPoint!)
fillPath.addArcWithCenter(arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
edgePath!.moveToPoint(prevPoint!)
edgePath!.addArcWithCenter(arcCenter, radius: self.cornerRadius, startAngle: startAngle, endAngle: endAngle, clockwise: true)
prevPoint = self.segmentPoints[(i + 1) % 4].0
}
edgePath?.applyTransform(CGAffineTransformMakeTranslation(0, -self.underOffset))
if edgePath != nil { edgePaths.append(edgePath!) }
}
fillPath.closePath()
fillPath.applyTransform(CGAffineTransformMakeTranslation(0, -self.underOffset))
let underPath = { () -> UIBezierPath in
let underPath = UIBezierPath()
underPath.moveToPoint(self.segmentPoints[2].1)
var startAngle = self.arcStartingAngles[3]
var endAngle = startAngle + CGFloat(M_PI/2.0)
underPath.addArcWithCenter(self.arcCenters[3], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true)
underPath.addLineToPoint(self.segmentPoints[3].1)
startAngle = self.arcStartingAngles[0]
endAngle = startAngle + CGFloat(M_PI/2.0)
underPath.addArcWithCenter(self.arcCenters[0], radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: true)
underPath.addLineToPoint(CGPointMake(self.segmentPoints[0].0.x, self.segmentPoints[0].0.y - self.underOffset))
startAngle = self.arcStartingAngles[1]
endAngle = startAngle - CGFloat(M_PI/2.0)
underPath.addArcWithCenter(CGPointMake(self.arcCenters[0].x, self.arcCenters[0].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false)
underPath.addLineToPoint(CGPointMake(self.segmentPoints[2].1.x - self.cornerRadius, self.segmentPoints[2].1.y + self.cornerRadius - self.underOffset))
startAngle = self.arcStartingAngles[0]
endAngle = startAngle - CGFloat(M_PI/2.0)
underPath.addArcWithCenter(CGPointMake(self.arcCenters[3].x, self.arcCenters[3].y - self.underOffset), radius: CGFloat(self.cornerRadius), startAngle: startAngle, endAngle: endAngle, clockwise: false)
underPath.closePath()
return underPath
}()
self.fillPath = fillPath
self.edgePaths = edgePaths
self.underPath = underPath
}
func attachmentPoints(direction: Direction) -> (CGPoint, CGPoint) {
let returnValue = (
self.segmentPoints[direction.clockwise().rawValue].0,
self.segmentPoints[direction.counterclockwise().rawValue].1)
return returnValue
}
func attachmentDirection() -> Direction? {
return self.attached
}
func attach(direction: Direction?) {
self.attached = direction
}
}
|
bsd-3-clause
|
50ceec8f53d324133666960339529670
| 36.147368 | 212 | 0.567488 | 5.220414 | false | false | false | false |
welbesw/BigcommerceApi
|
Pod/Classes/BigcommerceOrderMessage.swift
|
1
|
2317
|
//
// BigcommerceOrderMessage.swift
// Pods
//
// Created by William Welbes on 10/30/15.
//
//
import Foundation
open class BigcommerceOrderMessage: NSObject {
open var orderMessageId:NSNumber?
open var orderId: NSNumber?
open var staffId:NSNumber?
open var customerId:NSNumber?
open var type:String?
open var subject:String = ""
open var message:String = ""
open var status:String?
open var isFlagged:Bool = false
open var dateCreated:Date?
public init(jsonDictionary:NSDictionary) {
//Load the JSON dictionary into the order object
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEE, d MMM yyyy HH:mm:ss zzz"
if let id = jsonDictionary["id"] as? NSNumber {
self.orderMessageId = id
}
if let id = jsonDictionary["order_id"] as? NSNumber {
self.orderId = id
}
if let id = jsonDictionary["customer_id"] as? NSNumber {
self.customerId = id
}
if let id = jsonDictionary["staff_id"] as? NSNumber {
self.staffId = id
}
if let stringValue = jsonDictionary["type"] as? String {
self.type = stringValue
}
if let stringValue = jsonDictionary["subject"] as? String {
self.subject = stringValue
}
if let stringValue = jsonDictionary["message"] as? String {
self.message = stringValue
}
if let stringValue = jsonDictionary["status"] as? String {
self.status = stringValue
}
if let numberValue = jsonDictionary["is_flagged"] as? NSNumber {
self.isFlagged = numberValue.boolValue
}
if let dateString = jsonDictionary["date_created"] as? String {
if let date = dateFormatter.date(from: dateString) {
dateCreated = date
}
}
}
open override var description: String {
let shipmentIdString = self.orderMessageId != nil ? self.orderMessageId!.stringValue : ""
let description = "Order Message \(shipmentIdString)"
return description
}
}
|
mit
|
5008f3b491a98fb4851ed88f2a847122
| 25.94186 | 97 | 0.562365 | 5.058952 | false | false | false | false |
owncloud/ios
|
Owncloud iOs Client/Login/Login/ServerURLNormalizer.swift
|
1
|
4169
|
//
// ServerURLNormalizer.swift
// Owncloud iOs Client
//
// Created by David A. Velasco on 19/7/17.
//
//
/*
Copyright (C) 2017, ownCloud GmbH.
This code is covered by the GNU Public License Version 3.
For distribution utilizing Apple mechanisms please see https://owncloud.org/contribute/iOS-license-exception/
You should have received a copy of this license
along with this program. If not, see <http://www.gnu.org/licenses/gpl-3.0.en.html>.
*/
import Foundation
class ServerURLNormalizer {
let k_http_prefix : String = "http://"
let k_https_prefix : String = "https://"
let k_remove_to_suffix : String = "/index.php"
let k_remove_to_contained_path : String = "/index.php/apps/"
var normalizedURL = ""
var user: String?
var password: String?
var scheme: String? //TODO store scheme
func normalize(serverURL: String) {
self.normalizedURL = serverURL;
self.normalizedURL = stripAccidentalWhiteSpaces(inputURL: normalizedURL)
self.normalizedURL = stripUsernameAndPassword(inputURL: normalizedURL)
self.normalizedURL = stripIndexPhpOrAppsFilesFromUrl(inputURL: normalizedURL);
self.normalizedURL = grantFinalSlash(inputURL: normalizedURL)
}
// Strip accidental white spaces at the end and beginning of the received URL.
//
func stripAccidentalWhiteSpaces(inputURL: String) -> String {
var workURL: String = inputURL;
while(workURL.hasSuffix(" ")) { // final blanks
workURL = workURL.substring(to: workURL.index(before: workURL.endIndex))
}
while(workURL.hasPrefix(" ")) { // initial blanks
workURL = workURL.substring(from: workURL.index(after: workURL.startIndex))
}
return workURL
}
// Strip username and password inserted in the received URL, if any.
//
// Stores both values in 'user' and 'password' properties.
//
func stripUsernameAndPassword(inputURL: String) -> String {
var workURL: String = inputURL;
// inputURL without scheme prefix is accepted, but NSURLComponents will parse all the string as the scheme
var forcedPrefix = false;
if !(workURL.hasPrefix(k_https_prefix) || workURL.hasPrefix(k_http_prefix)) {
// add HTTPS as prefix to trick NSURLComponents
workURL = "\(k_https_prefix)\(workURL)"
forcedPrefix = true;
}
if let components = NSURLComponents(string: workURL) {
// save parsed user and password
self.user = components.user
self.password = components.password
// generate the URL as string again, without user and password
components.user = nil;
components.password = nil;
workURL = components.string!
// remove scheme if was not in inputURL
if forcedPrefix {
workURL = workURL.substring(from: workURL.range(of: k_https_prefix)!.upperBound)
}
return workURL
} else {
return inputURL
}
}
// Strip accepted paths for URLs copied directly from web browser
//
func stripIndexPhpOrAppsFilesFromUrl(inputURL: String) -> String {
var returnURL: String = inputURL
if inputURL.hasSuffix(k_remove_to_suffix) {
returnURL = inputURL.substring(to: inputURL.range(of: k_remove_to_suffix, options: NSString.CompareOptions.backwards)!.lowerBound)
} else if let rangeOfContainedPathToRemove = inputURL.range(of: k_remove_to_contained_path) {
returnURL = inputURL.substring(to: rangeOfContainedPathToRemove.lowerBound);
}
return returnURL
}
// Grant last character is /
//
func grantFinalSlash(inputURL: String) -> String {
if !inputURL.hasSuffix("/") {
return "\(inputURL)/"
}
return inputURL
}
}
|
gpl-3.0
|
9d7278dc2a5171d0d5dde12bc4931c65
| 30.824427 | 142 | 0.605901 | 4.571272 | false | false | false | false |
nevyn/SPDragNDrop
|
Examples/DragonFrame/DragonFrame/PhotoFrameViewController.swift
|
2
|
2192
|
//
// FirstViewController.swift
// DragonFrame
//
// Created by Nevyn Bengtsson on 2015-12-20.
// Copyright © 2015 ThirdCog. All rights reserved.
//
import UIKit
class PhotoFrameViewController: UIViewController, DragonDropDelegate {
@IBOutlet var imageView : UIImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Load image from last run.
imageView.image = self.image
// The user may drop things on the image view.
// This view controller will be the delegate to determine if and how
// drop operations will be handled.
DragonController.sharedController().registerDropTarget(self.imageView, delegate: self)
}
// When a dragging operation starts, this method is called for each drop target
// that this view controller is responsible for, to see if the drop target
// is potentially able to accept the contents of that drag'n'drop.
func dropTarget(droppable: UIView, canAcceptDrag drag: DragonInfo) -> Bool {
// Is there something image-like on the pasteboard? Then accept it.
if drag.pasteboard.pasteboardTypes().contains({ (str) -> Bool in
return UIPasteboardTypeListImage.containsObject(str)
}) {
return true
}
return false
}
// Once the user drops the item on a drop target view, this method is responsible
// for accepting the data and handling it.
func dropTarget(droppable: UIView, acceptDrag drag: DragonInfo, atPoint p: CGPoint) {
if let image = drag.pasteboard.image {
// We handle it by setting the main image view's image to the one
// that the user dropped, and ...
self.imageView.image = image
// ... also saving it to disk for next time.
self.image = image
}
}
// Helpers for loading/saving images from disk
var imageURL : NSURL {
get {
let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first!
return NSURL.fileURLWithPath(documentsPath).URLByAppendingPathComponent("image.jpg")
}
}
var image : UIImage? {
get {
return UIImage(contentsOfFile: self.imageURL.path!)
}
set {
if let image = newValue {
UIImageJPEGRepresentation(image, 0.8)?.writeToURL(self.imageURL, atomically: false)
}
}
}
}
|
apache-2.0
|
d1118dbf16f110394baacf2ff2834b4e
| 29.873239 | 108 | 0.722958 | 3.884752 | false | false | false | false |
manfengjun/KYMart
|
Section/LogAndReg/Controller/SJBLoginViewController.swift
|
1
|
5219
|
//
// LoginViewController.swift
// HNLYSJB
//
// Created by jun on 2017/6/2.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
import ReactiveCocoa
import ReactiveSwift
import Result
import YYCache
import IQKeyboardManagerSwift
class SJBLoginViewController: BaseViewController {
@IBOutlet weak var textView: UIView!
@IBOutlet weak var menuView: UIView!
@IBOutlet weak var accountT: UITextField!
@IBOutlet weak var passwordT: UITextField!
@IBOutlet weak var loginBtn: UIButton!
/// 闭包回调传值
var LoginResultClosure: LoginClosure? // 闭包
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
IQKeyboardManager.sharedManager().enable = true
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated)
IQKeyboardManager.sharedManager().enable = false
}
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
validated()
}
func setupUI() {
self.title = "登录"
setLeftButtonInNav(imageUrl: "nav_del.png", action: #selector(dismissLogin))
loginBtn.layer.masksToBounds = true
loginBtn.layer.cornerRadius = 5
textView.layer.masksToBounds = true
textView.layer.cornerRadius = 5
menuView.layer.masksToBounds = true
menuView.layer.cornerRadius = 5
}
func dismissLogin() {
self.dismiss(animated: true, completion: nil)
}
func loginHandle() {
SJBRequestModel.pull_fetchVerifyCodeData { (response, status) in
if status == 1 {
let verifycode = response as! String
let account = self.accountT.text
let password = self.passwordT.text
var registrationID = ""
if UserDefaults.standard.object(forKey: "registrationID") != nil
{
registrationID = UserDefaults.standard.object(forKey: "registrationID") as! String
}
let params = ["username":account!, "password":password!, "unique_id":SingleManager.getUUID(), "capache":verifycode, "push_id":registrationID]
SJBRequestModel.push_fetchLoginData(params: params as [String : AnyObject], completion: { (response, status) in
if status == 1{
SingleManager.instance.loginInfo = response as? KYLoginInfoModel
SingleManager.instance.loginInfo?.password = password
SingleManager.instance.isLogin = true
self.Toast(content: "登陆成功")
self.dismiss(animated: true, completion: nil)
self.LoginResultClosure?(true)
let cache = YYCache(name: "KYMart")
cache?.setObject(SingleManager.instance.loginInfo, forKey: "loginInfo")
}
else
{
self.Toast(content: response as! String)
self.LoginResultClosure?(false)
}
})
}
else
{
self.Toast(content: "未知错误")
self.LoginResultClosure?(false)
}
}
}
/**
登录响应闭包回调
*/
func loginResult(_ finished: @escaping LoginClosure) {
LoginResultClosure = finished
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
// MARK: - 响应事件
extension SJBLoginViewController{
@IBAction func loginAction(_ sender: UIButton) {
loginHandle()
}
@IBAction func regAction(_ sender: UITapGestureRecognizer) {
self.performSegue(withIdentifier: "L_register_SegueID", sender: sender)
}
@IBAction func forgetAction(_ sender: UITapGestureRecognizer) {
self.performSegue(withIdentifier: "L_forget_SegueID", sender: sender)
}
}
// MARK: - 业务逻辑
extension SJBLoginViewController
{
/// 验证数据正确性
func validated() {
let accountSignal = accountT.reactive.continuousTextValues.map { (text) -> Bool in
if let str = text {
return self.ContentIsValidated(text: str)
}
return false
}
let passSignal = passwordT.reactive.continuousTextValues.map { (text) -> Bool in
if let str = text {
return self.PassWordIsValidated(text: str)
}
return false
}
Signal.combineLatest(accountSignal, passSignal).observeValues { (accountLegal, passLegal) in
if accountLegal && passLegal{
self.loginBtn.isUserInteractionEnabled = true
self.loginBtn.backgroundColor = BAR_TINTCOLOR
}
else
{
self.loginBtn.isUserInteractionEnabled = false
self.loginBtn.backgroundColor = UIColor.lightGray
}
}
}
}
|
mit
|
dd005fd2d2de06623ca3b9924ffc6228
| 32.337662 | 157 | 0.578302 | 5.093254 | false | false | false | false |
haifengkao/ReactiveCache
|
Example/Pods/HanekeObjc/Pod/Classes/Log.swift
|
1
|
965
|
//
// Log.swift
// Haneke
//
// Created by Hermes Pique on 11/10/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import Foundation
struct Log {
fileprivate static let Tag = "[HANEKEObjc]"
fileprivate enum Level : String {
case Debug = "[DEBUG]"
case Error = "[ERROR]"
}
fileprivate static func log(_ level: Level, _ message: @autoclosure () -> String, _ error: NSError? = nil) {
if let error = error {
NSLog("%@%@ %@ with error %@", Tag, level.rawValue, message(), error)
} else {
NSLog("%@%@ %@", Tag, level.rawValue, message())
}
}
static func debug(_ message: @autoclosure () -> String, _ error: NSError? = nil) {
#if DEBUG
log(.Debug, message(), error)
#endif
}
static func error(_ message: @autoclosure () -> String, _ error: NSError? = nil) {
log(.Error, message(), error)
}
}
|
mit
|
24dab7cc46a573bee0a84201b6ececb6
| 24.394737 | 112 | 0.531606 | 4.054622 | false | false | false | false |
steryokhin/AsciiArtPlayer
|
src/AsciiArtPlayer/Pods/Swinject/Sources/Container.swift
|
5
|
9104
|
//
// Container.swift
// Swinject
//
// Created by Yoichi Tagaya on 7/23/15.
// Copyright © 2015 Swinject Contributors. All rights reserved.
//
import Foundation
/// The `Container` class represents a dependency injection container, which stores registrations of services
/// and retrieves registered services with dependencies injected.
///
/// **Example to register:**
///
/// let container = Container()
/// container.register(A.self) { _ in B() }
/// container.register(X.self) { r in Y(a: r.resolve(A.self)!) }
///
/// **Example to retrieve:**
///
/// let x = container.resolve(X.self)!
///
/// where `A` and `X` are protocols, `B` is a type conforming `A`, and `Y` is a type conforming `X` and depending on `A`.
public final class Container {
fileprivate var services = [ServiceKey: ServiceEntryType]()
fileprivate let parent: Container?
fileprivate var resolutionPool = ResolutionPool()
internal let lock: SpinLock // Used by SynchronizedResolver.
/// Instantiates a `Container` with its parent `Container`. The parent is optional.
///
/// - Parameter parent: The optional parent `Container`.
public init(parent: Container? = nil) {
self.parent = parent
self.lock = parent.map { $0.lock } ?? SpinLock()
}
/// Instantiates a `Container` with its parent `Container` and a closure registering services. The parent is optional.
///
/// - Parameters:
/// - parent: The optional parent `Container`.
/// - registeringClosure: The closure registering services to the new container instance.
public convenience init(parent: Container? = nil, registeringClosure: (Container) -> Void) {
self.init(parent: parent)
registeringClosure(self)
}
/// Removes all registrations in the container.
public func removeAll() {
services.removeAll()
}
/// Adds a registration for the specified service with the factory closure to specify how the service is resolved with dependencies.
///
/// - Parameters:
/// - serviceType: The service type to register.
/// - name: A registration name, which is used to differentiate from other registrations
/// that have the same service and factory types.
/// - factory: The closure to specify how the service type is resolved with the dependencies of the type.
/// It is invoked when the `Container` needs to instantiate the instance.
/// It takes a `ResolverType` to inject dependencies to the instance,
/// and returns the instance of the component type for the service.
///
/// - Returns: A registered `ServiceEntry` to configure more settings with method chaining.
@discardableResult
public func register<Service>(
_ serviceType: Service.Type,
name: String? = nil,
factory: (ResolverType) -> Service) -> ServiceEntry<Service>
{
return _register(serviceType, factory: factory, name: name)
}
/// This method is designed for the use to extend Swinject functionality.
/// Do NOT use this method unless you intend to write an extension or plugin to Swinject framework.
///
/// - Parameters:
/// - serviceType: The service type to register.
/// - factory: The closure to specify how the service type is resolved with the dependencies of the type.
/// It is invoked when the `Container` needs to instantiate the instance.
/// It takes a `ResolverType` to inject dependencies to the instance,
/// and returns the instance of the component type for the service.
/// - name: A registration name.
/// - option: A service key option for an extension/plugin.
///
/// - Returns: A registered `ServiceEntry` to configure more settings with method chaining.
@discardableResult
public func _register<Service, Factory>(
_ serviceType: Service.Type,
factory: Factory,
name: String? = nil,
option: ServiceKeyOptionType? = nil) -> ServiceEntry<Service>
{
let key = ServiceKey(factoryType: type(of: factory), name: name, option: option)
let entry = ServiceEntry(serviceType: serviceType, factory: factory)
services[key] = entry
return entry
}
/// Returns a synchronized view of the container for thread safety.
/// The returned container is `ResolverType` type. Call this method after you finish all service registrations to the original container.
///
/// - Returns: A synchronized container as `ResolverType`.
public func synchronize() -> ResolverType {
return SynchronizedResolver(container: self)
}
}
// MARK: - _ResolverType
extension Container: _ResolverType {
public func _resolve<Service, Factory>(name: String?, option: ServiceKeyOptionType? = nil, invoker: (Factory) -> Service) -> Service? {
resolutionPool.incrementDepth()
defer { resolutionPool.decrementDepth() }
var resolvedInstance: Service?
let key = ServiceKey(factoryType: Factory.self, name: name, option: option)
if let (entry, fromParent) = getEntry(key) as (ServiceEntry<Service>, Bool)? {
switch entry.objectScope {
case .none, .graph:
resolvedInstance = resolve(entry: entry, key: key, invoker: invoker)
case .container:
let ownEntry: ServiceEntry<Service>
if fromParent {
ownEntry = entry.copyExceptInstance()
services[key] = ownEntry
} else {
ownEntry = entry
}
if ownEntry.instance == nil {
ownEntry.instance = resolve(entry: entry, key: key, invoker: invoker) as Any
}
resolvedInstance = ownEntry.instance as? Service
case .hierarchy:
if entry.instance == nil {
entry.instance = resolve(entry: entry, key: key, invoker: invoker) as Any
}
resolvedInstance = entry.instance as? Service
}
}
return resolvedInstance
}
}
// MARK: - ResolverType
extension Container: ResolverType {
/// Retrieves the instance with the specified service type.
///
/// - Parameter serviceType: The service type to resolve.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type is found in the `Container`.
public func resolve<Service>(
_ serviceType: Service.Type) -> Service?
{
return resolve(serviceType, name: nil)
}
/// Retrieves the instance with the specified service type and registration name.
///
/// - Parameters:
/// - serviceType: The service type to resolve.
/// - name: The registration name.
///
/// - Returns: The resolved service type instance, or nil if no registration for the service type and name is found in the `Container`.
public func resolve<Service>(
_ serviceType: Service.Type,
name: String?) -> Service?
{
typealias FactoryType = (ResolverType) -> Service
return _resolve(name: name) { (factory: FactoryType) in factory(self) }
}
fileprivate func getEntry<Service>(_ key: ServiceKey) -> (ServiceEntry<Service>, Bool)? {
var fromParent = false
var entry = services[key] as? ServiceEntry<Service>
if entry == nil, let parent = self.parent {
if let (parentEntry, _) = parent.getEntry(key) as (ServiceEntry<Service>, Bool)? {
entry = parentEntry
fromParent = true
}
}
return entry.map { ($0, fromParent) }
}
fileprivate func resolve<Service, Factory>(entry: ServiceEntry<Service>, key: ServiceKey, invoker: (Factory) -> Service) -> Service {
let usesPool = entry.objectScope != .none
if usesPool, let pooledInstance = resolutionPool[key] as? Service {
return pooledInstance
}
let resolvedInstance = invoker(entry.factory as! Factory)
if usesPool {
if let pooledInstance = resolutionPool[key] as? Service {
// An instance for the key might be added by the factory invocation.
return pooledInstance
}
resolutionPool[key] = resolvedInstance as Any
}
if let completed = entry.initCompleted as? (ResolverType, Service) -> () {
resolutionPool.appendPendingCompletion({completed(self, resolvedInstance)})
}
return resolvedInstance
}
}
// MARK: CustomStringConvertible
extension Container: CustomStringConvertible {
public var description: String {
return "["
+ services.map { "\n { \($1.describeWithKey($0)) }" }.sorted().joined(separator: ",")
+ "\n]"
}
}
|
mit
|
98bf8d1eedbd841918585cdd69fb80bd
| 40.756881 | 141 | 0.616939 | 4.867914 | false | false | false | false |
Takanu/Pelican
|
Sources/Pelican/Session/Modules/Router/Route.swift
|
1
|
5126
|
//
// ChatSessionRoute.swift
//
// Created by Takanu Kyriako on 22/06/2017.
//
//
import Foundation
/**
The base class for filtering incoming updates either to functions or other routes for further filtering.
This base route class will handle all updates and perform no filtering, for pre-built Routes that do filter and
cover all common use-cases, see `RoutePass`, `RouteCommand`, `RouteListen` and `RouteManual`.
*/
open class Route: CustomStringConvertible {
/// The name of the route instance. This must be assigned on initialisation to allow for fetching nested routed in subscripts.
public var name: String
/// The action the route will execute if successful
public var action: ( (Update) -> (Bool) )?
/**
Whether or not the route is enabled. If disabled, the RouteController will ignore it when finding
a route to pass an update to.
*/
public var enabled: Bool = true
/// The routes to pass the request to next, if no action has been set or if the action fails.
public var nextRoutes: [Route] = []
/// The route to use if all other routes or actions are unable to handle the update.
public var fallbackRoute: Route?
public var description: String {
return """
\(name) Route
Enabled = \(enabled) | Action = \(action != nil) |
Routes = \(nextRoutes.map { $0.name }) | Fallback Route = \(fallbackRoute != nil)
"""
}
/**
Initialises a blank route that performs no filtering.
*/
public init(name: String, action: @escaping (Update) -> (Bool)) {
self.name = name
self.action = action
}
/**
Initialises a blank route that performs no filtering.
*/
public init(name: String, routes: [Route]) {
self.name = name
self.nextRoutes = routes
}
/**
Allows you to access routes that are linked to other routes
*/
public subscript(nameArray: [String]) -> Route? {
for name in nameArray {
for route in nextRoutes {
if route.name == name {
let nextNames = nameArray.dropFirst().filter { p in return true }
if nextNames.count == 0 {
return route
} else {
return route[nextNames]
}
}
}
}
return nil
}
/**
Accepts an update for a route to try and handle, based on it's own criteria.
- parameter update: The update to be handled.
- returns: True if handled successfully, false if not. Although the Route's action
function might be called if the Route determines it can accept the update, this function
can still return false if the action function returns as false.
*/
open func handle(_ update: Update) -> Bool {
return passUpdate(update)
}
/**
Allows a route to compare itself with another route of any type to see if they match.
*/
open func compare(_ route: Route) -> Bool {
if name != route.name { return false }
if enabled != route.enabled { return false }
if nextRoutes.count != route.nextRoutes.count { return false }
for (i, leftNextRoute) in nextRoutes.enumerated() {
let rightNextRoute = route.nextRoutes[i]
if leftNextRoute.compare(rightNextRoute) == false { return false }
}
return true
}
/**
When a handler function succeeds, this should always be called to decide where the update goes next.
*/
public func passUpdate(_ update: Update) -> Bool {
// Attempt to use an assigned action
if action != nil {
if action!(update) == true { return true }
}
// Attempt to find a route that will successfully handle the update.
for route in nextRoutes {
if route.enabled == true {
if route.handle(update) == true { return true }
}
}
// Attempt to use a fallback route
if fallbackRoute != nil {
if fallbackRoute!.enabled == true {
if fallbackRoute!.handle(update) == true { return true }
}
}
// Otherwise return in FAILURE.
return false
}
/**
Adds the given routes to the `nextRoutes` array. Convenience function.
*/
public func addRoutes(_ routes: Route...) {
for route in routes {
nextRoutes.append(route)
}
}
/**
Attempts to remove the given routes from the 'nextRoutes' array.
*/
public func removeRoutes(_ routes: Route...) {
for route in routes {
for (i, nextRoute) in nextRoutes.enumerated() {
if route.compare(nextRoute) == true {
nextRoutes.remove(at: i)
}
}
}
}
/**
Attempts to remove routes from the 'nextRoutes' array that match the given names.
*/
public func removeRoutes(_ names: String...) {
for incomingName in names {
if let routeIndex = nextRoutes.index(where: {$0.name == incomingName}) {
nextRoutes.remove(at: routeIndex)
}
}
}
/**
Empties the route of all actions, routes and fallbacks.
*/
open func clearAll() {
self.action = nil
self.nextRoutes = []
self.fallbackRoute = nil
}
/**
Closes the route system by ensuring all routes connected to it are cleared.
Providing no strong reference cycles are present, this will help ensure the Session closes.
*/
open func close() {
self.action = nil
self.fallbackRoute = nil
self.nextRoutes.forEach { T in T.close() }
self.nextRoutes = []
}
}
|
mit
|
39d5e894de67cd45587d8b481bd30328
| 23.179245 | 128 | 0.666797 | 3.661429 | false | false | false | false |
xedin/swift
|
test/Sema/struct_equatable_hashable.swift
|
1
|
13403
|
// RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/struct_equatable_hashable_other.swift -verify-ignore-unknown -swift-version 4
var hasher = Hasher()
struct Point: Hashable {
let x: Int
let y: Int
}
func point() {
if Point(x: 1, y: 2) == Point(x: 2, y: 1) { }
let _: Int = Point(x: 3, y: 5).hashValue
Point(x: 3, y: 5).hash(into: &hasher)
Point(x: 1, y: 2) == Point(x: 2, y: 1) // expected-warning {{result of operator '==' is unused}}
}
struct Pair<T: Hashable>: Hashable {
let first: T
let second: T
func same() -> Bool {
return first == second
}
}
func pair() {
let p1 = Pair(first: "a", second: "b")
let p2 = Pair(first: "a", second: "c")
if p1 == p2 { }
let _: Int = p1.hashValue
p1.hash(into: &hasher)
}
func localStruct() -> Bool {
struct Local: Equatable {
let v: Int
}
return Local(v: 5) == Local(v: 4)
}
//------------------------------------------------------------------------------
// Verify compiler can derive hash(into:) implementation from hashValue
struct CustomHashValue: Hashable {
let x: Int
let y: Int
static func ==(x: CustomHashValue, y: CustomHashValue) -> Bool { return true }
func hash(into hasher: inout Hasher) {}
}
func customHashValue() {
if CustomHashValue(x: 1, y: 2) == CustomHashValue(x: 2, y: 3) { }
let _: Int = CustomHashValue(x: 1, y: 2).hashValue
CustomHashValue(x: 1, y: 2).hash(into: &hasher)
}
//------------------------------------------------------------------------------
// Verify compiler can derive hashValue implementation from hash(into:)
struct CustomHashInto: Hashable {
let x: Int
let y: Int
func hash(into hasher: inout Hasher) {
hasher.combine(x)
hasher.combine(y)
}
static func ==(x: CustomHashInto, y: CustomHashInto) -> Bool { return true }
}
func customHashInto() {
if CustomHashInto(x: 1, y: 2) == CustomHashInto(x: 2, y: 3) { }
let _: Int = CustomHashInto(x: 1, y: 2).hashValue
CustomHashInto(x: 1, y: 2).hash(into: &hasher)
}
// Check use of an struct's synthesized members before the struct is actually declared.
struct UseStructBeforeDeclaration {
let eqValue = StructToUseBeforeDeclaration(v: 4) == StructToUseBeforeDeclaration(v: 5)
let hashValue = StructToUseBeforeDeclaration(v: 1).hashValue
let hashInto: (inout Hasher) -> Void = StructToUseBeforeDeclaration(v: 1).hash(into:)
}
struct StructToUseBeforeDeclaration: Hashable {
let v: Int
}
func getFromOtherFile() -> AlsoFromOtherFile { return AlsoFromOtherFile(v: 4) }
func overloadFromOtherFile() -> YetAnotherFromOtherFile { return YetAnotherFromOtherFile(v: 1.2) }
func overloadFromOtherFile() -> Bool { return false }
func useStructBeforeDeclaration() {
// Check structs from another file in the same module.
if FromOtherFile(v: "a") == FromOtherFile(v: "b") {}
let _: Int = FromOtherFile(v: "c").hashValue
FromOtherFile(v: "d").hash(into: &hasher)
if AlsoFromOtherFile(v: 3) == getFromOtherFile() {}
if YetAnotherFromOtherFile(v: 1.9) == overloadFromOtherFile() {}
}
// Even if the struct has only equatable/hashable members, it's not synthesized
// implicitly.
struct StructWithoutExplicitConformance {
let a: Int
let b: String
}
func structWithoutExplicitConformance() {
if StructWithoutExplicitConformance(a: 1, b: "b") == StructWithoutExplicitConformance(a: 2, b: "a") { } // expected-error{{binary operator '==' cannot be applied to two 'StructWithoutExplicitConformance' operands}}
// expected-note @-1 {{overloads for '==' exist with these partially matching parameter lists: }}
}
// Structs with non-hashable/equatable stored properties don't derive conformance.
struct NotHashable {}
struct StructWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}}
let a: NotHashable // expected-note {{stored property type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'StructWithNonHashablePayload' to 'Hashable'}}
// expected-note@-1 {{stored property type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'StructWithNonHashablePayload' to 'Equatable'}}
}
// ...but computed properties and static properties are not considered.
struct StructIgnoresComputedProperties: Hashable {
var a: Int
var b: String
static var staticComputed = NotHashable()
var computed: NotHashable { return NotHashable() }
}
func structIgnoresComputedProperties() {
if StructIgnoresComputedProperties(a: 1, b: "a") == StructIgnoresComputedProperties(a: 2, b: "c") {}
let _: Int = StructIgnoresComputedProperties(a: 3, b: "p").hashValue
StructIgnoresComputedProperties(a: 4, b: "q").hash(into: &hasher)
}
// Structs should be able to derive conformances based on the conformances of
// their generic arguments.
struct GenericHashable<T: Hashable>: Hashable {
let value: T
}
func genericHashable() {
if GenericHashable<String>(value: "a") == GenericHashable<String>(value: "b") { }
let _: Int = GenericHashable<String>(value: "c").hashValue
GenericHashable<String>(value: "c").hash(into: &hasher)
}
// But it should be an error if the generic argument doesn't have the necessary
// constraints to satisfy the conditions for derivation.
struct GenericNotHashable<T: Equatable>: Hashable { // expected-error 2 {{does not conform to protocol 'Hashable'}}
let value: T // expected-note 2 {{stored property type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'GenericNotHashable<T>' to 'Hashable'}}
}
func genericNotHashable() {
if GenericNotHashable<String>(value: "a") == GenericNotHashable<String>(value: "b") { }
let gnh = GenericNotHashable<String>(value: "b")
let _: Int = gnh.hashValue // No error. hashValue is always synthesized, even if Hashable derivation fails
gnh.hash(into: &hasher) // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hash'}}
}
// Synthesis can be from an extension...
struct StructConformsInExtension {
let v: Int
}
extension StructConformsInExtension : Equatable {}
// and explicit conformance in an extension should also work.
public struct StructConformsAndImplementsInExtension {
let v: Int
}
extension StructConformsAndImplementsInExtension : Equatable {
public static func ==(lhs: StructConformsAndImplementsInExtension, rhs: StructConformsAndImplementsInExtension) -> Bool {
return true
}
}
// No explicit conformance and it cannot be derived.
struct NotExplicitlyHashableAndCannotDerive {
let v: NotHashable // expected-note {{stored property type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Hashable'}}
// expected-note@-1 {{stored property type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Equatable'}}
}
extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}}
// A struct with no stored properties trivially derives conformance.
struct NoStoredProperties: Hashable {}
// Verify that conformance (albeit manually implemented) can still be added to
// a type in a different file.
extension OtherFileNonconforming: Hashable {
static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
}
// ...but synthesis in a type defined in another file doesn't work yet.
extension YetOtherFileNonconforming: Equatable {} // expected-error {{cannot be automatically synthesized in an extension in a different file to the type}}
// Verify that we can add Hashable conformance in an extension by only
// implementing hash(into:)
struct StructConformsAndImplementsHashIntoInExtension: Equatable {
let v: String
}
extension StructConformsAndImplementsHashIntoInExtension: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(v)
}
}
func structConformsAndImplementsHashIntoInExtension() {
let _: Int = StructConformsAndImplementsHashIntoInExtension(v: "a").hashValue
StructConformsAndImplementsHashIntoInExtension(v: "b").hash(into: &hasher)
}
struct GenericHashIntoInExtension<T: Hashable>: Equatable {
let value: T
}
extension GenericHashIntoInExtension: Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}
func genericHashIntoInExtension() {
let _: Int = GenericHashIntoInExtension<String>(value: "a").hashValue
GenericHashIntoInExtension(value: "b").hash(into: &hasher)
}
// Conditional conformances should be able to be synthesized
struct GenericDeriveExtension<T> {
let value: T
}
extension GenericDeriveExtension: Equatable where T: Equatable {}
extension GenericDeriveExtension: Hashable where T: Hashable {}
// Incorrectly/insufficiently conditional shouldn't work
struct BadGenericDeriveExtension<T> {
let value: T // expected-note {{stored property type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Hashable'}}
// expected-note@-1 {{stored property type 'T' does not conform to protocol 'Equatable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Equatable'}}
}
extension BadGenericDeriveExtension: Equatable {}
// expected-error@-1 {{type 'BadGenericDeriveExtension<T>' does not conform to protocol 'Equatable'}}
extension BadGenericDeriveExtension: Hashable where T: Equatable {}
// expected-error@-1 {{type 'BadGenericDeriveExtension' does not conform to protocol 'Hashable'}}
// But some cases don't need to be conditional, even if they look similar to the
// above
struct AlwaysHashable<T>: Hashable {}
struct UnusedGenericDeriveExtension<T> {
let value: AlwaysHashable<T>
}
extension UnusedGenericDeriveExtension: Hashable {}
// Cross-file synthesis is still disallowed for conditional cases
extension GenericOtherFileNonconforming: Equatable where T: Equatable {}
// expected-error@-1{{implementation of 'Equatable' cannot be automatically synthesized in an extension in a different file to the type}}
// rdar://problem/41852654
// There is a conformance to Equatable (or at least, one that implies Equatable)
// in the same file as the type, so the synthesis is okay. Both orderings are
// tested, to catch choosing extensions based on the order of the files, etc.
protocol ImplierMain: Equatable {}
struct ImpliedMain: ImplierMain {}
extension ImpliedOther: ImplierMain {}
// Hashable conformances that rely on a manual implementation of `hashValue`
// should produce a deprecation warning.
struct OldSchoolStruct: Hashable {
static func ==(left: OldSchoolStruct, right: OldSchoolStruct) -> Bool {
return true
}
var hashValue: Int { return 42 }
// expected-warning@-1{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'OldSchoolStruct' to 'Hashable' by implementing 'hash(into:)' instead}}
}
enum OldSchoolEnum: Hashable {
case foo
case bar
static func ==(left: OldSchoolEnum, right: OldSchoolEnum) -> Bool {
return true
}
var hashValue: Int { return 23 }
// expected-warning@-1{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'OldSchoolEnum' to 'Hashable' by implementing 'hash(into:)' instead}}
}
class OldSchoolClass: Hashable {
static func ==(left: OldSchoolClass, right: OldSchoolClass) -> Bool {
return true
}
var hashValue: Int { return -9000 }
// expected-warning@-1{{'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'OldSchoolClass' to 'Hashable' by implementing 'hash(into:)' instead}}
}
// However, it's okay to implement `hashValue` as long as `hash(into:)` is also
// provided.
struct MixedStruct: Hashable {
static func ==(left: MixedStruct, right: MixedStruct) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
var hashValue: Int { return 42 }
}
enum MixedEnum: Hashable {
case foo
case bar
static func ==(left: MixedEnum, right: MixedEnum) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
var hashValue: Int { return 23 }
}
class MixedClass: Hashable {
static func ==(left: MixedClass, right: MixedClass) -> Bool {
return true
}
func hash(into hasher: inout Hasher) {}
var hashValue: Int { return -9000 }
}
// Ensure equatable and hashable works with weak/unowned properties as well
struct Foo: Equatable, Hashable {
weak var foo: Bar?
unowned var bar: Bar
}
class Bar {
let bar: String
init(bar: String) {
self.bar = bar
}
}
extension Bar: Equatable, Hashable {
static func == (lhs: Bar, rhs: Bar) -> Bool {
return lhs.bar == rhs.bar
}
func hash(into hasher: inout Hasher) {}
}
// FIXME: Remove -verify-ignore-unknown.
// <unknown>:0: error: unexpected error produced: invalid redeclaration of 'hashValue'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool'
// <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
|
apache-2.0
|
d2221340f5fd13cf398afa557bc88f49
| 37.514368 | 216 | 0.725808 | 4.016482 | false | false | false | false |
SwiftGit2/SwiftGit2
|
SwiftGit2/Errors.swift
|
1
|
1812
|
import Foundation
import Clibgit2
public let libGit2ErrorDomain = "org.libgit2.libgit2"
internal extension NSError {
/// Returns an NSError with an error domain and message for libgit2 errors.
///
/// :param: errorCode An error code returned by a libgit2 function.
/// :param: libGit2PointOfFailure The name of the libgit2 function that produced the
/// error code.
/// :returns: An NSError with a libgit2 error domain, code, and message.
convenience init(gitError errorCode: Int32, pointOfFailure: String? = nil) {
let code = Int(errorCode)
var userInfo: [String: String] = [:]
if let message = errorMessage(errorCode) {
userInfo[NSLocalizedDescriptionKey] = message
} else {
userInfo[NSLocalizedDescriptionKey] = "Unknown libgit2 error."
}
if let pointOfFailure = pointOfFailure {
userInfo[NSLocalizedFailureReasonErrorKey] = "\(pointOfFailure) failed."
}
self.init(domain: libGit2ErrorDomain, code: code, userInfo: userInfo)
}
}
/// Returns the libgit2 error message for the given error code.
///
/// The error message represents the last error message generated by
/// libgit2 in the current thread.
///
/// :param: errorCode An error code returned by a libgit2 function.
/// :returns: If the error message exists either in libgit2's thread-specific registry,
/// or errno has been set by the system, this function returns the
/// corresponding string representation of that error. Otherwise, it returns
/// nil.
private func errorMessage(_ errorCode: Int32) -> String? {
let last = giterr_last()
if let lastErrorPointer = last {
return String(validatingUTF8: lastErrorPointer.pointee.message)
} else if UInt32(errorCode) == GIT_ERROR_OS.rawValue {
return String(validatingUTF8: strerror(errno))
} else {
return nil
}
}
|
mit
|
5e8915b360ea1f7b865104087fbd9b9c
| 35.24 | 87 | 0.724614 | 3.922078 | false | false | false | false |
fahidattique55/FAPanels
|
FAPanels/Classes/UIImage+FAPanel.swift
|
1
|
1956
|
//
// UIImage+FAPanel.swift
// FAPanels
//
// Created by Fahid Attique on 25/07/2017.
// Copyright © 2017 Fahid Attique. All rights reserved.
//
import Foundation
import UIKit
public extension UIImage {
// Get Array of imageViews containing the sliced images as per number of rows and columns specified
func slicesWith(rows: UInt, AndColumns columns: UInt, borderWidth: CGFloat = 0.0, borderColor: UIColor = .black, alpha: CGFloat = 1.0 ) -> [UIImageView] {
var slicedImageViews = [UIImageView]()
let imageSize: CGSize = size
var xPos: CGFloat = 0.0, yPos: CGFloat = 0.0
let width: CGFloat = imageSize.width/CGFloat(columns)
let height: CGFloat = imageSize.height/CGFloat(rows)
let imageViewWidth : CGFloat = UIScreen.main.bounds.size.width / CGFloat(columns)
let imageViewheight: CGFloat = UIScreen.main.bounds.size.height / CGFloat(rows)
for y in 0..<rows {
xPos = 0.0
for x in 0..<columns {
let rect: CGRect = CGRect(x: xPos, y: yPos, width: width * scale, height: height * scale)
let cImage: CGImage = cgImage!.cropping(to: rect)!
let dImage: UIImage = UIImage(cgImage: cImage)
let imageView: UIImageView = UIImageView(frame: CGRect(x: CGFloat(x)*width, y: CGFloat(y)*height, width: imageViewWidth, height: imageViewheight))
imageView.image = dImage
imageView.layer.borderColor = borderColor.cgColor
imageView.layer.borderWidth = borderWidth
imageView.alpha = alpha
slicedImageViews.append(imageView)
xPos += width * scale
}
yPos += height * scale
}
return slicedImageViews
}
}
|
apache-2.0
|
860ddb11ff65b1ddc34229f4adf21794
| 32.135593 | 162 | 0.570332 | 4.745146 | false | false | false | false |
collegboi/MBaaSKit
|
MBaaSKit/Classes/TBAnalytics.swift
|
1
|
8720
|
//
// TBAnalytics.swift
// Pods
//
// Created by Timothy Barnard on 08/02/2017.
//
//
import Foundation
public enum SendType: String {
case OpenApp = "OpenApp"
case CloseApp = "CloseApp"
case ViewOpen = "ViewOpen"
case ViewClose = "ViewClose"
case ButtonClick = "ButtonClick"
case Generic = "Generic"
}
public class TBAnalytics {
class private var dateFormatter : DateFormatter {
let dateFormatter = DateFormatter()
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss"
return dateFormatter
}
class private var nowDate: String {
return self.dateFormatter.string(from: NSDate() as Date)
}
//MARK: - Internal methods
class private func getTags() -> [String:AnyObject] {
var tags = [String:AnyObject]()
if tags["Build version"] == nil {
if let buildVersion: AnyObject = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as AnyObject?
{
tags["Build version"] = buildVersion as AnyObject?
tags["Build name"] = RCFileManager.readPlistString(value: "CFBundleDisplayName") as AnyObject?
}
}
#if os(iOS) || os(tvOS)
if (tags["OS version"] == nil) {
tags["OS version"] = UIDevice.current.systemVersion as AnyObject?
}
if (tags["Device model"] == nil) {
tags["Device model"] = UIDevice.current.model as AnyObject?
}
#endif
return tags
}
struct TBAnalyitcs: TBJSONSerializable {
var timeStamp: String = ""
var method: String = ""
var className: String = ""
var fileName: String = ""
var configVersion: String = ""
var type: String = ""
var tags = [String:AnyObject]()
init() {}
init(jsonObject: TBJSON) {}
}
/**
SendOpenApp
- parameters:
- app: Self if running from AppDelegate class
*/
public class func sendOpenApp(_ app: UIResponder , method: String? = #function , file: String? = #file) {
self.sendData(String(describing: type(of: app)), file: file ?? "", method: method ?? "", type: .OpenApp )
}
/**
SendOpenApp
- parameters:
- app: Self if running from UIVIew class
*/
public class func sendOpenApp(_ view: UIView , method: String? = #function , file: String? = #file){
self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .OpenApp )
}
/**
SendCloseApp
- parameters:
- app: Self if running from AppDelegate class
*/
public class func sendCloseApp(_ app: UIResponder , method: String? = #function , file: String? = #file) {
self.sendData(String(describing: type(of: app)), file: file ?? "", method: method ?? "", type: .CloseApp )
}
/**
SendCloseApp
- parameters:
- app: Self if running from UIView class
*/
public class func sendCloseApp(_ view: UIView , method: String? = #function , file: String? = #file){
self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .CloseApp )
}
/**
SendButtonClick
- parameters:
- view: Self if running from UIView class
*/
public class func sendButtonClick(_ view: UIView , method: String? = #function , file: String? = #file){
self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .ButtonClick )
}
/**
SendButtonClick
- parameters:
- view: Self if running from UIViewController class
*/
public class func sendButtonClick(_ view: UIViewController , method: String? = #function , file: String? = #file){
self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .ButtonClick)
}
/**
SendViewOpen
- parameters:
- view: Self if running from UIView class
*/
public class func sendViewOpen(_ view: UIView , method: String? = #function , file: String? = #file){
self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .ViewOpen )
}
/**
SendViewOpen
- parameters:
- view: Self if running from UIViewController class
*/
public class func sendViewOpen(_ view: UIViewController , method: String? = #function , file: String? = #file){
self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .ViewOpen)
}
/**
SendViewClose
- parameters:
- view: Self if running from UIView class
*/
public class func sendViewClose(_ view: UIView , method: String? = #function , file: String? = #file){
self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .ViewClose )
}
/**
SendViewClose
- parameters:
- view: Self if running from UIViewController class
*/
public class func sendViewClose(_ view: UIViewController , method: String? = #function , file: String? = #file){
self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: .ViewClose)
}
/**
Send
- parameters:
- view: Self if running from UIResponder class
- type: of tpye SendType
*/
public class func send(_ app: UIResponder, type: SendType , method: String? = #function , file: String? = #file) {
self.sendData(String(describing: type(of: app)), file: file ?? "", method: method ?? "", type: type )
}
/**
Send
- parameters:
- view: Self if running from UIView class
- type: of tpye SendType
*/
class func send(_ view: UIView ,type: SendType, method: String? = #function , file: String? = #file){
self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: type )
}
/**
Send
- parameters:
- view: Self if running from UIViewController class
- type: of tpye SendType
*/
class func send(_ view: UIViewController ,type: SendType , method: String? = #function , file: String? = #file){
self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "", type: type )
}
/**
Send
- parameters:
- view: Self if running from UIResponder class
*/
public class func send(_ app: UIResponder , method: String? = #function , file: String? = #file) {
self.sendData(String(describing: type(of: app)), file: file ?? "", method: method ?? "" )
}
/**
Send
- parameters:
- view: Self if running from UIView class
*/
public class func send(_ view: UIView , method: String? = #function , file: String? = #file){
self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "" )
}
/**
Send
- parameters:
- view: Self if running from UIViewController class
*/
public class func send(_ view: UIViewController , method: String? = #function , file: String? = #file){
self.sendData(String(describing: type(of: view)), file: file ?? "", method: method ?? "" )
}
private class func sendData(_ className: String, file:String, method:String, type: SendType = .Generic ) {
let doAnalytics = UserDefaults.standard.value(forKey: "doAnalytics") as? String ?? "0"
if doAnalytics == "1" {
let version = UserDefaults.standard.value(forKey: "version") as? String
var newAnalytics = TBAnalyitcs()
newAnalytics.className = className
newAnalytics.fileName = file
newAnalytics.method = method
newAnalytics.timeStamp = self.nowDate
newAnalytics.configVersion = version ?? "0.0"
newAnalytics.tags = self.getTags()
newAnalytics.type = type.rawValue
self.sendUserAnalytics(newAnalytics)
}
}
class private func sendUserAnalytics(_ tbAnalyitcs: TBAnalyitcs) {
tbAnalyitcs.sendInBackground("") { (completed, data) in
DispatchQueue.main.async {
if (completed) {
print("sent")
} else {
print("error")
}
}
}
}
}
|
mit
|
90eab402b7faf5eb38c8a7bd1b394a82
| 32.155894 | 118 | 0.569151 | 4.362181 | false | false | false | false |
digipost/ios
|
Digipost/AppointmentView.swift
|
1
|
11469
|
//
// Copyright (C) Posten Norge AS
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import UIKit
import EventKit
@objc class AppointmentView: MetadataView, UIPickerViewDataSource, UIPickerViewDelegate{
@IBOutlet weak var title: UILabel!
@IBOutlet weak var subTitle: UILabel!
@IBOutlet weak var startTimeTitle: UILabel!
@IBOutlet weak var startTime: UILabel!
@IBOutlet weak var arrivalTimeTitle: UILabel!
@IBOutlet weak var arrivalTime: UILabel!
@IBOutlet weak var placeTitle: UILabel!
@IBOutlet weak var place: UILabel!
@IBOutlet weak var addressButton: UIButton!
@IBOutlet weak var infoTitle1: UILabel!
@IBOutlet weak var infoText1: UILabel!
@IBOutlet weak var infoTitle2: UILabel!
@IBOutlet weak var infoText2: UILabel!
@IBOutlet weak var containerViewHeight: NSLayoutConstraint!
@IBOutlet weak var calendarButton: UIButton!
@IBOutlet weak var infoImage: UIImageView!
@IBOutlet weak var buttomDivider: UIView!
@IBOutlet weak var openMapsButton: UIButton!
var appointment: POSAppointment = POSAppointment()
let eventStore = EKEventStore()
var calendars = [EKCalendar]()
static var pickedCalenderIdentifier: String = ""
let permissionsErrorMessage = "For å legge til hendelser i kalenderen din, må du gi Digipost tilgang til Kalendere. Dette kan du endre under Personvern i Innstillinger."
@objc func instanceWithData(appointment: POSAppointment) -> UIView{
let view = UINib(nibName: "AppointmentView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! AppointmentView
view.translatesAutoresizingMaskIntoConstraints = false
view.appointment = appointment
view.title.attributedText = attributedString(text: appointment.title, lineSpacing: customTitleLineSpacing, minimumLineHeight: minimumTitleLineHeight)
if appointment.subTitle.characters.count > 1 {
view.subTitle.attributedText = attributedString(text: appointment.subTitle, lineSpacing: customTitleLineSpacing, minimumLineHeight: minimumTitleLineHeight)
}
view.startTimeTitle.text = NSLocalizedString("metadata start time title", comment:"Time:")
let timeAndDateString = "kl \(appointment.startTime.timeOnly())"+"\n"+appointment.startTime.dateOnly()
view.startTime.attributedText = attributedString(text: timeAndDateString, lineSpacing: customTextLineSpacing, minimumLineHeight: minimumTextLineHeight)
view.arrivalTimeTitle.text = NSLocalizedString("metadata arrival time title", comment:"Oppmøte:")
if appointment.arrivalTime.characters.count > 0 {
view.arrivalTime.attributedText = attributedString(text: appointment.arrivalTime, lineSpacing: customTextLineSpacing, minimumLineHeight: minimumTextLineHeight)
}else{
view.arrivalTime.text = "kl \(appointment.arrivalTimeDate.timeOnly())"
}
view.openMapsButton.setTitle(NSLocalizedString("metadata show maps", comment:"Åpne i Kart"), for: UIControlState.normal)
view.placeTitle.text = NSLocalizedString("metadata location title", comment:"Sted:")
let placeAndAddress = appointment.place + "\n" + appointment.address
view.place.attributedText = attributedString(text: placeAndAddress, lineSpacing: customTextLineSpacing, minimumLineHeight: minimumTextLineHeight)
let calendarButtonTitle = NSLocalizedString("metadata add to calendar", comment:"Legg til i kalender")
view.calendarButton.setTitle(calendarButtonTitle, for: UIControlState.normal)
var infoTextHeight = CGFloat(0)
if appointment.infoText1.length > 1 {
view.infoTitle1.text = appointment.infoTitle1
view.infoText1.attributedText = attributedString(text: appointment.infoText1, lineSpacing: customTextLineSpacing, minimumLineHeight: minimumTextLineHeight)
infoTextHeight += positiveHeightAdjustment(text: appointment.infoTitle1, width: view.infoTitle1.frame.width, lineSpacing: customTextLineSpacing, minimumLineHeight: minimumTextLineHeight)
infoTextHeight += positiveHeightAdjustment(text: appointment.infoText1, width: view.infoText1.frame.width, lineSpacing: customTextLineSpacing, minimumLineHeight: minimumTextLineHeight)
infoTextHeight += 50 //spaceBetweenDividerAndfirstInfoTitle
view.infoImage.isHidden = false
view.buttomDivider.isHidden = false
}else{
view.infoImage.isHidden = true
view.buttomDivider.isHidden = true
}
if appointment.infoText2.length > 1 {
view.infoTitle2.text = appointment.infoTitle2
view.infoText2.attributedText = attributedString(text: appointment.infoText2, lineSpacing: customTextLineSpacing, minimumLineHeight: minimumTextLineHeight)
infoTextHeight += positiveHeightAdjustment(text: appointment.infoTitle2, width: view.infoTitle2.frame.width, lineSpacing: customTextLineSpacing, minimumLineHeight: minimumTextLineHeight)
infoTextHeight += positiveHeightAdjustment(text: appointment.infoText2, width: view.infoText2.frame.width, lineSpacing: customTextLineSpacing, minimumLineHeight: minimumTextLineHeight)
infoTextHeight += 60 //spaceBetweenInfoText1AndInfoText2
}
infoTextHeight += positiveHeightAdjustment(text: appointment.title, width: view.title.frame.width, lineSpacing: customTitleLineSpacing, minimumLineHeight: minimumTitleLineHeight)
infoTextHeight += positiveHeightAdjustment(text: appointment.subTitle, width: view.subTitle.frame.width, lineSpacing: customTitleLineSpacing, minimumLineHeight: minimumTitleLineHeight)
view.containerViewHeight.constant += infoTextHeight
calendarPermissionsGranted()
calendars = eventStore.calendars(for: EKEntityType.event).filter { $0.allowsContentModifications}
view.layoutIfNeeded()
return view
}
func addedToCalender() {
calendarButton.setImage(UIImage(named: "Kalender-lagt-til")!, for: UIControlState.normal)
calendarButton.setTitle(NSLocalizedString("metadata addedto calendar", comment:"Lagt til i kalender"), for: UIControlState.normal)
}
@IBAction func addToCalendar(_ sender: Any) {
let eventTitle = title.text!
let message = calendarPermissionsGranted() ? getEventMessage() : permissionsErrorMessage
let modalAction = NSLocalizedString("metadata add to calendar", comment:"Legg til i kalender")
let alertController = UIAlertController(title: modalAction, message: message, preferredStyle: .alert)
if calendarPermissionsGranted() {
self.calendars = eventStore.calendars(for: EKEntityType.event).filter { $0.allowsContentModifications}
if self.calendars.count > 1 {
let frame = CGRect(x: 0, y: 120, width: 270, height: 80)
let calendarPicker = UIPickerView(frame: frame)
alertController.message?.append("\n\n\n\n\n")
calendarPicker.delegate = self
calendarPicker.showsSelectionIndicator = true
alertController.view.addSubview(calendarPicker)
}
alertController.addAction(UIAlertAction(title: modalAction, style: .default) { (action) in
if let calendar = AppointmentView.pickedCalenderIdentifier.characters.count > 1 && self.calendars.count > 1 ? self.getSelectedCalendar() : self.eventStore.defaultCalendarForNewEvents {
self.createEventInCalendar(calendar: calendar, title: eventTitle)
}
})
}
let modalCancel = NSLocalizedString("metadata calendar cancel", comment:"Avbryt")
alertController.addAction(UIAlertAction(title: modalCancel, style: .cancel) { (action) in
alertController.dismiss(animated: true, completion: {})
})
UIApplication.shared.keyWindow?.rootViewController?.present(alertController, animated: true, completion: nil)
}
func getSelectedCalendar() -> EKCalendar {
return calendars.filter { $0.calendarIdentifier == AppointmentView.pickedCalenderIdentifier}.first!
}
func getEventMessage() -> String {
let message = "\n" + NSLocalizedString("metadata calendar disclaimer", comment:"Obs! Innkallingen kan inneholde sensitiv informasjon som kan bli synlig for de som eventuelt har tilgang til din kalender.")
return message
}
@discardableResult func calendarPermissionsGranted() -> Bool {
switch EKEventStore.authorizationStatus(for: .event) {
case .authorized: return true
default: return AppointmentView.requestPermissions()
}
}
@discardableResult @objc static func requestPermissions() -> Bool{
var permissionsGranted = false
EKEventStore().requestAccess(to: .event, completion:
{(granted: Bool, error: Error?) -> Void in
permissionsGranted = granted
})
return permissionsGranted;
}
@IBAction func openAddressInMaps(_ sender: UIButton) {
let addr = appointment.address.replacingOccurrences(of: " ", with: ",").replacingOccurrences(of: "\n", with: ",")
let mapsUrl = URL(string: "http://maps.apple.com/?q=\(addr))")
UIApplication.shared.openURL(mapsUrl!)
}
func createEventInCalendar(calendar: EKCalendar, title: String){
let event = EKEvent(eventStore: self.eventStore)
event.calendar = calendar
event.title = title
event.startDate = appointment.startTime
event.endDate = appointment.endTime
event.location = appointment.address
event.notes = "\(arrivalTime.text!) \n\(appointment.subTitle) \n\n\(infoTitle1.text!) \n\(infoText1.text!) \n\n\(infoTitle2.text!) \n\(infoText2.text!) "
do {
try self.eventStore.save(event, span: .thisEvent, commit: true)
self.addedToCalender()
} catch {}
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return self.calendars.count
}
internal func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return self.calendars[row].title
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
AppointmentView.pickedCalenderIdentifier = self.calendars[row].calendarIdentifier
}
private func instanceFromNib() -> UIView {
return UINib(nibName: "AppointmentView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView
}
}
|
apache-2.0
|
216961a7384593a4645fa8f3c9bfbffb
| 52.325581 | 212 | 0.702137 | 4.916381 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/PhoneNumberConfirmCodeController.swift
|
1
|
5827
|
//
// PhoneNumberConfirmCodeController.swift
// Telegram
//
// Created by Mike Renoir on 17.03.2022.
// Copyright © 2022 Telegram. All rights reserved.
//
import Cocoa
import TGUIKit
import TelegramCore
import SwiftSignalKit
final class PhoneNumberCodeConfirmView : View {
private let desc = TextView()
fileprivate let input: Auth_CodeEntryContol = Auth_CodeEntryContol(frame: .zero)
fileprivate let next = TitleButton()
required init(frame frameRect: NSRect) {
super.init(frame: frameRect)
addSubview(input)
addSubview(desc)
addSubview(next)
next.autohighlight = false
next.scaleOnClick = true
updateLocalizationAndTheme(theme: theme)
}
func update(with count: Int, locked: Bool, takeNext: @escaping(String)->Void, takeError: @escaping()->Void) {
let size = self.input.update(count: count)
self.input.setFrameSize(size)
self.input.takeNext = takeNext
self.input.takeError = takeError
self.input.set(locked: locked, animated: true)
needsLayout = true
}
override func updateLocalizationAndTheme(theme: PresentationTheme) {
super.updateLocalizationAndTheme(theme: theme)
backgroundColor = theme.colors.background
next.set(color: theme.colors.underSelectedColor, for: .Normal)
next.set(background: theme.colors.accent, for: .Normal)
next.set(font: .medium(.text), for: .Normal)
next.set(text: strings().phoneNumberChangePhoneNumber, for: .Normal)
next.sizeToFit()
next.layer?.cornerRadius = 10
let infoLayout = TextViewLayout(.initialize(string: strings().phoneNumberCodeInfo, color: theme.colors.grayText, font: .normal(12)), alignment: .center)
self.desc.update(infoLayout)
needsLayout = true
}
override func layout() {
super.layout()
self.input.centerX(y: 30)
desc.resize(frame.width - 60 - 20)
desc.centerX(y: self.input.frame.maxY + 5)
next.setFrameSize(NSMakeSize(frame.width - 60, 40))
next.centerX(y: frame.height - next.frame.height - 50 - 30)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
private extension SentAuthorizationCodeType {
var lenght: Int32 {
switch self {
case let .call(length):
return length
case let .email(_, length, _, _, _):
return length
case let .otherSession(length):
return length
case let .sms(length):
return length
default:
return 5
}
}
}
final class PhoneNumberCodeConfirmController : GenericViewController<PhoneNumberCodeConfirmView> {
private let context: AccountContext
private let disposable = MetaDisposable()
private let data: ChangeAccountPhoneNumberData
private let phoneNumber: String
private var locked: Bool = false
init(context: AccountContext, data: ChangeAccountPhoneNumberData, phoneNumber: String) {
self.context = context
self.data = data
self.phoneNumber = phoneNumber
super.init(frame: .zero)
}
deinit {
disposable.dispose()
}
private func checkCode() {
if locked {
return
}
self.locked = true
let context = self.context
let signal = context.engine.accountData.requestChangeAccountPhoneNumber(phoneNumber: phoneNumber, phoneCodeHash: data.hash, phoneCode: self.genericView.input.value)
_ = showModalProgress(signal: signal, for: context.window).start(error: { [weak self] error in
var alertText: String = ""
switch error {
case .generic:
alertText = strings().changeNumberConfirmCodeErrorGeneric
case .invalidCode:
self?.genericView.input.shake()
self?.genericView.input.moveToStart()
self?.locked = false
return
case .codeExpired:
alertText = strings().changeNumberConfirmCodeErrorCodeExpired
case .limitExceeded:
alertText = strings().changeNumberConfirmCodeErrorLimitExceeded
}
alert(for: context.window, info: alertText)
self?.genericView.input.moveToStart()
self?.locked = false
}, completed: { [weak self] in
guard let phoneNumber = self?.phoneNumber else {
return
}
self?.locked = false
closeAllModals(window: context.window)
showModalText(for: context.window, text: strings().changeNumberConfirmCodeSuccess(phoneNumber))
})
}
override func viewDidLoad() {
super.viewDidLoad()
let sharedContext = self.context.sharedContext
let engine = context.engine
self.genericView.update(with: Int(self.data.type.lenght), locked: false, takeNext: { [weak self] _ in
self?.checkCode()
}, takeError: {
})
self.readyOnce()
}
override func returnKeyAction() -> KeyHandlerResult {
self.checkCode()
return .invoked
}
override var defaultBarTitle: String {
return strings().telegramPhoneNumberConfirmController
}
override var enableBack: Bool {
return true
}
override func firstResponder() -> NSResponder? {
return genericView.input.firstResponder()
}
override func becomeFirstResponder() -> Bool? {
return true
}
}
|
gpl-2.0
|
98a9fd9638f90766517858240dd20ce3
| 29.186528 | 172 | 0.60436 | 4.90404 | false | false | false | false |
data-licious/ceddl4swift
|
ceddl4swift/ceddl4swift/Security.swift
|
1
|
1026
|
//
// Security.swift
// ceddl4swift
//
// Created by Sachin Vas on 20/10/16.
// Copyright © 2016 Sachin Vas. All rights reserved.
//
import Foundation
open class Security: NSObject {
private var items: Dictionary<String, AnyObject> = [:]
open func getMap() -> Dictionary<String, AnyObject> {
return items
}
/// Construct a Security object. This is normally handled by calling .security() and .defaultSecurity().
public override init() {
super.init()
}
/// Adds a field to the Security object.
/// This is called from .security() and .defaultSecurity().
///
/// - Parameter field: Fieldname
/// - Parameter accessCategories: accessCategories for field.
open func addSecurity(_ field: String, accessCategories: Array<String>) {
if accessCategories.count == 1 {
items[field] = accessCategories[0] as AnyObject
} else if accessCategories.count > 1 {
items[field] = accessCategories as AnyObject
}
}
}
|
bsd-3-clause
|
133fe5979f4a5565bdc30a66d1be475b
| 25.973684 | 108 | 0.638049 | 4.270833 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.