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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pawan007/SmartZip
|
SmartZip/Controllers/Notifications/NotificationViewController.swift
|
1
|
2896
|
//
// NotificationViewController.swift
// SmartZip
//
// Created by Pawan Kumar on 02/06/16.
// Copyright © 2016 Modi. All rights reserved.
//
import Foundation
import UIKit
import StoreKit
class NotificationViewController: BaseViewController {
@IBOutlet weak var tableView: UITableView!
let CellIdentifierUnRead: String = "CellUnRead"
let CellIdentifierRead: String = "CellRead"
var location = NSMutableArray()
var favorite : Int = -1
override internal func viewDidLoad() {
super.viewDidLoad()
self.automaticallyAdjustsScrollViewInsets = false
self.tableView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0);
self.tableView.rowHeight = UITableViewAutomaticDimension;
self.tableView.estimatedRowHeight = 50.0;
self.tableView.tableFooterView = UIView()
self.tableView.allowsMultipleSelection = false
location.addObject("Thank you for purchasing the app.")
location.addObject("Photography event near your location.")
location.addObject("Cooking event near your location.")
location.addObject("Swimming event near your location.")
self.tableView.reloadData()
}
override internal func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.hidden = false
self.automaticallyAdjustsScrollViewInsets = false
self.tableView.contentInset = UIEdgeInsetsMake(0.0, 0.0, 0.0, 0.0);
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return location.count
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.reloadData()
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell! = nil
if indexPath.row > 1 {
cell = self.tableView.dequeueReusableCellWithIdentifier(CellIdentifierRead, forIndexPath: indexPath)
}
else {
cell = self.tableView.dequeueReusableCellWithIdentifier(CellIdentifierUnRead, forIndexPath: indexPath)
}
cell.selectionStyle = .Gray
let name: UILabel! = cell.viewWithTag(1000) as! UILabel
name.text = location[indexPath.row] as? String
return cell
}
// MARK:- IBActions
@IBAction override func menuButtonAction(sender: AnyObject) {
if let container = SideMenuManager.sharedManager().container {
container.toggleDrawerSide(.Left, animated: true) { (val) -> Void in
}
}
}
}
|
mit
|
c2a84cd8cb04f4bdbe2c20dffe2f4c1d
| 33.070588 | 114 | 0.667703 | 5.341328 | false | false | false | false |
snailjj/iOSDemos
|
SnailSwiftDemos/Pods/EZSwiftExtensions/Sources/DateExtensions.swift
|
2
|
8389
|
//
// DateExtensions.swift
// EZSwiftExtensions
//
// Created by Goktug Yilmaz on 15/07/15.
// Copyright (c) 2015 Goktug Yilmaz. All rights reserved.
//
import Foundation
extension Date {
public static let minutesInAWeek = 24 * 60 * 7
/// EZSE: Initializes Date from string and format
public init?(fromString string: String, format: String) {
let formatter = DateFormatter()
formatter.dateFormat = format
if let date = formatter.date(from: string) {
self = date
} else {
return nil
}
}
/// EZSE: Initializes Date from string returned from an http response, according to several RFCs / ISO
public init?(httpDateString: String) {
if let rfc1123 = Date(fromString: httpDateString, format: "EEE',' dd' 'MMM' 'yyyy HH':'mm':'ss zzz") {
self = rfc1123
return
}
if let rfc850 = Date(fromString: httpDateString, format: "EEEE',' dd'-'MMM'-'yy HH':'mm':'ss z") {
self = rfc850
return
}
if let asctime = Date(fromString: httpDateString, format: "EEE MMM d HH':'mm':'ss yyyy") {
self = asctime
return
}
if let iso8601DateOnly = Date(fromString: httpDateString, format: "yyyy-MM-dd") {
self = iso8601DateOnly
return
}
if let iso8601DateHrMinOnly = Date(fromString: httpDateString, format: "yyyy-MM-dd'T'HH:mmxxxxx") {
self = iso8601DateHrMinOnly
return
}
if let iso8601DateHrMinSecOnly = Date(fromString: httpDateString, format: "yyyy-MM-dd'T'HH:mm:ssxxxxx") {
self = iso8601DateHrMinSecOnly
return
}
if let iso8601DateHrMinSecMs = Date(fromString: httpDateString, format: "yyyy-MM-dd'T'HH:mm:ss.SSSxxxxx") {
self = iso8601DateHrMinSecMs
return
}
//self.init()
return nil
}
/// EZSE: Converts Date to String
public func toString(dateStyle: DateFormatter.Style = .medium, timeStyle: DateFormatter.Style = .medium) -> String {
let formatter = DateFormatter()
formatter.dateStyle = dateStyle
formatter.timeStyle = timeStyle
return formatter.string(from: self)
}
/// EZSE: Converts Date to String, with format
public func toString(format: String) -> String {
let formatter = DateFormatter()
formatter.dateFormat = format
return formatter.string(from: self)
}
/// EZSE: Calculates how many days passed from now to date
public func daysInBetweenDate(_ date: Date) -> Double {
var diff = self.timeIntervalSince1970 - date.timeIntervalSince1970
diff = fabs(diff/86400)
return diff
}
/// EZSE: Calculates how many hours passed from now to date
public func hoursInBetweenDate(_ date: Date) -> Double {
var diff = self.timeIntervalSince1970 - date.timeIntervalSince1970
diff = fabs(diff/3600)
return diff
}
/// EZSE: Calculates how many minutes passed from now to date
public func minutesInBetweenDate(_ date: Date) -> Double {
var diff = self.timeIntervalSince1970 - date.timeIntervalSince1970
diff = fabs(diff/60)
return diff
}
/// EZSE: Calculates how many seconds passed from now to date
public func secondsInBetweenDate(_ date: Date) -> Double {
var diff = self.timeIntervalSince1970 - date.timeIntervalSince1970
diff = fabs(diff)
return diff
}
/// EZSE: Easy creation of time passed String. Can be Years, Months, days, hours, minutes or seconds
public func timePassed() -> String {
let date = Date()
let calendar = Calendar.current
let components = (calendar as NSCalendar).components([.year, .month, .day, .hour, .minute, .second], from: self, to: date, options: [])
var str: String
if components.year! >= 1 {
components.year == 1 ? (str = "year") : (str = "years")
return "\(components.year!) \(str) ago"
} else if components.month! >= 1 {
components.month == 1 ? (str = "month") : (str = "months")
return "\(components.month!) \(str) ago"
} else if components.day! >= 1 {
components.day == 1 ? (str = "day") : (str = "days")
return "\(components.day!) \(str) ago"
} else if components.hour! >= 1 {
components.hour == 1 ? (str = "hour") : (str = "hours")
return "\(components.hour!) \(str) ago"
} else if components.minute! >= 1 {
components.minute == 1 ? (str = "minute") : (str = "minutes")
return "\(components.minute!) \(str) ago"
} else if components.second! >= 1 {
components.second == 1 ? (str = "second") : (str = "seconds")
return "\(components.second!) \(str) ago"
} else {
return "Just now"
}
}
/// EZSE: Check if date is in future.
public var isFuture: Bool {
return self > Date()
}
/// EZSE: Check if date is in past.
public var isPast: Bool {
return self < Date()
}
// EZSE: Check date if it is today
public var isToday: Bool {
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd"
return format.string(from: self) == format.string(from: Date())
}
/// EZSE: Check date if it is yesterday
public var isYesterday: Bool {
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd"
let yesterDay = Calendar.current.date(byAdding: .day, value: -1, to: Date())
return format.string(from: self) == format.string(from: yesterDay!)
}
/// EZSE: Check date if it is tomorrow
public var isTomorrow: Bool {
let format = DateFormatter()
format.dateFormat = "yyyy-MM-dd"
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: Date())
return format.string(from: self) == format.string(from: tomorrow!)
}
/// EZSE: Check date if it is within this month.
public var isThisMonth: Bool {
let today = Date()
return self.month == today.month && self.year == today.year
}
/// EZSE: Check date if it is within this week.
public var isThisWeek: Bool {
return self.minutesInBetweenDate(Date()) <= Double(Date.minutesInAWeek)
}
/// EZSE: Get the era from the date
public var era: Int {
return Calendar.current.component(Calendar.Component.era, from: self)
}
/// EZSE : Get the year from the date
public var year: Int {
return Calendar.current.component(Calendar.Component.year, from: self)
}
/// EZSE : Get the month from the date
public var month: Int {
return Calendar.current.component(Calendar.Component.month, from: self)
}
/// EZSE : Get the weekday from the date
public var weekday: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "EEEE"
return dateFormatter.string(from: self)
}
// EZSE : Get the month from the date
public var monthAsString: String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM"
return dateFormatter.string(from: self)
}
// EZSE : Get the day from the date
public var day: Int {
return Calendar.current.component(.day, from: self)
}
/// EZSE: Get the hours from date
public var hour: Int {
return Calendar.current.component(.hour, from: self)
}
/// EZSE: Get the minute from date
public var minute: Int {
return Calendar.current.component(.minute, from: self)
}
/// EZSE: Get the second from the date
public var second: Int {
return Calendar.current.component(.second, from: self)
}
/// EZSE : Gets the nano second from the date
public var nanosecond: Int {
return Calendar.current.component(.nanosecond, from: self)
}
#if os(iOS) || os(tvOS)
/// EZSE : Gets the international standard(ISO8601) representation of date
@available(iOS 10.0, *)
@available(tvOS 10.0, *)
public var iso8601: String {
let formatter = ISO8601DateFormatter()
return formatter.string(from: self)
}
#endif
}
|
apache-2.0
|
09e131950ccbf67ab983d584bd453589
| 33.665289 | 143 | 0.599476 | 4.275739 | false | false | false | false |
xuech/OMS-WH
|
OMS-WH/Classes/TakeOrder/器械信息/Controller/OnwayInventoryViewController.swift
|
1
|
3791
|
//
// OnwayInventoryViewController.swift
// OMS-WH
//
// Created by xuech on 2017/11/30.
// Copyright © 2017年 medlog. All rights reserved.
//
import UIKit
import SVProgressHUD
class OnwayInventoryViewController: UITableViewController {
var model: MedMaterialList?
var orderDetail : DealOrderInfoModel?
fileprivate var dataSource = [StockInWHModel]()
fileprivate var onWayView : OnWayInverntoryView?
fileprivate var paramters : [String:Any] = [:]
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.white
title = "在途库存"
setup()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
loadDataInTransitInventoryList()
}
private func setup(){
if let medMIInternalNo = model?.medMIInternalNo,let warehouse = model?.estMedMIWarehouse,let dlcode = orderDetail?.sOCreateByOrgCode{
paramters = ["medMIInternalNo":medMIInternalNo,"medMIWarehouse":warehouse,"sOCreateByOrgCode":dlcode,"pageNum":"1","pageSize":"20"]
}
tableView.rowHeight = 140
tableView.register(OnWayTableViewCell.self, forCellReuseIdentifier: "OnWayTableViewCell")
tableView.separatorStyle = .none
onWayView = OnWayInverntoryView(frame: CGRect(x: 0, y: 0, width: self.view.width, height: 250))
onWayView!.model = model
onWayView!.orderDetail = orderDetail
onWayView!.requestInventorySumParamters = paramters
tableView.tableHeaderView = onWayView!
}
private func loadDataInTransitInventoryList(){
moyaNetWork.request(.commonRequst(paramters: paramters , api: "oms-api-v3/businessData/medicalDevice/queryInTransitInventory")) { (result) in
switch result {
case let .success(moyaResponse):
do {
let moyaJSON = try moyaResponse.filterSuccessfulStatusCodes()
let data = try moyaJSON.mapJSON() as! [String:AnyObject]
guard data["code"] as! Int == 0 else
{
SVProgressHUD.showError(withStatus: data["msg"] as? String ?? "")
return
}
if let resultValue = data["info"] as? [String : AnyObject]{
if let res = resultValue["list"] as? [[String : AnyObject]] {
var childs = [StockInWHModel]()
for data in res {
childs.append(StockInWHModel(dict:data))
}
self.dataSource = childs
self.tableView.reloadData()
}
}
}
catch {}
case .failure(_):
SVProgressHUD.showError("网络请求错误")
break
}
}
}
}
extension OnwayInventoryViewController{
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return dataSource.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "OnWayTableViewCell") as! OnWayTableViewCell
let model = dataSource[indexPath.row]
cell.hpLB.text = "医院:\(model.hPName)"
cell.lotailLB.text = "批次/序列号:\(model.lotSerial)"
cell.outBoundLB.text = "出库单号:\(model.wONo)"
cell.countLB.text = "数量:\(model.inventory)"
cell.outBoundStatusLB.text = "出库单状态:\(model.statusByOutBoundName)"
return cell
}
}
|
mit
|
b5313216a9650c98516a5a77abbb05a7
| 37.474227 | 149 | 0.593783 | 4.724051 | false | false | false | false |
milseman/swift
|
test/SILGen/access_marker_gen.swift
|
10
|
5563
|
// RUN: %target-swift-frontend -parse-as-library -Xllvm -sil-full-demangle -enforce-exclusivity=checked -emit-silgen %s | %FileCheck %s
func modify<T>(_ x: inout T) {}
public struct S {
var i: Int
var o: AnyObject?
}
// CHECK-LABEL: sil hidden [noinline] @_T017access_marker_gen5initSAA1SVyXlSgF : $@convention(thin) (@owned Optional<AnyObject>) -> @owned S {
// CHECK: bb0(%0 : $Optional<AnyObject>):
// CHECK: [[BOX:%.*]] = alloc_box ${ var S }, var, name "s"
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [var] [[BOX]] : ${ var S }
// CHECK: [[ADDR:%.*]] = project_box [[MARKED_BOX]] : ${ var S }, 0
// CHECK: cond_br %{{.*}}, bb1, bb2
// CHECK: bb1:
// CHECK: [[ACCESS1:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S
// CHECK: assign %{{.*}} to [[ACCESS1]] : $*S
// CHECK: end_access [[ACCESS1]] : $*S
// CHECK: bb2:
// CHECK: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[ADDR]] : $*S
// CHECK: assign %{{.*}} to [[ACCESS2]] : $*S
// CHECK: end_access [[ACCESS2]] : $*S
// CHECK: bb3:
// CHECK: [[ACCESS3:%.*]] = begin_access [read] [unknown] [[ADDR]] : $*S
// CHECK: [[RET:%.*]] = load [copy] [[ACCESS3]] : $*S
// CHECK: end_access [[ACCESS3]] : $*S
// CHECK: return [[RET]] : $S
// CHECK-LABEL: } // end sil function '_T017access_marker_gen5initSAA1SVyXlSgF'
@inline(never)
func initS(_ o: AnyObject?) -> S {
var s: S
if o == nil {
s = S(i: 0, o: nil)
} else {
s = S(i: 1, o: o)
}
return s
}
@inline(never)
func takeS(_ s: S) {}
// CHECK-LABEL: sil @_T017access_marker_gen14modifyAndReadSyyF : $@convention(thin) () -> () {
// CHECK: bb0:
// CHECK: %[[BOX:.*]] = alloc_box ${ var S }, var, name "s"
// CHECK: %[[ADDRS:.*]] = project_box %[[BOX]] : ${ var S }, 0
// CHECK: %[[ACCESS1:.*]] = begin_access [modify] [unknown] %[[ADDRS]] : $*S
// CHECK: %[[ADDRI:.*]] = struct_element_addr %15 : $*S, #S.i
// CHECK: assign %{{.*}} to %[[ADDRI]] : $*Int
// CHECK: end_access %[[ACCESS1]] : $*S
// CHECK: %[[ACCESS2:.*]] = begin_access [read] [unknown] %[[ADDRS]] : $*S
// CHECK: %{{.*}} = load [copy] %[[ACCESS2]] : $*S
// CHECK: end_access %[[ACCESS2]] : $*S
// CHECK-LABEL: } // end sil function '_T017access_marker_gen14modifyAndReadSyyF'
public func modifyAndReadS() {
var s = initS(nil)
s.i = 42
takeS(s)
}
var global = S(i: 0, o: nil)
func readGlobal() -> AnyObject? {
return global.o
}
// CHECK-LABEL: sil hidden @_T017access_marker_gen10readGlobalyXlSgyF
// CHECK: [[ADDRESSOR:%.*]] = function_ref @_T017access_marker_gen6globalAA1SVfau :
// CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]()
// CHECK-NEXT: [[T1:%.*]] = pointer_to_address [[T0]] : $Builtin.RawPointer to [strict] $*S
// CHECK-NEXT: [[T2:%.*]] = begin_access [read] [dynamic] [[T1]]
// CHECK-NEXT: [[T3:%.*]] = struct_element_addr [[T2]] : $*S, #S.o
// CHECK-NEXT: [[T4:%.*]] = load [copy] [[T3]]
// CHECK-NEXT: end_access [[T2]]
// CHECK-NEXT: return [[T4]]
public struct HasTwoStoredProperties {
var f: Int = 7
var g: Int = 9
// CHECK-LABEL: sil hidden @_T017access_marker_gen22HasTwoStoredPropertiesV027noOverlapOnAssignFromPropToM0yyF : $@convention(method) (@inout HasTwoStoredProperties) -> ()
// CHECK: [[ACCESS1:%.*]] = begin_access [read] [unknown] [[SELF_ADDR:%.*]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[G_ADDR:%.*]] = struct_element_addr [[ACCESS1]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.g
// CHECK-NEXT: [[G_VAL:%.*]] = load [trivial] [[G_ADDR]] : $*Int
// CHECK-NEXT: end_access [[ACCESS1]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[ACCESS2:%.*]] = begin_access [modify] [unknown] [[SELF_ADDR]] : $*HasTwoStoredProperties
// CHECK-NEXT: [[F_ADDR:%.*]] = struct_element_addr [[ACCESS2]] : $*HasTwoStoredProperties, #HasTwoStoredProperties.f
// CHECK-NEXT: assign [[G_VAL]] to [[F_ADDR]] : $*Int
// CHECK-NEXT: end_access [[ACCESS2]] : $*HasTwoStoredProperties
mutating func noOverlapOnAssignFromPropToProp() {
f = g
}
}
class C {
final var x: Int = 0
}
func testClassInstanceProperties(c: C) {
let y = c.x
c.x = y
}
// CHECK-LABEL: sil hidden @_T017access_marker_gen27testClassInstancePropertiesyAA1CC1c_tF :
// CHECK: [[C:%.*]] = begin_borrow %0 : $C
// CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [read] [dynamic] [[CX]] : $*Int
// CHECK-NEXT: [[Y:%.*]] = load [trivial] [[ACCESS]]
// CHECK-NEXT: end_access [[ACCESS]]
// CHECK: [[C:%.*]] = begin_borrow %0 : $C
// CHECK-NEXT: [[CX:%.*]] = ref_element_addr [[C]] : $C, #C.x
// CHECK-NEXT: [[ACCESS:%.*]] = begin_access [modify] [dynamic] [[CX]] : $*Int
// CHECK-NEXT: assign [[Y]] to [[ACCESS]]
// CHECK-NEXT: end_access [[ACCESS]]
class D {
var x: Int = 0
}
// materializeForSet callback
// CHECK-LABEL: sil private [transparent] @_T017access_marker_gen1DC1xSifmytfU_
// CHECK: end_unpaired_access [dynamic] %1 : $*Builtin.UnsafeValueBuffer
// materializeForSet
// CHECK-LABEL: sil hidden [transparent] @_T017access_marker_gen1DC1xSifm
// CHECK: [[T0:%.*]] = ref_element_addr %2 : $D, #D.x
// CHECK-NEXT: begin_unpaired_access [modify] [dynamic] [[T0]] : $*Int
func testDispatchedClassInstanceProperty(d: D) {
modify(&d.x)
}
// CHECK-LABEL: sil hidden @_T017access_marker_gen35testDispatchedClassInstancePropertyyAA1DC1d_tF
// CHECK: [[D:%.*]] = begin_borrow %0 : $D
// CHECK: [[METHOD:%.*]] = class_method [[D]] : $D, #D.x!materializeForSet.1
// CHECK: apply [[METHOD]]({{.*}}, [[D]])
// CHECK-NOT: begin_access
// CHECK: end_borrow [[D]] from %0 : $D
|
apache-2.0
|
6b5c59fe91744dde247741e3530fdd2b
| 39.605839 | 171 | 0.59698 | 3.043217 | false | false | false | false |
spookd/DownloadManager
|
DownloadManager/Source/DownloadManager.swift
|
1
|
12978
|
//
// DownloadManager.swift
// DownloadManager
//
// Created by Nicolai Persson on 05/05/15.
// Copyright (c) 2015 Sprinkle. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
public protocol DownloadManagerDelegate: class {
func downloadManager(downloadManager: DownloadManager, downloadDidFail url: NSURL, error: NSError)
func downloadManager(downloadManager: DownloadManager, downloadDidStart url: NSURL, resumed: Bool)
func downloadManager(downloadManager: DownloadManager, downloadDidFinish url: NSURL)
func downloadManager(downloadManager: DownloadManager, downloadDidProgress url: NSURL, totalSize: UInt64, downloadedSize: UInt64, percentage: Double, averageDownloadSpeedInBytes: UInt64, timeRemaining: NSTimeInterval)
}
func ==(left: DownloadManager.Download, right: DownloadManager.Download) -> Bool {
return left.url == right.url
}
public class DownloadManager: NSObject, NSURLConnectionDataDelegate {
internal let queue = dispatch_queue_create("io.persson.DownloadManager", DISPATCH_QUEUE_CONCURRENT)
internal var delegates: [DownloadManagerDelegate] = []
internal var downloads: [DownloadManager.Download] = []
class Download: Equatable {
let url: NSURL
let filePath: String
let stream: NSOutputStream
let connection: NSURLConnection
var totalSize: UInt64
var downloadedSize: UInt64 = 0
// Variables used for calculating average download speed
// The lower the interval (downloadSampleInterval) the higher the accuracy (fluctuations)
internal let sampleInterval = 0.25
internal let sampledSecondsNeeded = 5.0
internal lazy var sampledBytesTotal: Int = {
return Int(ceil(self.sampledSecondsNeeded / self.sampleInterval))
}()
internal var samples: [UInt64] = []
internal var sampleTimer: Timer?
internal var lastAverageCalculated = NSDate()
internal var bytesWritten = 0
internal let queue = dispatch_queue_create("dk.dr.radioapp.DownloadManager.SampleQueue", DISPATCH_QUEUE_CONCURRENT)
var averageDownloadSpeed: UInt64 = UInt64.max
init(url: NSURL, filePath: String, totalSize: UInt64, connection: NSURLConnection) {
dispatch_set_target_queue(self.queue, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0))
self.url = url
self.filePath = filePath
self.totalSize = totalSize
if let dict: NSDictionary = NSFileManager.defaultManager().attributesOfItemAtPath(self.filePath, error: nil) {
self.downloadedSize = dict.fileSize()
}
self.stream = NSOutputStream(toFileAtPath: self.filePath, append: self.downloadedSize > 0)!
self.connection = connection
self.stream.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
self.stream.open()
self.sampleTimer?.invalidate()
self.sampleTimer = Timer(interval: self.sampleInterval, repeats: true, pauseInBackground: true, block: { [weak self] () -> () in
if let strongSelf = self {
dispatch_sync(strongSelf.queue, { () -> Void in
strongSelf.samples.append(UInt64(strongSelf.bytesWritten))
let diff = strongSelf.samples.count - strongSelf.sampledBytesTotal
if diff > 0 {
for i in (0...diff - 1) {
strongSelf.samples.removeAtIndex(0)
}
}
strongSelf.bytesWritten = 0
let now = NSDate()
if now.timeIntervalSinceDate(strongSelf.lastAverageCalculated) >= 5 && strongSelf.samples.count >= strongSelf.sampledBytesTotal {
var totalBytes: UInt64 = 0
for sample in strongSelf.samples {
totalBytes += sample
}
strongSelf.averageDownloadSpeed = UInt64(round(Double(totalBytes) / strongSelf.sampledSecondsNeeded))
strongSelf.lastAverageCalculated = now
}
})
}
})
}
func write(data: NSData) {
let written = self.stream.write(UnsafePointer<UInt8>(data.bytes), maxLength: data.length)
if written > 0 {
dispatch_async(self.queue, { () -> Void in
self.bytesWritten += written
})
}
}
func close() {
self.sampleTimer?.invalidate()
self.sampleTimer = nil
self.stream.close()
}
}
}
// MARK: Static vars
extension DownloadManager {
public class var sharedInstance: DownloadManager {
struct Singleton {
static let instance = DownloadManager()
}
return Singleton.instance
}
}
// MARK: Internal methods
extension DownloadManager {
internal func downloadForConnection(connection: NSURLConnection) -> Download? {
var result: Download? = nil
sync {
for download in self.downloads {
if download.connection == connection {
result = download
break
}
}
}
return result
}
internal func sync(closure: () -> Void) {
dispatch_sync(self.queue, closure)
}
internal func async(closure: () -> Void) {
dispatch_async(self.queue, closure)
}
}
// MARK: Public methods
extension DownloadManager {
public func subscribe(delegate: DownloadManagerDelegate) {
async {
for (index, d) in enumerate(self.delegates) {
if delegate === d {
return
}
}
self.delegates.append(delegate)
}
}
public func unsubscribe(delegate: DownloadManagerDelegate) {
async {
for (index, d) in enumerate(self.delegates) {
if delegate === d {
self.delegates.removeAtIndex(index)
return
}
}
}
}
public func isDownloading(url: NSURL) -> Bool {
var result = false
sync {
for download in self.downloads {
if download.url == url {
result = true
break
}
}
}
return result
}
public func download(url: NSURL, filePath: String) -> Bool {
var request = NSMutableURLRequest(URL: url)
if let dict: NSDictionary = NSFileManager.defaultManager().attributesOfItemAtPath(filePath, error: nil) {
request.addValue("bytes=\(dict.fileSize())-", forHTTPHeaderField: "Range")
}
if let connection = NSURLConnection(request: request, delegate: self, startImmediately: false) {
sync {
self.downloads.append(Download(url: url, filePath: filePath, totalSize: 0, connection: connection))
}
connection.scheduleInRunLoop(NSRunLoop.mainRunLoop(), forMode: NSDefaultRunLoopMode)
connection.start()
return true
}
return false
}
public func stopDownloading(url: NSURL) {
sync {
for download in self.downloads {
if download.url == url {
download.connection.cancel()
download.close()
self.downloads.remove(download)
break
}
}
}
}
func applicationWillTerminate() {
sync {
for download in self.downloads {
download.connection.cancel()
download.close()
}
}
}
}
// MARK: Public methods
extension DownloadManager {
public func connection(connection: NSURLConnection, didReceiveResponse response: NSURLResponse) {
if let download = self.downloadForConnection(connection) {
let contentLength = response.expectedContentLength
download.totalSize = contentLength == -1 ? 0 : UInt64(contentLength) + download.downloadedSize
sync {
for delegate in self.delegates {
delegate.downloadManager(self, downloadDidStart: download.url, resumed: download.totalSize > 0)
}
}
}
}
public func connection(connection: NSURLConnection, didReceiveData data: NSData) {
if let download = self.downloadForConnection(connection) {
var percentage: Double = 0
var remaining: NSTimeInterval = NSTimeInterval.NaN
sync {
download.write(data)
download.downloadedSize += UInt64(data.length)
if download.totalSize > 0 {
percentage = Double(download.downloadedSize) / Double(download.totalSize)
if download.averageDownloadSpeed != UInt64.max {
if download.averageDownloadSpeed == 0 {
remaining = NSTimeInterval.infinity
} else {
remaining = NSTimeInterval((download.totalSize - download.downloadedSize) / download.averageDownloadSpeed)
}
}
}
for delegate in self.delegates {
delegate.downloadManager(
self,
downloadDidProgress: download.url,
totalSize: download.totalSize,
downloadedSize: download.downloadedSize,
percentage: percentage,
averageDownloadSpeedInBytes: download.averageDownloadSpeed,
timeRemaining: remaining
)
}
}
}
}
public func connection(connection: NSURLConnection, didFailWithError error: NSError) {
if let download = self.downloadForConnection(connection) {
sync {
for delegate in self.delegates {
delegate.downloadManager(self, downloadDidFail: download.url, error: error)
}
download.close()
self.downloads.remove(download)
}
}
}
public func connectionDidFinishLoading(connection: NSURLConnection) {
if let download = self.downloadForConnection(connection) {
sync {
for delegate in self.delegates {
delegate.downloadManager(self, downloadDidFinish: download.url)
}
download.close()
self.downloads.remove(download)
}
}
}
}
|
mit
|
af33ba58d789c52c03fc3e4ac6f0283e
| 34.656593 | 221 | 0.54446 | 5.788582 | false | false | false | false |
jovito-royeca/ManaKit
|
Example/ManaKit/Maintainer/Maintainer+Sets.swift
|
1
|
2906
|
//
// Maintainer+Sets.swift
// ManaKit_Example
//
// Created by Jovito Royeca on 23/10/2018.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import Foundation
import ManaKit
import PostgresClientKit
import PromiseKit
extension Maintainer {
func setsData() -> [[String: Any]] {
guard let cachePath = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true).first else {
fatalError("Malformed cachePath")
}
let setsPath = "\(cachePath)/\(ManaKit.Constants.ScryfallDate)_\(setsFileName)"
let data = try! Data(contentsOf: URL(fileURLWithPath: setsPath))
guard let dict = try! JSONSerialization.jsonObject(with: data,
options: .mutableContainers) as? [String: Any] else {
fatalError("Malformed data")
}
guard let array = dict["data"] as? [[String: Any]] else {
fatalError("Malformed data")
}
return array
}
func filterSetBlocks(array: [[String: Any]], connection: Connection) -> [()->Promise<Void>] {
var filteredData = [String: String]()
for dict in array {
if let blockCode = dict["block_code"] as? String,
let block = dict["block"] as? String {
filteredData[blockCode] = block
}
}
let promises: [()->Promise<Void>] = filteredData.map { (blockCode, block) in
return {
return self.createSetBlockPromise(blockCode: blockCode,
block: block,
connection: connection)
}
}
return promises
}
func filterSetTypes(array: [[String: Any]], connection: Connection) -> [()->Promise<Void>] {
var filteredData = Set<String>()
for dict in array {
if let setType = dict["set_type"] as? String {
filteredData.insert(setType)
}
}
let promises: [()->Promise<Void>] = filteredData.map { setType in
return {
return self.createSetTypePromise(setType: setType,
connection: connection)
}
}
return promises
}
func filterSets(array: [[String: Any]], connection: Connection) -> [()->Promise<Void>] {
let filteredData = array.sorted(by: {
$0["parent_set_code"] as? String ?? "" < $1["parent_set_code"] as? String ?? ""
})
let promises: [()->Promise<Void>] = filteredData.map { dict in
return {
return self.createSetPromise(dict: dict,
connection: connection)
}
}
return promises
}
}
|
mit
|
52375510223dcbad64ad3882eb0ee538
| 34 | 119 | 0.517384 | 5.017271 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/Platform/Sources/PlatformUIKit/CheckboxView/CheckboxTableViewCell.swift
|
1
|
2415
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import RxSwift
public final class CheckboxTableViewCell: UITableViewCell {
// MARK: - Public Properties
public var viewModel: CheckboxViewModel! {
willSet {
disposeBag = DisposeBag()
}
didSet {
guard let viewModel = viewModel else { return }
viewModel
.textViewViewModel
.drive(interactableTextView.rx.viewModel)
.disposed(by: disposeBag)
viewModel
.image
.drive(checkboxImageView.rx.image)
.disposed(by: disposeBag)
}
}
// MARK: - Private Properties
private var disposeBag = DisposeBag()
private let interactableTextView = InteractableTextView()
private let checkboxImageView = UIImageView()
private let button = UIButton()
// MARK: - Lifecycle
override public init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setup()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
setup()
}
override public func prepareForReuse() {
super.prepareForReuse()
viewModel = nil
}
private func setup() {
selectionStyle = .none
contentView.addSubview(checkboxImageView)
contentView.addSubview(interactableTextView)
contentView.addSubview(button)
checkboxImageView.layout(size: .edge(16.0))
checkboxImageView.layout(edges: .leading, to: contentView, offset: 24)
checkboxImageView.layout(edges: .top, to: contentView, offset: 24)
interactableTextView.layout(edges: .top, to: checkboxImageView)
interactableTextView.layout(edge: .leading, to: .trailing, of: checkboxImageView, offset: 8.0)
interactableTextView.layout(edge: .trailing, to: .trailing, of: contentView, offset: -24)
interactableTextView.layout(edge: .bottom, to: .bottom, of: contentView, offset: -16)
button.layout(size: .edge(24.0))
button.layout(edges: .centerX, .centerY, to: checkboxImageView)
button.addTarget(self, action: #selector(toggled(sender:)), for: .touchUpInside)
}
@objc func toggled(sender: UIButton) {
viewModel.selectedRelay.accept(!viewModel.selectedRelay.value)
}
}
|
lgpl-3.0
|
4fcedacc82421a1e01f0a43ea8181364
| 32.068493 | 102 | 0.644159 | 4.789683 | false | false | false | false |
wbaumann/SmartReceiptsiOS
|
SmartReceipts/ViewControllers/TooltipPresenter.swift
|
2
|
6451
|
//
// TooltipPresenter.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 30/08/2018.
// Copyright © 2018 Will Baumann. All rights reserved.
//
import Foundation
import RxSwift
class TooltipPresenter {
private let bag = DisposeBag()
private weak var view: UIView!
private let trip: WBTrip
private var reportTooltip: TooltipView?
private var syncErrorTooltip: TooltipView?
private var reminderTooltip: TooltipView?
private let errorTapSubject = PublishSubject<SyncError>()
private let generateTapSubject = PublishSubject<Void>()
private let updateInsetsSubject = PublishSubject<UIEdgeInsets>()
private let reminderTapSubject = PublishSubject<Void>()
var updateInsets: Observable<UIEdgeInsets> { return updateInsetsSubject.asObservable() }
var errorTap: Observable<SyncError> { return errorTapSubject.asObservable() }
var generateTap: Observable<Void> { return generateTapSubject.asObservable() }
var reminderTap: Observable<Void> { return reminderTapSubject.asObservable() }
init(view: UIView, trip: WBTrip) {
self.trip = trip
self.view = view
BackupProvidersManager.shared.getCriticalSyncErrorStream()
.filter({ $0 != .unknownError })
.delay(0.1, scheduler: MainScheduler.instance)
.subscribe(onNext: { [unowned self] syncError in
self.presentSyncError(syncError)
}).disposed(by: bag)
AppNotificationCenter.didSyncBackup
.subscribe(onNext: { [unowned self] in
self.presentBackupReminderIfNeeded()
}).disposed(by: bag)
}
func presentSyncError(_ syncError: SyncError) {
syncErrorTooltip?.removeFromSuperview()
syncErrorTooltip = nil
updateInsetsSubject.onNext(TOOLTIP_INSETS)
let text = syncError.localizedDescription
syncErrorTooltip = TooltipView.showErrorOn(view: view, text: text)
syncErrorTooltip?.rx.action.subscribe(onNext: { [unowned self] in
self.syncErrorTooltip = nil
self.errorTapSubject.onNext(syncError)
self.updateViewInsets()
}).disposed(by: bag)
syncErrorTooltip?.rx.close.subscribe(onNext: { [unowned self] in
self.syncErrorTooltip = nil
self.updateViewInsets()
}).disposed(by: bag)
}
func presentBackupReminderIfNeeded() {
guard let text = TooltipService.shared.tooltipBackupReminder(), reportTooltip == nil else { return }
reminderTooltip?.removeFromSuperview()
reminderTooltip = nil
updateInsetsSubject.onNext(TOOLTIP_INSETS)
let offset = CGPoint(x: 0, y: TooltipView.HEIGHT)
reminderTooltip = TooltipView.showOn(view: view, text: text, image: #imageLiteral(resourceName: "info"), offset: offset)
reminderTooltip?.rx.action.subscribe(onNext: { [unowned self] in
TooltipService.shared.markBackupReminderDismissed()
self.reminderTapSubject.onNext(())
self.reminderTooltip = nil
self.updateViewInsets()
}).disposed(by: bag)
reminderTooltip?.rx.close.subscribe(onNext: { [unowned self] in
TooltipService.shared.markBackupReminderDismissed()
self.reminderTooltip = nil
self.updateViewInsets()
}).disposed(by: bag)
}
func presentReportHint() {
guard let text = TooltipService.shared.reportHint(), reportTooltip == nil else { return }
reminderTooltip?.removeFromSuperview()
reminderTooltip = nil
updateInsetsSubject.onNext(TOOLTIP_INSETS)
reminderTooltip = TooltipView.showOn(view: view, text: text, image: #imageLiteral(resourceName: "info"))
guard let tooltip = reminderTooltip else { return }
Observable.merge([tooltip.rx.action.asObservable(), tooltip.rx.close.asObservable()])
.subscribe(onNext: {
TooltipService.shared.markReportHintInteracted()
self.reminderTapSubject.onNext(())
self.reminderTooltip = nil
self.updateViewInsets()
}).disposed(by: bag)
}
func presentBackupPlusTooltip() {
guard let text = TooltipService.shared.backupPlusReminder(), reportTooltip == nil else { return }
reminderTooltip?.removeFromSuperview()
reminderTooltip = nil
updateInsetsSubject.onNext(TOOLTIP_INSETS)
reminderTooltip = TooltipView.showOn(view: view, text: text, image: #imageLiteral(resourceName: "info"))
reminderTooltip?.rx.action.subscribe(onNext: { [unowned self] in
TooltipService.shared.markBackupPlusDismissed()
self.reminderTapSubject.onNext(())
self.reminderTooltip = nil
self.updateViewInsets()
}).disposed(by: bag)
reminderTooltip?.rx.close.subscribe(onNext: { [unowned self] in
TooltipService.shared.markBackupPlusDismissed()
self.reminderTooltip = nil
self.updateViewInsets()
}).disposed(by: bag)
}
func presentGenerateIfNeeded() {
if !TooltipService.shared.moveToGenerateTrigger(for: trip) || syncErrorTooltip != nil || reminderTooltip != nil {
return
}
guard let text = TooltipService.shared.generateTooltip(for: trip), reportTooltip == nil else { return }
updateInsetsSubject.onNext(TOOLTIP_INSETS)
reportTooltip = TooltipView.showOn(view: view, text: text)
reportTooltip?.rx.action.subscribe(onNext: { [unowned self] in
TooltipService.shared.markMoveToGenerateDismiss()
self.generateTapSubject.onNext(())
self.reportTooltip = nil
self.updateViewInsets()
}).disposed(by: bag)
reportTooltip?.rx.close.subscribe(onNext: { [unowned self] in
TooltipService.shared.markMoveToGenerateDismiss()
self.reportTooltip = nil
self.updateViewInsets()
}).disposed(by: bag)
}
private func updateViewInsets() {
let insets: UIEdgeInsets = reportTooltip == nil && reminderTooltip == nil && syncErrorTooltip == nil ? .zero : TOOLTIP_INSETS
self.updateInsetsSubject.onNext(insets)
}
}
|
agpl-3.0
|
8137b591d2a33143e0241c580ade8a8a
| 39.062112 | 133 | 0.641395 | 4.835082 | false | false | false | false |
jeffreybergier/WaterMe2
|
WaterMe/WaterMe/StyleSheets/Font.swift
|
1
|
9164
|
//
// Font.swift
// WaterMe
//
// Created by Jeffrey Bergier on 9/20/18.
// Copyright © 2018 Saturday Apps.
//
// This file is part of WaterMe. Simple Plant Watering Reminders for iOS.
//
// WaterMe is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// WaterMe is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with WaterMe. If not, see <http://www.gnu.org/licenses/>.
//
import Datum
import UIKit
enum Font {
case sectionHeaderBold(ReminderHeaderCollectionReusableView.SectionOrTint)
case sectionHeaderRegular(ReminderSection)
case selectableTableViewCell
case selectableTableViewCellDisabled
case selectableTableViewCellHelper
case readOnlyTableViewCell
case textInputTableViewCell
case migratorTitle
case migratorSubtitle
case migratorBody
case migratorBodySmall
case migratorPrimaryButton
case migratorSecondaryButton
case reminderSummaryCancelButton
case reminderSummaryActionButton
case reminderSummaryPrimaryLabel
case reminderSummaryPrimaryLabelValueNIL
case reminderSummarySublabel
case tableHeaderActionButton
case emojiSuperSmall
case emojiSmall(accessibilityFontSizeEnabled: Bool)
case emojiLarge(accessibilityFontSizeEnabled: Bool)
case reminderVesselDragPreviewViewPrimary
case reminderVesselDragPreviewViewPrimaryDisabled
case reminderVesselDragPreviewViewSecondary
case reminderVesselCollectionViewCellPrimary(UIColor?)
case reminderVesselCollectionViewCellPrimaryDisabled
case reminderVesselCollectionViewCellSecondary
case dragInstructionalText(UIColor)
}
extension Font {
static let centerStyle: NSParagraphStyle = {
// swiftlint:disable:next force_cast
let p = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
p.alignment = .center
p.lineBreakMode = .byTruncatingMiddle
// swiftlint:disable:next force_cast
return p.copy() as! NSParagraphStyle
}()
static let truncateMiddleStyle: NSParagraphStyle = {
// swiftlint:disable:next force_cast
let p = NSParagraphStyle.default.mutableCopy() as! NSMutableParagraphStyle
p.lineBreakMode = .byTruncatingMiddle
// swiftlint:disable:next force_cast
return p.copy() as! NSParagraphStyle
}()
}
extension Font {
var attributes: [NSAttributedString.Key : Any] {
switch self {
case .reminderSummaryCancelButton:
return [
.font : Font.bodyPlusBold,
.foregroundColor : Color.tint,
.paragraphStyle : type(of: self).centerStyle
]
case .reminderSummaryActionButton:
return [
.font : Font.bodyPlus,
.foregroundColor : Color.tint,
.paragraphStyle : type(of: self).centerStyle
]
case .reminderSummaryPrimaryLabel:
return [
.font : Font.body,
.foregroundColor : Color.textPrimary
]
case .reminderSummaryPrimaryLabelValueNIL:
return [
.font : Font.body,
.foregroundColor : Color.textSecondary
]
case .reminderSummarySublabel:
return [
.font : Font.bodyMinusBold,
.foregroundColor : Color.textSecondary
]
case .migratorTitle:
return [
.font : Font.bodyPlusPlusPlus,
.foregroundColor : Color.textPrimary,
.paragraphStyle : type(of: self).centerStyle
]
case .migratorSubtitle:
return [
.font : Font.bodyPlusBold,
.foregroundColor : Color.textPrimary,
.paragraphStyle : type(of: self).centerStyle
]
case .migratorBody:
return [
.font : Font.body,
.foregroundColor : Color.textPrimary
]
case .migratorBodySmall:
return [
.font : Font.bodyMinus,
.foregroundColor : Color.textPrimary
]
case .migratorPrimaryButton:
return [
.font : Font.bodyPlusPlus
]
case .migratorSecondaryButton:
return [
.font : Font.body
]
case .tableHeaderActionButton:
return [
.font : Font.bodyBold,
.foregroundColor : Color.tint // fixes bug where button is not getting colored automatically
]
case .dragInstructionalText(let color):
return [
.font : Font.bodyPlusPlus,
.foregroundColor : color,
.paragraphStyle : type(of: self).centerStyle
]
case .reminderVesselCollectionViewCellPrimary(let color):
return [
.font : Font.bodyPlus,
.foregroundColor : color ?? Color.textPrimary,
.paragraphStyle : type(of: self).centerStyle
]
case .reminderVesselCollectionViewCellPrimaryDisabled:
return [
.font : Font.bodyPlus,
.foregroundColor : Color.textSecondary,
.paragraphStyle : type(of: self).centerStyle
]
case .reminderVesselDragPreviewViewPrimary:
return [
.font : Font.bodyIgnoringDynamicType,
.foregroundColor : Color.textPrimary
]
case .reminderVesselDragPreviewViewPrimaryDisabled:
return [
.font : Font.bodyIgnoringDynamicType,
.foregroundColor : Color.textSecondary
]
case .emojiSuperSmall:
return [
.font : UIFont.systemFont(ofSize: 20)
]
case .emojiSmall(let accessibilityFontSizeEnabled):
let baselineOffset: NSNumber = {
guard Font.customEmojiLoaded else { return 0 }
return accessibilityFontSizeEnabled ? -8 : -4
}()
return [
.font : Font.emojiFont(ofSize: accessibilityFontSizeEnabled ? 50 : 36),
.baselineOffset : baselineOffset
]
case .emojiLarge(let accessibilityFontSizeEnabled):
let baselineOffset: NSNumber = {
guard Font.customEmojiLoaded else { return 0 }
return accessibilityFontSizeEnabled ? -10 : -5
}()
return [
.font : Font.emojiFont(ofSize: accessibilityFontSizeEnabled ? 120 : 60),
.baselineOffset : baselineOffset
]
case .textInputTableViewCell:
return [
.font : Font.body,
.foregroundColor : Color.textPrimary
]
case .readOnlyTableViewCell:
return [
.font : Font.bodyMinus,
.foregroundColor : Color.textSecondary
]
case .selectableTableViewCell:
return [
.font : Font.bodyMinus,
.foregroundColor : Color.textPrimary
]
case .selectableTableViewCellDisabled:
return [
.font : Font.bodyMinus,
.foregroundColor : Color.textSecondary
]
case .selectableTableViewCellHelper:
return [
.font : Font.bodyMinusBold,
.foregroundColor : Color.textSecondary
]
case .reminderVesselCollectionViewCellSecondary:
var x = type(of: self).selectableTableViewCell.attributes
x[.paragraphStyle] = type(of: self).centerStyle
return x
case .reminderVesselDragPreviewViewSecondary:
return [
.font : Font.bodyMinusIgnoringDynamicType,
.foregroundColor : Color.textPrimary
]
case .sectionHeaderBold(let input):
let color: UIColor = {
switch input {
case .right(let tintColor):
return tintColor
case .left(let section):
return Color.color(for: section)
}
}()
return [
.font : Font.bodyBold,
.foregroundColor : color,
.paragraphStyle : type(of: self).truncateMiddleStyle
]
case .sectionHeaderRegular(let section):
return [
.font : Font.body,
.foregroundColor : Color.color(for: section),
.paragraphStyle : type(of: self).truncateMiddleStyle
]
}
}
}
|
gpl-3.0
|
8fa76218ed0f8cfdba9ea7b6981c3cce
| 35.799197 | 108 | 0.587799 | 5.470448 | false | false | false | false |
vector-im/vector-ios
|
Riot/Managers/RoomMessageLinkParser/RoomMessageURLParser.swift
|
2
|
1770
|
/*
Copyright 2019 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import Foundation
@objc enum RoomMessageURLType: Int {
case appleDataDetector
case http
case dummy
case unknown
}
/// URL parser for room messages.
@objcMembers
final class RoomMessageURLParser: NSObject {
// MARK: - Constants
private enum Scheme {
static let appleDataDetector = "x-apple-data-detectors"
static let http = "http"
static let https = "https"
}
private enum Constants {
static let dummyURL = "#"
}
// MARK: - Public
func parseURL(_ url: URL) -> RoomMessageURLType {
let roomMessageLink: RoomMessageURLType
if let scheme = url.scheme?.lowercased() {
switch scheme {
case Scheme.appleDataDetector:
roomMessageLink = .appleDataDetector
case Scheme.http, Scheme.https:
roomMessageLink = .http
default:
roomMessageLink = .unknown
}
} else if url.absoluteString == Constants.dummyURL {
roomMessageLink = .dummy
} else {
roomMessageLink = .unknown
}
return roomMessageLink
}
}
|
apache-2.0
|
d8f3a697efa3fca3364ebf39141321d0
| 26.230769 | 73 | 0.632203 | 4.822888 | false | false | false | false |
uasys/swift
|
test/SILGen/objc_generic_class.swift
|
1
|
2063
|
// RUN: %target-swift-frontend -sdk %S/Inputs -I %S/Inputs -enable-source-import %s -emit-silgen -enable-sil-ownership | %FileCheck %s
// REQUIRES: objc_interop
import gizmo
// Although we don't ever expose initializers and methods of generic classes
// to ObjC yet, a generic subclass of an ObjC class must still use ObjC
// deallocation.
// CHECK-NOT: sil hidden @_T0So7GenericCfd
// CHECK-NOT: sil hidden @_T0So8NSObjectCfd
class Generic<T>: NSObject {
var x: Int = 10
// CHECK-LABEL: sil hidden @_T018objc_generic_class7GenericCfD : $@convention(method) <T> (@owned Generic<T>) -> () {
// CHECK: bb0({{%.*}} : @owned $Generic<T>):
// CHECK: } // end sil function '_T018objc_generic_class7GenericCfD'
// CHECK-LABEL: sil hidden [thunk] @_T018objc_generic_class7GenericCfDTo : $@convention(objc_method) <T> (Generic<T>) -> () {
// CHECK: bb0([[SELF:%.*]] : @unowned $Generic<T>):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[NATIVE:%.*]] = function_ref @_T018objc_generic_class7GenericCfD
// CHECK: apply [[NATIVE]]<T>([[SELF_COPY]])
// CHECK: } // end sil function '_T018objc_generic_class7GenericCfDTo'
deinit {
// Don't blow up when 'self' is referenced inside an @objc deinit method
// of a generic class. <rdar://problem/16325525>
self.x = 0
}
}
// CHECK-NOT: sil hidden @_T018objc_generic_class7GenericCfd
// CHECK-NOT: sil hidden @_T0So8NSObjectCfd
// CHECK-LABEL: sil hidden @_T018objc_generic_class11SubGeneric1CfD : $@convention(method) <U, V> (@owned SubGeneric1<U, V>) -> () {
// CHECK: bb0([[SELF:%.*]] : @owned $SubGeneric1<U, V>):
// CHECK: [[SUPER_DEALLOC:%.*]] = super_method [[SELF]] : $SubGeneric1<U, V>, #Generic.deinit!deallocator.foreign : <T> (Generic<T>) -> () -> (), $@convention(objc_method) <τ_0_0> (Generic<τ_0_0>) -> ()
// CHECK: [[SUPER:%.*]] = upcast [[SELF:%.*]] : $SubGeneric1<U, V> to $Generic<Int>
// CHECK: apply [[SUPER_DEALLOC]]<Int>([[SUPER]])
class SubGeneric1<U, V>: Generic<Int> {
}
|
apache-2.0
|
2dc277dd2036b40fa3a05dd13bcf2ef8
| 46.930233 | 210 | 0.627365 | 3.287081 | false | false | false | false |
juliangrosshauser/HomeControl
|
HomeControl/Source/Room.swift
|
1
|
1225
|
//
// Room.swift
// HomeControl
//
// Created by Julian Grosshauser on 29/11/15.
// Copyright © 2015 Julian Grosshauser. All rights reserved.
//
/// Represents a room containing lights, blinds and consumers.
public struct Room {
//MARK: Properties
/// Room ID.
let id: UInt
/// Room name.
let name: String
/// Lights.
let lights: [Light]?
/// Blinds.
let blinds: [Blind]?
/// Consumers.
let consumers: [Consumer]?
//MARK: Initialization
/// Construct a `Room` with the specified lights, blinds and consumers.
init(id: UInt, name: String, lights: [Light]?, blinds: [Blind]?, consumers: [Consumer]?) {
self.id = id
self.name = name
self.lights = lights
self.blinds = blinds
self.consumers = consumers
}
}
//MARK: Equatable
extension Room: Equatable {}
public func ==(lhs: Room, rhs: Room) -> Bool {
return lhs.id == rhs.id && lhs.name == rhs.name && lhs.lights == rhs.lights && lhs.blinds == rhs.blinds && lhs.consumers == rhs.consumers
}
// Necessary because `==` for `Room`s doesn't compile otherwise.
public func ==<T: Equatable>(lhs: [T]?, rhs: [T]?) -> Bool {
return lhs == rhs
}
|
mit
|
92a6e835d2da23565adfe20e9932140a
| 22.538462 | 141 | 0.598856 | 3.675676 | false | false | false | false |
zapdroid/RXWeather
|
Pods/RxTest/Platform/Platform.Linux.swift
|
4
|
2744
|
//
// Platform.Linux.swift
// Platform
//
// Created by Krunoslav Zaher on 12/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
#if os(Linux)
import XCTest
import Glibc
import SwiftShims
import class Foundation.Thread
final class AtomicInt {
typealias IntegerLiteralType = Int
fileprivate var value: Int32 = 0
fileprivate var _lock = RecursiveLock()
func lock() {
_lock.lock()
}
func unlock() {
_lock.unlock()
}
func valueSnapshot() -> Int32 {
return value
}
}
extension AtomicInt: ExpressibleByIntegerLiteral {
convenience init(integerLiteral value: Int) {
self.init()
self.value = Int32(value)
}
}
func >(lhs: AtomicInt, rhs: Int32) -> Bool {
return lhs.value > rhs
}
func ==(lhs: AtomicInt, rhs: Int32) -> Bool {
return lhs.value == rhs
}
func AtomicFlagSet(_ mask: UInt32, _ atomic: inout AtomicInt) -> Bool {
atomic.lock(); defer { atomic.unlock() }
return (atomic.value & Int32(mask)) != 0
}
func AtomicOr(_ mask: UInt32, _ atomic: inout AtomicInt) -> Int32 {
atomic.lock(); defer { atomic.unlock() }
let value = atomic.value
atomic.value |= Int32(mask)
return value
}
func AtomicIncrement(_ atomic: inout AtomicInt) -> Int32 {
atomic.lock(); defer { atomic.unlock() }
atomic.value += 1
return atomic.value
}
func AtomicDecrement(_ atomic: inout AtomicInt) -> Int32 {
atomic.lock(); defer { atomic.unlock() }
atomic.value -= 1
return atomic.value
}
func AtomicCompareAndSwap(_ l: Int32, _ r: Int32, _ atomic: inout AtomicInt) -> Bool {
atomic.lock(); defer { atomic.unlock() }
if atomic.value == l {
atomic.value = r
return true
}
return false
}
extension Thread {
static func setThreadLocalStorageValue<T: AnyObject>(_ value: T?, forKey key: String) {
let currentThread = Thread.current
var threadDictionary = currentThread.threadDictionary
if let newValue = value {
threadDictionary[key] = newValue
} else {
threadDictionary[key] = nil
}
currentThread.threadDictionary = threadDictionary
}
static func getThreadLocalStorageValueForKey<T: AnyObject>(_ key: String) -> T? {
let currentThread = Thread.current
let threadDictionary = currentThread.threadDictionary
return threadDictionary[key] as? T
}
}
#endif
|
mit
|
ea9893e0e628e44c9cb78197bec7ee85
| 24.877358 | 95 | 0.568356 | 4.696918 | false | false | false | false |
dclelland/Gong
|
Sources/Gong/Core/MIDIDestination.swift
|
1
|
2477
|
//
// MIDIDestination.swift
// Gong
//
// Created by Daniel Clelland on 26/04/17.
// Copyright © 2017 Daniel Clelland. All rights reserved.
//
import Foundation
import CoreMIDI
public class MIDIDestination: MIDIEndpoint {
public convenience init?(named name: String) {
guard let destination = MIDIDestination.all.first(where: { $0.name == name }) else {
return nil
}
self.init(destination.reference)
}
public static var all: [MIDIDestination] {
let count = MIDIGetNumberOfDestinations()
return (0..<count).lazy.map { index in
return MIDIDestination(MIDIGetDestination(index))
}
}
}
extension MIDIDestination {
public func flushOutput() throws {
try MIDIFlushOutput(reference).midiError("Flushing MIDIDestination output")
}
}
extension MIDIDestination {
public typealias SystemExclusiveEventCompletion = () -> Void
// Disclaimer: I'm fairly certain this doesn't work, though I haven't really tested it yet.
// This function is what I would expect you would use if sending long SysEx messages with more than 256 bytes;
// otherwise, consider just using `MIDIMessage(bytes:)` instead.
public func send(systemExclusiveEvent bytes: [UInt8], completion: @escaping SystemExclusiveEventCompletion = {}) throws {
let completionReference = UnsafeMutablePointer<SystemExclusiveEventCompletion>.allocate(capacity: 1)
completionReference.initialize(to: completion)
let completionProcedure: MIDICompletionProc = { requestPointer in
guard let completion = requestPointer.pointee.completionRefCon?.assumingMemoryBound(to: SystemExclusiveEventCompletion.self).pointee else {
return
}
completion()
}
var request = Data(bytes).withUnsafeBytes { (pointer: UnsafeRawBufferPointer) in
return MIDISysexSendRequest(
destination: reference,
data: pointer.baseAddress!.assumingMemoryBound(to: UInt8.self),
bytesToSend: UInt32(bytes.count),
complete: false,
reserved: (0, 0, 0),
completionProc: completionProcedure,
completionRefCon: completionReference
)
}
try MIDISendSysex(&request).midiError("Sending system exclusive event")
}
}
|
mit
|
7ce4bf1d801695355135c67ff821bb11
| 32.917808 | 151 | 0.64378 | 4.86444 | false | false | false | false |
spweau/Test_DYZB
|
Test_DYZB/Test_DYZB/Classes/Home/Controller/RecommendViewController.swift
|
1
|
7416
|
//
// RecommendViewController.swift
// Test_DYZB
//
// Created by Spweau on 2017/2/23.
// Copyright © 2017年 sp. All rights reserved.
//
import UIKit
// mark- 定义常量
private let kItemMargin : CGFloat = 10
private let kItemW = (kScreenW - 3 * kItemMargin) / 2
private let kNormalItemH = kItemW * 3 / 4
private let kPrettyItemH = kItemW * 4 / 3
private let kHeaderViewH : CGFloat = 50
private let kCycleViewH = kScreenW * 3 / 8
private let kGameViewH : CGFloat = 90
private let kNormalCellID = "kNormalCellID"
private let kPrettyCellID = "kPrettyCellID"
private let kHeaderViewID = "kHeaderViewID"
class RecommendViewController: UIViewController {
//懒加载 属性
fileprivate lazy var recommendVM : RecommendViewModel = RecommendViewModel()
// lazy load
fileprivate lazy var collectionView : UICollectionView = { [unowned self] in
// 1. 创建布局
let layout = UICollectionViewFlowLayout()
layout.itemSize = CGSize(width: kItemW, height: kNormalItemH)
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = kItemMargin
// 设置组头
layout.headerReferenceSize = CGSize(width: kScreenW, height: kHeaderViewH)
// 设置组的内边距
layout.sectionInset = UIEdgeInsets(top: 0, left: kItemMargin, bottom: 0, right: kItemMargin)
// 2. 创建UICollectionView
let collectionView = UICollectionView(frame: self.view.bounds ,collectionViewLayout:layout )
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
// 添加约束
collectionView.autoresizingMask = [.flexibleHeight,.flexibleWidth]
// 注册cell
// collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: kNormalCellID)
collectionView.register( UINib(nibName: "CollectionNormalCell", bundle: nil) , forCellWithReuseIdentifier: kNormalCellID)
collectionView.register( UINib(nibName: "CollectionPrettyCell", bundle: nil) , forCellWithReuseIdentifier: kPrettyCellID)
// 注册组头View
// collectionView.register(UICollectionReusableView.self, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
collectionView.register( UINib(nibName: "CollectionHeaderView", bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: kHeaderViewID)
return collectionView
}()
fileprivate lazy var cycleView : RecommendCycleView = {
let cycleView = RecommendCycleView.recommendCycleView()
cycleView.frame = CGRect(x: 0, y: -(kCycleViewH + kGameViewH), width: kScreenW, height: kCycleViewH)
return cycleView
}()
fileprivate lazy var gameView : RecommendGameView = {
let gameView = RecommendGameView.recommendGameView()
gameView.frame = CGRect(x: 0, y: -kGameViewH, width: kScreenW, height: kGameViewH)
return gameView
}()
// cycle life
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.red
// 1. 设置UI界面
setupUI()
// 2. 网络请求
loadData()
}
}
// mark - 设置UI界面内容
extension RecommendViewController {
fileprivate func setupUI() {
//1.添加collectionView
view.addSubview(collectionView)
// 2.将CycleView添加到UICollectionView中
collectionView.addSubview(cycleView)
// 3.将gameView添加collectionView中
//collectionView.addSubview(gameView)
// 4.设置collectionView的内边距
collectionView.contentInset = UIEdgeInsets(top: kCycleViewH + kGameViewH, left: 0, bottom: 0, right: 0)
}
}
// mark - 网络请求
extension RecommendViewController {
fileprivate func loadData() {
// NetWorkTools.requestData(type: .GET, URLString: "http://httpbin.org/get", parameters: [ "name": "spweau", "age" : 26]) { (result) in
// print(result)
// }
// 1.请求推荐数据
recommendVM.requestData {
print("--------------")
self.collectionView.reloadData()
}
// 2.请求轮播数据
recommendVM.requestCycleData {
print("数据请求完成")
self.cycleView.cycleModels = self.recommendVM.cycleModels
}
}
}
//Mark - UICollectionView 的 dataSource 代理方法
extension RecommendViewController : UICollectionViewDataSource ,UICollectionViewDelegateFlowLayout{
func numberOfSections(in collectionView: UICollectionView) -> Int {
// 默认12
return recommendVM.anchorGroups.count
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
// 第一组 8个 , 其它 4个
// if section == 0 {
//
// return 8
// }
//
// return 4
let group = recommendVM.anchorGroups[section]
return group.anchors.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 0.取出模型对象
let group = recommendVM.anchorGroups[indexPath.section]
let anchor = group.anchors[indexPath.item]
// 1. 定义cell
var cell : CollectionBaseCell
// 2. 取cell
if indexPath.section == 1 {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kPrettyCellID, for: indexPath) as! CollectionPrettyCell
} else {
cell = collectionView.dequeueReusableCell(withReuseIdentifier: kNormalCellID, for: indexPath) as! CollectionNormalCell
}
cell.anchor = anchor
return cell
// cell.backgroundColor = UIColor.white
// return cell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
// 1. 取出section的headerView
let headerView = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: kHeaderViewID, for: indexPath) as! CollectionHeaderView
// headerView.backgroundColor = UIColor.green
// 取出模型
headerView.group = recommendVM.anchorGroups[indexPath.section]
return headerView
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
if indexPath.section == 1 {
return CGSize(width: kItemW, height: kPrettyItemH)
}
return CGSize(width: kItemW, height: kNormalItemH)
}
}
// Mark - UICollectionView 的 delegate 代理方法
extension RecommendViewController : UICollectionViewDelegate {
}
|
mit
|
8f5afe76cb5f4b5443f1d7c211f46417
| 29.096639 | 187 | 0.634371 | 5.790622 | false | false | false | false |
dn-m/PitchSpellingTools
|
PitchSpellingTools/PitchSpellingRules.swift
|
1
|
3003
|
//
// PitchSpellingRules.swift
// PitchSpellingTools
//
// Created by James Bean on 9/6/16.
//
//
/*
/// Rule that takes a cost multiplier, and a given input (either a single pitch spelling, or
/// a pair of pitch spellings), and returns a penalty.
typealias Rule<Input> = (Float) -> (Input) -> Float
// MARK: - Node-level rules
/// Avoid double sharp or double flat pitch spellings.
let doubleSharpOrDoubleFlat: Rule<Node> = { costMultiplier in
return { spelling in abs(spelling.quarterStep.rawValue) == 2 ? 1 : 0 }
}
/// Avoid three quarter sharp and three quarter flat pitch spellings.
let threeQuarterSharpOrThreeQuarterFlat: Rule<Node> = { costMultiplier in
return { spelling in abs(spelling.quarterStep.rawValue) == 1.5 ? 1 : 0 }
}
/// Avoid b sharp, e sharp, c flat, and f flat pitch spellings.
let badEnharmonic: Rule<Node> = { costMultiplier in
return { spelling in
switch (spelling.letterName, spelling.quarterStep) {
case (.b, .sharp), (.e, .sharp), (.c, .flat), (.f, .flat): return 1 * costMultiplier
default: return 0
}
}
}
/// Avoid pitch spellings that have quarter step and eighth step resolutions.
let quarterStepEighthStepCombination: Rule<Node> = { costMultiplier in
return { spelling in
switch (spelling.quarterStep.resolution, abs(spelling.eighthStep.rawValue)) {
case (.quarterStep, 0.25): return 1
default: return 0
}
}
}
// MARK: - Edge-level rules
/// Avoid unison intervals (this assumes that a unique set of pitch classes in the input).
let unison: Rule<Edge> = { costMultiplier in
return { (a,b) in a.letterName == b.letterName ? 1 : 0 }
}
/// Avoid augmented or diminished intervals.
let augmentedOrDiminished: Rule<Edge> = { costMultiplier in
return { (a,b) in
switch NamedInterval(a,b).quality {
case NamedInterval.Quality.augmented, NamedInterval.Quality.diminished: return 1
default: return 0
}
}
}
/// Avoid circumstances where the letter name value relationship is not equivalent to the
/// pitch class relationship (e.g., b sharp up, c natural)
let crossover: Rule<Edge> = { costMultiplier in
return { (a,b) in
return (a.letterName.steps < b.letterName.steps) != (a.pitchClass < b.pitchClass)
? 1
: 0
}
}
/// Avoid dyads with sharps and flats.
///
/// - TODO: Consider merging this into augmented / diminished.
let flatSharpIncompatibility: Rule<Edge> = { costMultiplier in
return { (a,b) in
return a.quarterStep.direction.rawValue * b.quarterStep.direction.rawValue == -1
? 1
: 0
}
}
// MARK: - Graph-level rules
/// Avoid up and down eighth step value mixtures.
let eighthStepDirectionIncompatibility: Rule<Edge> = { costMultiplier in
return { (a,b) in
switch (a.eighthStep.rawValue, b.eighthStep.rawValue) {
case (0, _), (_, 0), (-0.25, -0.25), (0.25, 0.25): return 0
default: return 1
}
}
}
*/
|
mit
|
f05bbab50ac817b85549fe1d023d541f
| 30.28125 | 92 | 0.655678 | 3.648846 | false | false | false | false |
fahidattique55/FAPanels
|
FAPanels/IQKeyboardManagerSwift/IQToolbar/IQUIView+IQKeyboardToolbar.swift
|
1
|
55491
|
//
// IQUIView+IQKeyboardToolbar.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-16 Iftekhar Qurashi.
//
// 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
fileprivate func < <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l < r
case (nil, _?):
return true
default:
return false
}
}
fileprivate func > <T : Comparable>(lhs: T?, rhs: T?) -> Bool {
switch (lhs, rhs) {
case let (l?, r?):
return l > r
default:
return rhs < lhs
}
}
private var kIQShouldHideToolbarPlaceholder = "kIQShouldHideToolbarPlaceholder"
private var kIQToolbarPlaceholder = "kIQToolbarPlaceholder"
private var kIQKeyboardToolbar = "kIQKeyboardToolbar"
/**
UIView category methods to add IQToolbar on UIKeyboard.
*/
public extension UIView {
/**
IQToolbar references for better customization control.
*/
public var keyboardToolbar: IQToolbar {
get {
var toolbar = inputAccessoryView as? IQToolbar
if (toolbar == nil)
{
toolbar = objc_getAssociatedObject(self, &kIQKeyboardToolbar) as? IQToolbar
}
if let unwrappedToolbar = toolbar {
return unwrappedToolbar
} else {
let newToolbar = IQToolbar()
objc_setAssociatedObject(self, &kIQKeyboardToolbar, newToolbar, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
return newToolbar
}
}
}
///-------------------------
/// MARK: Title
///-------------------------
/**
If `shouldHideToolbarPlaceholder` is YES, then title will not be added to the toolbar. Default to NO.
*/
public var shouldHideToolbarPlaceholder: Bool {
get {
let aValue: AnyObject? = objc_getAssociatedObject(self, &kIQShouldHideToolbarPlaceholder) as AnyObject?
if let unwrapedValue = aValue as? Bool {
return unwrapedValue
} else {
return false
}
}
set(newValue) {
objc_setAssociatedObject(self, &kIQShouldHideToolbarPlaceholder, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
self.keyboardToolbar.titleBarButton.title = self.drawingToolbarPlaceholder;
}
}
@available(*,deprecated, message: "This is renamed to `shouldHideToolbarPlaceholder` for more clear naming.")
public var shouldHidePlaceholderText: Bool {
get {
return shouldHideToolbarPlaceholder
}
set(newValue) {
shouldHideToolbarPlaceholder = newValue
}
}
/**
`toolbarPlaceholder` to override default `placeholder` text when drawing text on toolbar.
*/
public var toolbarPlaceholder: String? {
get {
let aValue = objc_getAssociatedObject(self, &kIQToolbarPlaceholder) as? String
return aValue
}
set(newValue) {
objc_setAssociatedObject(self, &kIQToolbarPlaceholder, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
self.keyboardToolbar.titleBarButton.title = self.drawingToolbarPlaceholder;
}
}
@available(*,deprecated, message: "This is renamed to `toolbarPlaceholder` for more clear naming.")
public var placeholderText: String? {
get {
return toolbarPlaceholder
}
set(newValue) {
toolbarPlaceholder = newValue
}
}
/**
`drawingToolbarPlaceholder` will be actual text used to draw on toolbar. This would either `placeholder` or `toolbarPlaceholder`.
*/
public var drawingToolbarPlaceholder: String? {
if (self.shouldHideToolbarPlaceholder)
{
return nil
}
else if (self.toolbarPlaceholder?.isEmpty == false) {
return self.toolbarPlaceholder
}
else if self.responds(to: #selector(getter: UITextField.placeholder)) {
if let textField = self as? UITextField {
return textField.placeholder
} else if let textView = self as? IQTextView {
return textView.placeholder
} else {
return nil
}
}
else {
return nil
}
}
@available(*,deprecated, message: "This is renamed to `drawingToolbarPlaceholder` for more clear naming.")
public var drawingPlaceholderText: String? {
return drawingToolbarPlaceholder
}
///---------------------
/// MARK: Private helper
///---------------------
fileprivate static func flexibleBarButtonItem () -> IQBarButtonItem {
struct Static {
static let nilButton = IQBarButtonItem(barButtonSystemItem:UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil)
}
Static.nilButton.isSystemItem = true
return Static.nilButton
}
///------------
/// MARK: Done
///------------
/**
Helper function to add Done button on keyboard.
@param target Target object for selector.
@param action Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
*/
public func addDoneOnKeyboardWithTarget(_ target : AnyObject?, action : Selector) {
addDoneOnKeyboardWithTarget(target, action: action, titleText: nil)
}
/**
Helper function to add Done button on keyboard.
@param target Target object for selector.
@param action Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addDoneOnKeyboardWithTarget (_ target : AnyObject?, action : Selector, titleText: String?) {
//If can't set InputAccessoryView. Then return
if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = self.keyboardToolbar
var items : [IQBarButtonItem] = []
//Title button
toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText
if #available(iOS 11, *) {
} else {
toolbar.titleBarButton.customView?.frame = CGRect.zero;
}
items.append(toolbar.titleBarButton)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Done button
var doneButton = toolbar.doneBarButton
if doneButton.isSystemItem == false {
doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: target, action: action)
doneButton.isSystemItem = true
doneButton.invocation = toolbar.doneBarButton.invocation
doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel
toolbar.doneBarButton = doneButton
}
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
}
}
}
/**
Helper function to add Done button on keyboard.
@param target Target object for selector.
@param action Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
*/
public func addDoneOnKeyboardWithTarget (_ target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingToolbarPlaceholder
}
addDoneOnKeyboardWithTarget(target, action: action, titleText: title)
}
///------------
/// MARK: Right
///------------
/**
Helper function to add Right button on keyboard.
@param image Image icon to use as right button.
@param target Target object for selector.
@param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addRightButtonOnKeyboardWithImage (_ image : UIImage, target : AnyObject?, action : Selector, titleText: String?) {
//If can't set InputAccessoryView. Then return
if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = self.keyboardToolbar
var items : [IQBarButtonItem] = []
//Title button
toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText
if #available(iOS 11, *) {
} else {
toolbar.titleBarButton.customView?.frame = CGRect.zero;
}
items.append(toolbar.titleBarButton)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Right button
var doneButton = toolbar.doneBarButton
if doneButton.isSystemItem == false {
doneButton.title = nil
doneButton.image = image
doneButton.target = target
doneButton.action = action
}
else
{
doneButton = IQBarButtonItem(image: image, style: UIBarButtonItem.Style.done, target: target, action: action)
doneButton.invocation = toolbar.doneBarButton.invocation
doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel
toolbar.doneBarButton = doneButton
}
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
}
}
}
/**
Helper function to add Right button on keyboard.
@param image Image icon to use as right button.
@param target Target object for selector.
@param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
*/
public func addRightButtonOnKeyboardWithImage (_ image : UIImage, target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingToolbarPlaceholder
}
addRightButtonOnKeyboardWithImage(image, target: target, action: action, titleText: title)
}
/**
Helper function to add Right button on keyboard.
@param text Title for rightBarButtonItem, usually 'Done'.
@param target Target object for selector.
@param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
*/
public func addRightButtonOnKeyboardWithText (_ text : String, target : AnyObject?, action : Selector) {
addRightButtonOnKeyboardWithText(text, target: target, action: action, titleText: nil)
}
/**
Helper function to add Right button on keyboard.
@param text Title for rightBarButtonItem, usually 'Done'.
@param target Target object for selector.
@param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addRightButtonOnKeyboardWithText (_ text : String, target : AnyObject?, action : Selector, titleText: String?) {
//If can't set InputAccessoryView. Then return
if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = self.keyboardToolbar
var items : [IQBarButtonItem] = []
//Title button
toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText
if #available(iOS 11, *) {
} else {
toolbar.titleBarButton.customView?.frame = CGRect.zero;
}
items.append(toolbar.titleBarButton)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Right button
var doneButton = toolbar.doneBarButton
if doneButton.isSystemItem == false {
doneButton.title = text
doneButton.image = nil
doneButton.target = target
doneButton.action = action
}
else
{
doneButton = IQBarButtonItem(title: text, style: UIBarButtonItem.Style.done, target: target, action: action)
doneButton.invocation = toolbar.doneBarButton.invocation
doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel
toolbar.doneBarButton = doneButton
}
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
}
}
}
/**
Helper function to add Right button on keyboard.
@param text Title for rightBarButtonItem, usually 'Done'.
@param target Target object for selector.
@param action Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
*/
public func addRightButtonOnKeyboardWithText (_ text : String, target : AnyObject?, action : Selector, shouldShowPlaceholder: Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingToolbarPlaceholder
}
addRightButtonOnKeyboardWithText(text, target: target, action: action, titleText: title)
}
///------------------
/// MARK: Cancel/Done
///------------------
/**
Helper function to add Cancel and Done button on keyboard.
@param target Target object for selector.
@param cancelAction Cancel button action name. Usually 'cancelAction:(IQBarButtonItem*)item'.
@param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
*/
public func addCancelDoneOnKeyboardWithTarget (_ target : AnyObject?, cancelAction : Selector, doneAction : Selector) {
addCancelDoneOnKeyboardWithTarget(target, cancelAction: cancelAction, doneAction: doneAction, titleText: nil)
}
/**
Helper function to add Cancel and Done button on keyboard.
@param target Target object for selector.
@param cancelAction Cancel button action name. Usually 'cancelAction:(IQBarButtonItem*)item'.
@param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addCancelDoneOnKeyboardWithTarget (_ target : AnyObject?, cancelAction : Selector, doneAction : Selector, titleText: String?) {
//If can't set InputAccessoryView. Then return
if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = self.keyboardToolbar
var items : [IQBarButtonItem] = []
//Cancel button
var cancelButton = toolbar.previousBarButton
if cancelButton.isSystemItem == false {
cancelButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.cancel, target: target, action: cancelAction)
cancelButton.isSystemItem = true
cancelButton.invocation = toolbar.previousBarButton.invocation
cancelButton.accessibilityLabel = toolbar.previousBarButton.accessibilityLabel
toolbar.previousBarButton = cancelButton
}
items.append(cancelButton)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Title
toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText
if #available(iOS 11, *) {
} else {
toolbar.titleBarButton.customView?.frame = CGRect.zero;
}
items.append(toolbar.titleBarButton)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Done button
var doneButton = toolbar.doneBarButton
if doneButton.isSystemItem == false {
doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: target, action: doneAction)
doneButton.isSystemItem = true
doneButton.invocation = toolbar.doneBarButton.invocation
doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel
toolbar.doneBarButton = doneButton
}
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
}
}
}
/**
Helper function to add Cancel and Done button on keyboard.
@param target Target object for selector.
@param cancelAction Cancel button action name. Usually 'cancelAction:(IQBarButtonItem*)item'.
@param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
*/
public func addCancelDoneOnKeyboardWithTarget (_ target : AnyObject?, cancelAction : Selector, doneAction : Selector, shouldShowPlaceholder: Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingToolbarPlaceholder
}
addCancelDoneOnKeyboardWithTarget(target, cancelAction: cancelAction, doneAction: doneAction, titleText: title)
}
///-----------------
/// MARK: Right/Left
///-----------------
/**
Helper function to add Left and Right button on keyboard.
@param target Target object for selector.
@param leftButtonTitle Title for leftBarButtonItem, usually 'Cancel'.
@param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
@param leftButtonAction Left button action name. Usually 'cancelAction:(IQBarButtonItem*)item'.
@param rightButtonAction Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
*/
public func addRightLeftOnKeyboardWithTarget( _ target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector) {
addRightLeftOnKeyboardWithTarget(target, leftButtonTitle: leftButtonTitle, rightButtonTitle: rightButtonTitle, rightButtonAction: rightButtonAction, leftButtonAction: leftButtonAction, titleText: nil)
}
/**
Helper function to add Left and Right button on keyboard.
@param target Target object for selector.
@param leftButtonTitle Title for leftBarButtonItem, usually 'Cancel'.
@param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
@param leftButtonAction Left button action name. Usually 'cancelAction:(IQBarButtonItem*)item'.
@param rightButtonAction Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addRightLeftOnKeyboardWithTarget( _ target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector, titleText: String?) {
//If can't set InputAccessoryView. Then return
if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = self.keyboardToolbar
var items : [IQBarButtonItem] = []
//Left button
var cancelButton = toolbar.previousBarButton
if cancelButton.isSystemItem == false {
cancelButton.title = rightButtonTitle
cancelButton.image = nil
cancelButton.target = target
cancelButton.action = rightButtonAction
}
else
{
cancelButton = IQBarButtonItem(title: leftButtonTitle, style: UIBarButtonItem.Style.plain, target: target, action: leftButtonAction)
cancelButton.invocation = toolbar.previousBarButton.invocation
cancelButton.accessibilityLabel = toolbar.previousBarButton.accessibilityLabel
toolbar.previousBarButton = cancelButton
}
items.append(cancelButton)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Title button
toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText
if #available(iOS 11, *) {
} else {
toolbar.titleBarButton.customView?.frame = CGRect.zero;
}
items.append(toolbar.titleBarButton)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Right button
var doneButton = toolbar.doneBarButton
if doneButton.isSystemItem == false {
doneButton.title = rightButtonTitle
doneButton.image = nil
doneButton.target = target
doneButton.action = rightButtonAction
}
else
{
doneButton = IQBarButtonItem(title: rightButtonTitle, style: UIBarButtonItem.Style.done, target: target, action: rightButtonAction)
doneButton.invocation = toolbar.doneBarButton.invocation
doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel
toolbar.doneBarButton = doneButton
}
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
}
}
}
/**
Helper function to add Left and Right button on keyboard.
@param target Target object for selector.
@param leftButtonTitle Title for leftBarButtonItem, usually 'Cancel'.
@param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
@param leftButtonAction Left button action name. Usually 'cancelAction:(IQBarButtonItem*)item'.
@param rightButtonAction Right button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
*/
public func addRightLeftOnKeyboardWithTarget( _ target : AnyObject?, leftButtonTitle : String, rightButtonTitle : String, rightButtonAction : Selector, leftButtonAction : Selector, shouldShowPlaceholder: Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingToolbarPlaceholder
}
addRightLeftOnKeyboardWithTarget(target, leftButtonTitle: leftButtonTitle, rightButtonTitle: rightButtonTitle, rightButtonAction: rightButtonAction, leftButtonAction: leftButtonAction, titleText: title)
}
///-------------------------
/// MARK: Previous/Next/Done
///-------------------------
/**
Helper function to add ArrowNextPrevious and Done button on keyboard.
@param target Target object for selector.
@param previousAction Previous button action name. Usually 'previousAction:(id)item'.
@param nextAction Next button action name. Usually 'nextAction:(id)item'.
@param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
*/
public func addPreviousNextDoneOnKeyboardWithTarget ( _ target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector) {
addPreviousNextDoneOnKeyboardWithTarget(target, previousAction: previousAction, nextAction: nextAction, doneAction: doneAction, titleText: nil)
}
/**
Helper function to add ArrowNextPrevious and Done button on keyboard.
@param target Target object for selector.
@param previousAction Previous button action name. Usually 'previousAction:(id)item'.
@param nextAction Next button action name. Usually 'nextAction:(id)item'.
@param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addPreviousNextDoneOnKeyboardWithTarget ( _ target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector, titleText: String?) {
//If can't set InputAccessoryView. Then return
if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = self.keyboardToolbar
var items : [IQBarButtonItem] = []
// Get the top level "bundle" which may actually be the framework
var bundle = Bundle(for: IQKeyboardManager.self)
if let resourcePath = bundle.path(forResource: "IQKeyboardManager", ofType: "bundle") {
if let resourcesBundle = Bundle(path: resourcePath) {
bundle = resourcesBundle
}
}
var imageLeftArrow : UIImage!
var imageRightArrow : UIImage!
if #available(iOS 10, *) {
imageLeftArrow = UIImage(named: "IQButtonBarArrowUp", in: bundle, compatibleWith: nil)
imageRightArrow = UIImage(named: "IQButtonBarArrowDown", in: bundle, compatibleWith: nil)
} else {
imageLeftArrow = UIImage(named: "IQButtonBarArrowLeft", in: bundle, compatibleWith: nil)
imageRightArrow = UIImage(named: "IQButtonBarArrowRight", in: bundle, compatibleWith: nil)
}
//Support for RTL languages like Arabic, Persia etc... (Bug ID: #448)
if #available(iOS 9, *) {
imageLeftArrow = imageLeftArrow?.imageFlippedForRightToLeftLayoutDirection()
imageRightArrow = imageRightArrow?.imageFlippedForRightToLeftLayoutDirection()
}
var prev = toolbar.previousBarButton
if prev.isSystemItem == false {
prev.title = nil
prev.image = imageLeftArrow
prev.target = target
prev.action = previousAction
}
else
{
prev = IQBarButtonItem(image: imageLeftArrow, style: UIBarButtonItem.Style.plain, target: target, action: previousAction)
prev.invocation = toolbar.previousBarButton.invocation
prev.accessibilityLabel = toolbar.previousBarButton.accessibilityLabel
toolbar.previousBarButton = prev
}
var next = toolbar.nextBarButton
if next.isSystemItem == false {
next.title = nil
next.image = imageRightArrow
next.target = target
next.action = nextAction
}
else
{
next = IQBarButtonItem(image: imageRightArrow, style: UIBarButtonItem.Style.plain, target: target, action: nextAction)
next.invocation = toolbar.nextBarButton.invocation
next.accessibilityLabel = toolbar.nextBarButton.accessibilityLabel
toolbar.nextBarButton = next
}
//Previous button
items.append(prev)
//Fixed space
let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: nil, action: nil)
fixed.isSystemItem = true
if #available(iOS 10, *) {
fixed.width = 6
} else {
fixed.width = 20
}
items.append(fixed)
//Next button
items.append(next)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Title button
toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText
if #available(iOS 11, *) {
} else {
toolbar.titleBarButton.customView?.frame = CGRect.zero;
}
items.append(toolbar.titleBarButton)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Done button
var doneButton = toolbar.doneBarButton
if doneButton.isSystemItem == false {
doneButton = IQBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.done, target: target, action: doneAction)
doneButton.isSystemItem = true
doneButton.invocation = toolbar.doneBarButton.invocation
doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel
toolbar.doneBarButton = doneButton
}
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
}
}
}
/**
Helper function to add ArrowNextPrevious and Done button on keyboard.
@param target Target object for selector.
@param previousAction Previous button action name. Usually 'previousAction:(id)item'.
@param nextAction Next button action name. Usually 'nextAction:(id)item'.
@param doneAction Done button action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
*/
public func addPreviousNextDoneOnKeyboardWithTarget ( _ target : AnyObject?, previousAction : Selector, nextAction : Selector, doneAction : Selector, shouldShowPlaceholder: Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingToolbarPlaceholder
}
addPreviousNextDoneOnKeyboardWithTarget(target, previousAction: previousAction, nextAction: nextAction, doneAction: doneAction, titleText: title)
}
///--------------------------
/// MARK: Previous/Next/Right
///--------------------------
/**
Helper function to add ArrowNextPrevious and Right button on keyboard.
@param target Target object for selector.
@param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
@param previousAction Previous button action name. Usually 'previousAction:(id)item'.
@param nextAction Next button action name. Usually 'nextAction:(id)item'.
@param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addPreviousNextRightOnKeyboardWithTarget( _ target : AnyObject?, rightButtonImage : UIImage, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, titleText : String?) {
//If can't set InputAccessoryView. Then return
if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = self.keyboardToolbar
var items : [IQBarButtonItem] = []
// Get the top level "bundle" which may actually be the framework
var bundle = Bundle(for: IQKeyboardManager.self)
if let resourcePath = bundle.path(forResource: "IQKeyboardManager", ofType: "bundle") {
if let resourcesBundle = Bundle(path: resourcePath) {
bundle = resourcesBundle
}
}
var imageLeftArrow : UIImage!
var imageRightArrow : UIImage!
if #available(iOS 10, *) {
imageLeftArrow = UIImage(named: "IQButtonBarArrowUp", in: bundle, compatibleWith: nil)
imageRightArrow = UIImage(named: "IQButtonBarArrowDown", in: bundle, compatibleWith: nil)
} else {
imageLeftArrow = UIImage(named: "IQButtonBarArrowLeft", in: bundle, compatibleWith: nil)
imageRightArrow = UIImage(named: "IQButtonBarArrowRight", in: bundle, compatibleWith: nil)
}
//Support for RTL languages like Arabic, Persia etc... (Bug ID: #448)
if #available(iOS 9, *) {
imageLeftArrow = imageLeftArrow?.imageFlippedForRightToLeftLayoutDirection()
imageRightArrow = imageRightArrow?.imageFlippedForRightToLeftLayoutDirection()
}
var prev = toolbar.previousBarButton
if prev.isSystemItem == false {
prev.title = nil
prev.image = imageLeftArrow
prev.target = target
prev.action = previousAction
}
else
{
prev = IQBarButtonItem(image: imageLeftArrow, style: UIBarButtonItem.Style.plain, target: target, action: previousAction)
prev.invocation = toolbar.previousBarButton.invocation
prev.accessibilityLabel = toolbar.previousBarButton.accessibilityLabel
toolbar.previousBarButton = prev
}
var next = toolbar.nextBarButton
if next.isSystemItem == false {
next.title = nil
next.image = imageRightArrow
next.target = target
next.action = nextAction
}
else
{
next = IQBarButtonItem(image: imageRightArrow, style: UIBarButtonItem.Style.plain, target: target, action: nextAction)
next.invocation = toolbar.nextBarButton.invocation
next.accessibilityLabel = toolbar.nextBarButton.accessibilityLabel
toolbar.nextBarButton = next
}
//Previous button
items.append(prev)
//Fixed space
let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: nil, action: nil)
fixed.isSystemItem = true
if #available(iOS 10, *) {
fixed.width = 6
} else {
fixed.width = 20
}
items.append(fixed)
//Next button
items.append(next)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Title button
toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText
if #available(iOS 11, *) {
} else {
toolbar.titleBarButton.customView?.frame = CGRect.zero;
}
items.append(toolbar.titleBarButton)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Right button
var doneButton = toolbar.doneBarButton
if doneButton.isSystemItem == false {
doneButton.title = nil
doneButton.image = rightButtonImage
doneButton.target = target
doneButton.action = rightButtonAction
}
else
{
doneButton = IQBarButtonItem(image: rightButtonImage, style: UIBarButtonItem.Style.done, target: target, action: rightButtonAction)
doneButton.invocation = toolbar.doneBarButton.invocation
doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel
toolbar.doneBarButton = doneButton
}
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
}
}
}
// /**
// Helper function to add ArrowNextPrevious and Right button on keyboard.
//
// @param target Target object for selector.
// @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
// @param previousAction Previous button action name. Usually 'previousAction:(id)item'.
// @param nextAction Next button action name. Usually 'nextAction:(id)item'.
// @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'.
// @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
// */
public func addPreviousNextRightOnKeyboardWithTarget( _ target : AnyObject?, rightButtonImage : UIImage, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, shouldShowPlaceholder : Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingToolbarPlaceholder
}
addPreviousNextRightOnKeyboardWithTarget(target, rightButtonImage: rightButtonImage, previousAction: previousAction, nextAction: nextAction, rightButtonAction: rightButtonAction, titleText: title)
}
/**
Helper function to add ArrowNextPrevious and Right button on keyboard.
@param target Target object for selector.
@param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
@param previousAction Previous button action name. Usually 'previousAction:(id)item'.
@param nextAction Next button action name. Usually 'nextAction:(id)item'.
@param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'.
*/
public func addPreviousNextRightOnKeyboardWithTarget( _ target : AnyObject?, rightButtonTitle : String, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector) {
addPreviousNextRightOnKeyboardWithTarget(target, rightButtonTitle: rightButtonTitle, previousAction: previousAction, nextAction: nextAction, rightButtonAction: rightButtonAction, titleText: nil)
}
/**
Helper function to add ArrowNextPrevious and Right button on keyboard.
@param target Target object for selector.
@param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
@param previousAction Previous button action name. Usually 'previousAction:(id)item'.
@param nextAction Next button action name. Usually 'nextAction:(id)item'.
@param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'.
@param titleText text to show as title in IQToolbar'.
*/
public func addPreviousNextRightOnKeyboardWithTarget( _ target : AnyObject?, rightButtonTitle : String, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, titleText : String?) {
//If can't set InputAccessoryView. Then return
if self.responds(to: #selector(setter: UITextField.inputAccessoryView)) {
// Creating a toolBar for phoneNumber keyboard
let toolbar = self.keyboardToolbar
var items : [IQBarButtonItem] = []
// Get the top level "bundle" which may actually be the framework
var bundle = Bundle(for: IQKeyboardManager.self)
if let resourcePath = bundle.path(forResource: "IQKeyboardManager", ofType: "bundle") {
if let resourcesBundle = Bundle(path: resourcePath) {
bundle = resourcesBundle
}
}
var imageLeftArrow : UIImage!
var imageRightArrow : UIImage!
if #available(iOS 10, *) {
imageLeftArrow = UIImage(named: "IQButtonBarArrowUp", in: bundle, compatibleWith: nil)
imageRightArrow = UIImage(named: "IQButtonBarArrowDown", in: bundle, compatibleWith: nil)
} else {
imageLeftArrow = UIImage(named: "IQButtonBarArrowLeft", in: bundle, compatibleWith: nil)
imageRightArrow = UIImage(named: "IQButtonBarArrowRight", in: bundle, compatibleWith: nil)
}
//Support for RTL languages like Arabic, Persia etc... (Bug ID: #448)
if #available(iOS 9, *) {
imageLeftArrow = imageLeftArrow?.imageFlippedForRightToLeftLayoutDirection()
imageRightArrow = imageRightArrow?.imageFlippedForRightToLeftLayoutDirection()
}
var prev = toolbar.previousBarButton
if prev.isSystemItem == false {
prev.title = nil
prev.image = imageLeftArrow
prev.target = target
prev.action = previousAction
}
else
{
prev = IQBarButtonItem(image: imageLeftArrow, style: UIBarButtonItem.Style.plain, target: target, action: previousAction)
prev.invocation = toolbar.previousBarButton.invocation
prev.accessibilityLabel = toolbar.previousBarButton.accessibilityLabel
toolbar.previousBarButton = prev
}
var next = toolbar.nextBarButton
if next.isSystemItem == false {
next.title = nil
next.image = imageRightArrow
next.target = target
next.action = nextAction
}
else
{
next = IQBarButtonItem(image: imageRightArrow, style: UIBarButtonItem.Style.plain, target: target, action: nextAction)
next.invocation = toolbar.nextBarButton.invocation
next.accessibilityLabel = toolbar.nextBarButton.accessibilityLabel
toolbar.nextBarButton = next
}
//Previous button
items.append(prev)
//Fixed space
let fixed = IQBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.fixedSpace, target: nil, action: nil)
fixed.isSystemItem = true
if #available(iOS 10, *) {
fixed.width = 6
} else {
fixed.width = 20
}
items.append(fixed)
//Next button
items.append(next)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Title button
toolbar.titleBarButton.title = shouldHideToolbarPlaceholder == true ? nil : titleText
if #available(iOS 11, *) {
} else {
toolbar.titleBarButton.customView?.frame = CGRect.zero;
}
items.append(toolbar.titleBarButton)
//Flexible space
items.append(UIView.flexibleBarButtonItem())
//Right button
var doneButton = toolbar.doneBarButton
if doneButton.isSystemItem == false {
doneButton.title = rightButtonTitle
doneButton.image = nil
doneButton.target = target
doneButton.action = rightButtonAction
}
else
{
doneButton = IQBarButtonItem(title: rightButtonTitle, style: UIBarButtonItem.Style.done, target: target, action: rightButtonAction)
doneButton.invocation = toolbar.doneBarButton.invocation
doneButton.accessibilityLabel = toolbar.doneBarButton.accessibilityLabel
toolbar.doneBarButton = doneButton
}
items.append(doneButton)
// Adding button to toolBar.
toolbar.items = items
// Setting toolbar to keyboard.
if let textField = self as? UITextField {
textField.inputAccessoryView = toolbar
switch textField.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
} else if let textView = self as? UITextView {
textView.inputAccessoryView = toolbar
switch textView.keyboardAppearance {
case UIKeyboardAppearance.dark:
toolbar.barStyle = UIBarStyle.black
default:
toolbar.barStyle = UIBarStyle.default
}
}
}
}
// /**
// Helper function to add ArrowNextPrevious and Right button on keyboard.
//
// @param target Target object for selector.
// @param rightButtonTitle Title for rightBarButtonItem, usually 'Done'.
// @param previousAction Previous button action name. Usually 'previousAction:(id)item'.
// @param nextAction Next button action name. Usually 'nextAction:(id)item'.
// @param rightButtonAction RightBarButton action name. Usually 'doneAction:(IQBarButtonItem*)item'.
// @param shouldShowPlaceholder A boolean to indicate whether to show textField placeholder on IQToolbar'.
// */
public func addPreviousNextRightOnKeyboardWithTarget( _ target : AnyObject?, rightButtonTitle : String, previousAction : Selector, nextAction : Selector, rightButtonAction : Selector, shouldShowPlaceholder : Bool) {
var title : String?
if shouldShowPlaceholder == true {
title = self.drawingToolbarPlaceholder
}
addPreviousNextRightOnKeyboardWithTarget(target, rightButtonTitle: rightButtonTitle, previousAction: previousAction, nextAction: nextAction, rightButtonAction: rightButtonAction, titleText: title)
}
///-----------------------------------
/// MARK: Enable/Disable Previous/Next
///-----------------------------------
/**
Helper function to enable and disable previous next buttons.
@param isPreviousEnabled BOOL to enable/disable previous button on keyboard.
@param isNextEnabled BOOL to enable/disable next button on keyboard..
*/
public func setEnablePrevious ( _ isPreviousEnabled : Bool, isNextEnabled : Bool) {
// Getting inputAccessoryView.
if let inputAccessoryView = self.inputAccessoryView as? IQToolbar {
// If it is IQToolbar and it's items are greater than zero.
if inputAccessoryView.items?.count > 3 {
if let items = inputAccessoryView.items {
if let prevButton = items[0] as? IQBarButtonItem {
if let nextButton = items[2] as? IQBarButtonItem {
if prevButton.isEnabled != isPreviousEnabled {
prevButton.isEnabled = isPreviousEnabled
}
if nextButton.isEnabled != isNextEnabled {
nextButton.isEnabled = isNextEnabled
}
}
}
}
}
}
}
}
|
apache-2.0
|
917b5e791a46d5135889bb1d3b590515
| 40.287946 | 220 | 0.596205 | 6.101264 | false | false | false | false |
xcodeswift/xcproj
|
Tests/XcodeProjTests/Objects/BuildPhase/PBXBuildPhaseTests.swift
|
1
|
1454
|
import Foundation
import XCTest
@testable import XcodeProj
final class PBXBuildPhaseTests: XCTestCase {
var subject: PBXBuildPhase!
var proj: PBXProj!
override func setUp() {
super.setUp()
subject = PBXSourcesBuildPhase()
proj = PBXProj.fixture()
proj.add(object: subject)
}
func test_add_files() throws {
let file = PBXFileElement(sourceTree: .absolute,
path: "path",
name: "name",
includeInIndex: false,
wrapsLines: true)
let buildFile = try subject.add(file: file)
XCTAssertEqual(subject.files?.contains(buildFile), true)
}
func test_add_files_only_once() throws {
let file = PBXFileElement(sourceTree: .absolute,
path: "path",
name: "name",
includeInIndex: false,
wrapsLines: true)
let buildFile = try subject.add(file: file)
let sameBuildFile = try subject.add(file: file)
XCTAssertEqual(buildFile, sameBuildFile, "Expected adding a file only once but it didn't")
let fileOccurrencesCount = subject.files?.filter { $0 == buildFile }.count
XCTAssertTrue(fileOccurrencesCount == 1, "Expected adding a file only once but it didn't")
}
}
|
mit
|
f71731f1f090ff4fa748bd56378f86ca
| 34.463415 | 98 | 0.547455 | 5.083916 | false | true | false | false |
LX314/GitHubApp
|
View/Repo/RepoInfoCell.swift
|
1
|
6883
|
//
// RepoInfoCell.swift
// MyGitHub
//
// Created by John LXThyme on 2017/3/29.
// Copyright © 2017年 John LXThyme. All rights reserved.
//
import UIKit
//class LXButton: UIButton {
// override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
// return CGRect(x: 5, y: 5, width: 30, height: 30)
// }
// override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
// return CGRect(x: 40, y: 5, width: 60, height: 40)
// }
//}
class RepoInfoCell: BaseCell {
lazy var label_name: UILabel = {
let label = UILabel()
label.frame = CGRect.zero
label.textColor = UIColor(fromHexString: "#0366D6")
label.font = UIFont.boldSystemFont(ofSize: 20)
return label
}()
lazy var label_description: UILabel = {
let label = UILabel()
label.frame = CGRect.zero
label.textColor = UIColor(fromHexString: "#586069")
label.font = UIFont.systemFont(ofSize: 18)
label.numberOfLines = 0
return label
}()
lazy var label_latestUpdate: UILabel = {
let label = UILabel()
label.frame = CGRect.zero
label.textColor = UIColor(fromHexString: "#586069")
label.font = UIFont.systemFont(ofSize: 14)
return label
}()
lazy var btn_language: LXButton = {
let lxbtn = LXButton(iconSize: CGSize(width: 20, height: 20))
lxbtn.btn.setTitleColor(UIColor(fromHexString: "#586069"), for: .normal)
lxbtn.btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
lxbtn.imgView.image = UIImage(named: "code.png")
return lxbtn
}()
lazy var btn_star: LXButton = {
let lxbtn = LXButton()
lxbtn.btn.setTitleColor(UIColor(fromHexString: "#586069"), for: .normal)
lxbtn.btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
lxbtn.imgView.image = UIImage(named: "heart.png")
return lxbtn
}()
lazy var btn_watch: LXButton = {
let lxbtn = LXButton()
lxbtn.btn.setTitleColor(UIColor(fromHexString: "#586069"), for: .normal)
lxbtn.btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
lxbtn.imgView.image = UIImage(named: "git-merge.png")
return lxbtn
}()
lazy var btn_fork: LXButton = {
let lxbtn = LXButton()
lxbtn.btn.setTitleColor(UIColor(fromHexString: "#586069"), for: .normal)
lxbtn.btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
lxbtn.imgView.image = UIImage(named: "eye.png")
return lxbtn
}()
lazy var btn_unstar: UIButton = {
let btn = UIButton(type: .roundedRect)
btn.setTitleColor(UIColor.black, for: .normal)
btn.setBackgroundImage(UIImage.image(with: UIColor.purple), for: .highlighted)
btn.setBackgroundImage(UIImage.image(with: UIColor.purple), for: .selected)
btn.layer.borderWidth = 1
btn.layer.borderColor = UIColor(fromHexString: "#cccccc").cgColor
btn.titleLabel?.font = UIFont.systemFont(ofSize: 20)
return btn
}()
override public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
initRepoInfoCell()
masonry()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
}
// MARK: - 填充数据
extension RepoInfoCell {
func resetCell(with item: [String: Any]) {
let full_name = item["full_name"] as! String
let description = item["description"] as? String
let stargazers_count = item["stargazers_count"] as! Int
let watchers_count = item["watchers_count"] as! Int
let language = item["language"] as? String
let forks_count = item["forks_count"] as! Int
let updated_at = item["updated_at"] as! String
label_name.text = full_name
label_description.text = description
label_latestUpdate.text = updated_at
btn_language.btn.setTitle(language, for: .normal)
btn_star.btn.setTitle("\(stargazers_count)", for: .normal)
btn_watch.btn.setTitle("\(watchers_count)", for: .normal)
btn_fork.btn.setTitle("\(forks_count)", for: .normal)
btn_unstar.setTitle("Unstar", for: .normal)
}
}
// MARK: - 初始化
extension RepoInfoCell {
func initRepoInfoCell() {
self.contentView.addSubview(label_name)
self.contentView.addSubview(label_description)
self.contentView.addSubview(label_latestUpdate)
self.contentView.addSubview(btn_language)
self.contentView.addSubview(btn_star)
self.contentView.addSubview(btn_watch)
self.contentView.addSubview(btn_fork)
// self.contentView.addSubview(btn_unstar)
self.contentView.backgroundColor = UIColor.clear
self.backgroundColor = UIColor.clear
// self.contentView.backgroundColor = UIColor(patternImage: UIImage(named: "bg-4.png")!)
}
func masonry() {
let padding = 20
self.label_name.snp.makeConstraints { (make) in
make.top.left.equalToSuperview().offset(20)
}
self.label_description.snp.makeConstraints { (make) in
make.top.equalTo(self.label_name.snp.bottom).offset(20)
make.left.equalToSuperview().offset(20)
// make.right.equalTo(self.btn_unstar.snp.left).offset(-20)
make.right.equalToSuperview().offset(-20)
make.bottom.equalTo(self.btn_star.snp.top).offset(-20)
}
self.btn_language.snp.makeConstraints { (make) in
make.left.equalToSuperview().offset(20)
make.bottom.equalToSuperview().offset(-20)
// make.size.equalTo(CGSize(width: 80, height: 35))
}
self.btn_star.snp.makeConstraints { (make) in
make.left.equalTo(self.btn_language.snp.right).offset(20)
make.bottom.equalToSuperview().offset(-20)
}
self.btn_watch.snp.makeConstraints { (make) in
make.left.equalTo(self.btn_star.snp.right).offset(20)
make.bottom.equalToSuperview().offset(-20)
}
self.btn_fork.snp.makeConstraints { (make) in
make.left.equalTo(self.btn_watch.snp.right).offset(padding)
make.bottom.equalToSuperview().offset(-padding)
}
self.label_latestUpdate.snp.makeConstraints { (make) in
make.top.equalToSuperview().offset(20)
make.right.equalToSuperview().offset(-20)
}
// self.btn_unstar.snp.makeConstraints { (make) in
// make.right.equalToSuperview().offset(-padding)
// make.centerY.equalToSuperview()
// make.size.equalTo(CGSize(width: 80, height: 40))
// }
}
}
|
mit
|
d59199d531fc4710b775a559ea1b8778
| 36.315217 | 95 | 0.627003 | 3.927918 | false | false | false | false |
snark/jumpcut
|
Jumpcut/Jumpcut/Bezel.swift
|
1
|
14940
|
//
// Bezel.swift
// Jumpcut
//
// Created by Steve Cook on 9/13/20.
//
import Cocoa
public struct BezelAppearance {
let bezelSize: CGSize
let outletSize: CGSize
let secondaryOutletSize: CGSize?
let windowAlpha: Double
let windowAttributes: AppearanceAttributes
let mainOutletAttributes: AppearanceAttributes
let secondaryOutletAttributes: AppearanceAttributes?
let outletFontColor: NSColor
}
public struct AppearanceAttributes {
let backgroundColor: NSColor
let borderWidth: Double
let borderColor: NSColor
let cornerRadius: Double
}
public class Bezel {
let window: KeyCaptureWindow
var shown: Bool = false
private var hasBeenOpened = false
fileprivate var mainOutlet: Outlet
fileprivate var secondaryOutlet: Outlet? // Used for display of stack number
// TODO: Add controls for positioning on window -- NB, not part of BezelAppearance
// -- Center, Top Left, Top Right, Top Center, Bottom Center
// TODO: Add controls for positioning main outlet, secondary outlet
// TODO: Add controls for changing the appearance
static let defaultAppearance = BezelAppearance(
bezelSize: CGSize(width: 325, height: 325),
outletSize: CGSize(width: 300, height: 200),
secondaryOutletSize: CGSize(width: 36, height: 30),
windowAlpha: 0.8,
windowAttributes: AppearanceAttributes(
backgroundColor: NSColor.init(calibratedWhite: 0.1, alpha: 0.6),
borderWidth: 0.0,
borderColor: .clear,
cornerRadius: 25.0
),
mainOutletAttributes: AppearanceAttributes(
backgroundColor: NSColor.init(calibratedWhite: 0.1, alpha: 0.9),
borderWidth: 1.0,
borderColor: .black,
cornerRadius: 12.0
),
secondaryOutletAttributes: AppearanceAttributes(
backgroundColor: NSColor.init(calibratedWhite: 0.1, alpha: 0.9),
borderWidth: 1.0,
borderColor: .black,
cornerRadius: 12.0
),
outletFontColor: .white
)
fileprivate static func makeOutlet(size: CGSize, attributes: AppearanceAttributes) -> Outlet {
return Outlet(
width: size.width,
height: size.height,
backgroundColor: attributes.backgroundColor,
cornerRadius: attributes.cornerRadius,
borderWidth: attributes.borderWidth,
borderColor: attributes.borderColor
)
}
public init() {
let appearance = Bezel.defaultAppearance
window = KeyCaptureWindow(contentRect: NSRect(origin: .zero, size: appearance.bezelSize),
styleMask: .borderless, backing: .buffered, defer: true)
mainOutlet = Bezel.makeOutlet(size: appearance.outletSize, attributes: appearance.mainOutletAttributes)
if let secondarySize = appearance.secondaryOutletSize {
var outletAttributes: AppearanceAttributes
if appearance.secondaryOutletAttributes != nil {
outletAttributes = appearance.secondaryOutletAttributes!
} else {
outletAttributes = appearance.mainOutletAttributes
}
secondaryOutlet = Bezel.makeOutlet(size: secondarySize, attributes: outletAttributes)
} else {
secondaryOutlet = nil
}
buildWindow(
windowAlpha: appearance.windowAlpha,
windowBackgroundColor: appearance.windowAttributes.backgroundColor,
windowCornerRadius: appearance.windowAttributes.cornerRadius
)
window.contentView!.addSubview(mainOutlet.embedderView)
if secondaryOutlet != nil {
window.contentView!.addSubview(secondaryOutlet!.embedderView)
}
var constraints = [
mainOutlet.embedderView.widthAnchor.constraint(equalToConstant: appearance.outletSize.width),
mainOutlet.embedderView.heightAnchor.constraint(equalToConstant: appearance.outletSize.height),
mainOutlet.embedderView.centerXAnchor.constraint(equalTo: window.contentView!.centerXAnchor),
mainOutlet.embedderView.bottomAnchor.constraint(equalTo: window.contentView!.bottomAnchor, constant: -10)
]
if secondaryOutlet != nil {
constraints.append(
secondaryOutlet!.embedderView.widthAnchor.constraint(
equalToConstant: appearance.secondaryOutletSize!.width
)
)
constraints.append(
secondaryOutlet!.embedderView.heightAnchor.constraint(
equalToConstant: appearance.secondaryOutletSize!.height
)
)
constraints.append(
secondaryOutlet!.embedderView.centerXAnchor.constraint(
equalTo: window.contentView!.centerXAnchor
)
)
constraints.append(
secondaryOutlet!.embedderView.bottomAnchor.constraint(
equalTo: mainOutlet.embedderView.topAnchor, constant: -10
)
)
}
NSLayoutConstraint.activate(constraints)
}
public func shouldSelectionPaste() -> Bool {
// Unlike the menu manager version, there's no toggling.
let paste =
UserDefaults.standard.value(forKey: SettingsPath.bezelSelectionPastes.rawValue) as? Bool ?? false
return paste
}
public func setKeyDownHandler(handler: @escaping (NSEvent) -> Void) {
window.keyDownHandler = handler
}
public func setMetaKeyReleaseHandler(handler: @escaping () -> Void) {
window.metaKeyReleaseHandler = handler
}
public func setText(text: String) {
mainOutlet.setText(text: text)
}
public func setSecondaryText(text: String) {
secondaryOutlet?.setText(text: text, align: .center)
}
public func setWindowSize(size: CGSize) {
var newFrame = window.frame
newFrame.size.height = size.height
newFrame.size.width = size.width
window.setFrame(newFrame, display: true)
}
func buildWindow(
windowAlpha: Double,
windowBackgroundColor: NSColor,
windowCornerRadius: Double
) {
// Not under caller's control
window.backgroundColor = .clear
window.hasShadow = false
window.hidesOnDeactivate = true
window.isOpaque = false
window.level = .modalPanel
window.titleVisibility = .hidden
window.titlebarAppearsTransparent = true
window.alphaValue = CGFloat(windowAlpha)
let contentView = NSView(frame: self.window.frame)
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.wantsLayer = true
contentView.layer!.cornerRadius = CGFloat(windowCornerRadius)
contentView.layer!.masksToBounds = true
contentView.layer!.backgroundColor = windowBackgroundColor.cgColor
// let effectView = NSVisualEffectView(frame: self.window.frame)
// effectView.translatesAutoresizingMaskIntoConstraints = false
// // Could also be ".popover" for a lighter appearance
// effectView.material = .dark
// effectView.state = .active
// effectView.translatesAutoresizingMaskIntoConstraints = false
//
// contentView.addSubview(effectView)
self.window.collectionBehavior = NSWindow.CollectionBehavior.canJoinAllSpaces
self.window.collectionBehavior = NSWindow.CollectionBehavior.moveToActiveSpace
self.window.contentView = contentView
}
public func hide() {
window.orderOut(nil)
shown = false
}
public func show() {
// Position the bezel on the screen currently accepting
// keyboard input, not "the first screen where it appeared";
// if we don't do this every time, changing the display
// setup leads to bad behavior.
//
// Relatedly there's strange behavior the first time we display, if
// we're trying to display to a secondary screen, where it just...
// doesn't appear. (And AFAICT continues to not appear until you switch
// mainScreen to screen 0.) So we'll accept a mild inconvenience (a check
// against a boolean, and a possible flash of the bezel) to deal with this.
// For tracking down purposes of the bug, it seems to be caused by the
// center call occuring before the window has been shown makeKeyAndOrderFront;
// commenting out window.center() solves the issue while obviously introducing
// its own problems.
if let mainScreen = NSScreen.main {
if !hasBeenOpened && mainScreen != NSScreen.screens[0] {
window.makeKeyAndOrderFront(self)
}
window.setFrameOrigin(mainScreen.visibleFrame.origin)
}
window.center()
window.makeKeyAndOrderFront(self)
shown = true
hasBeenOpened = true
}
}
private struct OutletFontConfig {
let color: NSColor
let size: Int
let monospaced: Bool
}
class EscapeView: NSView {
// ^-ESC doesn't naturally trigger a keyDown event; it's bound
// to cancelOperation by the default NSResponder. We may need
// to do something similar someday to avoid the Command-. binding.
override func performKeyEquivalent(with event: NSEvent) -> Bool {
switch Int(event.keyCode) {
// escape
case 53:
super.keyDown(with: event)
return true
default:
return super.performKeyEquivalent(with: event)
}
}
}
private class Outlet {
let embedderView: NSView
let textView: NSTextView
var fontConfig: OutletFontConfig
public init(
width: CGFloat,
height: CGFloat,
backgroundColor: NSColor,
cornerRadius: Double,
borderWidth: Double,
borderColor: NSColor,
fontSize: Int = 14,
fontColor: NSColor = .white
) {
let embedderRect = NSRect(x: 0, y: 0, width: width, height: height)
embedderView = EscapeView(frame: embedderRect)
textView = NSTextView(
frame: NSRect(
x: 2, y: 1, width: embedderRect.size.width - 4, height: embedderRect.size.height - 2
)
)
textView.isEditable = false
textView.isSelectable = false
// This is critical to preventing partial lines from displaying
textView.textContainer!.lineBreakMode = .byClipping
textView.backgroundColor = backgroundColor
textView.translatesAutoresizingMaskIntoConstraints = false
textView.textContainerInset = NSSize(width: 1, height: 1)
embedderView.translatesAutoresizingMaskIntoConstraints = false
embedderView.wantsLayer = true
embedderView.layer?.borderColor = borderColor.cgColor
embedderView.layer?.borderWidth = CGFloat(borderWidth)
embedderView.layer?.cornerRadius = CGFloat(cornerRadius)
embedderView.addSubview(textView)
NSLayoutConstraint.activate([
textView.widthAnchor.constraint(equalTo: embedderView.widthAnchor, constant: -2),
textView.heightAnchor.constraint(equalTo: embedderView.heightAnchor, constant: -2),
textView.centerXAnchor.constraint(equalTo: embedderView.centerXAnchor),
textView.centerYAnchor.constraint(equalTo: embedderView.centerYAnchor)
])
fontConfig = OutletFontConfig(
color: fontColor,
size: fontSize,
monospaced: false
)
}
public func setText(text: String) {
self.setText(text: text, align: nil)
}
public func setText(text: String, align: BezelAlignment?) {
// swiftlint:disable:next line_length
// Monospacing: https://stackoverflow.com/questions/46642335/how-do-i-get-a-monospace-font-that-respects-acessibility-settings
let paragraph = NSMutableParagraphStyle()
var useAlign = align
paragraph.lineSpacing = 1.2
if useAlign == nil {
let pref = UserDefaults.standard.object(forKey: SettingsPath.bezelAlignment.rawValue) as? String
useAlign = BezelAlignment(rawValue: pref ?? BezelAlignment.center.rawValue) ?? BezelAlignment.center
}
switch useAlign {
case .smartAlign:
if text.count > 100 || text.contains(where: { $0.isNewline }) {
paragraph.alignment = .left
} else {
paragraph.alignment = .center
}
case .left:
paragraph.alignment = .left
case .right:
paragraph.alignment = .right
default:
paragraph.alignment = .center
}
// We could set it to center here.
let font: NSFont
if fontConfig.monospaced {
// NB: We only have access to SF Mono/monospacedSystemFont in 10.15 or later.
if #available(OSX 10.15, *) {
// SF Mono looks significantly better than Courier New.
font = NSFont.monospacedSystemFont(ofSize: CGFloat(fontConfig.size), weight: NSFont.Weight.medium)
} else {
font = NSFont(name: "Courier New", size: CGFloat(fontConfig.size))!
}
} else {
font = NSFont.systemFont(ofSize: CGFloat(fontConfig.size))
}
let attributes: [NSAttributedString.Key: Any] = [
.font: font,
.foregroundColor: fontConfig.color,
.paragraphStyle: paragraph
]
let attrString = NSAttributedString(string: text, attributes: attributes)
textView.textStorage?.setAttributedString(attrString)
}
}
class KeyCaptureWindow: NSWindow {
override var acceptsFirstResponder: Bool { return true }
override var canBecomeKey: Bool { return true }
override var canBecomeMain: Bool { return true }
fileprivate var metaKeyReleaseHandler: (() -> Void)?
fileprivate var keyDownHandler: ((NSEvent) -> Void)?
override func keyDown(with event: NSEvent) {
// We will not pass through keyDown events while the bezel is active.
// super.keyDown(with: event)
if let keyDown = keyDownHandler {
keyDown(event)
}
}
override func cancelOperation(_ sender: Any?) {
return
}
override func flagsChanged(with event: NSEvent) {
if !event.modifierFlags.contains(.option) &&
!event.modifierFlags.contains(.command) &&
!event.modifierFlags.contains(.control) &&
!event.modifierFlags.contains(.shift) {
if let keyRelease = metaKeyReleaseHandler {
keyRelease()
}
}
super.flagsChanged(with: event)
}
}
|
mit
|
bd2c556690e825cc6049f9bbdea5f77f
| 36.822785 | 134 | 0.637952 | 5.037087 | false | false | false | false |
gabrielb82/ios_google_places_autocomplete
|
GooglePlacesAutocompleteExample/GooglePlacesAutocompleteExampleTests/GooglePlacesAutocompleteExampleTests.swift
|
4
|
3054
|
//
// GooglePlacesAutocompleteExampleTests.swift
// GooglePlacesAutocompleteExampleTests
//
// Created by Howard Wilson on 15/02/2015.
// Copyright (c) 2015 Howard Wilson. All rights reserved.
//
import Foundation
import UIKit
import XCTest
import GooglePlacesAutocomplete
class GooglePlacesAutocompleteTests: FBSnapshotTestCase, GooglePlacesAutocompleteDelegate {
let gpaViewController = GooglePlacesAutocomplete(apiKey: "APIKEY")
var expectation: XCTestExpectation!
func testGooglePlacesAutocomplete() {
let json: [String : AnyObject] = ["predictions" : [prediction1, prediction2]]
expectation = self.expectationWithDescription("Should return results")
OHHTTPStubs.stubRequestsPassingTest({ (request: NSURLRequest!) -> Bool in
return request.URL!.absoluteString == "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=Paris&key=APIKEY&types="
}, withStubResponse: { (request: NSURLRequest!) -> OHHTTPStubsResponse in
return OHHTTPStubsResponse(JSONObject: json, statusCode: 200, headers: nil)
})
self.gpaViewController.placeDelegate = self
UIApplication.sharedApplication().keyWindow!.rootViewController = UIViewController()
let rootVC = UIApplication.sharedApplication().keyWindow!.rootViewController!
rootVC.presentViewController(self.gpaViewController, animated: false, completion: {
self.snapshotVerifyView(self.gpaViewController.view, withIdentifier: "view")
self.gpaViewController.gpaViewController.searchBar(
self.gpaViewController.gpaViewController.searchBar,
textDidChange: "Paris"
)
})
self.waitForExpectationsWithTimeout(2.0, handler: nil)
}
func placesFound(places: [Place]) {
self.snapshotVerifyView(self.gpaViewController.view, withIdentifier: "search")
expectation.fulfill()
}
let prediction1: [String : AnyObject] = [
"description" : "Paris, France",
"id" : "691b237b0322f28988f3ce03e321ff72a12167fd",
"matched_substrings" : [
["length" : 5, "offset" : 0]
],
"place_id" : "ChIJD7fiBh9u5kcRYJSMaMOCCwQ",
"reference" : "CjQlAAAAbHAcwNAV9grGOKRGKz0czmHc_KsFufZ90X7ZhD0aPhWpyTb8-BQqe0GwWGDdGYzbEhBhFHGRSW6t6U8do2RzgUe0GhRZivpe7tNn7ujO7sWz6Vkv9CNyXg",
"terms" : [
["offset" : 0, "value" : "Paris"],
["offset" : 7, "value" : "France"]
],
"types" : [ "locality", "political", "geocode" ]
]
let prediction2: [String : AnyObject] = [
"description" : "Paris 17, Paris, France",
"id" : "126ccd7b36db3990466ee234998f25ab92ce88ac",
"matched_substrings" : [
["length" : 5, "offset" : 0]
],
"place_id" : "ChIJVRQP1aJv5kcRUBuUaMOCCwU",
"reference" : "CjQvAAAAR0bndCO53tJbbUDTclTXN6rgKRDEqCmsoYCDq5qpHCnOnhhrtyXmFSwWx-zVvWi0EhD6G6PPrJTOQEazhy5-JFhVGhRND1R7Or4V3lDaHkBcXt98X8u5mw",
"terms" : [
["offset" : 0, "value" : "Paris 17"],
["offset" : 10, "value" : "Paris"],
["offset" : 17, "value" : "France"]
],
"types" : [ "sublocality_level_1", "sublocality", "political", "geocode" ]
]
}
|
mit
|
8efadf4ecb48fa7d1d980e518f4724fe
| 36.703704 | 147 | 0.710216 | 3.510345 | false | true | false | false |
bencochran/LLVM.swift
|
LLVM/Function.swift
|
1
|
3024
|
//
// Created by Ben Cochran on 11/13/15.
// Copyright © 2015 Ben Cochran. All rights reserved.
//
public struct Function : ConstantType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
public init(name: String, type: FunctionType, inModule module: Module) {
ref = LLVMAddFunction(module.ref, name, type.ref)
}
public var intrinsicID: UInt32 {
return LLVMGetIntrinsicID(ref)
}
public var callConv: LLVMCallConv {
get {
return LLVMCallConv(rawValue: LLVMGetFunctionCallConv(ref))
}
set {
LLVMSetFunctionCallConv(ref, callConv.rawValue)
}
}
public var attributes: LLVMAttribute {
return LLVMGetFunctionAttr(ref)
}
// TODO: Roll add/remove into a setter on `attributes`
public func addAttribute(attribute: LLVMAttribute) {
LLVMAddFunctionAttr(ref, attribute)
}
public func removeAttribute(attribute: LLVMAttribute) {
LLVMRemoveFunctionAttr(ref, attribute)
}
public var paramCount: UInt32 {
return LLVMCountParams(ref)
}
public var params: [Argument] {
let count = Int(paramCount)
let refs = UnsafeMutablePointer<LLVMValueRef>.alloc(count)
defer { refs.dealloc(count) }
LLVMGetParams(ref, refs)
return UnsafeMutableBufferPointer(start: refs, count: count).map(Argument.init)
}
public func paramAtIndex(index: UInt32) -> Argument {
return Argument(ref: LLVMGetParam(ref, index))
}
public var basicBlockCount: UInt32 {
return LLVMCountBasicBlocks(ref)
}
public var basicBlocks: [BasicBlock] {
let count = Int(paramCount)
let refs = UnsafeMutablePointer<LLVMBasicBlockRef>.alloc(count)
defer { refs.dealloc(count) }
LLVMGetBasicBlocks(ref, refs)
return UnsafeMutableBufferPointer(start: refs, count: count).map(BasicBlock.init)
}
public var entry: BasicBlock {
return BasicBlock(ref: LLVMGetEntryBasicBlock(ref))
}
public func appendBasicBlock(name: String, context: Context) -> BasicBlock {
return BasicBlock(ref: LLVMAppendBasicBlockInContext(context.ref, ref, name))
}
// true = valid, false = invalid (opposite of LLVM’s whacky status)
public func verify() -> Bool {
return LLVMVerifyFunction(ref, LLVMReturnStatusAction) == 0
}
}
public struct Argument : ValueType {
public let ref: LLVMValueRef
public init(ref: LLVMValueRef) {
self.ref = ref
}
public var attributes: LLVMAttribute {
return LLVMGetFunctionAttr(ref)
}
// TODO: Roll add/remove into a setter on `attributes`
public func addAttribute(attribute: LLVMAttribute) {
LLVMAddFunctionAttr(ref, attribute)
}
public func removeAttribute(attribute: LLVMAttribute) {
LLVMRemoveFunctionAttr(ref, attribute)
}
}
|
mit
|
3a5079ea625b1c8a60c96a0856f930e7
| 28.048077 | 89 | 0.645482 | 4.359307 | false | false | false | false |
fespinoza/linked-ideas-osx
|
LinkedIdeas-iOS/AppDelegate.swift
|
1
|
1768
|
//
// AppDelegate.swift
// LinkedIdeas-iOS
//
// Created by Felipe Espinoza on 20/01/2018.
// Copyright © 2018 Felipe Espinoza Dev. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(
_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?
) -> Bool {
let window = UIWindow(frame: UIScreen.main.bounds)
let documentBrowserVC = DocumentBrowserViewController()
documentBrowserVC.view.frame = window.frame
let mainNavigationController = UINavigationController(rootViewController: documentBrowserVC)
mainNavigationController.isNavigationBarHidden = true
window.rootViewController = mainNavigationController
window.makeKeyAndVisible()
self.window = window
return true
}
func application(
_ app: UIApplication, open inputURL: URL, options: [UIApplicationOpenURLOptionsKey: Any] = [:]
) -> Bool {
// Ensure the URL is a file URL
guard inputURL.isFileURL else { return false }
// Reveal / import the document at the URL
guard let documentBrowserViewController = window?.rootViewController as? DocumentBrowserViewController else {
return false
}
documentBrowserViewController.revealDocument(at: inputURL, importIfNeeded: true) { (revealedDocumentURL, error) in
if let error = error {
// Handle the error appropriately
print("Failed to reveal the document at URL \(inputURL) with error: '\(error)'")
return
}
// Present the Document View Controller for the revealed URL
documentBrowserViewController.presentDocument(at: revealedDocumentURL!)
}
return true
}
}
|
mit
|
ec815b72001997c1cef7e4689613c211
| 30 | 118 | 0.729485 | 5.151603 | false | false | false | false |
tkersey/top
|
top/ViewModel.swift
|
1
|
1713
|
import Foundation
class ViewModel {
private var after: String? { return rows.last?.after }
private var loading = false
private var rows = [Row]()
private var rowsPlistURL: URL? {
return FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first?.appendingPathComponent("rows.plist")
}
private let service = Service()
private let subreddit = "science"
}
// MARK: - Source
extension ViewModel {
func load(_ after: String? = nil, reset: Bool = false, completion: @escaping () -> Void) {
loading = true
service.get(forSubreddit: subreddit, after: after) { [weak self] posts in
reset ? self?.rows = posts : self?.rows.append(contentsOf: posts)
DispatchQueue.main.async {
completion()
self?.loading = false
}
}
}
func update(completion: @escaping () -> Void) {
if !loading, let after = after {
load(after, completion: completion)
}
}
}
// MARK: - Rows
extension ViewModel {
var rowCount: Int {
return rows.count
}
func row(forIndexPath indexPath: IndexPath) -> Row {
return rows[indexPath.item]
}
}
// MARK: - State restoration
extension ViewModel {
func encodeRows() {
if let data = try? PropertyListEncoder().encode(rows), let url = rowsPlistURL {
try? data.write(to: url)
}
}
func decodeRows() {
if let url = rowsPlistURL, let data = try? Data(contentsOf: url), let rows = try? PropertyListDecoder().decode([Row].self, from: data) {
self.rows = rows
try? FileManager.default.removeItem(at: url)
}
}
}
|
mit
|
cf31b6602cdc2866cca68435e6c60cb6
| 27.081967 | 144 | 0.595447 | 4.25062 | false | false | false | false |
LittleRockInGitHub/LLRegex
|
Project/LLRegex/Playground.swift
|
1
|
3156
|
//
// Playground.swift
// LLRegex
//
// Created by Rock Yang on 2017/6/10.
// Copyright © 2017年 Rock Young. All rights reserved.
//
import Foundation
let numbers = Regex("(\\d)(\\d+)(\\d)")
let insensitive = Regex("LLRegex", options: [.caseInsensitive])
let runtimeError = Regex("") // Runtime error would be raised
let invalid = try? Regex(pattern: "") // nil returned
let s = "123-45-6789-0-123-45-6789-01234"
let subrange = s.characters.dropFirst(3).startIndex..<s.endIndex
struct Playground {
public func search() {
for match in numbers.matches(in: s) {
// enumerating
}
if let first = numbers.matches(in: s).first {
// first match
}
let allMatches: [Match] = numbers.matches(in: s).all // all matches
let subrangeMatches = numbers.matches(in: s, options: [.withTransparentBounds], range: subrange)
for case let match in subrangeMatches.dropFirst(1) where match.matched != "45" {
}
}
public func match() {
if let first = numbers.matches(in: s).first {
first.matched
first.range
first.groups.count
first.groups[1].matched
first.groups[1].range
let replacement = first.replacement(withTemplate: "$3$2$1")
}
}
public func namedCaptureGroups() {
let named = Regex("(?<year>\\d+)-(?<month>\\d+)-(?<day>\\d+)", options: .namedCaptureGroups)
let s = "Today is 2017-06-23."
for m in named.matches(in: s) {
m.groups["year"]?.matched
}
named.replacingAllMatches(in: s, replacement: .replaceWithTemplate("${month}/${day}/${year}"))
}
public func replace() {
numbers.replacingFirstMatch(in: s, replacement: .remove)
numbers.replacingAllMatches(in: s, range: subrange, replacement: .replaceWithTemplate("$3$2$1"))
numbers.replacingMatches(in: s) { (idx, match) -> Match.Replacing in
switch idx {
case 0:
return .keep // Keep unchanged
case 1:
return .remove // Remove the matched string
case 2:
return .replaceWithTemplate("$1-$3") // Replace with template
case 3:
return .replaceWithString({
return String(match.matched.characters.reversed()) // Relace with string
}())
default:
return .stop // Stop replacing
}
}
}
public func string() {
"123".isMatching("\\d+")
"llregex".isMatching(insensitive)
"123-456".isMatching("\\d+")
"123".replacingAll("1", with: "!")
"123".replacingAll(pattern: "(\\d)(\\d)", withTemplate: "$2$1")
"123".replacingFirst(pattern: numbers, in: subrange, withTemplate: "!")
s.split(seperator: "\\d")
}
}
|
mit
|
32f510a1a01844f08e33eb465c39eaef
| 27.151786 | 104 | 0.518237 | 4.403631 | false | false | false | false |
sonsongithub/UZImageCollection
|
UZImageCollection/ImageCollectionViewController.swift
|
1
|
11308
|
//
// ImageCollectionViewController.swift
// UZImageCollectionView
//
// Created by sonson on 2015/06/05.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
func imageViewFrame(destinationImageViewFrame:CGRect, imageSize:CGSize, contentMode:UIViewContentMode) -> CGRect {
var scaleToFitImageOverContainerView:CGFloat = 1.0 /**< アニメーションさせるビューを画面全体に引き伸ばすための比.アニメーションさせるビューの最終フレームサイズを決めるために使う. */
if destinationImageViewFrame.size.width / destinationImageViewFrame.size.height < imageSize.width / imageSize.height {
scaleToFitImageOverContainerView = destinationImageViewFrame.size.width / imageSize.width;
}
else {
scaleToFitImageOverContainerView = destinationImageViewFrame.size.height / imageSize.height;
}
var endFrame = CGRectMake(0, 0, imageSize.width * scaleToFitImageOverContainerView, imageSize.height * scaleToFitImageOverContainerView);
endFrame.origin.x = (destinationImageViewFrame.size.width - endFrame.size.width)/2
endFrame.origin.y = (destinationImageViewFrame.size.height - endFrame.size.height)/2
return endFrame
}
public class ImageCollectionViewController : UICollectionViewController, UICollectionViewDelegateFlowLayout {
var cellSize:CGFloat = 0
let collection:ImageCollection
var animatingImageView:UIImageView? = nil
var animatingBackgroundView:UIView? = nil
var currentFocusedPath:NSIndexPath = NSIndexPath(forItem: 0, inSection: 0)
func numberOfItemsInLine() -> Int {
return 3
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
init(collection:ImageCollection) {
self.collection = collection
let layout = UICollectionViewFlowLayout()
layout.scrollDirection = UICollectionViewScrollDirection.Vertical
layout.minimumLineSpacing = 0
super.init(collectionViewLayout: layout)
}
public required init?(coder aDecoder: NSCoder) {
self.collection = ImageCollection(newList: [])
super.init(coder: aDecoder)
}
public class func controller(URLList:[NSURL]) -> ImageCollectionViewController {
let collection = ImageCollection(newList: URLList)
let vc = ImageCollectionViewController(collection:collection)
return vc
}
public class func controllerInNavigationController(URLList:[NSURL]) -> UINavigationController {
let collection = ImageCollection(newList: URLList)
let vc = ImageCollectionViewController(collection:collection)
let nav = UINavigationController(rootViewController: vc)
return nav
}
public override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.registerClass(ImageCollectionViewCell.self, forCellWithReuseIdentifier: "Cell")
self.collectionView?.delegate = self
self.collectionView?.dataSource = self
self.collectionView?.alwaysBounceVertical = true
self.view.backgroundColor = UIColor.whiteColor()
self.collectionView?.backgroundColor = UIColor.whiteColor()
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ImageCollectionViewController.didMoveCurrentImage(_:)), name: ImageViewControllerDidChangeCurrentImage, object: nil)
cellSize = floor((self.view.frame.size.width - CGFloat(numberOfItemsInLine()) + 1) / CGFloat(numberOfItemsInLine()));
self.title = String(format: NSLocalizedString("%ld images", comment: ""), arguments: [self.collection.count])
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if let imageView = self.animatingImageView {
let backgroundView = UIView(frame: self.view.bounds)
backgroundView.backgroundColor = UIColor.whiteColor()
self.view.addSubview(backgroundView)
self.view.addSubview(imageView)
animatingBackgroundView = backgroundView
}
}
public override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let path = self.currentFocusedPath
let cell = self.collectionView?.cellForItemAtIndexPath(path)
if let imageView = self.animatingImageView {
if let cell = cell as? ImageCollectionViewCell {
cell.hidden = true
self.view.addSubview(imageView)
imageView.clipsToBounds = true
let destination = self.view.convertRect(cell.imageView.frame, fromView: cell.imageView.superview)
UIView.animateWithDuration(0.4,
animations: { () -> Void in
self.animatingBackgroundView?.alpha = 0
imageView.frame = destination
}, completion: { (success) -> Void in
imageView.removeFromSuperview()
self.animatingBackgroundView?.removeFromSuperview()
self.animatingImageView = nil
self.animatingBackgroundView = nil
cell.hidden = false
})
}
else {
UIView.animateWithDuration(0.4,
animations: { () -> Void in
imageView.alpha = 0
self.animatingBackgroundView?.alpha = 0
}, completion: { (success) -> Void in
imageView.removeFromSuperview()
self.animatingBackgroundView?.removeFromSuperview()
self.animatingImageView = nil
self.animatingBackgroundView = nil
})
}
}
}
func didMoveCurrentImage(notification:NSNotification) {
if let userInfo = notification.userInfo {
if let index = userInfo[ImageViewControllerDidChangeCurrentImageIndexKey] as? Int {
self.currentFocusedPath = NSIndexPath(forItem: index, inSection: 0)
if let collectionView = self.collectionView {
if let cell = collectionView.cellForItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0)) {
if !collectionView.visibleCells().contains(cell) {
collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.CenteredVertically, animated: true)
}
}
else{
collectionView.scrollToItemAtIndexPath(NSIndexPath(forItem: index, inSection: 0), atScrollPosition: UICollectionViewScrollPosition.CenteredVertically, animated: true)
}
}
}
}
}
}
extension ImageCollectionViewController {
public override func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
if let collectionView = self.collectionView {
for cell in collectionView.visibleCells() {
if let cell = cell as? ImageCollectionViewCell {
cell.reload(false)
}
}
}
}
}
extension ImageCollectionViewController {
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: cellSize, height: cellSize + 1)
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return 0
}
}
extension ImageCollectionViewController {
public override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
public override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return collection.count
}
public override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
if let cell = collectionView.cellForItemAtIndexPath(indexPath) as? ImageCollectionViewCell {
if let sourceImage = cell.fullImage() {
cell.hidden = true
let whiteBackgroundView = UIView(frame: self.view.bounds)
whiteBackgroundView.alpha = 0
whiteBackgroundView.backgroundColor = UIColor.whiteColor()
let imageView = UIImageView(image: sourceImage)
imageView.contentMode = .ScaleAspectFill
imageView.clipsToBounds = true
self.view.addSubview(whiteBackgroundView)
self.view.addSubview(imageView)
let sourceRect = self.view.convertRect(cell.imageView.frame, fromView: cell.imageView.superview)
let e = imageViewFrame(self.view.bounds, imageSize: sourceImage.size, contentMode: UIViewContentMode.ScaleAspectFill)
imageView.frame = sourceRect
UIView.animateWithDuration(0.4, animations: { () -> Void in
imageView.frame = e
whiteBackgroundView.alpha = 1
}, completion: { (success) -> Void in
let con = ImageViewPageController.controller(self.collection, index: indexPath.row, imageCollectionViewController:self)
self.presentViewController(con, animated: false) { () -> Void in
imageView.removeFromSuperview()
whiteBackgroundView.removeFromSuperview()
}
cell.hidden = false
})
}
}
}
public override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
if let cell = cell as? ImageCollectionViewCell {
cell.cancelDownloadingImage()
}
}
public override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as UICollectionViewCell
cell.prepareForReuse()
if let cell = cell as? ImageCollectionViewCell {
let imageURL = collection.URLList[indexPath.row]
cell.imageURL = imageURL
cell.reload(collectionView.decelerating)
}
return cell
}
}
|
mit
|
459b8c6fdafcbe4c18451006d8366ecd
| 43.197628 | 199 | 0.637542 | 6.150715 | false | false | false | false |
skonb/YapDatabaseExtensions
|
examples/iOS/Pods/PromiseKit/Swift Sources/when.swift
|
3
|
3344
|
/**
This general `when` is not the most useful since everything becomes
`AnyObject`. Swift generics are not ready for arbituary numbers of
varying generic types, so this is the best you get if you have more
than two things you need to `when` currently.
*/
private enum PromiseResult<T> {
case Busy
case Fulfilled(T)
}
public func when<T>(promises: [Promise<T>]) -> Promise<[T]> {
if promises.isEmpty {
return Promise<[T]>(value:[])
}
let (promise, fulfiller, rejecter) = Promise<[T]>.defer()
var results = [PromiseResult<T>](count: promises.count, repeatedValue: PromiseResult.Busy)
var x = 0
for (index, promise) in enumerate(promises) {
promise.then{ (value) -> Void in
results[index] = .Fulfilled(value)
if ++x == promises.count {
var values: [T] = []
for result in results {
switch result {
case .Busy:
// Does not happen in practise but makes the compiler happy
break
case .Fulfilled(let value):
values.append(value)
}
}
fulfiller(values)
}
}
promise.catch(body: rejecter)
}
return promise
}
public func when<T>(promises: Promise<T>...) -> Promise<[T]> {
return when(promises)
}
public func when<U,V>(promise1: Promise<U>, promise2: Promise<V>) -> Promise<(U,V)> {
let (promise, fulfiller, rejecter) = Promise<(U,V)>.defer()
var first:Any?
promise1.then{ u->() in
if let seal = first {
let fulfillment = (u, seal as! V)
fulfiller(fulfillment)
} else {
first = u
}
}
promise2.then{ v->() in
if let seal = first {
let fulfillment = (seal as! U, v)
fulfiller(fulfillment)
} else {
first = v
}
}
promise1.catch(body: rejecter)
promise2.catch(body: rejecter)
return promise
}
// For Void Promises we don't need type accumulations, so we can use recursion easily
private func when(promise1: Promise<Void>, # promise2: Promise<Void>) -> Promise<Void> {
let (promise, fulfiller, rejecter) = Promise<Void>.defer()
var first: Any?
promise1.then { ()->() in
if let other = first {
fulfiller()
} else {
first = promise1
}
}
promise2.then { ()->() in
if let other = first {
fulfiller()
} else {
first = promise2
}
}
let _:Void = promise1.catch(body: rejecter)
let _:Void = promise2.catch(body: rejecter)
return promise
}
/**
If your promises are all Void promises, then this will work for you.
TODO use the ... form once Swift isn't fucking brain dead about figuring out which when to pick
*/
public func when(promises: [Promise<Void>]) -> Promise<Void> {
switch promises.count {
case 0:
return Promise<Void>(value:())
case 1:
return promises[0]
case 2:
return when(promises[0], promise2: promises[1])
default:
let head = Array(promises[0..<promises.count - 1])
let tail = promises[promises.count - 1]
return when(when(head), promise2: tail)
}
}
|
mit
|
2a621b3e667450a39d55db39da9031bc
| 29.126126 | 96 | 0.558313 | 4.098039 | false | false | false | false |
icylydia/PlayWithLeetCode
|
367. Valid Perfect Square/solution.swift
|
1
|
434
|
class Solution {
func isPerfectSquare(num: Int) -> Bool {
var min = 1
var max = num
while min != max {
let mid = (min + max) / 2
let mid2 = mid * mid
if mid2 == num {
return true
} else if mid2 < num{
min = mid + 1
} else {
max = mid
}
}
return min * max == num
}
}
|
mit
|
337cbd9a7c45f45c51b5800c9c9fb4a0
| 23.111111 | 44 | 0.366359 | 4.34 | false | false | false | false |
dboyliao/NumSwift
|
dev/tryconvolution.swift
|
2
|
1383
|
#!/usr/bin/env swift
import Accelerate
var N = 6
var M = 3
var convN = N + M - 1
// print(N, M, convN)
var xf = [Float](count:N, repeatedValue:0.0)
var yf = [Float](count:M, repeatedValue:0.0)
for i in 0..<N {
xf[i] = Float(i+1)
}
for i in 0..<M {
yf[i] = Float(i+1)
}
var outputf = [Float](count:convN, repeatedValue:-1.0)
// padding zero
xf = [Float](count:convN-N, repeatedValue:0.0) + xf
var ptr_xf = UnsafePointer<Float>(xf)
var ptr_yf = UnsafePointer<Float>(yf).advancedBy(yf.count-1)
var ptr_outputf = UnsafeMutablePointer<Float>(outputf)
let strideOne = vDSP_Stride(1)
let strideNegOne = vDSP_Stride(-1)
vDSP_conv(ptr_xf, strideOne, ptr_yf, strideNegOne, ptr_outputf, strideOne, vDSP_Length(convN), vDSP_Length(M))
print("[Float]: \(outputf)")
// sleep(3)
var xd = [Double](count:N, repeatedValue:0.0)
var yd = [Double](count:M, repeatedValue:0.0)
for i in 0..<N {
xd[i] = Double(i+1)
}
for i in 0..<M {
yd[i] = Double(i+1)
}
var outputd = [Double](count:convN, repeatedValue:0.0)
// padding zero
xd = [Double](count:convN - N, repeatedValue:0) + xd
var ptr_xd = UnsafePointer<Double>(xd)
var ptr_yd = UnsafePointer<Double>(yd).advancedBy(yd.count-1)
var ptr_outputd = UnsafeMutablePointer<Double>(outputd)
vDSP_convD(ptr_xd, 1, ptr_yd, -1, ptr_outputd, 1,
vDSP_Length(convN), vDSP_Length(M))
print("[Double]: \(outputd)")
// sleep(3)
|
mit
|
e1ab4149f79a21dc1635da81d4a1e577
| 23.714286 | 110 | 0.661605 | 2.644359 | false | false | false | false |
SuperAwesomeLTD/sa-kws-app-demo-ios
|
KWSDemo/KWSTextField.swift
|
1
|
928
|
//
// UITextField+KWSStyle.swift
// KWSDemo
//
// Created by Gabriel Coman on 22/06/2016.
// Copyright © 2016 Gabriel Coman. All rights reserved.
//
import UIKit
import RxSwift
import RxCocoa
class KWSTextField: UITextField {
// public border value
public var border: UIView?
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
// set background color
self.backgroundColor = UIColor.clear
// set size
let W = UIScreen.main.bounds.width - 40
let H = 30
// add a border
border = UIView()
border?.frame = CGRect(x: 0, y: H-1, width: Int(W), height: 1)
border?.backgroundColor = UIColor.lightGray
self.addSubview(border!)
}
func setRedOrGrayBorder (_ isValid: Bool) {
border?.backgroundColor = isValid ? UIColor.lightGray : UIColor.red
}
}
|
gpl-3.0
|
13d29d0dbd79522fcc95c0465b3d6c31
| 22.769231 | 75 | 0.599784 | 4.271889 | false | false | false | false |
spritekitbook/spritekitbook-swift
|
Chapter 9/Start/SpaceRunner/SpaceRunner/Math.swift
|
17
|
1535
|
//
// Math.swift
// SpaceRunner
//
// Created by Jeremy Novak on 8/30/16.
// Copyright © 2016 Spritekit Book. All rights reserved.
//
import SpriteKit
func DegreesToRadians(degrees: CGFloat) -> CGFloat {
return degrees * CGFloat(M_PI) / 180.0
}
func RadiansToDegrees(radians: CGFloat) -> CGFloat {
return radians * 180.0 / CGFloat(M_PI)
}
func Smooth(startPoint: CGFloat, endPoint: CGFloat, percentToMove: CGFloat) -> CGFloat {
return (startPoint * (1 - percentToMove)) + endPoint * percentToMove
}
func AngleBetweenPoints(targetPosition: CGPoint, currentPosition: CGPoint) -> CGFloat {
let deltaX = targetPosition.x - currentPosition.x
let deltaY = targetPosition.y - currentPosition.y
return CGFloat(atan2(Float(deltaY), Float(deltaX))) - DegreesToRadians(degrees: 90)
}
func DistanceBetweenPoints(firstPoint: CGPoint, secondPoint: CGPoint) -> CGFloat {
return CGFloat(hypotf(Float(secondPoint.x - firstPoint.x), Float(secondPoint.y - firstPoint.y)))
}
func Clamp(value: CGFloat, min: CGFloat, max: CGFloat) -> CGFloat {
var newMin = min
var newMax = max
if (min > max) {
newMin = max
newMax = min
}
return value < newMin ? newMin : value < newMax ? value : newMax
}
func RandomIntegerBetween(min: Int, max: Int) -> Int {
return Int(UInt32(min) + arc4random_uniform(UInt32(max - min + 1)))
}
func RandomFloatRange(min: CGFloat, max: CGFloat) -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF) * (max - min) + min
}
|
apache-2.0
|
d81fb1a415aa4fa5026d5ca5b4408ccb
| 27.407407 | 100 | 0.680574 | 3.696386 | false | false | false | false |
i-schuetz/SwiftCharts
|
SwiftCharts/Views/ChartPointTargetingView.swift
|
4
|
2586
|
//
// ChartPointTargetingView.swift
// swift_charts
//
// Created by ischuetz on 15/04/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
open class ChartPointTargetingView: UIView {
fileprivate let animDuration: Float
fileprivate let animDelay: Float
fileprivate let lineHorizontal: UIView
fileprivate let lineVertical: UIView
fileprivate let lineWidth = 1
fileprivate let lineHorizontalTargetFrame: CGRect
fileprivate let lineVerticalTargetFrame: CGRect
public init(chartPoint: ChartPoint, screenLoc: CGPoint, animDuration: Float, animDelay: Float, layer: ChartCoordsSpaceLayer, chart: Chart) {
self.animDuration = animDuration
self.animDelay = animDelay
let axisOriginX = layer.modelLocToScreenLoc(x: layer.xAxis.first)
let axisOriginY = layer.modelLocToScreenLoc(y: layer.yAxis.last)
let axisLengthX = layer.modelLocToScreenLoc(x: layer.xAxis.last) - axisOriginX
let axisLengthY = abs(axisOriginY - layer.modelLocToScreenLoc(y: layer.yAxis.first))
lineHorizontal = UIView(frame: CGRect(x: axisOriginX, y: axisOriginY, width: axisLengthX, height: CGFloat(lineWidth)))
lineVertical = UIView(frame: CGRect(x: axisOriginX, y: axisOriginY, width: CGFloat(lineWidth), height: axisLengthY))
lineHorizontal.backgroundColor = UIColor.black
lineVertical.backgroundColor = UIColor.red
let lineWidthHalf = lineWidth / 2
var targetFrameH = lineHorizontal.frame
targetFrameH.origin.y = screenLoc.y - CGFloat(lineWidthHalf)
lineHorizontalTargetFrame = targetFrameH
var targetFrameV = lineVertical.frame
targetFrameV.origin.x = screenLoc.x - CGFloat(lineWidthHalf)
lineVerticalTargetFrame = targetFrameV
super.init(frame: chart.bounds)
}
required public init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override open func didMoveToSuperview() {
addSubview(lineHorizontal)
addSubview(lineVertical)
func targetState() {
lineHorizontal.frame = lineHorizontalTargetFrame
lineVertical.frame = lineVerticalTargetFrame
}
if animDuration =~ 0 {
targetState()
} else {
UIView.animate(withDuration: TimeInterval(animDuration), delay: TimeInterval(animDelay), options: .curveEaseOut, animations: {
targetState()
}, completion: nil)
}
}
}
|
apache-2.0
|
758ad57e82002976714796021054231a
| 35.422535 | 144 | 0.679814 | 4.91635 | false | false | false | false |
christinaxinli/Ana-Maria-Fox-Walking-Tour
|
slg - beta - 2/JourneyViewController.swift
|
1
|
3935
|
import UIKit
import Crashlytics
class JourneyViewController: UIPageViewController, UIPageViewControllerDataSource, UIPageViewControllerDelegate {
var currentFox: String! = "NA"
var pageNames: [String] = []
func createNames () -> [String] {
print(" createNames \(currentFox)")
switch currentFox {
case "Fox1":
let Fox1: [String] = ["Fox1_pg1","Fox1_pg2","Fox1_pg3", "Fox1_pg4"]
pageNames.append(contentsOf: Fox1)
case "Fox2":
let Fox2: [String] = ["Fox2_pg1","Fox2_pg2","Fox2_pg3", "Fox2_pg4"]
pageNames.append(contentsOf: Fox2)
case "Fox3":
print("Fox 3")
let Fox3: [String] = ["Fox3_pg1","Fox3_pg2","Fox3_pg3", "Fox3_pg4","Fox3_pg5"]
pageNames.append(contentsOf: Fox3)
case "Fox4":
print("Fox 4")
let Fox4: [String] = ["Fox4_pg1","Fox4_pg2","Fox4_pg3","Fox4_pg4"]
pageNames.append(contentsOf: Fox4)
default:
pageNames.append("InstructionsViewController")
}
return pageNames
}
func VCInstance(name: String) -> UIViewController {
let thisViewController = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: name)
if let journeyController = thisViewController as? ViewController {
journeyController.currentFox = self.currentFox;
print("works")
return journeyController
}
return thisViewController
}
lazy var VCArr: [UIViewController] = {
var names = self.createNames()
var VCs: [UIViewController] = []
for i in 0..<names.count {
VCs.append(self.VCInstance(name: names[i]))
}
return VCs
} ()
override func viewDidLoad() {
super.viewDidLoad()
self.dataSource = self
self.delegate = self
if let firstVC = VCArr.first {
setViewControllers([firstVC], direction: .forward, animated: true, completion: nil)
}
Answers.logCustomEvent(withName: "View loaded",
customAttributes: [
"Which View": currentFox!
])
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = VCArr.index(of: viewController) else {
return nil
}
let previousIndex = viewControllerIndex - 1
guard previousIndex >= 0 else {
return VCArr.first
}
guard VCArr.count > previousIndex else {
return nil
}
return VCArr[previousIndex]
}
internal func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
guard let viewControllerIndex = VCArr.index(of: viewController) else {
return nil
}
let nextIndex = viewControllerIndex + 1
guard nextIndex < VCArr.count else {
return VCArr.first
}
guard VCArr.count > nextIndex else {
return nil
}
return VCArr[nextIndex]
}
internal func presentationCount(for pageViewController: UIPageViewController) -> Int {
return VCArr.count
}
internal func presentationIndex(for pageViewController: UIPageViewController) -> Int {
guard let firstViewController = viewControllers?.first, let firstViewControllerIndex = VCArr.index(of: firstViewController) else {
return 0
}
return firstViewControllerIndex
}
}
|
mit
|
eaf2ff499459a8414fd20ab122662998
| 29.984252 | 157 | 0.574333 | 4.882134 | false | false | false | false |
mikina/Right-Direction
|
RightDirection/RightDirection/Controller/ScoreTable/ScoreBoardTableCoordinator.swift
|
1
|
929
|
//
// ScoreBoardTableCoordinator.swift
// RightDirection
//
// Created by Mike Mikina on 3/17/16.
// Copyright © 2016 FDT. All rights reserved.
//
import UIKit
class ScoreBoardTableCoordinator: NSObject {
@IBOutlet var tableView: UITableView!
@IBOutlet var dataSource: ScoreBoardTableDataSource!
@IBOutlet var delegate: ScoreBoardTableDelegate!
override func awakeFromNib() {
super.awakeFromNib()
}
func setup() {
self.registerCells()
}
func reloadData(data: [ScoreItem]) {
self.dataSource.data = data;
self.delegate.data = data;
if data.count == 0 {
self.tableView.hidden = true
}
else {
self.tableView.hidden = false
self.tableView.reloadData()
}
}
func registerCells() {
let nib = UINib(nibName: String(ScoreBoardTableCell), bundle: nil)
self.tableView.registerNib(nib, forCellReuseIdentifier: String(ScoreBoardTableCell))
}
}
|
mit
|
1c5ba0267367042be0dc7fde38b253cf
| 22.2 | 88 | 0.6875 | 4.070175 | false | false | false | false |
ksco/swift-algorithm-club-cn
|
Ordered Set/OrderedSet.playground/Sources/Random.swift
|
1
|
650
|
import Foundation
// Returns a random number between the given range.
public func random(min: Int, max: Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}
// Generates a random alphanumeric string of a given length.
extension String {
public static func random(length: Int = 8) -> String {
let base = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
var randomString: String = ""
for _ in 0..<length {
let randomValue = arc4random_uniform(UInt32(base.characters.count))
randomString += "\(base[base.startIndex.advancedBy(Int(randomValue))])"
}
return randomString
}
}
|
mit
|
d492614319f9bf8c3d5408c1a47412c9
| 31.5 | 79 | 0.707692 | 4.220779 | false | false | false | false |
TonyStark106/NiceKit
|
NiceKit/Sources/Service/Debug/Log.swift
|
1
|
5421
|
//
// Log.swift
// Pods
//
// Created by 吕嘉豪 on 2017/3/20.
//
//
import Foundation
// 在工程里加上这两个全局方法强制使用 Log
//#if DEBUG
// public func print(_ items: Any..., separator: String = "", terminator: String = "") {
// assert(false, "不要直接用 print(), 请使用 Log")
// }
// public func NSLog(_ format: String, _ args: CVarArg...) {
// assert(false, "不要直接用 NSLog(), 请使用 Log")
// }
//#endif
public enum LogLevel: String {
case debug = "DEBUG"
case info = "INFO"
case warning = "WARNING"
case error = "ERROR"
private var intValue: Int {
switch self {
case .debug:
return 1
case .info:
return 2
case .warning:
return 3
case .error:
return 4
}
}
static func >(l: LogLevel, r: LogLevel) -> Bool {
return l.intValue > r.intValue
}
static func >=(l: LogLevel, r: LogLevel) -> Bool {
return l.intValue >= r.intValue
}
static func <(l: LogLevel, r: LogLevel) -> Bool {
return l.intValue < r.intValue
}
static func <=(l: LogLevel, r: LogLevel) -> Bool {
return l.intValue <= r.intValue
}
}
public protocol LogDelegate: class {
func didLog(msg: String, level: LogLevel)
func didInput(msg: String)
}
public class Log {
public static var isEnabled = true
public weak static var delegate: LogDelegate?
private static var _logList = [String]()
public static var logList: [String] {
return _logList
}
public static var history: String {
return _logList.reduce("", { (res, cur) -> String in
return res + cur + "\n"
})
}
public static var shouldCache = false
public static func cleanCache() {
_logList.removeAll()
}
public static var outputLevel: LogLevel = .debug
private static var logQueue = DispatchQueue(label: "io.nicekit.log", attributes: [])
public static var logErrorColor = UIColor.nice.hsbColor(6, 74, 91, 1)
public static var logWarningColor = UIColor.nice.hsbColor(48, 99, 100, 1)
public static var logInfoColor = UIColor.nice.hsbColor(224, 50, 63, 1)
public static var logDebugColor = UIColor.nice.hsbColor(145, 77, 80, 1)
public static var showFunctionName: Bool = true
public static var showThreadName: Bool = true
public static var showFileName: Bool = true
public static var showLineNumber: Bool = true
public static var showLevel: Bool = true
public static var showDate: Bool = true
public static func debug(msg: String, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line) {
log(level: .debug, msg: msg, functionName: String(describing: functionName), fileName: String(describing: fileName), lineNumber: lineNumber)
}
public static func info(msg: String, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line) {
log(level: .info, msg: msg, functionName: String(describing: functionName), fileName: String(describing: fileName), lineNumber: lineNumber)
}
public static func warning(msg: String, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line) {
log(level: .warning, msg: msg, functionName: String(describing: functionName), fileName: String(describing: fileName), lineNumber: lineNumber)
}
public static func error(msg: String, functionName: StaticString = #function, fileName: StaticString = #file, lineNumber: Int = #line) {
log(level: .error, msg: msg, functionName: String(describing: functionName), fileName: String(describing: fileName), lineNumber: lineNumber)
}
public static func log(level: LogLevel, msg: String, functionName: String, fileName: String, lineNumber: Int) {
if isEnabled == false {
return
}
if level < outputLevel {
return
}
var threadName = ""
if showThreadName {
var _threadName = ""
if Thread.isMainThread {
_threadName = "[main] "
} else {
if let tn = Thread.current.name, !tn.isEmpty {
_threadName = "[\(tn)] "
} else {
_threadName = String(format: "[%p] ", Thread.current)
}
}
threadName = _threadName
}
logQueue.async {
var output = ""
if showLevel {
output += "[\(level)]\n"
}
if showThreadName {
output += "[ThreadName]: \(threadName)\n"
}
if showFileName {
let fn = (String(fileName) as NSString).lastPathComponent
output += "[FileName]: \(fn)\n"
}
if showLineNumber {
output += "[LineNumber]: \(lineNumber)\n"
}
if showFunctionName {
output += "[FunctionName]: \(functionName)\n"
}
output += msg + "\n"
if shouldCache {
_logList.append(output)
}
if level >= outputLevel {
print(output)
}
}
}
}
|
mit
|
0dc9315caeefca350e71877fac4f2678
| 32.018519 | 150 | 0.569265 | 4.420661 | false | false | false | false |
AndreMuis/Algorithms
|
MoveZerosToEndOfArray.playground/Contents.swift
|
1
|
563
|
//
// Move zeros to end of array
//
func moveZeros(inout numbers : [Int])
{
var index : Int = 0
var swapIndex : Int = 0
while index < numbers.count - 1
{
if numbers[index] == 0 && numbers[index + 1] != 0
{
let tmp : Int = numbers[swapIndex]
numbers[swapIndex] = numbers[index + 1]
numbers[index + 1] = tmp
swapIndex = swapIndex + 1
}
index = index + 1
}
}
var numbers : [Int] = [0, 4, 3, 0, 0, 7, 5]
moveZeros(&numbers)
numbers
|
mit
|
80e853cac45550e6a3d53085fbf287f3
| 16.060606 | 57 | 0.483126 | 3.563291 | false | false | false | false |
Joachimdj/JobResume
|
Apps/Forum17/2017/Forum/Views/LectureItemView.swift
|
1
|
9798
|
//
// LectureItem.swift
// Forum
//
// Created by Joachim Dittman on 13/08/2017.
// Copyright © 2017 Joachim Dittman. All rights reserved.
//
import UIKit
class LectureItemView: UIViewController {
var lc = [Lecture]()
var fullCard = UIScrollView()
let signupButton = UIButton()
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = .white
var titleLabel: UILabel!
var line: UILabel!
var who: UITextView!
var when: UILabel!
var whereAt: UILabel!
let userImage = UIImageView()
var cardButton: UIButton!
let headerImage = UIImageView()
var desc: UITextView!
let participantView = UIScrollView(frame: CGRect(x: 0,y: 210, width: UIScreen.main.bounds.width, height: 80))
fullCard.frame = CGRect(x:0,y: 60, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-60)
fullCard.backgroundColor = UIColor.white
fullCard.layer.borderColor = UIColor.black.cgColor
fullCard.layer.borderWidth = 2.0
let bImage = UIButton()
bImage.frame = CGRect(x: -10,y: 0,width: 70,height: 70)
bImage.setImage(UIImage(named: "ic_close")!.withRenderingMode(UIImageRenderingMode.alwaysTemplate), for: UIControlState())
bImage.tintColor = UIColor.black
bImage.addTarget(self, action: #selector(close(_:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(bImage)
print("titleLabel")
titleLabel = UILabel(frame: CGRect(x:20,y: 24, width: UIScreen.main.bounds.width - 40, height: 20))
titleLabel.text = lc[0].name?.uppercased()
titleLabel.textAlignment = NSTextAlignment.center
titleLabel.font = UIFont(name:"HelveticaNeue-Bold", size: 15)
titleLabel.textColor = UIColor.black
print("headerImage")
headerImage.frame = CGRect(x: 0,y: 0,width: UIScreen.main.bounds.width,height: 250)
print(lc[0].headerImage!)
if(lc[0].headerImage != "")
{
let URLHeader = URL(string: (lc[0].headerImage)!)!
headerImage.kf.setImage(with: URLHeader, placeholder: UIImage(named:"noPic"), options: nil, progressBlock: nil, completionHandler: { (image, error, CacheType, imageURL) in
})
}
else
{
headerImage.image = UIImage(named:"noPic")
}
var start:CGFloat = 0
var k = 0
var lecturerString = ""
if(lc[0].lecturer != nil)
{
let a = lc[0].lecturer?.count
let calculateStart = (Int((UIScreen.main.bounds.width/2)) - (a! * 35))
start = CGFloat(calculateStart)
print("lecture")
for i in lc[0].lecturer! {
let image = UIImageView()
image.frame = CGRect(x: start,y: 5, width: 60, height: 60)
if(i.value["image"] != "")
{
let URL = Foundation.URL(string: i.value["image"]!)!
image.backgroundColor = .white
image.kf.setImage(with: URL, placeholder:UIImage(named:"icon"), options: nil, progressBlock: nil, completionHandler: { (image, error, CacheType, imageURL) in
})
}
else
{
image.backgroundColor = .white
image.image = UIImage(named:"icon")
}
print("lecture")
image.layer.borderWidth = 2.0
image.layer.borderColor = UIColor.lightGray.cgColor
image.clipsToBounds = true;
image.layer.cornerRadius = image.frame.width/2;
participantView.addSubview(image)
print("lecture")
if(i.value["name"] != "")
{
if(a == 1){lecturerString += "\(i.value["name"]!)"} else
{
if(k < a!-2){lecturerString += "\(i.value["name"]!), "}
else
{
if(k < a!-1){lecturerString += "\(i.value["name"]!) "} else {lecturerString += "& \(i.value["name"]!)"}
}
}
}
k += 1
start += 70
}
}
line = UILabel(frame: CGRect(x: 5,y: 340, width: fullCard.frame.size.width-10, height: 4))
line.backgroundColor = UIColor.lightGray
let attrStr = try! NSAttributedString(
data: "Af \(lecturerString)".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
print("who")
who = UITextView(frame: CGRect(x: 5,y: 265, width: fullCard.frame.size.width-10, height: 50))
who.attributedText = attrStr
who.textAlignment = NSTextAlignment.center
who.font = UIFont(name:"HelveticaNeue-bold", size: 14)
who.textColor = UIColor.black
print("when")
when = UILabel(frame: CGRect(x: 5,y: 318, width: fullCard.frame.size.width-10, height: 20))
when.text = "\(String(describing: lc[0].startTime!)) - \(String(describing: lc[0].endTime!))"
when.textAlignment = NSTextAlignment.right
when.font = UIFont(name:"HelveticaNeue-Bold", size: 20)
when.textColor = UIColor.black
print("whereAt")
whereAt = UILabel(frame: CGRect(x: 5,y: 318, width: fullCard.frame.size.width-10, height: 20))
whereAt.text = "\(String(describing: lc[0].place!))"
whereAt.textAlignment = NSTextAlignment.left
whereAt.font = UIFont(name:"HelveticaNeue-Bold", size: 18)
whereAt.textColor = UIColor.black
desc = UITextView(frame: CGRect(x: 5,y: 340, width: fullCard.frame.size.width-10, height: 600))
print("desc")
desc.textAlignment = .left
let descStr = try! NSAttributedString(
data: (lc[0].desc?.data(using: String.Encoding.unicode, allowLossyConversion: true)!)!,
options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
documentAttributes: nil)
desc.attributedText = descStr
desc.isEditable = false
desc.font = UIFont (name: "Helvetica Neue", size: 15)
desc.isScrollEnabled = false
desc.textColor = UIColor.black
desc.backgroundColor = UIColor.clear
cardButton = UIButton(frame: CGRect(x: 0,y: 0, width: fullCard.frame.size.width, height: fullCard.frame.size.height))
fullCard.addSubview(who)
fullCard.addSubview(userImage)
self.view.addSubview(titleLabel)
fullCard.addSubview(line)
fullCard.addSubview(when)
fullCard.addSubview(whereAt)
fullCard.addSubview(cardButton)
fullCard.addSubview(headerImage)
fullCard.addSubview(participantView)
fullCard.addSubview(desc)
if(lc[0].status == 0)
{
fullCard.contentSize = CGSize(width: fullCard.frame.size.width, height:desc.contentSize.height + 60)
signupButton.frame = CGRect(x: 0,y: UIScreen.main.bounds.height-50, width: UIScreen.main.bounds.width, height: 50)
signupButton.alpha = 0.0
if((User.favoriteLectures[lc[0].day]?.filter{$0.id == lc[0].id && $0.signedUp == true}.count)! == 0)
{
signupButton.setTitle("Tilmeld mig", for: .normal)
signupButton.backgroundColor = UIColor.infoBlue()
signupButton.tag = 0
}
else
{
self.signupButton.tag = 1
self.signupButton.backgroundColor = .red
self.signupButton.setTitle("Afmeld mig!", for: .normal)
}
signupButton.setTitleColor(UIColor.white, for: .normal)
signupButton.addTarget(self, action: #selector(signup(sender:)), for: UIControlEvents.touchUpInside)
self.view.addSubview(signupButton)
}
else
{
fullCard.contentSize = CGSize(width: fullCard.frame.size.width, height:desc.contentSize.height + 100)
fullCard.frame = CGRect(x:0,y: 60, width: UIScreen.main.bounds.width, height: UIScreen.main.bounds.height-60)
}
self.view.addSubview(fullCard)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Diacose of any resources that can be recreated.
}
func close(_ sender:AnyObject)
{
self.dismiss(animated: true, completion: nil)
}
func signup(sender:AnyObject)
{
if(sender.tag == 0 || lc[0].signedUp == false)
{
print("add")
if(UserController().addToFavoritList(type: "lecture", lecture: lc[0], auctionItem:nil) == true)
{
lc[0].signedUp = true
self.signupButton.tag = 1
self.signupButton.backgroundColor = .red
self.signupButton.setTitle("Afmeld mig!", for: .normal)
}
}
else
{
print("remove")
if(UserController().removeFromFavoritList(type: "lecture", lecture: lc[0], auctionItem:nil) == true)
{
lc[0].signedUp = false
self.signupButton.tag = 0
self.signupButton.backgroundColor = .infoBlue()
self.signupButton.setTitle("Tilmeld mig!", for: .normal)
}
}
}
}
|
mit
|
4f96a01f16d7ae254759d779948ec9c0
| 39.991632 | 183 | 0.562417 | 4.407108 | false | false | false | false |
igormatyushkin014/Sensitive
|
Source/Classes/Recognizers/Tap/TapGestureRecognizer.swift
|
1
|
1439
|
//
// TapGestureRecognizer.swift
// Sensitive
//
// Created by Igor Matyushkin on 17.12.15.
// Copyright © 2015 Igor Matyushkin. All rights reserved.
//
import UIKit
public final class TapGestureRecognizer: UITapGestureRecognizer, UIGestureRecognizerDelegate {
// MARK: Class variables & properties
// MARK: Class methods
// MARK: Initializers
public init(handler: @escaping GestureRecognizerHandler<UITapGestureRecognizer>) {
super.init(target: nil, action: nil)
self.handler = handler
self.recognizeSimultaneouslyWithOtherGestures = true
self.addTarget(self, action: #selector(runHandler))
}
// MARK: Deinitializer
deinit {
}
// MARK: Variables & properties
fileprivate var handler: GestureRecognizerHandler<UITapGestureRecognizer>?
public var recognizeSimultaneouslyWithOtherGestures: Bool {
get {
return self.delegate === self
}
set {
self.delegate = self
}
}
// MARK: Public methods
// MARK: Private methods
@objc
internal func runHandler() {
self.handler?(self)
}
// MARK: Protocol methods
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
|
mit
|
b4488a3a81e74818aec4b522f8f60aec
| 23.372881 | 164 | 0.64395 | 5.406015 | false | false | false | false |
paulstringer/TicTacToe
|
TicTacToe WatchKit Extension/InterfaceController.swift
|
1
|
1245
|
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
var gameFactory = GameFactory()
//MARK: Interface
@IBOutlet var picker: WKInterfacePicker!
//MARK:- Interface Controller Lifecyle
override func awake(withContext context: Any?) {
super.awake(withContext: context)
configureNewGamePicker()
}
override func willActivate() {
super.willActivate()
}
override func didDeactivate() {
super.didDeactivate()
}
override func contextForSegue(withIdentifier segueIdentifier: String) -> Any? {
return gameFactory
}
//MARK:- Game Picker Interface
fileprivate func configureNewGamePicker() {
let items = GameType.allValues.map { (type) -> WKPickerItem in
return pickerItemForGameType(type)
}
picker.setItems(items)
}
fileprivate func pickerItemForGameType(_ type: GameType) -> WKPickerItem {
let item = WKPickerItem()
item.contentImage = WKImage(imageName: "\(type)")
return item
}
@IBAction func pickerAction(_ value: Int) {
gameFactory.gameType = GameType.allValues[value]
}
}
|
mit
|
bdce39c73cecad86e8163d684fdf3c32
| 23.411765 | 83 | 0.631325 | 5.123457 | false | false | false | false |
AshuMishra/MBPedometer
|
MBPedometer/View Controllers/MBPedoMeterViewController.swift
|
1
|
9196
|
//
// ViewController.swift
// MBPedometer
//
// Created by Ashutosh on 21/06/15.
// Copyright (c) 2015 Ashutosh. All rights reserved.
//
import UIKit
import CoreMotion
class MBPedoMeterViewController: UIViewController,UITextFieldDelegate {
@IBOutlet weak var datePicker: UIDatePicker!
@IBOutlet weak var startDateTextField: UITextField!
@IBOutlet weak var endDateTextField: UITextField!
@IBOutlet weak var todayUpdatesView: UIView!
@IBOutlet weak var previousUpdatesView: UIView!
@IBOutlet weak var previousDayResultContainer: MBResultContainer!
@IBOutlet weak var segmentButton: UISegmentedControl!
@IBOutlet weak var resultContainer: MBResultContainer!
@IBOutlet weak var footImageView: UIImageView!
@IBOutlet weak var activityStatusLabel: UILabel!
@IBOutlet weak var datePickerView: UIView!
var startDate: NSDate?
var endDate: NSDate?
var cumulativeActivity: Activity!
var activeTextField:UITextField!
let activityManager = CMMotionActivityManager()
//MARK: ViewController Life Cycle
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Home"
self.setUpActivity()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
if (self.segmentButton.selectedSegmentIndex == 0) {
var currentEndDate = NSDate()
var currentStartDate = self.midnightOfToday(currentEndDate)
//The following method increments the current status of the various acitivies
PedometerManager.sharedInstance.calculateStepsForInterval(startDate:currentStartDate, endDate:currentEndDate) { (activity, error) -> Void in
if (error == nil) {
self.cumulativeActivity = activity!
self.resultContainer.updateResultWithActiviy(activity!)
PedometerManager.sharedInstance.startStepCounterFromDate(self.cumulativeActivity.endDate, completionBlock: { (currentActivity, error) -> Void in
//Get current values of the activity
var finalActivity = Activity(startDate: currentActivity!.startDate, endDate: currentActivity!.endDate)
//Add newly fetched values
finalActivity.stepCount = NSNumber(int:self.cumulativeActivity.stepCount.intValue + currentActivity!.stepCount.intValue)
finalActivity.distanceCovered = NSNumber(double:self.cumulativeActivity.distanceCovered.doubleValue + currentActivity!.distanceCovered.doubleValue)
finalActivity.floorsAscended = NSNumber(int:self.cumulativeActivity.floorsAscended.intValue + currentActivity!.floorsAscended.intValue)
finalActivity.floorsDescended = NSNumber(int:self.cumulativeActivity.floorsDescended.intValue + currentActivity!.floorsDescended.intValue)
//update UI
self.resultContainer.updateResultWithActiviy(finalActivity)
})
}
else if (error?.code == 105) {
self.showAlertWithMessage("you are not allowed to use Motion feature of app. Please go to Settings and allow the permission.")
}
}
}
}
override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
PedometerManager.sharedInstance.stopCountingUpdates()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: IBActions
@IBAction func didSelectDate(sender: AnyObject) {
self.activeTextField.text = formatDate(self.datePicker.date)
if (self.activeTextField.isEqual(self.startDateTextField)) {
self.startDate = self.datePicker.date
}else {
self.endDate = self.datePicker.date
}
}
@IBAction func didTapEndTap(sender: UIButton) {
self.activeTextField = self.endDateTextField
self.endDateTextField.backgroundColor = UIColor(red: 153/255.0, green: 204.0/255, blue: 255/255.0, alpha: 1)
self.startDateTextField.backgroundColor = UIColor.clearColor()
self.datePicker.maximumDate = NSDate()
self.datePicker.minimumDate = NSDate(timeIntervalSinceNow: -86400 * 7)
self.datePickerView.hidden = false
}
@IBAction func didTapStartDate(sender: AnyObject) {
self.activeTextField = self.startDateTextField
self.startDateTextField.backgroundColor = UIColor(red: 153/255.0, green: 204.0/255, blue: 255/255.0, alpha: 1)
self.endDateTextField.backgroundColor = UIColor.clearColor()
self.datePicker.minimumDate = NSDate(timeIntervalSinceNow: -86400 * 7)
self.datePicker.maximumDate = NSDate()
self.datePickerView.hidden = false
}
@IBAction func calculateSteps(sender: AnyObject) {
if (self.readyForCalulation()) {
PedometerManager.sharedInstance.calculateStepsForInterval(startDate:self.startDate!, endDate: self.endDate!) { (activity, error) -> Void in
self.previousDayResultContainer.updateResultWithActiviy(activity!)
self.datePickerView.hidden = true
}
}
}
@IBAction func didChangeSegment(sender: UISegmentedControl) {
switch(sender.selectedSegmentIndex){
case 0:
self.todayUpdatesView.hidden = false
self.previousUpdatesView.hidden = true
case 1:
self.todayUpdatesView.hidden = true
self.previousUpdatesView.hidden = false
default:
self.todayUpdatesView.hidden = false
self.previousUpdatesView.hidden = false
}
}
@IBAction func didTapPickerClose(sender: AnyObject) {
self.datePickerView.hidden = true
}
//MARK: Touch Handlers
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
let touch = touches.first as? UITouch
var point = touch?.locationInView(self.view)
if (CGRectContainsPoint(self.datePickerView.frame, point!) == false) {
datePickerView.hidden = true //Hide datepicker when tapped outside of date picker
}
}
//MARK:Private Helpers
//Check for condition before calculating steps
func readyForCalulation() -> Bool {
var shouldCalculateNow = true
if (self.startDate == nil || self.endDate == nil) {
self.showAlertWithMessage("Please choose start and end date.")
shouldCalculateNow = false
}
else if (self.startDate?.compare(self.endDate!) == NSComparisonResult.OrderedDescending) {
self.showAlertWithMessage("End date should be later than start date.")
shouldCalculateNow = false
}
else if (!PedometerManager.sharedInstance.checkStepCountingAvailability()) {
self.showAlertWithMessage("Step Counting Not Avaliable.")
shouldCalculateNow = false
}else if (!PedometerManager.sharedInstance.checkFloorCountingAvailability()) {
self.showAlertWithMessage("Floor Counting Not Avaliable.")
shouldCalculateNow = true
}
return shouldCalculateNow
}
//Shows alert with custom messages
func showAlertWithMessage(message:String!)->() {
var alertController = UIAlertController(title: "Error", message:message, preferredStyle: UIAlertControllerStyle.Alert)
var action = UIAlertAction(title: "OK", style: UIAlertActionStyle.Cancel, handler: nil)
alertController.addAction(action)
self.presentViewController(alertController, animated: true, completion: nil)
}
//Update imageView and status label according to the user's motion actvity
func setUpActivity() {
if(CMMotionActivityManager.isActivityAvailable()) {
self.activityManager.startActivityUpdatesToQueue(NSOperationQueue.mainQueue(), withHandler: { (data: CMMotionActivity!) in
dispatch_async(dispatch_get_main_queue(), { () in
if(data.stationary == true) {
self.activityStatusLabel.text = "Stationary"
self.footImageView.image = UIImage(named: "stationary.png")
}
else if (data.walking == true){
self.activityStatusLabel.text = "Walking"
self.footImageView.image = UIImage(named: "Walking Man.jpg")
}
else if (data.running == true){
self.activityStatusLabel.text = "Running"
self.footImageView.image = UIImage(named: "running_man.png")
}
})
MBUtility.changeViewToCircle(self.footImageView.layer, bordorWidth: 3.0, cornerRadius: self.footImageView.frame.size.height / 2, borderColor: UIColor(red: 219.0/255.0, green: 182.0/255.0, blue: 72.0/255.0, alpha: 1.0))
})
}
}
//Format date string to be displayed on labels
func formatDate(date:NSDate)->(String!) {
var dataFormatter:NSDateFormatter? = NSDateFormatter()
dataFormatter?.dateFormat = "MM'/'dd'/'yyyy HH:mm"
var formattedDate:String? = dataFormatter!.stringFromDate(date)
return formattedDate
}
//Calculates midnight of today
func midnightOfToday(date:NSDate) -> (NSDate) {
let cal = NSCalendar.currentCalendar()
let comps = cal.components(.CalendarUnitYear | .CalendarUnitMonth | .CalendarUnitDay | .CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitSecond, fromDate: NSDate())
comps.hour = 0
comps.minute = 0
comps.second = 0
let timeZone = NSTimeZone.systemTimeZone()
cal.timeZone = timeZone
return cal.dateFromComponents(comps)!
}
}
|
mit
|
aeba0839908b8d430dd3d14afbd00052
| 38.637931 | 226 | 0.712157 | 4.595702 | false | false | false | false |
satorun/CountAnimationLabel
|
CountUpAnimation.playground/Contents.swift
|
1
|
2479
|
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class CountAnimationLabel: UILabel {
var startTime: CFTimeInterval!
var fromValue: Int!
var toValue: Int!
var duration: TimeInterval!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initialSetup()
}
override func awakeFromNib() {
super.awakeFromNib()
initialSetup()
}
init() {
super.init(frame: .zero)
initialSetup()
}
private func initialSetup() {
textAlignment = .right
}
func animate(from fromValue: Int, to toValue: Int, duration: TimeInterval) {
text = "\(fromValue)"
self.startTime = CACurrentMediaTime()
self.fromValue = fromValue
self.toValue = toValue
self.duration = duration
let link = CADisplayLink(target: self, selector: #selector(updateValue))
link.add(to: .current, forMode: .commonModes)
}
@objc func updateValue(link: CADisplayLink) {
let dt = (link.timestamp - self.startTime) / duration
if dt >= 1.0 {
text = "\(toValue!)"
link.invalidate()
return
}
let current = Int(Double(toValue - fromValue) * dt) + fromValue
text = "\(current)"
//print("\(link.timestamp), \(link.targetTimestamp)")
}
}
class MyViewController : UIViewController {
var label: CountAnimationLabel!
override func loadView() {
let view = UIView()
view.backgroundColor = .white
label = CountAnimationLabel()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.text = "Hello World!"
label.textColor = .black
let button = UIButton()
button.frame = CGRect(x: 150, y: 300, width: 50, height: 20)
button.setTitleColor(.blue, for: .normal)
button.setTitle("start!", for: .normal)
button.addTarget(self, action: #selector(animation), for: .touchUpInside)
view.addSubview(label)
view.addSubview(button)
self.view = view
}
@objc func animation() {
label.animate(from: 150, to: 1030, duration: 3)
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
|
mit
|
bfe319d992e8c55c136e790999a57fdc
| 24.556701 | 81 | 0.577249 | 4.749042 | false | false | false | false |
etiennemartin/jugglez
|
Jugglez/SKColor+Theme.swift
|
1
|
2138
|
//
// SKColor+Theme.swift
// Jugglez
//
// Created by Etienne Martin on 2015-03-22.
// Copyright (c) 2015 Etienne Martin. All rights reserved.
//
import SpriteKit
extension SKColor {
// General colors
class func themeLightBackgroundColor() -> SKColor {
return SKColor(red: 0.95, green: 0.95, blue: 0.95, alpha: 1.0)
}
class func themeDarkBackgroundColor() -> SKColor {
return SKColor(red: 0.8, green: 0.8, blue: 0.8, alpha: 1.0)
}
class func themeGrayTapCircleColor() -> SKColor {
return SKColor(red: 0.6, green: 0.6, blue: 0.6, alpha: 0.65)
}
class func themeDarkFontColor() -> SKColor {
return SKColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1.0)
}
class func themeButtonTextColor() -> SKColor {
return SKColor.whiteColor().colorWithAlphaComponent(0.85)
}
// Game Mode colors
class func themeEasyModeColor() -> SKColor {
return SKColor(red: 0.04, green: 0.63, blue: 0.54, alpha: 1)
}
class func themeMediumModeColor() -> SKColor {
return SKColor(red: 0.47, green: 0.57, blue: 0.82, alpha: 1)
}
class func themeHardModeColor() -> SKColor {
return SKColor(red: 0.96, green: 0.49, blue: 0.29, alpha: 1)
}
class func themeExpertModeColor() -> SKColor {
return SKColor(red: 0.95, green: 0.17, blue: 0.22, alpha: 1)
}
class func themeHighScoreModeColor() -> SKColor {
return SKColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1)
}
// Returns the proper color for a given GameMode
class func colorForGameMode(mode: GameMode) -> SKColor {
if mode == GameMode.Easy {
return SKColor.themeEasyModeColor()
} else if mode == GameMode.Medium {
return SKColor.themeMediumModeColor()
} else if mode == GameMode.Hard {
return SKColor.themeHardModeColor()
} else if mode == GameMode.Expert {
return SKColor.themeExpertModeColor()
} else if mode == GameMode.HighScore {
return SKColor.themeHighScoreModeColor()
}
return SKColor.clearColor()
}
}
|
mit
|
6512d78f9da7ced5d7daa25bd34ddf1e
| 29.542857 | 70 | 0.614125 | 3.724739 | false | false | false | false |
creatubbles/ctb-api-swift
|
CreatubblesAPIClient/Sources/Requests/Content/ContentResponseHandler.swift
|
1
|
2890
|
//
// ContentResponseHandler.swift
// CreatubblesAPIClient
//
// Copyright (c) 2017 Creatubbles Pte. Ltd.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import ObjectMapper
public class ContentResponseHandler: ResponseHandler {
fileprivate let completion: ContentEntryClosure?
fileprivate let validator: Validatable = ContentDataFilter()
public init(completion: ContentEntryClosure?) {
self.completion = completion
}
override public func handleResponse(_ response: Dictionary<String, AnyObject>?, error: Error?) {
var validEntries: [ContentEntry] = []
var invalidEntries: [ContentEntry] = []
if let response = response,
let mappers = Mapper<ContentEntryMapper>().mapArray(JSONObject: response["data"]) {
let metadata = MappingUtils.metadataFromResponse(response)
let pageInfo = MappingUtils.pagingInfoFromResponse(response)
let dataMapper = MappingUtils.dataIncludeMapperFromResponse(response, metadata: metadata)
mappers.forEach({ (mapper) in
let contentEntry = ContentEntry(mapper: mapper, dataMapper: dataMapper)
validator.isValid(contentEntry) ? validEntries.append(contentEntry) : invalidEntries.append(contentEntry)
})
let responseData = ResponseData(objects: validEntries, rejectedObjects: invalidEntries, pagingInfo: pageInfo, error: ErrorTransformer.errorFromResponse(response, error: error))
executeOnMainQueue { self.completion?(responseData) }
} else {
let responseData = ResponseData(objects: validEntries, rejectedObjects: validEntries, pagingInfo: nil, error: ErrorTransformer.errorFromResponse(response, error: error))
executeOnMainQueue { self.completion?(responseData) }
}
}
}
|
mit
|
326f76b399f352bee7c9f087760028b0
| 47.166667 | 188 | 0.723183 | 4.898305 | false | false | false | false |
gudjao/XLPagerTabStrip
|
Example/Example/BarExampleViewController.swift
|
2
|
3239
|
// BarExampleViewController.swift
// XLPagerTabStrip ( https://github.com/xmartlabs/XLPagerTabStrip )
//
// Copyright (c) 2017 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import XLPagerTabStrip
class BarExampleViewController: BarPagerTabStripViewController {
var isReload = false
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
// set up style before super view did load is executed
settings.style.selectedBarBackgroundColor = .orange
// -
super.viewDidLoad()
}
// MARK: - PagerTabStripDataSource
override func viewControllers(for pagerTabStripController: PagerTabStripViewController) -> [UIViewController] {
let child_1 = TableChildExampleViewController(style: .plain, itemInfo: "Table View")
let child_2 = ChildExampleViewController(itemInfo: "View")
let child_3 = TableChildExampleViewController(style: .grouped, itemInfo: "Table View 2")
let child_4 = ChildExampleViewController(itemInfo: "View 2")
guard isReload else {
return [child_1, child_2, child_3, child_4]
}
var childViewControllers = [child_1, child_2, child_3, child_4]
for (index, _) in childViewControllers.enumerated(){
let nElements = childViewControllers.count - index
let n = (Int(arc4random()) % nElements) + index
if n != index{
swap(&childViewControllers[index], &childViewControllers[n])
}
}
let nItems = 1 + (arc4random() % 4)
return Array(childViewControllers.prefix(Int(nItems)))
}
override func reloadPagerTabStripView() {
isReload = true
if arc4random() % 2 == 0 {
pagerBehaviour = .progressive(skipIntermediateViewControllers: arc4random() % 2 == 0, elasticIndicatorLimit: arc4random() % 2 == 0 )
}
else {
pagerBehaviour = .common(skipIntermediateViewControllers: arc4random() % 2 == 0)
}
super.reloadPagerTabStripView()
}
}
|
mit
|
b03ce006687c0fe4f3bce15811564958
| 40 | 144 | 0.673973 | 4.777286 | false | false | false | false |
ZhengShouDong/CloudPacker
|
Sources/CloudPacker/Libraries/CryptoSwift/Blowfish.swift
|
1
|
23876
|
//
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
// https://en.wikipedia.org/wiki/Blowfish_(cipher)
// Based on Paul Kocher implementation
//
public final class Blowfish {
public enum Error: Swift.Error {
/// Data padding is required
case dataPaddingRequired
/// Invalid key or IV
case invalidKeyOrInitializationVector
/// Invalid IV
case invalidInitializationVector
}
public static let blockSize: Int = 8 // 64 bit
fileprivate let blockMode: BlockMode
fileprivate let padding: Padding
fileprivate var decryptWorker: BlockModeWorker!
fileprivate var encryptWorker: BlockModeWorker!
private let N = 16 // rounds
private var P: Array<UInt32>
private var S: Array<Array<UInt32>>
private let origP: Array<UInt32> = [
0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822,
0x299f31d0, 0x082efa98, 0xec4e6c89, 0x452821e6, 0x38d01377,
0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5,
0xb5470917, 0x9216d5d9, 0x8979fb1b,
]
private let origS: Array<Array<UInt32>> = [
[
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
],
[
0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
],
[
0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
],
[
0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6,
],
]
public init(key: Array<UInt8>, blockMode: BlockMode = .CBC(iv: Array<UInt8>(repeating: 0, count: Blowfish.blockSize)), padding: Padding) throws {
precondition(key.count >= 5 && key.count <= 56)
self.blockMode = blockMode
self.padding = padding
S = origS
P = origP
expandKey(key: key)
try setupBlockModeWorkers()
}
private func setupBlockModeWorkers() throws {
encryptWorker = try blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: encrypt)
switch blockMode {
case .CFB, .OFB, .CTR:
decryptWorker = try blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: encrypt)
default:
decryptWorker = try blockMode.worker(blockSize: Blowfish.blockSize, cipherOperation: decrypt)
}
}
private func reset() {
S = origS
P = origP
// todo expand key
}
private func expandKey(key: Array<UInt8>) {
var j = 0
for i in 0..<(N + 2) {
var data: UInt32 = 0x0
for _ in 0..<4 {
data = (data << 8) | UInt32(key[j])
j += 1
if j >= key.count {
j = 0
}
}
P[i] ^= data
}
var datal: UInt32 = 0
var datar: UInt32 = 0
for i in stride(from: 0, to: N + 2, by: 2) {
encryptBlowfishBlock(l: &datal, r: &datar)
P[i] = datal
P[i + 1] = datar
}
for i in 0..<4 {
for j in stride(from: 0, to: 256, by: 2) {
encryptBlowfishBlock(l: &datal, r: &datar)
S[i][j] = datal
S[i][j + 1] = datar
}
}
}
fileprivate func encrypt(block: ArraySlice<UInt8>) -> Array<UInt8>? {
var result = Array<UInt8>()
var l = UInt32(bytes: block[block.startIndex..<block.startIndex.advanced(by: 4)])
var r = UInt32(bytes: block[block.startIndex.advanced(by: 4)..<block.startIndex.advanced(by: 8)])
encryptBlowfishBlock(l: &l, r: &r)
// because everything is too complex to be solved in reasonable time o_O
result += [
UInt8((l >> 24) & 0xff),
UInt8((l >> 16) & 0xff),
]
result += [
UInt8((l >> 8) & 0xff),
UInt8((l >> 0) & 0xff),
]
result += [
UInt8((r >> 24) & 0xff),
UInt8((r >> 16) & 0xff),
]
result += [
UInt8((r >> 8) & 0xff),
UInt8((r >> 0) & 0xff),
]
return result
}
fileprivate func decrypt(block: ArraySlice<UInt8>) -> Array<UInt8>? {
var result = Array<UInt8>()
var l = UInt32(bytes: block[block.startIndex..<block.startIndex.advanced(by: 4)])
var r = UInt32(bytes: block[block.startIndex.advanced(by: 4)..<block.startIndex.advanced(by: 8)])
decryptBlowfishBlock(l: &l, r: &r)
// because everything is too complex to be solved in reasonable time o_O
result += [
UInt8((l >> 24) & 0xff),
UInt8((l >> 16) & 0xff),
]
result += [
UInt8((l >> 8) & 0xff),
UInt8((l >> 0) & 0xff),
]
result += [
UInt8((r >> 24) & 0xff),
UInt8((r >> 16) & 0xff),
]
result += [
UInt8((r >> 8) & 0xff),
UInt8((r >> 0) & 0xff),
]
return result
}
/// Encrypts the 8-byte padded buffer
///
/// - Parameters:
/// - l: left half
/// - r: right half
fileprivate func encryptBlowfishBlock(l: inout UInt32, r: inout UInt32) {
var Xl = l
var Xr = r
for i in 0..<N {
Xl = Xl ^ P[i]
Xr = F(x: Xl) ^ Xr
(Xl, Xr) = (Xr, Xl)
}
(Xl, Xr) = (Xr, Xl)
Xr = Xr ^ P[self.N]
Xl = Xl ^ P[self.N + 1]
l = Xl
r = Xr
}
/// Decrypts the 8-byte padded buffer
///
/// - Parameters:
/// - l: left half
/// - r: right half
fileprivate func decryptBlowfishBlock(l: inout UInt32, r: inout UInt32) {
var Xl = l
var Xr = r
for i in (2...N + 1).reversed() {
Xl = Xl ^ P[i]
Xr = F(x: Xl) ^ Xr
(Xl, Xr) = (Xr, Xl)
}
(Xl, Xr) = (Xr, Xl)
Xr = Xr ^ P[1]
Xl = Xl ^ P[0]
l = Xl
r = Xr
}
private func F(x: UInt32) -> UInt32 {
let f1 = S[0][Int(x >> 24) & 0xff]
let f2 = S[1][Int(x >> 16) & 0xff]
let f3 = S[2][Int(x >> 8) & 0xff]
let f4 = S[3][Int(x & 0xff)]
return ((f1 &+ f2) ^ f3) &+ f4
}
}
extension Blowfish: Cipher {
/// Encrypt the 8-byte padded buffer, block by block. Note that for amounts of data larger than a block, it is not safe to just call encrypt() on successive blocks.
///
/// - Parameter bytes: Plaintext data
/// - Returns: Encrypted data
public func encrypt<C: Collection>(_ bytes: C) throws -> Array<UInt8> where C.Element == UInt8, C.IndexDistance == Int, C.Index == Int {
let bytes = padding.add(to: Array(bytes), blockSize: Blowfish.blockSize) // FIXME: Array(bytes) copies
var out = Array<UInt8>()
out.reserveCapacity(bytes.count)
for chunk in bytes.batched(by: Blowfish.blockSize) {
out += encryptWorker.encrypt(chunk)
}
if blockMode.options.contains(.paddingRequired) && (out.count % Blowfish.blockSize != 0) {
throw Error.dataPaddingRequired
}
return out
}
/// Decrypt the 8-byte padded buffer
///
/// - Parameter bytes: Ciphertext data
/// - Returns: Plaintext data
public func decrypt<C: Collection>(_ bytes: C) throws -> Array<UInt8> where C.Element == UInt8, C.IndexDistance == Int, C.Index == Int {
if blockMode.options.contains(.paddingRequired) && (bytes.count % Blowfish.blockSize != 0) {
throw Error.dataPaddingRequired
}
var out = Array<UInt8>()
out.reserveCapacity(bytes.count)
for chunk in Array(bytes).batched(by: Blowfish.blockSize) {
out += decryptWorker.decrypt(chunk) // FIXME: copying here is innefective
}
out = padding.remove(from: out, blockSize: Blowfish.blockSize)
return out
}
}
|
apache-2.0
|
a834f78f04fc00e39ddb270e9f7f175d
| 43.459963 | 217 | 0.624963 | 2.375149 | false | false | false | false |
335g/Bass
|
Bass/Types/State.swift
|
1
|
6600
|
// Copyright © 2016 Yoshiki Kudo. All rights reserved.
// MARK: - StateType
public protocol StateType: Pointed {
associatedtype StateS
associatedtype ResultS
associatedtype ValuesS = (ResultS, StateS)
var run: StateS -> Identity<ValuesS> { get }
init(_ run: StateS -> Identity<ValuesS>)
}
// MARK: - StateType: Pointed
public extension StateType {
public typealias PointedValue = ResultS
public static func pure(a: ResultS) -> Self {
return Self.init {
Identity((a, $0) as! ValuesS)
}
}
}
// MARK: - StateType - method
public extension StateType where ValuesS == (ResultS, StateS) {
/// Evaluate a state computation with the given initial state and
/// return the final value, discarding the final state.
public func eval(state: StateS) -> ResultS {
return run(state).value.0
}
/// Evaluate a state computation with the given initial state and
/// return the final state, discarding the final value.
public func exec(state: StateS) -> StateS {
return run(state).value.1
}
/// `with(f:)` executes action on a state modified by applying `f`.
public func with(f: StateS -> StateS) -> Self {
return Self.init {
self.run(f($0))
}
}
}
// MARK: - StateType - map/flatMap
public extension StateType where ValuesS == (ResultS, StateS) {
public func map<Result2>(f: (ResultS, StateS) -> (Result2, StateS)) -> State<StateS, Result2, (Result2, StateS)> {
return State {
let (r, s) = self.run($0).value
return Identity(f(r, s))
}
}
public func map<Result2>(f: ResultS -> Result2) -> State<StateS, Result2, (Result2, StateS)> {
return map { r, s in (f(r), s) }
}
public func flatMap<Result2>(fn: ResultS -> State<StateS, Result2, (Result2, StateS)>) -> State<StateS, Result2, (Result2, StateS)> {
return State { s in
self.run(s).map{ fn($0).run($1).value }
}
}
public func ap<Result2, ST: StateType where ST.StateS == StateS, ST.ResultS == ResultS -> Result2, ST.ValuesS == (ResultS -> Result2, StateS)>(fn: ST) -> State<StateS, Result2, (Result2, StateS)> {
return State { s in
fn.run(s).flatMap{ f, s2 in
self.run(s2).map{ (f($0), $1) }
}
}
}
}
/// Alias for `map(f:)`
public func <^> <S, R1, R2, ST: StateType where ST.StateS == S, ST.ResultS == R1, ST.ValuesS == (R1, S)>(f: R1 -> R2, state: ST) -> State<S, R2, (R2, S)> {
return state.map(f)
}
/// Alias for `flatMap(g:)`
public func >>- <S, R1, R2, ST: StateType where ST.StateS == S, ST.ResultS == R1, ST.ValuesS == (R1, S)>(state: ST, f: R1 -> State<S, R2, (R2, S)>) -> State<S, R2, (R2, S)> {
return state.flatMap(f)
}
/// Alias for `ap(fn:)`
public func <*> <S, R1, R2, ST1: StateType, ST2: StateType where ST1.StateS == S, ST1.ResultS == R1 -> R2, ST1.ValuesS == (R1 -> R2, S), ST2.StateS == S, ST2.ResultS == R1, ST2.ValuesS == (R1, S)>(fn: ST1, g: ST2) -> State<S, R2, (R2, S)> {
return g.ap(fn)
}
// MARK: - StateType (ValuesS: OptionalType) - map/flatMap
public extension StateType where ValuesS == (ResultS, StateS)? {
public func map<Result2>(f: (ResultS, StateS) -> (Result2, StateS)) -> State<StateS, Result2, (Result2, StateS)?> {
return State {
Identity(f <^> self.run($0).value)
}
}
public func map<Result2>(f: ResultS -> Result2) -> State<StateS, Result2, (Result2, StateS)?> {
return map { r, s in (f(r), s) }
}
public func flatMap<Result2>(fn: ResultS -> State<StateS, Result2, (Result2, StateS)>) -> State<StateS, Result2, (Result2, StateS)?> {
return State { s in
self.run(s).map { fn($0).run($1).value }
}
}
public func ap<Result2, ST: StateType where ST.StateS == StateS, ST.ResultS == ResultS -> Result2, ST.ValuesS == (ResultS -> Result2, StateS)>(fn: ST) -> State<StateS, Result2, (Result2, StateS)?> {
return State { s in
fn.run(s).flatMap{ f, s2 in
self.run(s2).map{ (f($0), $1) }
}
}
}
}
/// Alias for `map(f:)`
public func <^> <S, R1, R2, ST: StateType where ST.StateS == S, ST.ResultS == R1, ST.ValuesS == (R1, S)?>(f: R1 -> R2, state: ST) -> State<S, R2, (R2, S)?> {
return state.map(f)
}
/// Alias for `flatMap(g:)`
public func >>- <S, R1, R2, ST: StateType where ST.StateS == S, ST.ResultS == R1, ST.ValuesS == (R1, S)?>(state: ST, f: R1 -> State<S, R2, (R2, S)>) -> State<S, R2, (R2, S)?> {
return state.flatMap(f)
}
/// Alias for `ap(fn:)`
public func <*> <S, R1, R2, ST1: StateType, ST2: StateType where ST1.StateS == S, ST1.ResultS == R1 -> R2, ST1.ValuesS == (R1 -> R2, S), ST2.StateS == S, ST2.ResultS == R1, ST2.ValuesS == (R1, S)?>(fn: ST1, g: ST2) -> State<S, R2, (R2, S)?> {
return g.ap(fn)
}
// MAKR: - State - Kleisli
public func >>->> <S, A, B, C>(left: A -> State<S, B, (B, S)>, right: B -> State<S, C, (C, S)>) -> A -> State<S, C, (C, S)> {
return { left($0) >>- right }
}
public func <<-<< <S, A, B, C>(left: B -> State<S, C, (C, S)>, right: A -> State<S, B, (B, S)>) -> A -> State<S, C, (C, S)> {
return right >>->> left
}
// MARK: - Lift
public func lift<S, A, B, C>(f: (A, B) -> C) -> State<S, A -> B -> C, (A -> B -> C, S)> {
return .pure(curry(f))
}
public func lift<S, A, B, C, D>(f: (A, B, C) -> D) -> State<S, A -> B -> C -> D, (A -> B -> C -> D, S)> {
return .pure(curry(f))
}
public func lift<S, A, B, C, D, E>(f: (A, B, C, D) -> E) -> State<S, A -> B -> C -> D -> E, (A -> B -> C -> D -> E, S)> {
return .pure(curry(f))
}
// MARK: - State
public struct State<S, A, V> {
public let run: S -> Identity<V>
}
// MARK: - State: StateType
extension State: StateType {
public typealias StateS = S
public typealias ResultS = A
public typealias ValuesS = V
public init(_ run: S -> Identity<V>) {
self.run = run
}
}
// MARK: - State: Pointed
public extension State {
public typealias PointedValue = A
}
// MARK: - Functions
/// Fetch the current value of the state within the monad.
public func get<S>() -> State<S, S, (S, S)> {
return State {
Identity($0, $0)
}
}
/// `put(state:)` sets the state within the monad to `s`
public func put<S>(state: S) -> State<S, (), ((), S)> {
return State { _ in
Identity((), state)
}
}
/// Get a specific component of the state, using a projection function supplied.
public func gets<S, A>(f: S -> A) -> State<S, A, (A, S)> {
return State {
Identity(f($0), $0)
}
}
/// `modify(f:)` is an action that updates the state to the result of applying `f`
/// to the current state.
public func modify<S>(f: S -> S) -> State<S, (), ((), S)> {
return State {
Identity((), f($0))
}
}
/// A variant of `modify(f:)` in which the computation is strict in the new state.
public func modify2<S>(f: S -> S) -> State<S, (), ((), S)> {
return get() >>- { put(f($0)) }
}
|
mit
|
186008af1f037e242cd05613cd22ec3e
| 28.859729 | 242 | 0.595545 | 2.621772 | false | false | false | false |
mapsme/omim
|
iphone/Maps/UI/PlacePage/PlacePageLayout/Content/UGC/UGCAddReview/UGCAddReviewController.swift
|
5
|
4426
|
@objc(MWMGCReviewSaver)
protocol UGCReviewSaver {
typealias onSaveHandler = (Bool) -> Void
func saveUgc(placePageData: PlacePageData, model: UGCReviewModel, language: String, resultHandler: @escaping onSaveHandler)
}
@objc(MWMUGCAddReviewController)
final class UGCAddReviewController: MWMTableViewController {
private weak var textCell: UGCAddReviewTextCell?
private var reviewPosted = false
private enum Sections {
case ratings
case text
}
private let placePageData: PlacePageData
private let model: UGCReviewModel
private let saver: UGCReviewSaver
private var sections: [Sections] = []
@objc init(placePageData: PlacePageData, rating: UgcSummaryRatingType, saver: UGCReviewSaver) {
self.placePageData = placePageData
self.saver = saver
let ratings = placePageData.ratingCategories.map {
UGCRatingStars(title: $0, value: CGFloat(rating.rawValue))
}
model = UGCReviewModel(ratings: ratings, text: "")
super.init(nibName: toString(UGCAddReviewController.self), bundle: nil)
title = placePageData.previewData.title
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
sections.append(.ratings)
sections.append(.text)
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .done, target: self, action: #selector(onDone))
configTableView()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if isMovingFromParent && !reviewPosted {
Statistics.logEvent(kStatUGCReviewCancel)
}
}
private func configTableView() {
tableView.registerNib(cellClass: UGCAddReviewRatingCell.self)
tableView.registerNib(cellClass: UGCAddReviewTextCell.self)
tableView.estimatedRowHeight = 48
tableView.rowHeight = UITableView.automaticDimension
}
@objc private func onDone() {
guard let text = textCell?.reviewText else {
assertionFailure()
return
}
reviewPosted = true
model.text = text
saver.saveUgc(placePageData: placePageData,
model: model,
language: textCell?.reviewLanguage ?? "en",
resultHandler: { (saveResult) in
guard let nc = self.navigationController else { return }
if !saveResult {
nc.popViewController(animated: true)
return
}
Statistics.logEvent(kStatUGCReviewSuccess)
let onSuccess = { Toast.toast(withText: L("ugc_thanks_message_auth")).show() }
let onError = { Toast.toast(withText: L("ugc_thanks_message_not_auth")).show() }
let onComplete = { () -> Void in nc.popToRootViewController(animated: true) }
if User.isAuthenticated() || !FrameworkHelper.isNetworkConnected() {
if User.isAuthenticated() {
onSuccess()
} else {
onError()
}
nc.popViewController(animated: true)
} else {
let authVC = AuthorizationViewController(barButtonItem: self.navigationItem.rightBarButtonItem!,
source: .afterSaveReview,
successHandler: {_ in onSuccess()},
errorHandler: {_ in onError()},
completionHandler: {_ in onComplete()})
self.present(authVC, animated: true, completion: nil)
}
})
}
override func numberOfSections(in _: UITableView) -> Int {
return sections.count
}
override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
switch sections[section] {
case .ratings: return model.ratings.count
case .text: return 1
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch sections[indexPath.section] {
case .ratings:
let cell = tableView.dequeueReusableCell(withCellClass: UGCAddReviewRatingCell.self, indexPath: indexPath) as! UGCAddReviewRatingCell
cell.model = model.ratings[indexPath.row]
return cell
case .text:
let cell = tableView.dequeueReusableCell(withCellClass: UGCAddReviewTextCell.self, indexPath: indexPath) as! UGCAddReviewTextCell
cell.reviewText = model.text
textCell = cell
return cell
}
}
}
|
apache-2.0
|
37b7f29c22b4464a0fb4a549e6bb438c
| 33.310078 | 139 | 0.665612 | 4.863736 | false | false | false | false |
webventil/Kroekln
|
Kroekln/Kroekln/DatabaseManager.swift
|
1
|
5196
|
//
// DatabaseManager.swift
// Kroekln
//
// Created by Arne Tempelhof on 03.11.14.
// Copyright (c) 2014 webventil. All rights reserved.
//
import UIKit
import CoreData
class DatabaseManager: NSObject {
internal class func shared()->DatabaseManager {
struct Static{
static let s_manager = DatabaseManager()
}
return Static.s_manager
}
func createPlayer() -> Player
{
let entityName: String = "Player"
let entityDescription = NSEntityDescription.entityForName(entityName, inManagedObjectContext: managedObjectContext!)
var player: Player = Player(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext)
return player
}
internal func getPlayer() -> Player
{
var request = NSFetchRequest()
request.entity = NSEntityDescription.entityForName("Player", inManagedObjectContext: DatabaseManager.shared().managedObjectContext!)
var error: NSError? = nil
var results = managedObjectContext?.executeFetchRequest(request, error: &error)
if results?.count > 0 {
let player = results?.first as? Player
return player!
} else {
var player = createPlayer()
saveContext()
return player
}
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "com.webventil.Kroekln" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
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.
var modelURL = NSBundle.mainBundle().URLForResource("Kroekln", withExtension: "momd")
if(modelURL == nil) {
modelURL = NSBundle.mainBundle().URLForResource("Kroekln", withExtension: "mom")
}
return NSManagedObjectModel(contentsOfURL: modelURL!)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return 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
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Kroekln.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = 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 \(error), \(error!.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
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
internal func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// 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.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
|
mit
|
973a0a24bb4c32c7287713305e96e035
| 43.033898 | 288 | 0.693803 | 5.504237 | false | false | false | false |
jarocht/iOS-Bootcamp-Summer2015
|
HW5/AutoLayoutDistanceCalculator/DistanceCalculator/ViewController.swift
|
1
|
1481
|
//
// ViewController.swift
// DistanceCalculator
//
// Created by X Code User on 7/14/15.
// Copyright (c) 2015 gvsu.edu. All rights reserved.
//
// Remo Hoeppli & Tim Jaroch
// GVSU - CIS 380 - Lab03
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var clearButton: UIButton!
@IBOutlet weak var convertButton: UIButton!
@IBOutlet weak var inputTextField: UITextField!
@IBOutlet weak var resultLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func supportedInterfaceOrientations() -> Int {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
@IBAction func ConvertBtnClick(sender: AnyObject) {
if (inputTextField.text != nil){
var input: Double = (inputTextField.text as NSString).doubleValue
var result = input * 1.60934
resultLabel.text = String(format: "Distance is %.6f Kilometers", result)
hideKeyboard()
}
}
@IBAction func ClearBtnClick(sender: AnyObject) {
inputTextField.text = ""
resultLabel.text = ""
hideKeyboard()
}
func hideKeyboard(){
self.inputTextField.resignFirstResponder()
}
}
|
gpl-2.0
|
1c9cfca2ca6d0bcc3c4dfbc00ec4643b
| 27.480769 | 84 | 0.64551 | 4.746795 | false | false | false | false |
tkremenek/swift
|
test/IRGen/class_resilience_thunks.swift
|
20
|
3175
|
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_class_thunks.swiftmodule -module-name=resilient_class_thunks %S/../Inputs/resilient_class_thunks.swift
// RUN: %target-swift-frontend -I %t -emit-ir %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
// RUN: %target-swift-frontend -I %t -emit-ir -O %s
// CHECK: %swift.type = type { [[INT:i32|i64]] }
import resilient_class_thunks
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s23class_resilience_thunks21testDispatchThunkBase1b1ty010resilient_a1_C00G0CyxG_xtlF"(%T22resilient_class_thunks4BaseC* %0, %swift.opaque* noalias nocapture %1)
public func testDispatchThunkBase<T>(b: Base<T>, t: T) {
// CHECK: call swiftcc void @"$s22resilient_class_thunks4BaseC6takesTyyxFTj"(%swift.opaque* noalias nocapture {{%.*}}, %T22resilient_class_thunks4BaseC* swiftself %0)
b.takesT(t)
// CHECK: call swiftcc void @"$s22resilient_class_thunks4BaseC8takesIntyySiFTj"([[INT]] 0, %T22resilient_class_thunks4BaseC* swiftself %0)
b.takesInt(0)
// CHECK: call swiftcc void @"$s22resilient_class_thunks4BaseC14takesReferenceyyAA6ObjectCFTj"(%T22resilient_class_thunks6ObjectC* {{%.*}}, %T22resilient_class_thunks4BaseC* swiftself %0)
b.takesReference(Object())
// CHECK: ret void
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s23class_resilience_thunks24testDispatchThunkDerived1dy010resilient_a1_C00G0C_tF"(%T22resilient_class_thunks7DerivedC* %0)
public func testDispatchThunkDerived(d: Derived) {
// CHECK: call swiftcc void @"$s22resilient_class_thunks4BaseC6takesTyyxFTj"(%swift.opaque* noalias nocapture dereferenceable({{4|8}}) {{%.*}}, %T22resilient_class_thunks4BaseC* swiftself {{%.*}})
d.takesT(0)
// CHECK: call swiftcc void @"$s22resilient_class_thunks7DerivedC8takesIntyySiSgFTj"([[INT]] 0, i8 1, %T22resilient_class_thunks7DerivedC* swiftself %0)
d.takesInt(nil)
// CHECK: call swiftcc void @"$s22resilient_class_thunks4BaseC14takesReferenceyyAA6ObjectCFTj"(%T22resilient_class_thunks6ObjectC* null, %T22resilient_class_thunks4BaseC* swiftself {{%.*}})
d.takesReference(nil)
// CHECK: ret void
}
// We had a bug where if a non-resilient class overrides a method from a
// resilient class, calling the override would directly access the vtable
// entry of the resilient class, instead of going through the dispatch
// thunk.
open class MyDerived : Base<Int> {
// Override has different formal type but is ABI-compatible
open override func takesReference(_: Object) {}
}
// CHECK-LABEL: define{{( dllexport)?}}{{( protected)?}} swiftcc void @"$s23class_resilience_thunks27testDispatchThunkMyOverride1d1oyAA0G7DerivedC_010resilient_a1_C06ObjectCtF"(%T23class_resilience_thunks9MyDerivedC* %0, %T22resilient_class_thunks6ObjectC* %1)
public func testDispatchThunkMyOverride(d: MyDerived, o: Object) {
// CHECK: call swiftcc void @"$s22resilient_class_thunks4BaseC14takesReferenceyyAA6ObjectCFTj"
d.takesReference(o)
// CHECK: ret void
}
public func testDispatchThunkCast(d: Derived) {
_ = d.returnsSuperclass()
}
|
apache-2.0
|
3574dc8172453194c57d5b2e53c52810
| 51.04918 | 260 | 0.751181 | 3.443601 | false | true | false | false |
corchwll/amos-ss15-proj5_ios
|
MobileTimeAccounting/BusinessLogic/Utilities/VacationTimeHelper.swift
|
1
|
4386
|
/*
Mobile Time Accounting
Copyright (C) 2015
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import Foundation
let vacationTimeHelper = VacationTimeHelper()
class VacationTimeHelper
{
let ExpiringMonth = 4
let calendar = NSCalendar.currentCalendar()
/*
Calculates current vacation days left.
@methodtype Helper
@pre Profile is set
@post Returns current vacation days left
*/
func getCurrentVacationDaysLeft(currentDate: NSDate)->Int
{
let totalVacationDays = profileDAO.getProfile()!.totalVacationTime
let currentDateCompontents = calendar.components(.CalendarUnitMonth | .CalendarUnitYear, fromDate: currentDate)
var currentVacationDays = 0
if currentDateCompontents.month >= ExpiringMonth
{
currentVacationDays = getVacationDaysForYear(currentDateCompontents.year)
}
else
{
currentVacationDays = getVacationDaysForYear(currentDateCompontents.year - 1)
}
return profileDAO.getProfile()!.totalVacationTime - currentVacationDays
}
/*
Calculates vacation days for a given year from delimiter month this year to delimiter month next year.
@methodtype Helper
@pre Delimiter month set to valid month value
@post Returns vacation days for a given year
*/
private func getVacationDaysForYear(year: Int)->Int
{
let fromTime = NSDate(month: ExpiringMonth, year: year, calendar: calendar).startOfMonth()!
let toTime = fromTime.dateByAddingMonths(11)!.endOfMonth()!
return getVacationDaysInRange(fromTime, toTime: toTime) + getInitialVacationDays(fromTime, toTime: toTime)
}
/*
Calculates all vacation days in a given time range.
@methodtype Helper
@pre Valid time range (from time before to time)
@post Vacation day in range are returned
*/
private func getVacationDaysInRange(fromTime: NSDate, toTime: NSDate)->Int
{
let vacationProject = projectManager.getDefaultProject(.Vacation)!
let vacationSessions = sessionDAO.getSessions(fromTime, toTime: toTime, project: vacationProject)
var vacationDays = 0
for vacationSession in vacationSessions
{
vacationDays++
}
return vacationDays
}
/*
Returns initial vacation days (Vacation days on registration). If registration date is in between from and to time the users initial vacation days are returned else 0.
@methodtype Helper
@pre To time after form time
@post Returns initial vacation days
*/
private func getInitialVacationDays(fromTime: NSDate, toTime: NSDate)->Int
{
let registrationDate = profileDAO.getProfile()!.registrationDate
if registrationDate.timeIntervalSince1970 >= fromTime.timeIntervalSince1970 && registrationDate.timeIntervalSince1970 <= toTime.timeIntervalSince1970
{
return profileDAO.getProfile()!.currentVacationTime
}
return 0
}
/*
Validates if vacation days are about to expire, triggers in the last month before expiration.
@methodtype Boolean Query
@pre -
@post Returns if vacation days are about to expire
*/
func isExpiring(currentDate: NSDate)->Bool
{
let currentDateCompontents = calendar.components(.CalendarUnitMonth, fromDate: currentDate)
if currentDateCompontents.month >= ExpiringMonth - 3 && currentDateCompontents.month <= ExpiringMonth - 1
{
return true
}
return false
}
}
|
agpl-3.0
|
74bbb8cd245fa48d6bb7025850a0129e
| 33 | 175 | 0.670087 | 5.064665 | false | false | false | false |
ifabijanovic/swtor-holonet
|
ios/HoloNetTests/Module/App/UI/TestNavigator.swift
|
1
|
1803
|
//
// TestNavigator.swift
// SWTOR HoloNet
//
// Created by Ivan Fabijanovic on 12/03/2017.
// Copyright © 2017 Ivan Fabijanović. All rights reserved.
//
import UIKit
class TestNavigator: Navigator {
var didShowAlert = false
var alertTitle: String?
var alertMessage: String?
var alertActions: [UIAlertAction]?
var didNavigate = false
var navigatedFrom: UIViewController?
var navigatedTo: AppScreen?
var didOpenUrl = false
var openedUrl: URL?
func showAlert(title: String?, message: String?, actions: [UIAlertAction]) {
self.didShowAlert = true
self.alertTitle = title
self.alertMessage = message
self.alertActions = actions
}
func showNetworkErrorAlert(cancelHandler: AlertActionHandler?, retryHandler: AlertActionHandler?) {
self.didShowAlert = true
}
func showMaintenanceAlert(handler: AlertActionHandler?) {
self.didShowAlert = true
}
func navigate(from: UIViewController, to: AppScreen, animated: Bool) {
self.didNavigate = true
self.navigatedFrom = from
self.navigatedTo = to
}
func open(url: URL) {
self.didOpenUrl = true
self.openedUrl = url
}
}
extension TestNavigator {
typealias UIAlertHandler = @convention(block) (UIAlertAction) -> Void
func tap(style: UIAlertActionStyle) {
guard let action = self.alertActions?.filter({ $0.style == style }).first else { return }
if let block = action.value(forKey: "handler") {
let pointer = UnsafeRawPointer(Unmanaged<AnyObject>.passUnretained(block as AnyObject).toOpaque())
let handler = unsafeBitCast(pointer, to: UIAlertHandler.self)
handler(action)
}
}
}
|
gpl-3.0
|
7f856c59add8048aed851837108d8c62
| 27.587302 | 110 | 0.647973 | 4.536524 | false | false | false | false |
pietgk/EuropeanaApp
|
EuropeanaApp/EuropeanaApp/Classes/Model/Operations/GetPOIsOfBeaconOperation.swift
|
1
|
2004
|
//
// GetPOIsOfBeaconOperation.swift
// ArtWhisper
//
// Created by Axel Roest on 04/01/16.
// Copyright © 2016 Phluxus. All rights reserved.
//
/* Get POIs to which this beacon belongs
*/
import Foundation
class GetPOIsOfBeaconOperation : GroupOperation {
// MARK: Properties
// MARK: Initialization
init(beacon:IXBeacon) {
super.init(operations: [])
// should be our URL or
let url = NSURL(string: "http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_month.geojson")!
let task = NSURLSession.sharedSession().downloadTaskWithURL(url) { url, response, error in
self.downloadFinished(url, response: response as? NSHTTPURLResponse, error: error)
}
let taskOperation = URLSessionTaskOperation(task: task)
let reachabilityCondition = ReachabilityCondition(host: url)
taskOperation.addCondition(reachabilityCondition)
let networkObserver = NetworkObserver()
taskOperation.addObserver(networkObserver)
addOperation(taskOperation)
}
func downloadFinished(url: NSURL?, response: NSHTTPURLResponse?, error: NSError?) {
if let localURL = url {
// do {
// /*
// If we already have a file at this location, just delete it.
// Also, swallow the error, because we don't really care about it.
// */
// try NSFileManager.defaultManager().removeItemAtURL(cacheFile)
// }
// catch { }
// do {
// try NSFileManager.defaultManager().moveItemAtURL(localURL, toURL: cacheFile)
// }
// catch let error as NSError {
// aggregateError(error)
// }
}
else if let error = error {
aggregateError(error)
}
else {
// Do nothing, and the operation will automatically finish.
}
}
}
|
mit
|
e521ae65ed31b02d23acda1fea2a0578
| 30.3125 | 110 | 0.584124 | 4.615207 | false | false | false | false |
Incipia/Conduction
|
Conduction/Classes/ConductionRoute.swift
|
1
|
4931
|
//
// ConductionRoute.swift
// Bindable
//
// Created by Leif Meyer on 2/3/18.
//
import Foundation
public enum ConductionRouteComponent: Equatable {
case path(String)
case routing(ConductionRouting)
case nonRouting(String, Any?)
// MARK: - Public Properties
public var routingName: String {
switch self {
case .path(let name): return name
case .routing(let router): return router.routingName
case .nonRouting(let name, _): return name
}
}
// MARK: - Equatable
public static func ==(lhs: ConductionRouteComponent, rhs: ConductionRouteComponent) -> Bool {
return lhs.routingName == rhs.routingName
}
}
public struct ConductionRoute: Equatable, RawRepresentable {
// MARK: - Public Properties
public var components: [ConductionRouteComponent] = []
// MARK: - Init
public init() {}
public init(components: [ConductionRouteComponent]) {
self.components = components
}
// MARK: - Public
public func forwardRouteUpdate(route: ConductionRoute, completion: ((_ success: Bool) -> Void)?) -> Bool {
guard route != self else {
completion?(true)
return true
}
var lastRouter: (router: ConductionRouting, index: Int)? = nil
for (index, component) in components.enumerated() {
if index >= route.components.count || component != route.components[index] {
break
}
switch component {
case .routing(let router): lastRouter = (router: router, index: index)
default: break
}
}
guard let router = lastRouter else { return false }
let remainingComponents = router.index < route.components.count ? Array(route.components.suffix(from: router.index + 1)) : []
router.router.update(newRoute: ConductionRoute(components: remainingComponents), completion: completion)
return true
}
// MARK: - Operators
public static func +(lhs: ConductionRoute, rhs: ConductionRoute) -> ConductionRoute {
var components = lhs.components
components.append(contentsOf: rhs.components)
return ConductionRoute(components: components)
}
// MARK: - Equatable
public static func ==(lhs: ConductionRoute, rhs: ConductionRoute) -> Bool {
return lhs.components == rhs.components
}
// MARK: - RawRepresentable
public init?(rawValue: String) {
components = rawValue.split(separator: "/").map { .path(String($0)) }
}
public var rawValue: String {
return components.map { $0.routingName }.joined(separator: "/")
}
}
public protocol ConductionRouting: class {
// MARK: - Public Properties
var routingName: String { get }
var route: ConductionRoute { get }
var navigationContext: UINavigationController? { get }
var modalContext: UIViewController? { get }
weak var routeParent: ConductionRouting? { get set }
var routeChild: ConductionRouting? { get set }
// MARK: - Public
@discardableResult func appendRouteChild(_ conductionRouting: ConductionRouting, animated: Bool) -> Bool
func routeChildRemoved(animated: Bool)
func update(newRoute: ConductionRoute, completion: ((_ success: Bool) -> Void)?)
func showInRoute(routeContext: ConductionRouting, animated: Bool) -> Bool
@discardableResult func dismissFromRoute(animated: Bool) -> Bool
}
public extension ConductionRouting {
// MARK: - Public Properties
var childRoute: ConductionRoute {
guard let routeChild = routeChild else { return ConductionRoute() }
return ConductionRoute(components: [.routing(routeChild)]) + routeChild.route
}
// MARK: - ConductionRouting
var routingName: String { return "" }
var route: ConductionRoute { return childRoute }
var navigationContext: UINavigationController? { return nil }
var modalContext: UIViewController? { return nil }
func showInRoute(routeContext: ConductionRouting, animated: Bool) -> Bool {
routeParent = routeContext
return true
}
@discardableResult func dismissFromRoute(animated: Bool) -> Bool {
routeParent?.routeChildRemoved(animated: animated)
routeParent = nil
return true
}
@discardableResult func appendRouteChild(_ conductionRouting: ConductionRouting, animated: Bool) -> Bool {
if let routeChild = routeChild {
return routeChild.appendRouteChild(conductionRouting, animated: animated)
}
guard conductionRouting.showInRoute(routeContext: self, animated: animated) else { return false }
routeChild = conductionRouting
return true
}
func routeChildRemoved(animated: Bool) {
routeChild = nil
}
// MARK: - Public
func update(newRoute: ConductionRoute, completion: ((_ success: Bool) -> Void)? = nil) {
guard !self.route.forwardRouteUpdate(route: newRoute, completion: completion) else { return }
completion?(false)
}
}
|
mit
|
c09dd6c8d8b8c3bbd91e9f44c8f3ec9a
| 33.243056 | 131 | 0.676942 | 4.490893 | false | false | false | false |
shorlander/firefox-ios
|
Client/Frontend/Settings/CustomSearchViewController.swift
|
4
|
10258
|
/* 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 UIKit
import Shared
import SnapKit
import Storage
import WebImage
import Deferred
private let log = Logger.browserLogger
class CustomSearchError: MaybeErrorType {
enum Reason {
case DuplicateEngine, FormInput
}
var reason: Reason!
internal var description: String {
return "Search Engine Not Added"
}
init(_ reason: Reason) {
self.reason = reason
}
}
class CustomSearchViewController: SettingsTableViewController {
fileprivate var urlString: String?
fileprivate var engineTitle = ""
fileprivate lazy var spinnerView: UIActivityIndicatorView = {
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
spinner.hidesWhenStopped = true
return spinner
}()
override func viewDidLoad() {
super.viewDidLoad()
title = Strings.SettingsAddCustomEngineTitle
view.addSubview(spinnerView)
spinnerView.snp.makeConstraints { make in
make.center.equalTo(self.view.snp.center)
}
}
fileprivate func addSearchEngine(_ searchQuery: String, title: String) {
spinnerView.startAnimating()
let trimmedQuery = searchQuery.trimmingCharacters(in: .whitespacesAndNewlines)
let trimmedTitle = title.trimmingCharacters(in: .whitespacesAndNewlines)
createEngine(forQuery: trimmedQuery, andName: trimmedTitle).uponQueue(DispatchQueue.main) { result in
self.spinnerView.stopAnimating()
guard let engine = result.successValue else {
let alert: UIAlertController
let error = result.failureValue as? CustomSearchError
alert = (error?.reason == .DuplicateEngine) ?
ThirdPartySearchAlerts.duplicateCustomEngine() : ThirdPartySearchAlerts.incorrectCustomEngineForm()
self.navigationItem.rightBarButtonItem?.isEnabled = true
self.present(alert, animated: true, completion: nil)
return
}
self.profile.searchEngines.addSearchEngine(engine)
_ = self.navigationController?.popViewController(animated: true)
SimpleToast().showAlertWithText(Strings.ThirdPartySearchEngineAdded)
}
}
func createEngine(forQuery query: String, andName name: String) -> Deferred<Maybe<OpenSearchEngine>> {
let deferred = Deferred<Maybe<OpenSearchEngine>>()
guard let template = getSearchTemplate(withString: query),
let url = URL(string: template.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlFragmentAllowed)!), url.isWebPage() else {
deferred.fill(Maybe(failure: CustomSearchError(.FormInput)))
return deferred
}
// ensure we haven't already stored this template
guard engineExists(name: name, template: template) == false else {
deferred.fill(Maybe(failure: CustomSearchError(.DuplicateEngine)))
return deferred
}
FaviconFetcher.fetchFavImageForURL(forURL: url, profile: profile).uponQueue(DispatchQueue.main) { result in
let image = result.successValue ?? FaviconFetcher.getDefaultFavicon(url)
let engine = OpenSearchEngine(engineID: nil, shortName: name, image: image, searchTemplate: template, suggestTemplate: nil, isCustomEngine: true)
//Make sure a valid scheme is used
let url = engine.searchURLForQuery("test")
let maybe = (url == nil) ? Maybe(failure: CustomSearchError(.FormInput)) : Maybe(success: engine)
deferred.fill(maybe)
}
return deferred
}
private func engineExists(name: String, template: String) -> Bool {
return profile.searchEngines.orderedEngines.contains { (engine) -> Bool in
return engine.shortName == name || engine.searchTemplate == template
}
}
func getSearchTemplate(withString query: String) -> String? {
let SearchTermComponent = "%s" //Placeholder in User Entered String
let placeholder = "{searchTerms}" //Placeholder looked for when using Custom Search Engine in OpenSearch.swift
if query.contains(SearchTermComponent) {
return query.replacingOccurrences(of: SearchTermComponent, with: placeholder)
}
return nil
}
override func generateSettings() -> [SettingSection] {
func URLFromString(_ string: String?) -> URL? {
guard let string = string else {
return nil
}
return URL(string: string)
}
let titleField = CustomSearchEngineTextView(placeholder: Strings.SettingsAddCustomEngineTitlePlaceholder, labelText: Strings.SettingsAddCustomEngineTitleLabel, settingIsValid: { text in
return text != nil && text != ""
}, settingDidChange: {fieldText in
guard let title = fieldText else {
return
}
self.engineTitle = title
})
titleField.textField.accessibilityIdentifier = "customEngineTitle"
let urlField = CustomSearchEngineTextView(placeholder: Strings.SettingsAddCustomEngineURLPlaceholder, labelText: Strings.SettingsAddCustomEngineURLLabel, height: 133, settingIsValid: { text in
//Can check url text text validity here.
return true
}, settingDidChange: {fieldText in
self.urlString = fieldText
})
urlField.textField.autocapitalizationType = .none
urlField.textField.accessibilityIdentifier = "customEngineUrl"
let basicSettings: [Setting] = [titleField, urlField]
let settings: [SettingSection] = [
SettingSection(footerTitle: NSAttributedString(string: "http://youtube.com/search?q=%s"), children: basicSettings)
]
self.navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .save, target: self, action: #selector(self.addCustomSearchEngine(_:)))
self.navigationItem.rightBarButtonItem?.accessibilityIdentifier = "customEngineSaveButton"
return settings
}
func addCustomSearchEngine(_ nav: UINavigationController?) {
self.view.endEditing(true)
navigationItem.rightBarButtonItem?.isEnabled = false
if let url = self.urlString {
self.addSearchEngine(url, title: self.engineTitle)
}
}
}
class CustomSearchEngineTextView: Setting, UITextViewDelegate {
fileprivate let Padding: CGFloat = 8
fileprivate let TextFieldOffset: CGFloat = 80
fileprivate let TextLabelHeight: CGFloat = 44
fileprivate var TextFieldHeight: CGFloat = 44
fileprivate let defaultValue: String?
fileprivate let placeholder: String
fileprivate let labelText: String
fileprivate let settingDidChange: ((String?) -> Void)?
fileprivate let settingIsValid: ((String?) -> Bool)?
let textField = UITextView()
let placeholderLabel = UILabel()
init(defaultValue: String? = nil, placeholder: String, labelText: String, height: CGFloat = 44, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) {
self.defaultValue = defaultValue
self.TextFieldHeight = height
self.settingDidChange = settingDidChange
self.settingIsValid = isValueValid
self.placeholder = placeholder
self.labelText = labelText
textField.addSubview(placeholderLabel)
super.init(cellHeight: TextFieldHeight)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if let id = accessibilityIdentifier {
textField.accessibilityIdentifier = id + "TextField"
}
placeholderLabel.textColor = UIColor(red: 0.0, green: 0.0, blue: 0.0980392, alpha: 0.22)
placeholderLabel.text = placeholder
placeholderLabel.frame = CGRect(x: 0, y: 0, width: textField.frame.width, height: TextLabelHeight)
textField.font = placeholderLabel.font
textField.textContainer.lineFragmentPadding = 0
textField.keyboardType = .URL
textField.autocorrectionType = .no
textField.delegate = self
cell.isUserInteractionEnabled = true
cell.accessibilityTraits = UIAccessibilityTraitNone
cell.contentView.addSubview(textField)
cell.textLabel?.text = labelText
cell.selectionStyle = .none
textField.snp.makeConstraints { make in
make.height.equalTo(TextFieldHeight)
make.trailing.equalTo(cell.contentView).offset(-Padding)
make.leading.equalTo(cell.contentView).offset(TextFieldOffset)
}
cell.textLabel?.snp.remakeConstraints { make in
make.trailing.equalTo(textField.snp.leading).offset(-Padding)
make.leading.equalTo(cell.contentView).offset(Padding)
make.height.equalTo(TextLabelHeight)
}
}
override func onClick(_ navigationController: UINavigationController?) {
textField.becomeFirstResponder()
}
fileprivate func isValid(_ value: String?) -> Bool {
guard let test = settingIsValid else {
return true
}
return test(prepareValidValue(userInput: value))
}
func prepareValidValue(userInput value: String?) -> String? {
return value
}
func textViewDidBeginEditing(_ textView: UITextView) {
placeholderLabel.isHidden = textField.text != ""
}
func textViewDidChange(_ textView: UITextView) {
placeholderLabel.isHidden = textField.text != ""
settingDidChange?(textView.text)
let color = isValid(textField.text) ? UIConstants.TableViewRowTextColor : UIConstants.DestructiveRed
textField.textColor = color
}
func textViewDidEndEditing(_ textView: UITextView) {
placeholderLabel.isHidden = textField.text != ""
settingDidChange?(textView.text)
}
}
|
mpl-2.0
|
b0e075e1ae41dedf9c900f4d4491cbf3
| 38.914397 | 204 | 0.667577 | 5.398947 | false | false | false | false |
SimonLYU/Swift-Transitioning
|
highGo2/LYUBigImageFlowLayout.swift
|
1
|
590
|
//
// LYUBigImageFlowLayout.swift
// highGo2
//
// Created by 吕旭明 on 16/8/4.
// Copyright © 2016年 lyu. All rights reserved.
//
import UIKit
class LYUBigImageFlowLayout: UICollectionViewFlowLayout {
override func prepareLayout() {
itemSize = UIScreen.mainScreen().bounds.size
minimumLineSpacing = 0
minimumInteritemSpacing = 0
scrollDirection = .Horizontal
collectionView?.pagingEnabled = true
collectionView?.showsVerticalScrollIndicator = false
collectionView?.showsHorizontalScrollIndicator = false
}
}
|
mit
|
d8e35627c6aac151d977cc5ed308b649
| 24.26087 | 62 | 0.695353 | 4.882353 | false | false | false | false |
chiehwen/Swift3-Exercises
|
String.swift
|
1
|
355
|
print("Hello World")
let helloString = "Hello"
let worldString = "World"
let combinedString = helloString + worldString
print(helloString)
print(worldString)
print(combinedString)
let myNumber = 10
let theTruth = "My lucky number is \(myNumber)"
print(myNumber)
print(theTruth)
let myString = "1"
Int(myString)
let pi = "3.141596"
Floot(pi)
Double(pi)
|
mit
|
200afe5bdb1455969e37fe575e5120ee
| 16.8 | 47 | 0.749296 | 2.909836 | false | false | false | false |
mparrish91/gifRecipes
|
application/PostCommentViewController.swift
|
1
|
5957
|
//
// PostCommentViewController.swift
// reddift
//
// Created by sonson on 2016/11/21.
// Copyright © 2016年 sonson. All rights reserved.
//
import reddift
import Foundation
let PostCommentViewControllerDidSendCommentName = Notification.Name(rawValue: "PostCommentViewControllerDidSendCommentName")
class PostCommentViewController: UIViewController, FromFieldViewDelegate {
let thing: Thing
let textView = UITextView(frame: CGRect.zero)
var bottomSpaceConstraint: NSLayoutConstraint?
let fromFieldView = FromFieldView(frame: CGRect.zero)
let fieldHeight = CGFloat(44)
static func controller(with thing: Thing) -> UINavigationController {
let controller = PostCommentViewController(with: thing)
let navigationController = UINavigationController(rootViewController: controller)
return navigationController
}
required init?(coder aDecoder: NSCoder) {
self.thing = Link(id: "")
super.init(coder: aDecoder)
}
init(with thing: Thing) {
self.thing = thing
super.init(nibName: nil, bundle: nil)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
textView.contentOffset = CGPoint(x: 0, y: -108)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func viewDidLoad() {
let views = [
"textView": textView,
"accountBaseView": fromFieldView
]
super.viewDidLoad()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "backOnBarButton"), style: .plain, target: self, action: #selector(PostCommentViewController.close(sender:)))
self.navigationItem.rightBarButtonItem = UIBarButtonItem(image: #imageLiteral(resourceName: "send"), style: .plain, target: self, action: #selector(PostCommentViewController.send(sender:)))
self.view.addSubview(textView)
textView.addSubview(fromFieldView)
textView.translatesAutoresizingMaskIntoConstraints = false
self.view.backgroundColor = UIColor.white
fromFieldView.backgroundColor = UIColor.white
var contentInset = textView.contentInset
contentInset.top = fieldHeight
textView.contentInset = contentInset
fromFieldView.frame = CGRect(x: 0, y: -fieldHeight, width: self.view.frame.size.width, height: fieldHeight)
textView.setNeedsLayout()
textView.alwaysBounceVertical = true
self.view.addConstraints (
NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[textView]-0-|", options: NSLayoutFormatOptions(), metrics: nil, views: views)
)
let topConstraint = NSLayoutConstraint(item: self.view, attribute: .top, relatedBy: .equal, toItem: textView, attribute: .top, multiplier: 1, constant: 0)
let bottomSpaceConstraint = NSLayoutConstraint(item: self.view, attribute: .bottom, relatedBy: .equal, toItem: textView, attribute: .bottom, multiplier: 1, constant: 0)
self.bottomSpaceConstraint = bottomSpaceConstraint
self.view.addConstraint(topConstraint)
self.view.addConstraint(bottomSpaceConstraint)
NotificationCenter.default.addObserver(self, selector: #selector(PostCommentViewController.keyboardWillChangeFrame(notification:)), name: .UIKeyboardWillHide, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(PostCommentViewController.keyboardWillChangeFrame(notification:)), name: .UIKeyboardDidChangeFrame, object: nil)
let str = "test\n **bold** \n"
textView.text = str
setupAccountView()
fromFieldView.delegate = self
}
func didTapFromFieldView(sender: FromFieldView) {
if let s = UIApplication.shared.keyWindow?.rootViewController?.storyboard {
let nav = s.instantiateViewController(withIdentifier: "AccountListNavigationController")
self.present(nav, animated: true, completion: nil)
}
}
func setupAccountView() {
}
func close(sender: Any) {
self.dismiss(animated: true, completion: nil)
}
func send(sender: Any) {
do {
try UIApplication.appDelegate()?.session?.postComment(self.textView.text, parentName: thing.name, completion: { (result) in
switch result {
case .failure(let error):
print(error)
case .success(let comment):
print(comment)
DispatchQueue.main.async {
let userInfo: [String: Any] = [
"newComment": comment,
"parent": self.thing
]
self.dismiss(animated: true, completion: nil)
NotificationCenter.default.post(name: PostCommentViewControllerDidSendCommentName, object: nil, userInfo: userInfo)
}
}
})
} catch {
// let nserror = NSError(domain: "", code: 0, userInfo: [NSLocalizedDescriptionKey:"\(error)"])
// postNotification(name: LinkContainerCellarDidLoadName, userInfo: [LinkContainerCellar.errorKey: nserror, LinkContainerCellar.providerKey: self])
}
// self.dismiss(animated: true, completion: nil)
}
func keyboardWillChangeFrame(notification: Notification) {
if let userInfo = notification.userInfo {
if let rect = userInfo[UIKeyboardFrameEndUserInfoKey] as? CGRect, let bottomSpaceConstraint = self.bottomSpaceConstraint {
print(rect)
let h = self.view.frame.size.height - rect.origin.y
bottomSpaceConstraint.constant = h
}
}
}
}
|
mit
|
e3ae60022f1e80b7847936c772ce8a4e
| 40.636364 | 208 | 0.645784 | 5.245815 | false | false | false | false |
kickstarter/ios-oss
|
Library/ViewModels/ResetPasswordViewModel.swift
|
1
|
3663
|
import KsApi
import ReactiveExtensions
import ReactiveSwift
public protocol ResetPasswordViewModelInputs {
/// Call when the view loads
func viewDidLoad()
/// Call when email textfield input is entered
func emailChanged(_ email: String?)
/// Call when reset button is pressed
func resetButtonPressed()
/// Call when OK button is pressed on reset confirmation popup
func confirmResetButtonPressed()
}
public protocol ResetPasswordViewModelOutputs {
/// Sets whether the email text field is the first responder.
var emailTextFieldBecomeFirstResponder: Signal<(), Never> { get }
/// Emits email address to set email textfield
var setEmailInitial: Signal<String, Never> { get }
/// Emits Bool representing form validity
var formIsValid: Signal<Bool, Never> { get }
/// Emits email String when reset is successful
var showResetSuccess: Signal<String, Never> { get }
/// Emits after user closes popup confirmation
var returnToLogin: Signal<(), Never> { get }
/// Emits error message String on reset fail
var showError: Signal<String, Never> { get }
}
public protocol ResetPasswordViewModelType {
var inputs: ResetPasswordViewModelInputs { get }
var outputs: ResetPasswordViewModelOutputs { get }
}
public final class ResetPasswordViewModel: ResetPasswordViewModelType, ResetPasswordViewModelInputs,
ResetPasswordViewModelOutputs {
public init() {
self.emailTextFieldBecomeFirstResponder = self.viewDidLoadProperty.signal
self.setEmailInitial = self.emailProperty.signal.skipNil()
.takeWhen(self.viewDidLoadProperty.signal)
.take(first: 1)
self.formIsValid = self.viewDidLoadProperty.signal
.flatMap { [email = emailProperty.producer] _ in email }
.map { $0 ?? "" }
.map(isValidEmail)
.skipRepeats()
let resetEvent = self.emailProperty.signal.skipNil()
.takeWhen(self.resetButtonPressedProperty.signal)
.switchMap { email in
AppEnvironment.current.apiService.resetPassword(email: email)
.mapConst(email)
.materialize()
}
self.showResetSuccess = resetEvent.values().map { email in
Strings.forgot_password_we_sent_an_email_to_email_address_with_instructions_to_reset_your_password(
email: email
)
}
self.showError = resetEvent.errors()
.map { envelope in
if envelope.httpCode == 404 {
return Strings.forgot_password_error()
} else {
return Strings.general_error_something_wrong()
}
}
self.returnToLogin = self.confirmResetButtonPressedProperty.signal
}
fileprivate let viewDidLoadProperty = MutableProperty(())
public func viewDidLoad() {
self.viewDidLoadProperty.value = ()
}
fileprivate let emailProperty = MutableProperty<String?>(nil)
public func emailChanged(_ email: String?) {
self.emailProperty.value = email
}
fileprivate let resetButtonPressedProperty = MutableProperty(())
public func resetButtonPressed() {
self.resetButtonPressedProperty.value = ()
}
fileprivate let confirmResetButtonPressedProperty = MutableProperty(())
public func confirmResetButtonPressed() {
self.confirmResetButtonPressedProperty.value = ()
}
public let emailTextFieldBecomeFirstResponder: Signal<(), Never>
public let formIsValid: Signal<Bool, Never>
public let showResetSuccess: Signal<String, Never>
public var returnToLogin: Signal<(), Never>
public var setEmailInitial: Signal<String, Never>
public let showError: Signal<String, Never>
public var inputs: ResetPasswordViewModelInputs { return self }
public var outputs: ResetPasswordViewModelOutputs { return self }
}
|
apache-2.0
|
99b590ee5ad9ac2335303b8c9ca0a8de
| 33.556604 | 105 | 0.729457 | 4.807087 | false | false | false | false |
Chaosspeeder/YourGoals
|
YourGoals/Business/Data Model/Generator/TestDataGenerator.swift
|
1
|
1273
|
//
// TestDataGenerator.swift
// YourFitnessPlan
//
// Created by André Claaßen on 21.05.16.
// Copyright © 2016 André Claaßen. All rights reserved.
//
import Foundation
import UIKit
class TestDataGenerator {
let manager:GoalsStorageManager!
let generators:[GeneratorProtocol]
init(manager:GoalsStorageManager) {
self.manager = manager
generators = [
StrategyGenerator(manager: self.manager),
TasksGenerator(manager: self.manager)
]
}
func generate() throws {
try manager.deleteRepository()
try generators.forEach{ try $0.generate() }
try manager.saveContext()
}
}
class TestDataInitializer:Initializer {
func initialize(context: InitializerContext) {
do {
let retriever = StrategyManager(manager: context.defaultStorageManager)
let strategy = try retriever.retrieveActiveStrategy()
let generator = TestDataGenerator(manager: context.defaultStorageManager)
if strategy == nil {
try generator.generate()
}
}
catch let error {
fatalError("couldn't create or access test data: \(error.localizedDescription)")
}
}
}
|
lgpl-3.0
|
155dc5a4ffe6715957e1290ba59ba151
| 25.978723 | 92 | 0.626972 | 4.953125 | false | true | false | false |
talk2junior/iOSND-Beginning-iOS-Swift-3.0
|
Playground Collection/Part 2 - Robot Maze 2/Branching with If Statements/Bouncer.playground/Contents.swift
|
1
|
954
|
//:If Statements Exercise: The Bouncer
// Here's the struct the represents the people who want to come in to the club
struct Clubgoer {
var name: String
var age: Int
var onGuestList: Bool
init(name: String, age:Int, onGuestList: Bool){
self.name = name
self.age = age
self.onGuestList = onGuestList
}
}
// Here are the people who want to come in.
var ayush = Clubgoer(name: "Ayush", age: 19, onGuestList: true)
var gabrielle = Clubgoer(name: "Gabrielle", age: 29, onGuestList: true)
var chris = Clubgoer(name: "Chris", age: 32, onGuestList: false)
func admit(person: Clubgoer) {
print("\(person.name), come and party with us!")
}
func deny(person: Clubgoer) {
print("Sorry, \(person.name), maybe you can go play Bingo with the Android team.")
}
func screen(person: Clubgoer) {
// TODO: Add your if statement here!
}
func screenUnder21(_ person: Clubgoer) {
// TODO: Add your if statement here!
}
|
mit
|
fe7667a6a414aa7687ebe4d9df72a77e
| 27.058824 | 86 | 0.678197 | 3.212121 | false | false | false | false |
younata/RSSClient
|
TethysAppSpecs/SettingsRepositorySpec.swift
|
1
|
2871
|
import Quick
import Nimble
import Tethys
private class FakeSettingsRepositorySubscriber: NSObject, SettingsRepositorySubscriber {
fileprivate var didCallChangeSetting = false
fileprivate func didChangeSetting(_: SettingsRepository) {
didCallChangeSetting = true
}
}
class SettingsRepositorySpec: QuickSpec {
override func spec() {
var subject: SettingsRepository! = nil
var userDefaults: FakeUserDefaults! = nil
var subscriber: FakeSettingsRepositorySubscriber! = nil
beforeEach {
userDefaults = FakeUserDefaults()
subject = SettingsRepository(userDefaults: userDefaults)
subscriber = FakeSettingsRepositorySubscriber()
subject.addSubscriber(subscriber)
subscriber.didCallChangeSetting = false
}
it("calls 'didChangeSetting' on the new subscriber whenever it's added") {
let newSubscriber = FakeSettingsRepositorySubscriber()
subject.addSubscriber(newSubscriber)
expect(newSubscriber.didCallChangeSetting) == true
expect(subscriber.didCallChangeSetting) == false
}
describe("estimatedReadingLabel") {
it("is initially yes") {
expect(subject.showEstimatedReadingLabel) == true
}
describe("when set") {
beforeEach {
subject.showEstimatedReadingLabel = false
}
it("records the result") {
expect(subject.showEstimatedReadingLabel) == false
}
it("notifies subscribers") {
expect(subscriber.didCallChangeSetting) == true
}
it("persists if userDefaults is not nil") {
let newRepository = SettingsRepository(userDefaults: userDefaults)
expect(newRepository.showEstimatedReadingLabel) == false
}
}
}
describe("refreshControl") {
it("is initially .spinner") {
expect(subject.refreshControl) == RefreshControlStyle.spinner
}
describe("when set") {
beforeEach {
subject.refreshControl = .breakout
}
it("records the result") {
expect(subject.refreshControl) == RefreshControlStyle.breakout
}
it("notifies subscribers") {
expect(subscriber.didCallChangeSetting) == true
}
it("persists if userDefaults is not nil") {
let newRepository = SettingsRepository(userDefaults: userDefaults)
expect(newRepository.refreshControl) == RefreshControlStyle.breakout
}
}
}
}
}
|
mit
|
dd40329b1c8925e999ddb0e20678681b
| 33.178571 | 88 | 0.574713 | 6.056962 | false | false | false | false |
zjjzmw1/SwiftCodeFragments
|
SwiftCodeFragments/CodeFragments/Category/String+JCString.swift
|
1
|
6709
|
//
// String+JCString.swift
// JCSwiftKitDemo
//
// Created by molin.JC on 2017/1/6.
// Copyright © 2017年 molin. All rights reserved.
//
import Foundation
import UIKit
extension String {
public var length: Int {
get {
return self.characters.count;
}
}
func toNumber() -> NSNumber? {
let number = NumberFormatter.init().number(from: self);
return number;
}
func toInt() -> Int? {
let number = self.toNumber();
if (number != nil) {
return number?.intValue;
}
return 0;
}
func toFloat() -> Float? {
let number = self.toNumber();
if (number != nil) {
return number?.floatValue;
}
return 0;
}
func toBool() -> Bool? {
let number = self.toInt()!;
if (number > 0) {
return true;
}
let lowercased = self.lowercased()
switch lowercased {
case "true", "yes", "1":
return true;
case "false", "no", "0":
return false;
default:
return false;
}
}
/// UTF8StringEncoding编码转换成Data
func dataUsingUTF8StringEncoding() -> Data? {
return self.data(using: String.Encoding.utf8);
}
/// 获取当前的日期,格式为:yyyy-MM-dd HH:mm:ss
static func dateString() -> String {
return NSDate.init().string();
}
/// 获取当前的日期, 格式自定义
func dateString(format: String) -> String {
return NSDate.init().stringWithFormat(format: format);
}
/// 根据字体大小计算文本的Size
func widthFor(font: UIFont) -> CGFloat {
return self.sizeFor(font: font, size: CGSize.init(width: CGFloat(MAXFLOAT), height: CGFloat(MAXFLOAT))).width;
}
func heightFor(font: UIFont) -> CGFloat {
return self.heightFor(font: font, width: CGFloat(MAXFLOAT));
}
func heightFor(font: UIFont, width: CGFloat) -> CGFloat {
return self.sizeFor(font: font, size: CGSize.init(width: width, height: CGFloat(MAXFLOAT))).height;
}
func sizeFor(font: UIFont, size: CGSize) -> CGSize {
return self.sizeFor(font: font, size: size, lineBreakMode: NSLineBreakMode.byWordWrapping);
}
/// 根据字体大小,所要显示的size,以及字段样式来计算文本的size
///
/// - Parameters:
/// - font: 字体
/// - size: 所要显示的size
/// - lineBreakMode: 字段样式
/// - Returns: CGSize大小
func sizeFor(font: UIFont?, size: CGSize, lineBreakMode: NSLineBreakMode) -> CGSize {
var cFont = font;
if (cFont == nil) {
cFont = UIFont.systemFont(ofSize: 15);
}
var attr = Dictionary<String, Any>.init();
attr[NSFontAttributeName] = cFont;
if (lineBreakMode != NSLineBreakMode.byWordWrapping) {
let paragraphStyle = NSMutableParagraphStyle.init();
paragraphStyle.lineBreakMode = lineBreakMode;
attr[NSParagraphStyleAttributeName] = paragraphStyle;
}
let rect = (self as NSString).boundingRect(with: size, options: [NSStringDrawingOptions.usesLineFragmentOrigin, NSStringDrawingOptions.usesFontLeading], attributes: attr, context: nil);
return rect.size;
}
/// 去掉头尾的空格
func stringByTrimSpace() -> String {
let set = CharacterSet.whitespacesAndNewlines;
return self.trimmingCharacters(in: set);
}
/// 替换掉某个字符串
///
/// - Parameters:
/// - replacement: 要替换成的字符串
/// - targets: 要被替换的字符串
/// - Returns: String
func stringReplacement(replacement: String, targets: String...) -> String? {
var complete = self;
for target in targets {
complete = complete.replacingOccurrences(of: target, with: replacement);
}
return complete;
}
/// 是否包含某字符串
func contain(ofString: String) -> Bool {
return (self.range(of: ofString) != nil);
}
/// 根据正则表达式判断
///
/// - Parameter format: 正则表达式的样式
/// - Returns: Bool
func evaluate(format: String) -> Bool {
let predicate = NSPredicate.init(format: "SELF MATCHES %@", format);
return predicate.evaluate(with: self);
}
/// 邮箱的正则表达式
func regexpEmail() -> Bool {
let format = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
return self.evaluate(format: format);
}
/// IP地址的正则表达式
func regexpIp() -> Bool {
let format = "((2[0-4]\\d|25[0-5]|[01]?\\d\\d?)\\.){3}(2[0-4]\\d|25[0-5]|[01]?\\d\\d?)"
return self.evaluate(format: format);
}
/// HTTP链接 (例如 http://www.baidu.com )
func regexpHTTP() -> Bool {
let format = "([hH]ttp[s]{0,1})://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\-~!@#$%^&*+?:_/=<>.\',;]*)?"
return self.evaluate(format: format);
}
/// UUID
static func stringWithUUID() -> String {
let uuid = CFUUIDCreate(nil);
let str = CFUUIDCreateString(nil, uuid);
return str! as String;
}
/// 判断是否是为整数
func isPureInteger() -> Bool {
let scanner = Scanner.init(string: self);
var integerValue: Int?;
return scanner.scanInt(&integerValue!) && scanner.isAtEnd;
}
/// 判断是否为浮点数,可做小数判断
func isPureFloat() -> Bool {
let scanner = Scanner.init(string: self);
var floatValue: Float?;
return scanner.scanFloat(&floatValue!) && scanner.isAtEnd;
}
/// 输出格式:123,456;每隔三个就有","
static func stringFormatterWithDecimal(number: NSNumber) -> String {
return String.stringFormatter(style: NumberFormatter.Style.decimal, number: number);
}
/// number转换百分比: 12,345,600%
static func stringFormatterWithPercent(number: NSNumber) -> String {
return String.stringFormatter(style: NumberFormatter.Style.percent, number: number);
}
/// 设置NSNumber输出的格式
///
/// - Parameters:
/// - style: 格式
/// - number: NSNumber数据
/// - Returns: String
static func stringFormatter(style: NumberFormatter.Style, number: NSNumber) -> String {
let formatter = NumberFormatter.init();
formatter.numberStyle = style;
return formatter.string(from: number)!;
}
}
|
mit
|
51d8613f72a94cf4b051bbd3376651b6
| 28.971429 | 193 | 0.565459 | 4.089669 | false | false | false | false |
mejdan/Swift-TableView-master
|
SwiftTest2/SwiftTableViewController.swift
|
1
|
1663
|
// Copyright (c) 2014 Zack McBride. All rights reserved.
import UIKit
class SwiftTableViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet var tableView : UITableView
let defaultCells = ["First Row table View", "Second Row table View", "Third Row table View", "Fourth Row table View"]
let defaultDetail = ["First Detail", "Second Detail", "Third Detail", "Fourth Detail"]
let defaultSub = [ "First subtitles text","Second subtitles texte", "Third subtitles text", "Fourth subtitles text"]
override func viewDidLoad() {
super.viewDidLoad()
title = "Swift TableView"
tableView.delegate = self
tableView.dataSource = self
}
// UITableViewDataSource Functions
func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
return defaultCells.count
}
func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! {
let data = defaultCells[indexPath.row]
let dataDetail = defaultSub [indexPath.row]
let cell = UITableViewCell(style: .Subtitle, reuseIdentifier: nil)
cell.textLabel.text = data;
cell.detailTextLabel.text = dataDetail
return cell;
}
// UITableViewDelegate Functions
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!) {
let swiftDetailViewController = SwiftDetailViewController(tableViewComment: defaultDetail[indexPath.row])
self.navigationController.pushViewController(swiftDetailViewController, animated: true)
}
}
|
mit
|
67bd7cdbf53420642901e367ced8a7f7
| 35.955556 | 121 | 0.706554 | 5.347267 | false | false | false | false |
danielloureda/congenial-sniffle
|
Project1/Project1/DetailViewController.swift
|
1
|
833
|
//
// DetailViewController.swift
// Project1
//
// Created by Daniel Loureda Arteaga on 18/5/17.
// Copyright © 2017 Dano. All rights reserved.
//
import UIKit
class DetailViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
var selectedImage: String?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.hidesBarsOnTap = true
}
override func viewDidLoad() {
super.viewDidLoad()
if let imageToLoad = selectedImage {
title = imageToLoad
imageView.image = UIImage(named: imageToLoad)
}
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillAppear(animated)
navigationController?.hidesBarsOnTap = false
}
}
|
apache-2.0
|
767e072b3887cec0f5521419f80488ab
| 22.771429 | 57 | 0.652644 | 4.923077 | false | false | false | false |
duming91/Hear-You
|
Pods/RAMAnimatedTabBarController/RAMAnimatedTabBarController/RAMAnimatedTabBarController.swift
|
2
|
13429
|
// AnimationTabBarController.swift
//
// Copyright (c) 11/10/14 Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
extension RAMAnimatedTabBarItem {
override public var badgeValue: String? {
get {
return badge?.text
}
set(newValue) {
if newValue == nil {
badge?.removeFromSuperview()
badge = nil;
return
}
if badge == nil {
badge = RAMBadge.bage()
if let contanerView = self.iconView!.icon.superview {
badge!.addBadgeOnView(contanerView)
}
}
badge?.text = newValue
}
}
}
public class RAMAnimatedTabBarItem: UITabBarItem {
@IBOutlet public var animation: RAMItemAnimation!
public var textFont: UIFont = UIFont.systemFontOfSize(10)
@IBInspectable public var textColor: UIColor = UIColor.blackColor()
@IBInspectable public var iconColor: UIColor = UIColor.clearColor() // if alpha color is 0 color ignoring
@IBInspectable var bgDefaultColor: UIColor = UIColor.clearColor() // background color
@IBInspectable var bgSelectedColor: UIColor = UIColor.clearColor()
public var badge: RAMBadge? // use badgeValue to show badge
public var iconView: (icon: UIImageView, textLabel: UILabel)?
public func playAnimation() {
assert(animation != nil, "add animation in UITabBarItem")
guard animation != nil && iconView != nil else {
return
}
animation.playAnimation(iconView!.icon, textLabel: iconView!.textLabel)
}
public func deselectAnimation() {
guard animation != nil && iconView != nil else {
return
}
animation.deselectAnimation(
iconView!.icon,
textLabel: iconView!.textLabel,
defaultTextColor: textColor,
defaultIconColor: iconColor)
}
public func selectedState() {
guard animation != nil && iconView != nil else {
return
}
animation.selectedState(iconView!.icon, textLabel: iconView!.textLabel)
}
}
extension RAMAnimatedTabBarController {
public func changeSelectedColor(textSelectedColor:UIColor, iconSelectedColor:UIColor) {
let items = tabBar.items as! [RAMAnimatedTabBarItem]
for index in 0..<items.count {
let item = items[index]
item.animation.textSelectedColor = textSelectedColor
item.animation.iconSelectedColor = iconSelectedColor
if item == self.tabBar.selectedItem {
item.selectedState()
}
}
}
public func animationTabBarHidden(isHidden:Bool) {
guard let items = tabBar.items as? [RAMAnimatedTabBarItem] else {
fatalError("items must inherit RAMAnimatedTabBarItem")
}
for item in items {
if let iconView = item.iconView {
iconView.icon.superview?.hidden = isHidden
}
}
self.tabBar.hidden = isHidden;
}
public func setSelectIndex(from from: Int, to: Int) {
selectedIndex = to
guard let items = tabBar.items as? [RAMAnimatedTabBarItem] else {
fatalError("items must inherit RAMAnimatedTabBarItem")
}
let containerFrom = items[from].iconView?.icon.superview
containerFrom?.backgroundColor = items[from].bgDefaultColor
items[from].deselectAnimation()
let containerTo = items[to].iconView?.icon.superview
containerTo?.backgroundColor = items[to].bgSelectedColor
items[to].playAnimation()
}
}
public class RAMAnimatedTabBarController: UITabBarController {
private var didInit: Bool = false
private var didLoadView: Bool = false
// MARK: life circle
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.didInit = true
self.initializeContainers()
}
public init(viewControllers: [UIViewController]) {
super.init(nibName: nil, bundle: nil)
self.didInit = true
// Set initial items
self.setViewControllers(viewControllers, animated: false)
self.initializeContainers()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.didInit = true
self.initializeContainers()
}
override public func viewDidLoad() {
super.viewDidLoad()
self.didLoadView = true
self.initializeContainers()
}
private func initializeContainers() {
if !self.didInit || !self.didLoadView {
return
}
let containers = self.createViewContainers()
self.createCustomIcons(containers)
}
// MARK: create methods
private func createCustomIcons(containers : NSDictionary) {
guard let items = tabBar.items as? [RAMAnimatedTabBarItem] else {
fatalError("items must inherit RAMAnimatedTabBarItem")
}
var index = 0
for item in items {
guard let itemImage = item.image else {
fatalError("add image icon in UITabBarItem")
}
guard let container = containers["container\(items.count - 1 - index)"] as? UIView else {
fatalError()
}
container.tag = index
let renderMode = CGColorGetAlpha(item.iconColor.CGColor) == 0 ? UIImageRenderingMode.AlwaysOriginal :
UIImageRenderingMode.AlwaysTemplate
let icon = UIImageView(image: item.image?.imageWithRenderingMode(renderMode))
icon.translatesAutoresizingMaskIntoConstraints = false
icon.tintColor = item.iconColor
// text
let textLabel = UILabel()
textLabel.text = item.title
textLabel.backgroundColor = UIColor.clearColor()
textLabel.textColor = item.textColor
textLabel.font = item.textFont
textLabel.textAlignment = NSTextAlignment.Center
textLabel.translatesAutoresizingMaskIntoConstraints = false
container.backgroundColor = (items as [RAMAnimatedTabBarItem])[index].bgDefaultColor
container.addSubview(icon)
createConstraints(icon, container: container, size: itemImage.size, yOffset: -5)
container.addSubview(textLabel)
let textLabelWidth = tabBar.frame.size.width / CGFloat(items.count) - 5.0
createConstraints(textLabel, container: container, size: CGSize(width: textLabelWidth , height: 10), yOffset: 16)
item.iconView = (icon:icon, textLabel:textLabel)
if 0 == index { // selected first elemet
item.selectedState()
container.backgroundColor = (items as [RAMAnimatedTabBarItem])[index].bgSelectedColor
}
item.image = nil
item.title = ""
index += 1
}
}
private func createConstraints(view:UIView, container:UIView, size:CGSize, yOffset:CGFloat) {
let constX = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.CenterX,
relatedBy: NSLayoutRelation.Equal,
toItem: container,
attribute: NSLayoutAttribute.CenterX,
multiplier: 1,
constant: 0)
container.addConstraint(constX)
let constY = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.CenterY,
relatedBy: NSLayoutRelation.Equal,
toItem: container,
attribute: NSLayoutAttribute.CenterY,
multiplier: 1,
constant: yOffset)
container.addConstraint(constY)
let constW = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: size.width)
view.addConstraint(constW)
let constH = NSLayoutConstraint(item: view,
attribute: NSLayoutAttribute.Height,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: size.height)
view.addConstraint(constH)
}
private func createViewContainers() -> NSDictionary {
guard let items = tabBar.items else {
fatalError("add items in tabBar")
}
var containersDict = [String: AnyObject]()
for index in 0..<items.count {
let viewContainer = createViewContainer()
containersDict["container\(index)"] = viewContainer
}
var formatString = "H:|-(0)-[container0]"
for index in 1..<items.count {
formatString += "-(0)-[container\(index)(==container0)]"
}
formatString += "-(0)-|"
let constranints = NSLayoutConstraint.constraintsWithVisualFormat(formatString,
options:NSLayoutFormatOptions.DirectionRightToLeft,
metrics: nil,
views: (containersDict as [String : AnyObject]))
view.addConstraints(constranints)
return containersDict
}
private func createViewContainer() -> UIView {
let viewContainer = UIView();
viewContainer.backgroundColor = UIColor.clearColor() // for test
viewContainer.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(viewContainer)
// add gesture
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(RAMAnimatedTabBarController.tapHandler(_:)))
tapGesture.numberOfTouchesRequired = 1
viewContainer.addGestureRecognizer(tapGesture)
// add constrains
let constY = NSLayoutConstraint(item: viewContainer,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 0)
view.addConstraint(constY)
let constH = NSLayoutConstraint(item: viewContainer,
attribute: NSLayoutAttribute.Height,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: tabBar.frame.size.height)
viewContainer.addConstraint(constH)
return viewContainer
}
// MARK: actions
func tapHandler(gesture:UIGestureRecognizer) {
guard let items = tabBar.items as? [RAMAnimatedTabBarItem] else {
fatalError("items must inherit RAMAnimatedTabBarItem")
}
guard let gestureView = gesture.view else {
return
}
let currentIndex = gestureView.tag
let controller = self.childViewControllers[currentIndex]
if let shouldSelect = delegate?.tabBarController?(self, shouldSelectViewController: controller)
where !shouldSelect {
return
}
if selectedIndex != currentIndex {
let animationItem : RAMAnimatedTabBarItem = items[currentIndex]
animationItem.playAnimation()
let deselectItem = items[selectedIndex]
let containerPrevious : UIView = deselectItem.iconView!.icon.superview!
containerPrevious.backgroundColor = items[currentIndex].bgDefaultColor
deselectItem.deselectAnimation()
let container : UIView = animationItem.iconView!.icon.superview!
container.backgroundColor = items[currentIndex].bgSelectedColor
selectedIndex = gestureView.tag
delegate?.tabBarController?(self, didSelectViewController: controller)
} else if selectedIndex == currentIndex {
if let navVC = self.viewControllers![selectedIndex] as? UINavigationController {
navVC.popToRootViewControllerAnimated(true)
}
}
}
}
|
gpl-3.0
|
9cf97971f3239f4be5952e79688310ed
| 32.826196 | 125 | 0.628565 | 5.562966 | false | false | false | false |
PANDA-Guide/PandaGuideApp
|
PandaGuide/ApiRouter.swift
|
1
|
3845
|
//
// ApiRouter.swift
// PandaGuide
//
// Created by Arnaud Lenglet on 22/04/2017.
// Copyright © 2017 ESTHESIX. All rights reserved.
//
import Alamofire
import os.log
enum ApiRouter: URLRequestConvertible {
// MARK: - Available routes
case signin(Parameters)
case signup(Parameters)
case userDestroy(id: Int, parameters: Parameters)
case helpRequestCreate(Parameters)
case helpRequestDetails(id: Int)
case helpRequestUpdate(id: Int, parameters: Parameters)
case helpSolutionUpdate(id: Int, parameters: Parameters)
case registerDevice(deviceToken: String)
// MARK: - Route configuration
// MARK: Methods
var method: HTTPMethod {
switch self {
case .signin:
return .post
case .signup:
return .post
case .userDestroy:
return .delete
case .helpRequestCreate:
return .post
case .helpRequestDetails:
return .get
case .helpRequestUpdate:
return .patch
case .helpSolutionUpdate:
return .patch
case .registerDevice:
return .post
}
}
// MARK: Paths
var path: String {
switch self {
case .signin:
return "/sessions"
case .signup:
return "/users"
case .userDestroy(let id, _):
return "/users/\(id)"
case .helpRequestCreate:
return "/help_requests"
case .helpRequestDetails(let id):
return "/help_requests/\(id)"
case .helpRequestUpdate(let id, _):
return "/help_requests/\(id)"
case .helpSolutionUpdate(let id, _):
return "/solutions/\(id)"
case .registerDevice(_):
return "/devices"
}
}
// MARK: - URLRequestConvertible
internal func asURLRequest() throws -> URLRequest {
let url = try ApiConfigurator.shared.apiUrl.asURL()
var urlRequest = URLRequest(url: url.appendingPathComponent(path))
urlRequest.httpMethod = method.rawValue
// Add Authorization header
if SessionService().isSignedIn() {
let currentUser = CurrentUser.get() as! CurrentUser
urlRequest.addValue("Token token=\(currentUser.auth_token)", forHTTPHeaderField: "Authorization")
}
switch self {
case .signin(let parameters):
urlRequest = try JSONEncoding.default.encode(urlRequest, with: parameters)
case .signup(let parameters):
urlRequest = try JSONEncoding.default.encode(urlRequest, with: parameters)
case .userDestroy(_, let parameters):
urlRequest = try JSONEncoding.default.encode(urlRequest, with: parameters)
case .helpRequestCreate(let parameters):
urlRequest = try JSONEncoding.default.encode(urlRequest, with: parameters)
case .helpRequestDetails(_):
urlRequest = try JSONEncoding.default.encode(urlRequest)
case .helpRequestUpdate(_, let parameters):
urlRequest = try JSONEncoding.default.encode(urlRequest, with: parameters)
case .helpSolutionUpdate(_, let parameters):
urlRequest = try JSONEncoding.default.encode(urlRequest, with: parameters)
case .registerDevice(let token):
let parameters: Parameters = ["token": token]
urlRequest = try JSONEncoding.default.encode(urlRequest, with: parameters)
}
os_log("🛣 ApiRouter, request generated: %@ %@",
log: .default, type: .debug, urlRequest.httpMethod!, (urlRequest.url?.absoluteString)!)
return urlRequest
}
}
|
gpl-3.0
|
89ff5adae35e06f6633c008fd61a5fd2
| 27.664179 | 109 | 0.58969 | 5.128171 | false | false | false | false |
PANDA-Guide/PandaGuideApp
|
PandaGuide/CameraButton.swift
|
1
|
4304
|
//
// CameraButton.swift
// PandaGuide
//
// Created by Pierre Dulac on 26/05/2017.
// Copyright © 2017 ESTHESIX. All rights reserved.
//
import UIKit
import Cartography
public protocol CameraButtonDelegate {
func buttonWasTapped()
}
class CameraButton: UIButton {
public var delegate: CameraButtonDelegate?
private let strokeLayer = CALayer()
private let innerLayer = CALayer()
private let iconImageView: UIImageView = {
let iv = UIImageView()
iv.translatesAutoresizingMaskIntoConstraints = false
return iv
}()
private let initialStrokeLayerColor = UIColor.white.withAlphaComponent(1.0).cgColor
private let initialInnerLayerColor = UIColor.brandOrange.cgColor
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
override func layoutSubviews() {
super.layoutSubviews()
strokeLayer.frame = bounds
strokeLayer.cornerRadius = bounds.size.width / 2
innerLayer.frame = bounds.insetBy(dx: 1.0, dy: 1.0)
innerLayer.cornerRadius = bounds.size.width / 2
}
private func commonInit() {
let gesture = UILongPressGestureRecognizer(target: self, action: #selector(CameraButton.handleTapGesture(gesture:)))
gesture.minimumPressDuration = 0
gesture.numberOfTouchesRequired = 1
gesture.allowableMovement = 30 // NB: only effective before `minimumPressDuration` has been reached
addGestureRecognizer(gesture)
self.backgroundColor = UIColor.clear
strokeLayer.backgroundColor = UIColor.clear.cgColor
strokeLayer.borderWidth = 6.0
strokeLayer.borderColor = initialStrokeLayerColor
layer.insertSublayer(strokeLayer, at: 0)
innerLayer.backgroundColor = initialInnerLayerColor
layer.insertSublayer(innerLayer, at: 0)
iconImageView.image = #imageLiteral(resourceName: "panda-eyes")
iconImageView.contentMode = .scaleAspectFit
addSubview(iconImageView)
}
private var didSetupConstraints: Bool = false
override func updateConstraints() {
if !didSetupConstraints {
didSetupConstraints = true
setupConstraints()
}
super.updateConstraints()
}
private func setupConstraints() {
constrain(iconImageView) { image in
image.center == image.superview!.center
image.width == 0.6 * image.superview!.width
image.height == image.width
}
}
private func resetStyles() {
strokeLayer.borderColor = initialStrokeLayerColor
innerLayer.backgroundColor = initialInnerLayerColor
}
private let touchDistanceThreshold: CGFloat = 200.0
private var initialTouchLocation: CGPoint = .zero
private func cancelGesture(gesture: UIGestureRecognizer) {
gesture.isEnabled = false
gesture.isEnabled = true
}
private func hasTouchMovedTooMuch(gesture: UIGestureRecognizer) -> Bool {
if gesture is UILongPressGestureRecognizer {
let loc = gesture.location(in: self)
if gesture.state == .began {
initialTouchLocation = loc
} else if gesture.state == .changed {
let distance = sqrt(pow(loc.x - initialTouchLocation.x, 2) + pow(loc.y - initialTouchLocation.y, 2))
if distance > touchDistanceThreshold {
return true
}
}
}
return false
}
@objc fileprivate func handleTapGesture(gesture: UILongPressGestureRecognizer) {
// UI changes
switch gesture.state {
case .began, .changed:
// switch colors
strokeLayer.borderColor = initialInnerLayerColor
innerLayer.backgroundColor = initialStrokeLayerColor
default:
// restore colors
resetStyles()
}
if (hasTouchMovedTooMuch(gesture: gesture)) {
cancelGesture(gesture: gesture)
return
}
// Logic
if gesture.state == .ended {
// trigger photo
delegate?.buttonWasTapped()
}
}
}
|
gpl-3.0
|
0b163bcfd00d3babc96232175f3f9145
| 28.472603 | 124 | 0.639321 | 5.273284 | false | false | false | false |
lotpb/iosSQLswift
|
mySQLswift/LookupData.swift
|
1
|
16396
|
//
// LookupData.swift
// mySQLswift
//
// Created by Peter Balsamo on 1/10/16.
// Copyright © 2016 Peter Balsamo. All rights reserved.
//
import UIKit
import Parse
protocol LookupDataDelegate: class {
func cityFromController(passedData: NSString)
func stateFromController(passedData: NSString)
func zipFromController(passedData: NSString)
func salesFromController(passedData: NSString)
func salesNameFromController(passedData: NSString)
func jobFromController(passedData: NSString)
func jobNameFromController(passedData: NSString)
func productFromController(passedData: NSString)
func productNameFromController(passedData: NSString)
}
class LookupData: UIViewController, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating {
weak var delegate:LookupDataDelegate?
@IBOutlet weak var tableView: UITableView?
var zipArray : NSMutableArray = NSMutableArray()
var salesArray : NSMutableArray = NSMutableArray()
var jobArray : NSMutableArray = NSMutableArray()
var adproductArray : NSMutableArray = NSMutableArray()
var filteredString : NSMutableArray = NSMutableArray()
var lookupItem : String?
var refreshControl: UIRefreshControl!
var isFilltered = false
var searchController: UISearchController!
var resultsController: UITableViewController!
override func viewDidLoad() {
super.viewDidLoad()
let titleButton: UIButton = UIButton(frame: CGRectMake(0, 0, 100, 32))
titleButton.setTitle(String(format: "%@ %@", "Lookup", (self.lookupItem)!), forState: UIControlState.Normal)
titleButton.titleLabel?.font = Font.navlabel
titleButton.titleLabel?.textAlignment = NSTextAlignment.Center
titleButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
titleButton.addTarget(self, action: Selector(), forControlEvents: UIControlEvents.TouchUpInside)
self.navigationItem.titleView = titleButton
self.tableView!.delegate = self
self.tableView!.dataSource = self
self.tableView!.estimatedRowHeight = 44
self.tableView!.rowHeight = UITableViewAutomaticDimension
self.tableView!.backgroundColor = UIColor(white:0.90, alpha:1.0)
self.automaticallyAdjustsScrollViewInsets = false
searchController = UISearchController(searchResultsController: resultsController)
searchController.searchBar.searchBarStyle = .Prominent
searchController.searchResultsUpdater = self
searchController.searchBar.showsBookmarkButton = false
searchController.searchBar.showsCancelButton = true
searchController.searchBar.placeholder = "Search here..."
searchController.searchBar.sizeToFit()
definesPresentationContext = true
searchController.dimsBackgroundDuringPresentation = true
searchController.hidesNavigationBarDuringPresentation = false
//tableView!.tableHeaderView = searchController.searchBar
tableView!.tableFooterView = UIView(frame: .zero)
UISearchBar.appearance().barTintColor = UIColor(white:0.45, alpha:1.0)
self.presentViewController(searchController, animated: true, completion: nil)
//users = []
//foundUsers = []
resultsController = UITableViewController(style: .Plain)
resultsController.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "UserFoundCell")
resultsController.tableView.dataSource = self
resultsController.tableView.delegate = self
parseData()
self.refreshControl = UIRefreshControl()
refreshControl.backgroundColor = UIColor.clearColor()
refreshControl.tintColor = UIColor.blackColor()
self.refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh")
self.refreshControl.addTarget(self, action: #selector(LookupData.refreshData), forControlEvents: UIControlEvents.ValueChanged)
self.tableView!.addSubview(refreshControl)
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.barTintColor = UIColor(white:0.45, alpha:1.0)
}
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Refresh
func refreshData(sender:AnyObject) {
parseData()
self.refreshControl?.endRefreshing()
}
// MARK: - Table View
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if tableView == self.tableView {
if (lookupItem == "City") {
return zipArray.count
} else if (lookupItem == "Salesman") {
return salesArray.count
} else if (lookupItem == "Job") {
return jobArray.count
} else if (lookupItem == "Product") || (lookupItem == "Advertiser") {
return adproductArray.count
}
} else {
//return foundUsers.count
return filteredString.count
}
return 1
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cellIdentifier: String!
if tableView == self.tableView {
cellIdentifier = "Cell"
} else {
cellIdentifier = "UserFoundCell"
}
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath)
cell.selectionStyle = UITableViewCellSelectionStyle.None
if UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiom.Pad {
cell.textLabel!.font = Font.celltitle
} else {
cell.textLabel!.font = Font.celltitle
}
if (tableView == self.tableView) {
if (lookupItem == "City") {
cell.textLabel!.text = (zipArray[indexPath.row] .valueForKey("City") as? String)!
} else if (lookupItem == "Salesman") {
cell.textLabel!.text = (salesArray[indexPath.row] .valueForKey("Salesman") as? String)!
} else if (lookupItem == "Job") {
cell.textLabel!.text = (jobArray[indexPath.row] .valueForKey("Description") as? String)!
} else if (lookupItem == "Product") {
cell.textLabel!.text = (adproductArray[indexPath.row] .valueForKey("Products") as? String)!
} else if (lookupItem == "Advertiser") {
cell.textLabel!.text = (adproductArray[indexPath.row] .valueForKey("Advertiser") as? String)!
}
} else {
if (lookupItem == "City") {
//cell.textLabel!.text = foundUsers[indexPath.row]
cell.textLabel!.text = (filteredString[indexPath.row] .valueForKey("City") as? String)!
} else if (lookupItem == "Salesman") {
cell.textLabel!.text = (filteredString[indexPath.row] .valueForKey("Salesman") as? String)!
} else if (lookupItem == "Job") {
cell.textLabel!.text = (filteredString[indexPath.row] .valueForKey("Description") as? String)!
} else if (lookupItem == "Product") {
cell.textLabel!.text = (filteredString[indexPath.row] .valueForKey("Products") as? String)!
} else if (lookupItem == "Advertiser") {
cell.textLabel!.text = (filteredString[indexPath.row] .valueForKey("Advertiser") as? String)!
}
}
//cell.textLabel!.text = cityName
return cell
}
// MARK: - Search
func filterContentForSearchText(searchText: String) {
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
/*
let searchString = searchController.searchBar.text
// Filter the data array and get only those countries that match the search text.
filteredString = zipArray.filter({ (str.objectForKey("City")) -> Bool in
let countryText: NSString = country
return (countryText.rangeOfString(searchString, options: NSStringCompareOptions.CaseInsensitiveSearch).location) != NSNotFound
})
self.resultsController.tableView.reloadData() */
}
// MARK: - Parse
func parseData() {
let query = PFQuery(className:"Zip")
query.limit = 1000
query.orderByAscending("City")
query.cachePolicy = PFCachePolicy.CacheThenNetwork
query.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let temp: NSArray = objects! as NSArray
self.zipArray = temp.mutableCopy() as! NSMutableArray
self.tableView!.reloadData()
} else {
print("Error")
}
}
let query1 = PFQuery(className:"Salesman")
query1.limit = 1000
query1.orderByAscending("Salesman")
query1.cachePolicy = PFCachePolicy.CacheThenNetwork
query1.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let temp: NSArray = objects! as NSArray
self.salesArray = temp.mutableCopy() as! NSMutableArray
self.tableView!.reloadData()
} else {
print("Error")
}
}
let query2 = PFQuery(className:"Job")
query2.limit = 1000
query2.orderByAscending("Description")
query2.cachePolicy = PFCachePolicy.CacheThenNetwork
query2.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let temp: NSArray = objects! as NSArray
self.jobArray = temp.mutableCopy() as! NSMutableArray
self.tableView!.reloadData()
} else {
print("Error")
}
}
if (lookupItem == "Product") {
let query3 = PFQuery(className:"Product")
query3.limit = 1000
query3.orderByDescending("Products")
query3.cachePolicy = PFCachePolicy.CacheThenNetwork
query3.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let temp: NSArray = objects! as NSArray
self.adproductArray = temp.mutableCopy() as! NSMutableArray
self.tableView!.reloadData()
} else {
print("Error")
}
}
} else {
let query4 = PFQuery(className:"Advertising")
query4.limit = 1000
query4.orderByDescending("Advertiser")
query4.cachePolicy = PFCachePolicy.CacheThenNetwork
query4.findObjectsInBackgroundWithBlock { (objects: [PFObject]?, error: NSError?) -> Void in
if error == nil {
let temp: NSArray = objects! as NSArray
self.adproductArray = temp.mutableCopy() as! NSMutableArray
self.tableView!.reloadData()
} else {
print("Error")
}
}
}
}
// MARK: - Segues
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if (!isFilltered) {
if (lookupItem == "City") {
zipArray.objectAtIndex(indexPath.row)
} else if (lookupItem == "Salesman") {
salesArray.objectAtIndex(indexPath.row)
} else if (lookupItem == "Job") {
jobArray.objectAtIndex(indexPath.row)
} else if (lookupItem == "Product") {
adproductArray.objectAtIndex(indexPath.row)
} else if (lookupItem == "Advertiser") {
adproductArray.objectAtIndex(indexPath.row)
}
} else {
filteredString.objectAtIndex(indexPath.row)
}
passDataBack()
}
func passDataBack() {
let indexPath = self.tableView!.indexPathForSelectedRow!.row
if (!isFilltered) {
if (lookupItem == "City") {
self.delegate? .cityFromController((zipArray.objectAtIndex(indexPath) .valueForKey("City") as? String)!)
self.delegate? .stateFromController((zipArray[indexPath] .valueForKey("State") as? String)!)
self.delegate? .zipFromController((zipArray[indexPath] .valueForKey("zipCode") as? String)!)
} else if (lookupItem == "Salesman") {
self.delegate? .salesFromController((salesArray.objectAtIndex(indexPath) .valueForKey("SalesNo") as? String)!)
self.delegate? .salesNameFromController((salesArray[indexPath] .valueForKey("Salesman") as? String)!)
} else if (lookupItem == "Job") {
self.delegate? .jobFromController((jobArray[indexPath] .valueForKey("JobNo") as? String)!)
self.delegate? .jobNameFromController((jobArray.objectAtIndex(indexPath) .valueForKey("Description") as? String)!)
} else if (lookupItem == "Product") {
self.delegate? .productFromController((adproductArray[indexPath] .valueForKey("ProductNo") as? String)!)
self.delegate? .productNameFromController((adproductArray[indexPath] .valueForKey("Products") as? String)!)
} else {
self.delegate? .productFromController((adproductArray[indexPath] .valueForKey("AdNo") as? String)!)
self.delegate? .productNameFromController((adproductArray[indexPath] .valueForKey("Advertiser") as? String)!)
}
} else {
if (lookupItem == "City") {
self.delegate? .cityFromController((filteredString.objectAtIndex(indexPath) .valueForKey("City") as? String)!)
self.delegate? .stateFromController((filteredString[indexPath] .valueForKey("State") as? String)!)
self.delegate? .zipFromController((filteredString[indexPath] .valueForKey("zipCode") as? String)!)
} else if (lookupItem == "Salesman") {
self.delegate? .salesFromController((filteredString.objectAtIndex(indexPath) .valueForKey("SalesNo") as? String)!)
self.delegate? .salesNameFromController((filteredString[indexPath] .valueForKey("Salesman") as? String)!)
} else if (lookupItem == "Job") {
self.delegate? .jobFromController((filteredString[indexPath] .valueForKey("JobNo") as? String)!)
self.delegate? .jobNameFromController((filteredString.objectAtIndex(indexPath) .valueForKey("Description") as? String)!)
} else if (lookupItem == "Product") {
self.delegate? .productFromController((filteredString[indexPath] .valueForKey("ProductNo") as? String)!)
self.delegate? .productNameFromController((filteredString[indexPath] .valueForKey("Products") as? String)!)
} else {
self.delegate? .productFromController((filteredString[indexPath] .valueForKey("AdNo") as? String)!)
self.delegate? .productNameFromController((filteredString[indexPath] .valueForKey("Advertiser") as? String)!)
}
}
self.navigationController?.popViewControllerAnimated(true)
}
}
//-----------------------end------------------------------
|
gpl-2.0
|
becedf3bae67a127cae78991540a6399
| 41.918848 | 138 | 0.608173 | 5.434206 | false | false | false | false |
frankeh/swift-corelibs-libdispatch
|
src/swift/IO.swift
|
1
|
3601
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import CDispatch
public extension DispatchIO {
public enum StreamType : UInt {
case stream = 0
case random = 1
}
public struct CloseFlags : OptionSet, RawRepresentable {
public let rawValue: UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public static let stop = CloseFlags(rawValue: 1)
}
public struct IntervalFlags : OptionSet, RawRepresentable {
public let rawValue: UInt
public init(rawValue: UInt) { self.rawValue = rawValue }
public init(nilLiteral: ()) { self.rawValue = 0 }
public static let strictInterval = IntervalFlags(rawValue: 1)
}
public class func read(fromFileDescriptor: Int32, maxLength: Int, runningHandlerOn queue: DispatchQueue, handler: @escaping (_ data: DispatchData, _ error: Int32) -> Void) {
dispatch_read(fromFileDescriptor, maxLength, queue.__wrapped) { (data: dispatch_data_t, error: Int32) in
handler(DispatchData(data: data), error)
}
}
public class func write(toFileDescriptor: Int32, data: DispatchData, runningHandlerOn queue: DispatchQueue, handler: @escaping (_ data: DispatchData?, _ error: Int32) -> Void) {
dispatch_write(toFileDescriptor, data.__wrapped.__wrapped, queue.__wrapped) { (data: dispatch_data_t?, error: Int32) in
handler(data.flatMap { DispatchData(data: $0) }, error)
}
}
public convenience init(
type: StreamType,
fileDescriptor: Int32,
queue: DispatchQueue,
cleanupHandler: @escaping (_ error: Int32) -> Void)
{
self.init(__type: type.rawValue, fd: fileDescriptor, queue: queue, handler: cleanupHandler)
}
public convenience init(
type: StreamType,
path: UnsafePointer<Int8>,
oflag: Int32,
mode: mode_t,
queue: DispatchQueue,
cleanupHandler: @escaping (_ error: Int32) -> Void)
{
self.init(__type: type.rawValue, path: path, oflag: oflag, mode: mode, queue: queue, handler: cleanupHandler)
}
public convenience init(
type: StreamType,
io: DispatchIO,
queue: DispatchQueue,
cleanupHandler: @escaping (_ error: Int32) -> Void)
{
self.init(__type: type.rawValue, io: io, queue: queue, handler: cleanupHandler)
}
public func read(offset: off_t, length: Int, queue: DispatchQueue, ioHandler: @escaping (_ done: Bool, _ data: DispatchData?, _ error: Int32) -> Void) {
dispatch_io_read(self.__wrapped, offset, length, queue.__wrapped) { (done: Bool, data: dispatch_data_t?, error: Int32) in
ioHandler(done, data.flatMap { DispatchData(data: $0) }, error)
}
}
public func write(offset: off_t, data: DispatchData, queue: DispatchQueue, ioHandler: @escaping (_ done: Bool, _ data: DispatchData?, _ error: Int32) -> Void) {
dispatch_io_write(self.__wrapped, offset, data.__wrapped.__wrapped, queue.__wrapped) { (done: Bool, data: dispatch_data_t?, error: Int32) in
ioHandler(done, data.flatMap { DispatchData(data: $0) }, error)
}
}
public func setInterval(interval: DispatchTimeInterval, flags: IntervalFlags = []) {
dispatch_io_set_interval(self.__wrapped, interval.rawValue, flags.rawValue)
}
public func close(flags: CloseFlags = []) {
dispatch_io_close(self.__wrapped, flags.rawValue)
}
}
|
apache-2.0
|
522f4e6a18917d8df3c9eb42ad79b152
| 36.123711 | 178 | 0.679533 | 3.716202 | false | false | false | false |
Acidburn0zzz/firefox-ios
|
Client/Frontend/Library/RecentlyClosedTabsPanel.swift
|
1
|
5872
|
/* 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 UIKit
import Shared
import Storage
import XCGLogger
private let log = Logger.browserLogger
private struct RecentlyClosedPanelUX {
static let IconSize = CGSize(width: 23, height: 23)
static let IconBorderColor = UIColor.Photon.Grey30
static let IconBorderWidth: CGFloat = 0.5
}
class RecentlyClosedTabsPanel: UIViewController, LibraryPanel {
weak var libraryPanelDelegate: LibraryPanelDelegate?
let profile: Profile
fileprivate lazy var tableViewController = RecentlyClosedTabsPanelSiteTableViewController(profile: profile)
init(profile: Profile) {
self.profile = profile
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.theme.tableView.headerBackground
tableViewController.libraryPanelDelegate = libraryPanelDelegate
tableViewController.recentlyClosedTabsPanel = self
self.addChild(tableViewController)
tableViewController.didMove(toParent: self)
self.view.addSubview(tableViewController.view)
tableViewController.view.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
}
}
class RecentlyClosedTabsPanelSiteTableViewController: SiteTableViewController {
weak var libraryPanelDelegate: LibraryPanelDelegate?
var recentlyClosedTabs: [ClosedTab] = []
weak var recentlyClosedTabsPanel: RecentlyClosedTabsPanel?
fileprivate lazy var longPressRecognizer: UILongPressGestureRecognizer = {
return UILongPressGestureRecognizer(target: self, action: #selector(RecentlyClosedTabsPanelSiteTableViewController.longPress))
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.addGestureRecognizer(longPressRecognizer)
tableView.accessibilityIdentifier = "Recently Closed Tabs List"
self.recentlyClosedTabs = profile.recentlyClosedTabs.tabs
}
@objc fileprivate func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer) {
guard longPressGestureRecognizer.state == .began else { return }
let touchPoint = longPressGestureRecognizer.location(in: tableView)
guard let indexPath = tableView.indexPathForRow(at: touchPoint) else { return }
presentContextMenu(for: indexPath)
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = super.tableView(tableView, cellForRowAt: indexPath)
guard let twoLineCell = cell as? TwoLineImageOverlayCell else {
return cell
}
let tab = recentlyClosedTabs[indexPath.row]
let displayURL = tab.url.displayURL ?? tab.url
twoLineCell.descriptionLabel.isHidden = false
twoLineCell.titleLabel.text = tab.title
twoLineCell.titleLabel.isHidden = tab.title?.isEmpty ?? true ? true : false
twoLineCell.descriptionLabel.text = displayURL.absoluteDisplayString
let site: Favicon? = (tab.faviconURL != nil) ? Favicon(url: tab.faviconURL!) : nil
cell.imageView?.layer.borderColor = RecentlyClosedPanelUX.IconBorderColor.cgColor
cell.imageView?.layer.borderWidth = RecentlyClosedPanelUX.IconBorderWidth
cell.imageView?.contentMode = .center
cell.imageView?.setImageAndBackground(forIcon: site, website: displayURL) { [weak cell] in
cell?.imageView?.image = cell?.imageView?.image?.createScaled(RecentlyClosedPanelUX.IconSize)
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
guard let libraryPanelDelegate = libraryPanelDelegate else {
log.warning("No site or no URL when selecting row.")
return
}
let visitType = VisitType.typed // Means History, too.
libraryPanelDelegate.libraryPanel(didSelectURL: recentlyClosedTabs[indexPath.row].url, visitType: visitType)
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
// Functions that deal with showing header rows.
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.recentlyClosedTabs.count
}
}
extension RecentlyClosedTabsPanelSiteTableViewController: LibraryPanelContextMenu {
func presentContextMenu(for site: Site, with indexPath: IndexPath, completionHandler: @escaping () -> PhotonActionSheet?) {
guard let contextMenu = completionHandler() else { return }
self.present(contextMenu, animated: true, completion: nil)
}
func getSiteDetails(for indexPath: IndexPath) -> Site? {
let closedTab = recentlyClosedTabs[indexPath.row]
let site: Site
if let title = closedTab.title {
site = Site(url: String(describing: closedTab.url), title: title)
} else {
site = Site(url: String(describing: closedTab.url), title: "")
}
return site
}
func getContextMenuActions(for site: Site, with indexPath: IndexPath) -> [PhotonActionSheetItem]? {
return getDefaultContextMenuActions(for: site, libraryPanelDelegate: libraryPanelDelegate)
}
}
extension RecentlyClosedTabsPanel: Themeable {
func applyTheme() {
tableViewController.tableView.reloadData()
}
}
|
mpl-2.0
|
027a9969a6cbdd17a0b9116a8dbf734d
| 38.945578 | 134 | 0.713215 | 5.271095 | false | false | false | false |
djwbrown/swift
|
stdlib/public/SDK/Foundation/Date.swift
|
2
|
14066
|
//===----------------------------------------------------------------------===//
//
// 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 Foundation // Clang module
import CoreFoundation
import _SwiftCoreFoundationOverlayShims
/**
`Date` represents a single point in time.
A `Date` is independent of a particular calendar or time zone. To represent a `Date` to a user, you must interpret it in the context of a `Calendar`.
*/
public struct Date : ReferenceConvertible, Comparable, Equatable {
public typealias ReferenceType = NSDate
fileprivate var _time : TimeInterval
/// The number of seconds from 1 January 1970 to the reference date, 1 January 2001.
public static let timeIntervalBetween1970AndReferenceDate : TimeInterval = 978307200.0
/// The interval between 00:00:00 UTC on 1 January 2001 and the current date and time.
public static var timeIntervalSinceReferenceDate : TimeInterval {
return CFAbsoluteTimeGetCurrent()
}
/// Returns a `Date` initialized to the current date and time.
public init() {
_time = CFAbsoluteTimeGetCurrent()
}
/// Returns a `Date` initialized relative to the current date and time by a given number of seconds.
public init(timeIntervalSinceNow: TimeInterval) {
self.init(timeIntervalSinceReferenceDate: timeIntervalSinceNow + CFAbsoluteTimeGetCurrent())
}
/// Returns a `Date` initialized relative to 00:00:00 UTC on 1 January 1970 by a given number of seconds.
public init(timeIntervalSince1970: TimeInterval) {
self.init(timeIntervalSinceReferenceDate: timeIntervalSince1970 - Date.timeIntervalBetween1970AndReferenceDate)
}
/**
Returns a `Date` initialized relative to another given date by a given number of seconds.
- Parameter timeInterval: The number of seconds to add to `date`. A negative value means the receiver will be earlier than `date`.
- Parameter date: The reference date.
*/
public init(timeInterval: TimeInterval, since date: Date) {
self.init(timeIntervalSinceReferenceDate: date.timeIntervalSinceReferenceDate + timeInterval)
}
/// Returns a `Date` initialized relative to 00:00:00 UTC on 1 January 2001 by a given number of seconds.
public init(timeIntervalSinceReferenceDate ti: TimeInterval) {
_time = ti
}
/**
Returns the interval between the date object and 00:00:00 UTC on 1 January 2001.
This property's value is negative if the date object is earlier than the system's absolute reference date (00:00:00 UTC on 1 January 2001).
*/
public var timeIntervalSinceReferenceDate: TimeInterval {
return _time
}
/**
Returns the interval between the receiver and another given date.
- Parameter another: The date with which to compare the receiver.
- Returns: The interval between the receiver and the `another` parameter. If the receiver is earlier than `anotherDate`, the return value is negative. If `anotherDate` is `nil`, the results are undefined.
- SeeAlso: `timeIntervalSince1970`
- SeeAlso: `timeIntervalSinceNow`
- SeeAlso: `timeIntervalSinceReferenceDate`
*/
public func timeIntervalSince(_ date: Date) -> TimeInterval {
return self.timeIntervalSinceReferenceDate - date.timeIntervalSinceReferenceDate
}
/**
The time interval between the date and the current date and time.
If the date is earlier than the current date and time, this property's value is negative.
- SeeAlso: `timeIntervalSince(_:)`
- SeeAlso: `timeIntervalSince1970`
- SeeAlso: `timeIntervalSinceReferenceDate`
*/
public var timeIntervalSinceNow: TimeInterval {
return self.timeIntervalSinceReferenceDate - CFAbsoluteTimeGetCurrent()
}
/**
The interval between the date object and 00:00:00 UTC on 1 January 1970.
This property's value is negative if the date object is earlier than 00:00:00 UTC on 1 January 1970.
- SeeAlso: `timeIntervalSince(_:)`
- SeeAlso: `timeIntervalSinceNow`
- SeeAlso: `timeIntervalSinceReferenceDate`
*/
public var timeIntervalSince1970: TimeInterval {
return self.timeIntervalSinceReferenceDate + Date.timeIntervalBetween1970AndReferenceDate
}
/// Return a new `Date` by adding a `TimeInterval` to this `Date`.
///
/// - parameter timeInterval: The value to add, in seconds.
/// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more.
public func addingTimeInterval(_ timeInterval: TimeInterval) -> Date {
return self + timeInterval
}
/// Add a `TimeInterval` to this `Date`.
///
/// - parameter timeInterval: The value to add, in seconds.
/// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more.
public mutating func addTimeInterval(_ timeInterval: TimeInterval) {
self += timeInterval
}
/**
Creates and returns a Date value representing a date in the distant future.
The distant future is in terms of centuries.
*/
public static let distantFuture = Date(timeIntervalSinceReferenceDate: 63113904000.0)
/**
Creates and returns a Date value representing a date in the distant past.
The distant past is in terms of centuries.
*/
public static let distantPast = Date(timeIntervalSinceReferenceDate: -63114076800.0)
public var hashValue: Int {
if #available(OSX 10.12, iOS 10.0, *) {
return Int(bitPattern: __CFHashDouble(_time))
} else { // 10.11 and previous behavior fallback; this must allocate a date to reference the hash value and then throw away the reference
return NSDate(timeIntervalSinceReferenceDate: _time).hash
}
}
/// Compare two `Date` values.
public func compare(_ other: Date) -> ComparisonResult {
if _time < other.timeIntervalSinceReferenceDate {
return .orderedAscending
} else if _time > other.timeIntervalSinceReferenceDate {
return .orderedDescending
} else {
return .orderedSame
}
}
/// Returns true if the two `Date` values represent the same point in time.
public static func ==(lhs: Date, rhs: Date) -> Bool {
return lhs.timeIntervalSinceReferenceDate == rhs.timeIntervalSinceReferenceDate
}
/// Returns true if the left hand `Date` is earlier in time than the right hand `Date`.
public static func <(lhs: Date, rhs: Date) -> Bool {
return lhs.timeIntervalSinceReferenceDate < rhs.timeIntervalSinceReferenceDate
}
/// Returns true if the left hand `Date` is later in time than the right hand `Date`.
public static func >(lhs: Date, rhs: Date) -> Bool {
return lhs.timeIntervalSinceReferenceDate > rhs.timeIntervalSinceReferenceDate
}
/// Returns a `Date` with a specified amount of time added to it.
public static func +(lhs: Date, rhs: TimeInterval) -> Date {
return Date(timeIntervalSinceReferenceDate: lhs.timeIntervalSinceReferenceDate + rhs)
}
/// Returns a `Date` with a specified amount of time subtracted from it.
public static func -(lhs: Date, rhs: TimeInterval) -> Date {
return Date(timeIntervalSinceReferenceDate: lhs.timeIntervalSinceReferenceDate - rhs)
}
/// Add a `TimeInterval` to a `Date`.
///
/// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more.
public static func +=(lhs: inout Date, rhs: TimeInterval) {
lhs = lhs + rhs
}
/// Subtract a `TimeInterval` from a `Date`.
///
/// - warning: This only adjusts an absolute value. If you wish to add calendrical concepts like hours, days, months then you must use a `Calendar`. That will take into account complexities like daylight saving time, months with different numbers of days, and more.
public static func -=(lhs: inout Date, rhs: TimeInterval) {
lhs = lhs - rhs
}
}
extension Date : CustomDebugStringConvertible, CustomStringConvertible, CustomReflectable {
/**
A string representation of the date object (read-only).
The representation is useful for debugging only.
There are a number of options to acquire a formatted string for a date including: date formatters (see
[NSDateFormatter](//apple_ref/occ/cl/NSDateFormatter) and [Data Formatting Guide](//apple_ref/doc/uid/10000029i)), and the `Date` function `description(locale:)`.
*/
public var description: String {
// Defer to NSDate for description
return NSDate(timeIntervalSinceReferenceDate: _time).description
}
/**
Returns a string representation of the receiver using the given
locale.
- Parameter locale: A `Locale`. If you pass `nil`, `Date` formats the date in the same way as the `description` property.
- Returns: A string representation of the `Date`, using the given locale, or if the locale argument is `nil`, in the international format `YYYY-MM-DD HH:MM:SS ±HHMM`, where `±HHMM` represents the time zone offset in hours and minutes from UTC (for example, "`2001-03-24 10:45:32 +0600`").
*/
public func description(with locale: Locale?) -> String {
return NSDate(timeIntervalSinceReferenceDate: _time).description(with: locale)
}
public var debugDescription: String {
return description
}
public var customMirror: Mirror {
let c: [(label: String?, value: Any)] = [
("timeIntervalSinceReferenceDate", timeIntervalSinceReferenceDate)
]
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}
extension Date : _ObjectiveCBridgeable {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSDate {
return NSDate(timeIntervalSinceReferenceDate: _time)
}
public static func _forceBridgeFromObjectiveC(_ x: NSDate, result: inout Date?) {
if !_conditionallyBridgeFromObjectiveC(x, result: &result) {
fatalError("Unable to bridge \(_ObjectiveCType.self) to \(self)")
}
}
public static func _conditionallyBridgeFromObjectiveC(_ x: NSDate, result: inout Date?) -> Bool {
result = Date(timeIntervalSinceReferenceDate: x.timeIntervalSinceReferenceDate)
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: NSDate?) -> Date {
var result: Date?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
extension NSDate : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
return AnyHashable(self as Date)
}
}
extension Date : CustomPlaygroundQuickLookable {
var summary: String {
let df = DateFormatter()
df.dateStyle = .medium
df.timeStyle = .short
return df.string(from: self)
}
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(summary)
}
}
extension Date : Codable {
public init(from decoder: Decoder) throws {
// FIXME: This is a hook for bypassing a conditional conformance implementation to apply a strategy (see SR-5206). Remove this once conditional conformance is available.
let container = try decoder.singleValueContainer()
if let decoder = container as? _JSONDecoder {
switch decoder.options.dateDecodingStrategy {
case .deferredToDate:
break /* fall back to default implementation below; this would recurse */
default:
// _JSONDecoder has a hook for Dates; this won't recurse since we're not going to defer back to Date in _JSONDecoder.
self = try container.decode(Date.self)
return
}
}
let timestamp = try container.decode(Double.self)
self = Date(timeIntervalSinceReferenceDate: timestamp)
}
public func encode(to encoder: Encoder) throws {
// FIXME: This is a hook for bypassing a conditional conformance implementation to apply a strategy (see SR-5206). Remove this once conditional conformance is available.
// We are allowed to request this container as long as we don't encode anything through it when we need the keyed container below.
var container = encoder.singleValueContainer()
if let encoder = container as? _JSONEncoder {
switch encoder.options.dateEncodingStrategy {
case .deferredToDate:
break /* fall back to default implementation below; this would recurse */
default:
// _JSONEncoder has a hook for Dates; this won't recurse since we're not going to defer back to Date in _JSONEncoder.
try container.encode(self)
return
}
}
try container.encode(self.timeIntervalSinceReferenceDate)
}
}
|
apache-2.0
|
27e8b492accf3f280e89314aa703dc74
| 42.141104 | 293 | 0.680958 | 5.162996 | false | false | false | false |
yangzhiqiang/SensoroSensorDemo
|
SensoroSensorDemo/UpgradeDeviceController.swift
|
1
|
3426
|
//
// UpgradeDeviceController.swift
// SensoroSensorKitTest
//
// Created by David Yang on 2018/3/27.
// Copyright © 2018年 Sensoro. All rights reserved.
//
import UIKit
import SensoroSensorKit
class UpgradeDeviceController: UIViewController {
var device : SensoroDevice? = nil;
@IBOutlet weak var progressLabel: UILabel!
@IBOutlet weak var statusLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
@IBAction func upgradeDevice(_ sender: Any) {
//获取指定的DFU固件
// if let firmwarePath = Bundle.main.path(forResource: "tracker_dfu_test", ofType: "zip", inDirectory: "firmware") {
if let firmwarePath = Bundle.main.path(forResource: "SENSORO_TK_DFU_V1.0.1_20180611", ofType: "zip", inDirectory: "firmware") {
print(firmwarePath);
//调用函数进行升级。
device?.upgrade(password: "eb]J9{;dxw6MvI-i", firmware: firmwarePath, progressWatcher: { (progress) in
//指示固件传输进度。
self.progressLabel.text = String(format : "%.1f%%",progress);
}, stateWatcher: { (state, error) in
//指示固件传输的阶段
if error == nil {//如果没有错误,则根据状态进行判断。
var tip = "";
switch state {
case .ready:
tip = "准备进入DFU";
case .enteringDFU:
tip = "正在进入DFU";
case .dfuTransfering:
tip = "正在传输数据";
case .disconnecting:
tip = "连接断开";
case .validating:
tip = "正在校验";
case .completed:
tip = "更新完成";
case .timeout:
tip = "更新超时";
case .failed:
tip = "更新失败";
case .recall:
tip = "多次调用";
}
self.statusLabel.text = tip;
print(tip);
}else{//出现错误,则输出错误,升级失败。
let tip = "更新失败: \(error?.localizedDescription ?? "nil")"
self.statusLabel.text = tip;
print(tip);
if let deviceInfo = (error as NSError?)?.userInfo {
if let deviceCode = deviceInfo["deviceError"] as? String {
print("Device Error : \(deviceCode)")
}
}
}
})
}
}
}
|
mit
|
035de7d3af5bf532c2912f2ca03726d2
| 33.095745 | 135 | 0.49142 | 4.826807 | false | false | false | false |
katherinexchoi/food-tracker
|
FoodTracker/ViewController.swift
|
1
|
2540
|
//
// ViewController.swift
// FoodTracker
//
// Created by Katherine Choi on 9/7/16.
// Copyright © 2016 Katherine Choi. All rights reserved.
//
import UIKit
class ViewController: UIViewController, UITextFieldDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
// MARK: Properties
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var mealNameLabel: UILabel!
@IBOutlet weak var photoImageView: UIImageView!
@IBOutlet weak var ratingControl: RatingControl!
override func viewDidLoad() {
super.viewDidLoad()
// Handle the text field's user input through delegate callbacks
nameTextField.delegate = self
}
// MARK: UITextFieldDelegate
// MARK: UIImagePickerControllerDelegate
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
// Dismiss the picker if the user canceled.
dismissViewControllerAnimated(true, completion: nil)
}
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
// The info dictionary contains multiple representations of the image, and this uses the original.
let selectedImage = info[UIImagePickerControllerOriginalImage] as! UIImage
// Set photoImageView to display the selected image.
photoImageView.image = selectedImage
// Dismiss the picker.
dismissViewControllerAnimated(true, completion: nil)
}
// MARK: Actions
@IBAction func selectImageFromPhotoLibrary(sender: UITapGestureRecognizer) {
// Hide the keyboard
nameTextField.resignFirstResponder()
// UIImagePickerController is a view controller that lets a user pick media from their photo library.
let imagePickerController = UIImagePickerController()
// Only allow photos to be picked, not taken.
imagePickerController.sourceType = .PhotoLibrary
// Make sure ViewController is notified when the user picks an image.
imagePickerController.delegate = self
presentViewController(imagePickerController, animated: true, completion: nil)
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
// Hide the keyboard
textField.resignFirstResponder()
return true
}
func textFieldDidEndEditing(textField: UITextField) {
mealNameLabel.text = textField.text
}
}
|
mit
|
42da2c6a017b050bfc3377c2871c7188
| 33.310811 | 126 | 0.69358 | 6.223039 | false | false | false | false |
michikono/swift-using-typealiases-as-generics
|
swift-using-typealiases-as-generics-i.playground/Pages/typealias-for-self 3.xcplaygroundpage/Contents.swift
|
2
|
1325
|
//: Typealias for Self - one reason for using classes
//: =================================================
//: [Previous](@previous)
protocol Material {}
struct Wood: Material {}
struct Glass: Material {}
struct Metal: Material {}
struct Cotton: Material {}
//: We changed `factory()` to return `Self` instead of `T`
protocol Furniture {
typealias M: Material
typealias M2: Material
func mainMaterial() -> M
func secondaryMaterial() -> M2
static func factory() -> Self // <=====
}
//: using `final class` sets up static dispatching
final class Chair: Furniture {
func mainMaterial() -> Wood {
return Wood()
}
func secondaryMaterial() -> Cotton {
return Cotton()
}
static func factory() -> Chair {
return Chair()
}
}
//: **This next code snippet will not compile -- which is good!**
//: Notice here that `Chair` can not be the return type for `factory()`. Change `Chair` => `Lamp` to fix this error
final class Lamp: Furniture {
func mainMaterial() -> Glass {
return Glass()
}
func secondaryMaterial() -> Metal {
return Metal()
}
static func factory() -> Chair { // <=== change Chair => Lamp to fix this error
return Chair() // <=== change Chair => Lamp to fix this error
}
}
//: [Next](@next)
|
mit
|
ca98520759487b44d953a4c2fc9387a1
| 24 | 115 | 0.587925 | 4.076923 | false | false | false | false |
maxoly/PulsarKit
|
PulsarKitExample/PulsarKitExample/Controllers/Basic/Merge/SimpleMergeViewController.swift
|
1
|
2194
|
//
// SimpleMergeViewController.swift
// PulsarKitExample
//
// Created by Massimo Oliviero on 03/05/21.
// Copyright © 2021 Nacoon. All rights reserved.
//
import UIKit
import PulsarKit
final class SimpleMergeViewController: BaseViewController {
let section1 = SourceSection()
let section2 = SourceSection()
var elements1: [AnyHashable] = [
User(id: 1, name: "User 1"),
User(id: 2, name: "User 2"),
User(id: 3, name: "User 3"),
User(id: 4, name: "User 4")
]
var mergeElements1 = [
User(id: 2, name: "User 2\n(reloaded)"),
User(id: 21, name: "User 2.1\n(new)"),
User(id: 4, name: "User 4\n(reloaded)"),
User(id: 6, name: "User 6\n(new)"),
User(id: 7, name: "User 7\n(new)")
]
var elements2 = [
User(id: 100, name: "User 100"),
User(id: 200, name: "User 200"),
User(id: 300, name: "User 300"),
User(id: 400, name: "User 400")
]
var mergeElements2 = [
User(id: 200, name: "User 200\n(reloaded)"),
User(id: 2100, name: "User 200.1\n(new)"),
User(id: 400, name: "User 400\n(reloaded)"),
User(id: 600, name: "User 600\n(new)"),
User(id: 700, name: "User 700\n(new)")
]
override func viewDidLoad() {
super.viewDidLoad()
title = "Merge"
populateSource()
populateNavigationBar()
}
@objc
func mergeButtonDidTouch(_ sender: Any) {
section1.merge(models: mergeElements1)
section2.merge(models: mergeElements2)
source.update(invalidateLayout: true)
}
}
extension SimpleMergeViewController {
func populateSource() {
source.add(section: section1)
source.add(section: section2)
section1.add(models: elements1)
section2.add(models: elements2)
}
func populateNavigationBar() {
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .organize,
target: self,
action: #selector(mergeButtonDidTouch(_:)))
}
}
|
mit
|
463146416dd17afa0fef302c19bf98af
| 28.24 | 103 | 0.551756 | 3.813913 | false | false | false | false |
yotao/YunkuSwiftSDKTEST
|
YunkuSwiftSDK/YunkuSwiftSDK/Class/Utils/Digest.swift
|
1
|
2863
|
//
// Digest.swift
// SwiftDigest
//
// Created by Brent Royal-Gordon on 8/26/14.
// Copyright (c) 2014 Groundbreaking Software. All rights reserved.
//
import Foundation
import CommonCrypto
/// Digest is an immutable object representing a completed digest. Use the Digest
/// object to fetch the completed digest in various forms.
final public class Digest: Equatable, Comparable, Hashable {
/// The digest as a series of bytes.
public let bytes: [UInt8]
/// The digest as an NSData object.
public lazy var data: NSData = {
var temp = self.bytes
return NSData(bytes: &temp, length: temp.count)
}()
/// The digest as a hexadecimal string.
public lazy var hex: String = self.bytes.map { byte in byte.toHex() }.reduce("", +)
/// The digest as a base64-encoded String.
public func base64WithOptions(options: NSData.Base64EncodingOptions) -> String {
return data.base64EncodedString(options: options)
}
/// The digest as an NSData object of base64-encoded bytes.
public func base64DataWithOptions(options: NSData.Base64EncodingOptions) -> NSData {
return data.base64EncodedData(options: options) as NSData
}
/// Creates a Digest from an array of bytes. You should not normally need to
/// call this yourself.
public init(bytes: [UInt8]) {
self.bytes = bytes
}
/// Creates a Digest by copying the algorithm object and finish()ing it. You
/// should not normally need to call this yourself.
public convenience init<Algorithm: AlgorithmType>( algorithm: Algorithm) {
var algorithm = algorithm
self.init(bytes: algorithm.finish())
}
public lazy var hashValue: Int = {
// This should actually be a great hashValue for cryptographic digest
// algorithms, since each bit should contain as much entropy as
// every other.
var value: Int = 0
let usedBytes = self.bytes[0 ..< min(self.bytes.count, MemoryLayout<Int>.size)]
for byte in usedBytes {
value <<= 8
value &= Int(byte)
}
return value
}()
}
/// Tests if two digests are exactly equal.
public func == (lhs: Digest, rhs: Digest) -> Bool {
return lhs.bytes == rhs.bytes
}
/// Tests which digest is "less than" the other. Note that this comparison treats
/// shorter digests as "less than" longer digests; this should only occur if you
/// compare digests created by different algorithms.
public func < (lhs: Digest, rhs: Digest) -> Bool {
if lhs.bytes.count < rhs.bytes.count {
// rhs is a larger number
return true
}
if lhs.bytes.count > rhs.bytes.count {
// lhs is a larger number
return false
}
return lhs.bytes.lexicographicallyPrecedes(rhs.bytes)
}
|
mit
|
e052db87aa96841c12e680cae05672e9
| 32.290698 | 88 | 0.646525 | 4.337879 | false | false | false | false |
Caiflower/SwiftWeiBo
|
花菜微博/花菜微博/Classes/Tools(工具)/Other/CFCommon.swift
|
1
|
1471
|
//
// CFCommon.swift
// 花菜微博
//
// Created by 花菜ChrisCai on 2016/12/18.
// Copyright © 2016年 花菜ChrisCai. All rights reserved.
//
import Foundation
// MARK: - 全局通知
/// 用户是否登录通知
let kUserShoudLoginNotification = "userShoudLoginNotification"
/// 用户登录成功通知
let kUserLoginSuccessNotification = "kUserLoginSuccessNotification"
/// 用户token过期通知
let kUserTokenDidExpireNotification = "kUserTokenDidExpireNotification"
// MARK: - 应用程序信息
/// 新浪微博Appkey
let SinaAppKey = "941749531"
/// 应用程序加密信息
let SinaAppSecret = "96e15facd4e5d81626e66dd4a41bb5b7"
/// 回到地址 - 登录成功完成跳转的URL
let SinaRedirectURI = "http://caiflower.com"
// MARK: - 各种key
let CFBoundelVersionKey = "CFBoundelVersionKey"
// MARK: - 微博常数
/// 头像高度
let CFStatusIconViewHeight: CGFloat = 34
/// 底部工具条高度
let CFStatusToolbarHeight: CGFloat = 36
/// 通用间距
let CFCommonMargin: CGFloat = 12
/// 微博配图外部间距
let CFStatusPictureViewOutterMargin: CGFloat = CFCommonMargin
/// 微博配图内部间距
let CFStatusPictureViewInnerMargin: CGFloat = 3
/// 微博配图视图宽度
let CFStatusPictureViewWidth: CGFloat = UIScreen.main.cf_screenWidth - 2 * CFStatusPictureViewOutterMargin
/// 微博配图单个配图宽高
let CFStatusPictureItemWidth: CGFloat = (CFStatusPictureViewWidth - 2 * CFStatusPictureViewInnerMargin) / 3
|
apache-2.0
|
82656d97a71b7f858df7a139da2eaaf3
| 23.56 | 107 | 0.769544 | 3.231579 | false | false | false | false |
silence0201/Swift-Study
|
Learn/09.面向对象/统一性原则-1.playground/section-1.swift
|
1
|
328
|
private class Employee {
var no: Int = 0
var name: String = ""
var job: String?
var salary: Double = 0
var dept: Department?
}
internal struct Department {
var no: Int = 0
var name: String = ""
}
public let emp = Employee() //编译错误
public var dept = Department() //编译错误
|
mit
|
50d59adb46ab54c4cd81cd8a918e14e5
| 15.421053 | 40 | 0.589744 | 3.545455 | false | false | false | false |
kesun421/firefox-ios
|
Sync/Synchronizers/TabsSynchronizer.swift
|
5
|
8813
|
/* 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 Shared
import Storage
import XCGLogger
import Deferred
import SwiftyJSON
private let log = Logger.syncLogger
let TabsStorageVersion = 1
open class TabsSynchronizer: TimestampedSingleCollectionSynchronizer, Synchronizer {
public required init(scratchpad: Scratchpad, delegate: SyncDelegate, basePrefs: Prefs, why: SyncReason) {
super.init(scratchpad: scratchpad, delegate: delegate, basePrefs: basePrefs, why: why, collection: "tabs")
}
override var storageVersion: Int {
return TabsStorageVersion
}
var tabsRecordLastUpload: Timestamp {
set(value) {
self.prefs.setLong(value, forKey: "lastTabsUpload")
}
get {
return self.prefs.unsignedLongForKey("lastTabsUpload") ?? 0
}
}
fileprivate func createOwnTabsRecord(_ tabs: [RemoteTab]) -> Record<TabsPayload> {
let guid = self.scratchpad.clientGUID
let tabsJSON = JSON([
"id": guid,
"clientName": self.scratchpad.clientName,
"tabs": tabs.flatMap { $0.toDictionary() }
])
if Logger.logPII {
log.verbose("Sending tabs JSON \(tabsJSON.stringValue() ?? "nil")")
}
let payload = TabsPayload(tabsJSON)
return Record(id: guid, payload: payload, ttl: ThreeWeeksInSeconds)
}
fileprivate func uploadOurTabs(_ localTabs: RemoteClientsAndTabs, toServer tabsClient: Sync15CollectionClient<TabsPayload>) -> Success {
// check to see if our tabs have changed or we're in a fresh start
let lastUploadTime: Timestamp? = (self.tabsRecordLastUpload == 0) ? nil : self.tabsRecordLastUpload
if let lastUploadTime = lastUploadTime,
lastUploadTime >= (Date.now() - (OneMinuteInMilliseconds)) {
log.debug("Not uploading tabs: already did so at \(lastUploadTime).")
return succeed()
}
return localTabs.getTabsForClientWithGUID(nil) >>== { tabs in
if let lastUploadTime = lastUploadTime {
// TODO: track this in memory so we don't have to hit the disk to figure out when our tabs have
// changed and need to be uploaded.
if tabs.every({ $0.lastUsed < lastUploadTime }) {
return succeed()
}
}
let tabsRecord = self.createOwnTabsRecord(tabs)
log.debug("Uploading our tabs: \(tabs.count).")
var uploadStats = SyncUploadStats()
uploadStats.sent += 1
// We explicitly don't send If-Unmodified-Since, because we always
// want our upload to succeed -- we own the record.
return tabsClient.put(tabsRecord, ifUnmodifiedSince: nil) >>== { resp in
if let ts = resp.metadata.lastModifiedMilliseconds {
// Protocol says this should always be present for success responses.
log.debug("Tabs record upload succeeded. New timestamp: \(ts).")
self.tabsRecordLastUpload = ts
} else {
uploadStats.sentFailed += 1
}
return succeed()
} >>== effect({ self.statsSession.recordUpload(stats: uploadStats) })
}
}
open func synchronizeLocalTabs(_ localTabs: RemoteClientsAndTabs, withServer storageClient: Sync15StorageClient, info: InfoCollections) -> SyncResult {
func onResponseReceived(_ response: StorageResponse<[Record<TabsPayload>]>) -> Success {
func afterWipe() -> Success {
var downloadStats = SyncDownloadStats()
let doInsert: (Record<TabsPayload>) -> Deferred<Maybe<(Int)>> = { record in
let remotes = record.payload.isValid() ? record.payload.remoteTabs : []
let ins = localTabs.insertOrUpdateTabsForClientGUID(record.id, tabs: remotes)
// Since tabs are all sent within a single record, we don't count number of tabs applied
// but number of records. In this case it's just one.
downloadStats.applied += 1
ins.upon() { res in
if let inserted = res.successValue {
if inserted != remotes.count {
log.warning("Only inserted \(inserted) tabs, not \(remotes.count). Malformed or missing client?")
}
downloadStats.applied += 1
} else {
downloadStats.failed += 1
}
}
return ins
}
let ourGUID = self.scratchpad.clientGUID
let records = response.value
let responseTimestamp = response.metadata.lastModifiedMilliseconds
log.debug("Got \(records.count) tab records.")
// We can only insert tabs for clients that we know locally, so
// first we fetch the list of IDs and intersect the two.
// TODO: there's a much more efficient way of doing this.
return localTabs.getClientGUIDs()
>>== { clientGUIDs in
let filtered = records.filter({ $0.id != ourGUID && clientGUIDs.contains($0.id) })
if filtered.count != records.count {
log.debug("Filtered \(records.count) records down to \(filtered.count).")
}
let allDone = all(filtered.map(doInsert))
return allDone.bind { (results) -> Success in
if let failure = results.find({ $0.isFailure }) {
return deferMaybe(failure.failureValue!)
}
self.lastFetched = responseTimestamp!
return succeed()
}
} >>== effect({ self.statsSession.downloadStats })
}
// If this is a fresh start, do a wipe.
if self.lastFetched == 0 {
log.info("Last fetch was 0. Wiping tabs.")
return localTabs.wipeRemoteTabs()
>>== afterWipe
}
return afterWipe()
}
if let reason = self.reasonToNotSync(storageClient) {
return deferMaybe(SyncStatus.notStarted(reason))
}
let keys = self.scratchpad.keys?.value
let encoder = RecordEncoder<TabsPayload>(decode: { TabsPayload($0) }, encode: { $0.json })
if let encrypter = keys?.encrypter(self.collection, encoder: encoder) {
let tabsClient = storageClient.clientForCollection(self.collection, encrypter: encrypter)
statsSession.start()
if !self.remoteHasChanges(info) {
// upload local tabs if they've changed or we're in a fresh start.
return uploadOurTabs(localTabs, toServer: tabsClient)
>>> { deferMaybe(self.completedWithStats) }
}
return tabsClient.getSince(self.lastFetched)
>>== onResponseReceived
>>> { self.uploadOurTabs(localTabs, toServer: tabsClient) }
>>> { deferMaybe(self.completedWithStats) }
}
log.error("Couldn't make tabs factory.")
return deferMaybe(FatalError(message: "Couldn't make tabs factory."))
}
/**
* This is a dedicated resetting interface that does both tabs and clients at the
* same time.
*/
open static func resetClientsAndTabsWithStorage(_ storage: ResettableSyncStorage, basePrefs: Prefs) -> Success {
let clientPrefs = BaseCollectionSynchronizer.prefsForCollection("clients", withBasePrefs: basePrefs)
let tabsPrefs = BaseCollectionSynchronizer.prefsForCollection("tabs", withBasePrefs: basePrefs)
clientPrefs.removeObjectForKey("lastFetched")
tabsPrefs.removeObjectForKey("lastFetched")
return storage.resetClient()
}
}
extension RemoteTab {
public func toDictionary() -> Dictionary<String, Any>? {
let tabHistory = history.flatMap { $0.absoluteString }
if tabHistory.isEmpty {
return nil
}
return [
"title": title,
"icon": icon?.absoluteString as Any? ?? NSNull(),
"urlHistory": tabHistory,
"lastUsed": millisecondsToDecimalSeconds(lastUsed)
]
}
}
|
mpl-2.0
|
21aaeecfda88651b9ca40f42470a1d59
| 41.781553 | 155 | 0.576081 | 5.532329 | false | false | false | false |
ashfurrow/FunctionalReactiveAwesome
|
Pods/RxSwift/RxSwift/RxSwift/Rx.swift
|
4
|
1442
|
//
// Rx.swift
// Rx
//
// Created by Krunoslav Zaher on 2/14/15.
// Copyright (c) 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
#if TRACE_RESOURCES
// counts resources
// used to detect resource leaks during unit tests
// it's not perfect, but works well
public var resourceCount: Int32 = 0
#endif
// This is the pipe operator (left associative function application operator)
// a >- b >- c == c(b(a))
// The reason this one is chosen for now is because
// * It's subtle, doesn't add a lot of visual noise
// * It's short
// * It kind of looks like ASCII art horizontal sink to the right
//
infix operator >- { associativity left precedence 91 }
public func >- <In, Out>(lhs: In, @noescape rhs: In -> Out) -> Out {
return rhs(lhs)
}
func contract(@autoclosure condition: () -> Bool) {
if !condition() {
let exception = NSException(name: "ContractError", reason: "Contract failed", userInfo: nil)
exception.raise()
}
}
// Swift doesn't have a concept of abstract metods.
// This function is being used as a runtime check that abstract methods aren't being called.
func abstractMethod<T>() -> T {
rxFatalError("Abstract method")
let dummyValue: T? = nil
return dummyValue!
}
func rxFatalError(lastMessage: String) {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage)
}
|
mit
|
237d260eefcfef0654a4e7cf759ccb98
| 28.428571 | 115 | 0.680999 | 3.774869 | false | false | false | false |
supdann/SwiftyTools
|
Tools/SwiftyTools.swift
|
1
|
3789
|
//
// JSONTools.swift
// SwiftTools
//
// Created by Daniel Montano on 13.07.16.
//
import Foundation
import SwiftyJSON
////////////////////////////////////////////////////////
// MARK: JSON Tools
////////////////////////////////////////////////////////
public protocol JSONable {
func toJSON() -> JSON
}
class JSONTools{
class func createSwiftyJSONDataset(withKey key: String? = nil,jsonableArray: [JSONable]) -> JSON{
var swiftyArray = [JSON]()
for jsonItem in jsonableArray {
swiftyArray.append(jsonItem.toJSON())
}
if let uKey = key {
return [uKey: JSON(swiftyArray).arrayObject!] as JSON
}
return JSON(swiftyArray)
}
class func getRawDataFrom(jsonObject: JSON) -> NSData{
return try! jsonObject.rawData()
}
class func saveJSONFile(filename: String, rawData: NSData) -> Bool{
return FileTools.saveFile(filename, data: rawData)
}
class func loadJSONFile(filename: String) -> JSON?{
if let fileData = FileTools.loadFile(filename) {
return JSON(data: fileData)
}
return nil
}
}
////////////////////////////////////////////////////////
// MARK: File Tools
////////////////////////////////////////////////////////
class FileTools{
static let documentsDirectory = try! NSFileManager.defaultManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true).path!
static let documentsDirectoryPath = NSURL(string: documentsDirectory)!
static let fileManager = NSFileManager.defaultManager()
class func loadFile(filename: String) -> NSData?{
let filepath = documentsDirectoryPath.URLByAppendingPathComponent(filename)
// creating a .json file in the Documents folder
if checkIfFileExistsOnDevice(filename) {
if let data = try? NSData(contentsOfFile: filepath.absoluteString, options: NSDataReadingOptions.DataReadingUncached ){
return data
} else {
print("Problem loading NSData.")
}
} else {
print("File doesn't exist.")
}
return nil
}
class func saveFile(filename: String, data: NSData) -> Bool{
let jsonFilePath = documentsDirectoryPath.URLByAppendingPathComponent(filename)
// creating a .json file in the Documents folder
if !checkIfFileExistsOnDevice(filename) {
let created = fileManager.createFileAtPath(jsonFilePath.absoluteString, contents: nil, attributes: nil)
if created {
print("File created ")
} else {
print("File could not be created for some reason.")
return false
}
}
do {
let file = try NSFileHandle(forWritingToURL: jsonFilePath)
file.writeData(data)
print("JSON data was written successfully!")
return true
} catch let error as NSError {
print("Couldn't write to file: \(error.localizedDescription)")
return false
}
}
class func checkIfFileExistsOnDevice(filename:String) -> Bool{
var fileExists: Bool = false
let jsonFilePath = documentsDirectoryPath.URLByAppendingPathComponent(filename)
var isDirectory: ObjCBool = false
// creating a .json file in the Documents folder
if fileManager.fileExistsAtPath(jsonFilePath.absoluteString, isDirectory: &isDirectory) {
fileExists = true
}
return fileExists
}
}
|
mit
|
b63ee891e9ea0f5caed0806efef70bcb
| 29.556452 | 178 | 0.564793 | 5.555718 | false | false | false | false |
Laptopmini/SwiftyArtik
|
Source/NotificationsAPI.swift
|
1
|
3824
|
//
// NotificationsAPI.swift
// SwiftyArtik
//
// Created by Paul-Valentin Mini on 8/31/17.
// Copyright © 2017 Paul-Valentin Mini. All rights reserved.
//
import Foundation
import PromiseKit
import Alamofire
open class NotificationsAPI {
// MARK: - Get Messages
/// Get the Messages associated with a notification using pagination.
///
/// - Parameters:
/// - nid: The Notification's id
/// - count: The count of results, max `100`
/// - offset: The offset for pagination, default: `0`
/// - order: The order of the results, default: `.ascending`
/// - Returns: A `Promise<Page<Message>>`
open class func getMessages(nid: String, count: Int, offset: Int = 0, order: PaginationOrder = .ascending) -> Promise<Page<Message>> {
let promise = Promise<Page<Message>>.pending()
let path = SwiftyArtikSettings.basePath + "/notifications/\(nid)/messages"
let parameters: [String:Any] = [
"count": count,
"offset": offset,
"order": order.rawValue
]
APIHelpers.makeRequest(url: path, method: .get, parameters: parameters, encoding: URLEncoding.queryString).then { response -> Void in
if let total = response["total"] as? Int64, let offset = response["offset"] as? Int64, let count = response["count"] as? Int64, let messages = response["data"] as? [[String:Any]] {
let page = Page<Message>(offset: offset, total: total)
if messages.count != Int(count) {
promise.reject(ArtikError.json(reason: .countAndContentDoNotMatch))
return
}
for item in messages {
if let message = Message(JSON: item) {
page.data.append(message)
} else {
promise.reject(ArtikError.json(reason: .invalidItem))
return
}
}
promise.fulfill(page)
} else {
promise.reject(ArtikError.json(reason: .unexpectedFormat))
}
}.catch { error -> Void in
promise.reject(error)
}
return promise.promise
}
/// Get the Messages associated with a notification using recursive requests.
/// WARNING: May strongly impact your rate limit and quota.
///
/// - Parameters:
/// - nid: The Notification's id
/// - order: The order of the results, default: `.ascending`
/// - Returns: A `Promise<Page<Message>>`
open class func getMessages(nid: String, order: PaginationOrder = .ascending) -> Promise<Page<Message>> {
return self.getMessagesRecursive(Page<Message>(), nid: nid, order: order)
}
// MARK: - Private Helpers
private class func getMessagesRecursive(_ container: Page<Message>, offset: Int = 0, nid: String, order: PaginationOrder) -> Promise<Page<Message>> {
let promise = Promise<Page<Message>>.pending()
self.getMessages(nid: nid, count: 100, offset: offset, order: order).then { result -> Void in
container.data.append(contentsOf: result.data)
container.total = result.total
if container.total > Int64(container.data.count) {
self.getMessagesRecursive(container, offset: Int(result.offset) + result.data.count, nid: nid, order: order).then { result -> Void in
promise.fulfill(result)
}.catch { error -> Void in
promise.reject(error)
}
} else {
promise.fulfill(container)
}
}.catch { error -> Void in
promise.reject(error)
}
return promise.promise
}
}
|
mit
|
3cac2cfd46a2868a4d0aea948bfcb992
| 40.107527 | 192 | 0.570494 | 4.513577 | false | false | false | false |
massada/swift-collections
|
Collections/ArrayDeque.swift
|
1
|
9590
|
//
// ArrayDeque.swift
// Collections
//
// Copyright (c) 2016 José Massada <[email protected]>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
/// A fast, double-ended queue of `Element` implemented with a modified dynamic
/// array.
public struct ArrayDeque<Element> : ExpressibleByArrayLiteral {
typealias Storage = ArrayDequeBuffer<Element>
/// Constructs an empty `ArrayDeque`.
public init() {
storage_ = Storage()
}
/// Constructs with at least the given number of elements worth of storage.
public init(minimumCapacity: Int) {
storage_ = Storage(minimumCapacity: minimumCapacity)
}
/// Constructs from an `Array` literal.
public init(arrayLiteral elements: Element...) {
storage_ = Storage(minimumCapacity: elements.count)
for element in elements {
storage_.append(element)
}
}
/// Constructs from an arbitrary sequence with elements of type `Element`.
public init<
S : Sequence>(_ sequence: S) where S.Iterator.Element == Element
{
storage_ = Storage(minimumCapacity: sequence.underestimatedCount)
for element in sequence {
storage_.append(element)
}
}
/// The storage capacity.
public var capacity: Int {
return storage_.capacity
}
/// The number of elements.
public var count: Int {
return storage_.count
}
/// The elements storage.
var storage_: Storage
}
extension ArrayDeque : DequeCollectionType {
/// Reserve enough space to store `minimumCapacity` elements.
///
/// - Postcondition: `capacity >= minimumCapacity` and the array deque has
/// mutable contiguous storage.
///
/// - Complexity: O(`self.count`).
public mutating func reserveCapacity(_ minimumCapacity: Int) {
makeUniqueMutableStorage()
storage_.reserveCapacity(minimumCapacity)
}
/// Prepends `newElement` to the `ArrayDeque`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: amortized O(1).
public mutating func prepend(_ newElement: Element) {
makeUniqueMutableStorage()
storage_.prepend(newElement)
}
/// Prepends the elements of `newElements` to the `ArrayDeque`.
///
/// - Complexity: O(*length of `newElements`*).
public mutating func prependContentsOf<
S : Sequence>(_ newElements: S) where S.Iterator.Element == Element
{
reserveCapacity(newElements.underestimatedCount)
for element in newElements.reversed() {
storage_.prepend(element)
}
}
/// Prepends the elements of `newElements` to the `ArrayDeque`.
///
/// - Complexity: O(*length of `newElements`*).
public mutating func prependContentsOf<
C : Collection>(_ newElements: C) where C.Iterator.Element == Element
{
reserveCapacity(numericCast(newElements.count))
for element in newElements.reversed() {
storage_.prepend(element)
}
}
/// Appends `newElement` to the `ArrayDeque`.
///
/// Applying `successor()` to the index of the new element yields
/// `self.endIndex`.
///
/// - Complexity: amortized O(1).
public mutating func append(_ newElement: Element) {
makeUniqueMutableStorage()
storage_.append(newElement)
}
/// Appends the elements of `newElements` to the `ArrayDeque`.
///
/// - Complexity: O(*length of `newElements`*).
public mutating func appendContentsOf<
S : Sequence>(_ newElements: S) where S.Iterator.Element == Element
{
reserveCapacity(newElements.underestimatedCount)
for element in newElements {
storage_.append(element)
}
}
/// Appends the elements of `newElements` to the `ArrayDeque`.
///
/// - Complexity: O(*length of `newElements`*).
public mutating func appendContentsOf<
C : Collection>(_ newElements: C) where C.Iterator.Element == Element
{
reserveCapacity(numericCast(newElements.count))
for element in newElements {
storage_.append(element)
}
}
/// Removes the element at `startIndex` and returns it.
///
/// - Complexity: O(1).
/// - Requires: `self.count > 0`.
public mutating func removeFirst() -> Element {
precondition(count > 0, "can't remove items from an empty collection")
makeUniqueMutableStorage()
return storage_.removeFirst()
}
/// Removes the first `n` elements.
///
/// - Complexity: O(`n`).
/// - Requires: `n >= 0 && self.count >= n`.
public mutating func removeFirst(_ n: Int) {
if n == 0 {
return
}
precondition(n >= 0, "number of elements to remove should be non-negative")
precondition(count >= n,
"can't remove more items from a collection than it contains")
makeUniqueMutableStorage()
storage_.removeFirst(n)
}
/// Removes the element at the end and returns it.
///
/// - Complexity: O(1).
/// - Requires: `count > 0`.
public mutating func removeLast() -> Element {
precondition(count > 0, "can't remove items from an empty collection")
makeUniqueMutableStorage()
return storage_.removeLast()
}
/// Removes the last `n` elements.
///
/// - Complexity: O(`n`).
/// - Requires: `n >= 0 && self.count >= n`.
public mutating func removeLast(_ n: Int) {
if n == 0 {
return
}
precondition(n >= 0, "number of elements to remove should be non-negative")
precondition(count >= n,
"can't remove more items from a collection than it contains")
makeUniqueMutableStorage()
storage_.removeLast(n)
}
/// Removes all elements.
///
/// Invalidates all indices with respect to `self`.
///
/// - Parameter keepCapacity: if `true`, is a non-binding request to
/// avoid releasing storage, which can be a useful optimization
/// when `self` is going to be grown again.
///
/// - Postcondition: `capacity == 0` if `keepCapacity` is `false`.
///
/// - Complexity: O(`self.count`).
public mutating func removeAll(keepCapacity: Bool = false) {
if !isKnownUniquelyReferenced(&storage_) {
let capacity = (keepCapacity) ? storage_.capacity : 0
storage_ = Storage(minimumCapacity: capacity)
} else {
storage_.removeAll(keepCapacity: keepCapacity)
}
}
/// Creates a new storage if this array deque is not backed by a
/// uniquely-referenced mutable storage.
mutating func makeUniqueMutableStorage() {
if !isKnownUniquelyReferenced(&storage_) {
storage_ = Storage(buffer: storage_)
}
}
}
extension ArrayDeque : BidirectionalCollection, MutableCollection {
/// A type that represents a valid position in the collection.
///
/// Valid indices consist of the position of every element and a
/// "past the end" position that's not valid for use as a subscript.
public typealias Index = Int
/// The position of the first element in a non-empty collection.
///
/// In an empty collection, `startIndex == endIndex`.
public var startIndex: Index {
return 0
}
/// A "past-the-end" element index; the successor of the last valid
/// subscript argument.
public var endIndex: Index {
return storage_.count
}
/// Access the `index`th element.
///
/// - Complexity: O(1).
public subscript(index: Index) -> Element {
get {
checkIndex(index)
return storage_[index]
} set {
checkIndex(index)
makeUniqueMutableStorage()
storage_[index] = newValue
}
}
public subscript(bounds: Range<Index>) -> BidirectionalSlice<ArrayDeque> {
get {
fatalError()
} set {
fatalError()
}
}
/// Returns the position immediately after the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be less than
/// `endIndex`.
/// - Returns: The index value immediately after `i`.
public func index(after i: Index) -> Index {
checkIndex(i)
return i &+ 1
}
/// Returns the position immediately before the given index.
///
/// - Parameter i: A valid index of the collection. `i` must be greater than
/// `startIndex`.
/// - Returns: The index value immediately before `i`.
public func index(before i: Index) -> Index {
checkIndex(i)
return i &- 1
}
/// Checks that the given `index` is valid.
func checkIndex(_ index: Index) {
precondition(index >= startIndex && index <= endIndex, "index out of range")
}
}
extension ArrayDeque : CustomStringConvertible, CustomDebugStringConvertible {
/// A textual representation of `self`.
public var description: String {
return Array(self).description
}
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
return "ArrayDeque(\(description))"
}
}
/// Returns `true` if these array deques contain the same elements.
public func ==<Element : Equatable>(
lhs: ArrayDeque<Element>, rhs: ArrayDeque<Element>
) -> Bool {
return lhs.elementsEqual(rhs)
}
/// Returns `true` if these array deques do not contain the same elements.
public func !=<Element : Equatable>(
lhs: ArrayDeque<Element>, rhs: ArrayDeque<Element>
) -> Bool {
return !lhs.elementsEqual(rhs)
}
|
apache-2.0
|
ec46e2db85d45ea595c8cae99bd11e20
| 28.504615 | 80 | 0.66107 | 4.340878 | false | false | false | false |
manavgabhawala/swift
|
test/IRGen/abi_v7k.swift
|
1
|
10631
|
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -emit-ir -primary-file %s -module-name test_v7k | %FileCheck %s
// RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -S -primary-file %s -module-name test_v7k | %FileCheck -check-prefix=V7K %s
// REQUIRES: CPU=armv7k
// REQUIRES: OS=watchos
// CHECK-LABEL: define hidden swiftcc float @_TF8test_v7k9addFloats{{.*}}(float, float)
// CHECK: fadd float %0, %1
// CHECK ret float
// V7K-LABEL: __TF8test_v7k9addFloats{{.*}}
// V7K: vadd.f32 s0, s0, s1
func addFloats(x: Float, y : Float) -> Float {
return x+y
}
// CHECK-LABEL: define hidden swiftcc double @_TF8test_v7k10addDoubles{{.*}}(double, double, double)
// CHECK: fadd double %0, %1
// CHECK: fadd double
// CHECK: ret double
// V7K-LABEL: __TF8test_v7k10addDoubles
// V7K: vadd.f64 d0, d0, d1
// V7K: vadd.f64 d0, d0, d2
func addDoubles(x: Double, y: Double, z: Double) -> Double {
return x+y+z
}
// CHECK-LABEL: define hidden swiftcc float @_TF8test_v7k6addFDF{{.*}}(float, double, float)
// CHECK: fmul float
// CHECK: ret float
// V7K-LABEL: __TF8test_v7k6addFDF
// V7K: vmul.f32 s0, s0, s1
// z is back-filled to s1
func addFDF(x: Float, y: Double, z: Float) -> Float {
return x*z
}
// CHECK-LABEL: define hidden swiftcc double @_TF8test_v7k8addStackFT{{.*}}(double, double, double, double, double, double, double, float, double)
// CHECK: fadd double
// CHECK: ret double
// V7K-LABEL: __TF8test_v7k8addStackFT
// V7K: vldr d16, [sp]
// V7K: vadd.f64 d0, d6, d16
// a is assigned to d6, c is passed via stack
func addStack(d0: Double, d1: Double, d2: Double, d3: Double, d4: Double,
d5: Double, a: Double, b: Float, c: Double) -> Double {
return a+c
}
// CHECK-LABEL: define hidden swiftcc float @_TF8test_v7k9addStack2{{.*}}(double, double, double, double, double, double, double, float, double, float)
// CHECK: fadd float
// V7K-LABEL: __TF8test_v7k9addStack2
// V7K: vldr s0, [sp, #8]
// V7K: vadd.f32 s0, s14, s0
// a is assigned to s14, b is via stack, c is via stack since it can't be back-filled to s15
func addStack2(d0: Double, d1: Double, d2: Double, d3: Double, d4: Double,
d5: Double, d6: Double, a: Float, b: Double, c: Float) -> Float {
return a+c
}
// Passing various enums:
// CHECK-LABEL: define hidden swiftcc void @_TF8test_v7k9testEmpty{{.*}}()
// V7K-LABEL: __TF8test_v7k9testEmpty
enum Empty {}
func testEmpty(x: Empty) -> Empty {
return x
}
// CHECK-LABEL: define hidden swiftcc i32 @_TF8test_v7k10testSingle{{.*}}()
// CHECK: ret i32 1
// V7K-LABEL: __TF8test_v7k10testSingle
// V7K: movw r0, #1
enum SingleCase { case X }
func testSingle(x: SingleCase) -> Int32{
switch x {
case SingleCase.X:
return 1
}
}
// CHECK-LABEL: define hidden swiftcc double @_TF8test_v7k8testData{{.*}}(i32, double)
// CHECK: ret double
// V7K-LABEL: __TF8test_v7k8testData
// V7K: vstr d0
// V7K: vmov.f64 d0
enum DataCase { case Y(Int, Double) }
func testData(x: DataCase) -> Double {
switch x {
case let .Y(i, d):
return d
}
}
// CHECK-LABEL: define hidden swiftcc i32 @_TF8test_v7k10testClike2{{.*}}(i8)
// CHECK: [[ID:%[0-9]+]] = phi i32 [ 2, {{.*}} ], [ 1, {{.*}} ]
// CHECK: ret i32 [[ID]]
// V7K-LABEL: __TF8test_v7k10testClike2
// V7K: tst r0, #1
// V7K: movw r0, #1
// V7K: movw r0, #2
enum CLike2 {
case A
case B
}
func testClike2(x: CLike2) -> Int {
switch x {
case CLike2.A:
return 1
case CLike2.B:
return 2
}
}
// CHECK-LABEL: define hidden swiftcc i32 @_TF8test_v7k10testClike8{{.*}}(i32, i8)
// CHECK: [[ID:%[0-9]+]] = phi i32 [ -1, {{.*}} ], [ 1, {{.*}} ]
// CHECK: ret i32 [[ID]]
// V7K-LABEL: __TF8test_v7k10testClike8
// V7K: sxtb r1, r1
// V7K: cmp r1, #0
// V7K: movw r0, #1
// V7K: mvn r0, #0
enum CLike8 {
case A
case B
case C
case D
case E
case F
case G
case H
}
func testClike8(t: Int, x: CLike8) -> Int {
switch x {
case CLike8.A:
return 1
default:
return -1
}
}
// layout of the enum: the tag bit is set for the no-data cases, which are then
// assigned values in the data area of the enum in declaration order
// CHECK-LABEL: define hidden swiftcc double @_TF8test_v7k11testSingleP{{.*}}(i32, i32, i8)
// CHECK: br i1
// CHECK: switch i32 [[ID:%[0-9]+]]
// CHECK: [[FIRST:%[0-9]+]] = zext i32 %0 to i64
// CHECK: [[SECOND:%[0-9]+]] = zext i32 %1 to i64
// CHECK: [[TEMP:%[0-9]+]] = shl i64 [[SECOND]], 32
// CHECK: [[RESULT:%[0-9]+]] = or i64 [[FIRST]], [[TEMP]]
// CHECK: bitcast i64 [[RESULT]] to double
// CHECK: phi double [ 0.000000e+00, {{.*}} ]
// V7K-LABEL: __TF8test_v7k11testSingleP
// V7K: tst r2, #1
// V7K: vmov.f64 d0
enum SinglePayload {
case Paragraph
case Char(Double)
case Chapter
}
func testSingleP(x: SinglePayload) -> Double {
switch x {
case let .Char(d):
return d
default:
return 0.0
}
}
// CHECK-LABEL: define hidden swiftcc double @_TF8test_v7k10testMultiP{{.*}}(i32, i32, i8)
// CHECK: [[FIRST:%[0-9]+]] = zext i32 %0 to i64
// CHECK: [[SECOND:%[0-9]+]] = zext i32 %1 to i64
// CHECK: [[TEMP:%[0-9]+]] = shl i64 [[SECOND]], 32
// CHECK: [[RESULT:%[0-9]+]] = or i64 [[FIRST]], [[TEMP]]
// CHECK: bitcast i64 [[RESULT]] to double
// CHECK: sitofp i32 {{.*}} to double
// CHECK: phi double [ 0.000000e+00, {{.*}} ]
// CHECK: ret double
// V7K-LABEL: __TF8test_v7k10testMultiP
// V7K: vldr d0
// Backend will assign r0, r1 and r2 for input parameters and d0 for return values.
class Bignum {}
enum MultiPayload {
case X(Int)
case Y(Double)
case Z(Bignum)
}
func testMultiP(x: MultiPayload) -> Double {
switch x {
case let .X(i):
return Double(i)
case let .Y(d):
return d
default:
return 0.0
}
}
// CHECK-LABEL: define hidden swiftcc float @_TF8test_v7k7testOpt{{.*}}(i32, i8)
// CHECK: entry:
// CHECK: [[TR:%.*]] = trunc i8 %1
// CHECK: br i1 [[TR]], {{.*}}, label %[[PAYLOADLABEL:.*]]
// CHECK: <label>:[[PAYLOADLABEL]]
// CHECK: [[ID:%[0-9]+]] = bitcast i32 %0 to float
// CHECK: ret float [[ID]]
// V7K-LABEL: __TF8test_v7k7testOpt
// V7K: tst r1, #1
// V7K: str r0, [r7, #-4]
// V7K: beq [[RET:LBB.*]]
// V7K: [[RET]]:
// V7K: ldr r0, [r7, #-4]
// V7K: vmov s0, r0
// V7K: mov sp, r7
// V7K: pop {r7, pc}
func testOpt(x: Float?) -> Float {
return x!
}
// Returning tuple: (Int, Int)
// CHECK-LABEL: define hidden swiftcc { i32, i32 } @_TF8test_v7k6minMaxF{{.*}}(i32, i32)
// V7K-LABEL: __TF8test_v7k6minMaxF
// V7K: ldr r0
// V7K: ldr r1
func minMax(x : Int, y : Int) -> (min: Int, max: Int) {
var currentMin = x
var currentMax = y
if y < x {
currentMin = y
currentMax = x
}
return (currentMin, currentMax)
}
// Returning struct: Double x 4; Int8, Double, Double;
struct MyRect {
var x : Double
var y : Double
var w : Double
var h : Double
}
struct MyPoint {
var x: Double
var y: Double
}
struct MySize {
var w: Double
var h: Double
}
struct MyRect2 {
var t: Int8
var p : MyPoint
init() {
t = 1
p = MyPoint(x : 0.0, y: 0.0)
}
}
struct MyRect4 {
var t: Int8
var p : MyPoint
var s: MySize
init() {
t = 1
p = MyPoint(x : 0.0, y: 0.0)
s = MySize(w: 1.0, h: 2.0)
}
}
// CHECK-LABEL: define hidden swiftcc { double, double, double, double } @_TF8test_v7k8testRet2{{.*}}(double, i32)
// V7K-LABEL: __TF8test_v7k8testRet2
// double in d0, i32 in r0, return in d0,...,d3
// V7K: vmov [[ID:s[0-9]+]], r0
// V7K: vcvt.f64.s32 [[ID2:d[0-9]+]], [[ID]]
// V7K: vstr d0, [sp]
// V7K: vmov.f64 d0, [[ID2]]
// V7K: bl
// V7K: vldr [[ID3:d[0-9]+]], [sp]
// V7K: vmov.f64 d2, [[ID3]]
func testRet2(w : Double, i : Int) -> MyRect {
var r = MyRect(x : Double(i), y : 2.0, w : 3.0, h : 4.0)
r.w = w
return r
}
// CHECK-LABEL: define hidden swiftcc { i8, double, double } @_TF8test_v7k8testRet3{{.*}}()
// V7K-LABEL: __TF8test_v7k8testRet3
func testRet3() -> MyRect2 {
var r = MyRect2()
return r
}
// Returning tuple?: (Int x 6)?
// CHECK-LABEL: define hidden swiftcc void @_TF8test_v7k7minMax2{{.*}}({{%GSq.*}} noalias nocapture sret, i32, i32)
// V7K-LABEL: __TF8test_v7k7minMax2
// We will indirectly return an optional with the address in r0, input parameters will be in r1 and r2
// V7K: cmp r1, r2
// V7K: str r0, [sp, [[IDX:#[0-9]+]]]
// V7K: ldr [[R0_RELOAD:r[0-9]+]], [sp, [[IDX]]]
// V7K: str {{.*}}, [{{.*}}[[R0_RELOAD]]]
// V7K: str {{.*}}, [{{.*}}[[R0_RELOAD]], #4]
// V7K: str {{.*}}, [{{.*}}[[R0_RELOAD]], #8]
// V7K: str {{.*}}, [{{.*}}[[R0_RELOAD]], #12]
// V7K: str {{.*}}, [{{.*}}[[R0_RELOAD]], #16]
// V7K: str {{.*}}, [{{.*}}[[R0_RELOAD]], #20]
// V7K: and {{.*}}, {{.*}}, #1
// V7K: strb {{.*}}, [{{.*}}[[R0_RELOAD]], #24]
func minMax2(x : Int, y : Int) -> (min: Int, max: Int, min2: Int, max2: Int, min3: Int, max3: Int)? {
if x == y {
return nil
}
var currentMin = x
var currentMax = y
if y < x {
currentMin = y
currentMax = x
}
return (currentMin, currentMax, currentMin, currentMax, currentMin, currentMax)
}
// Returning struct?: {Int x 6}?
// CHECK-LABEL: define hidden swiftcc void @_TF8test_v7k7minMax3{{.*}}({{%GSq.*}} noalias nocapture sret, i32, i32)
// V7K-LABEL: __TF8test_v7k7minMax3
struct Ret {
var min:Int
var max:Int
var min2, max2 : Int
var min3, max3 : Int
}
func minMax3(x : Int, y : Int) -> Ret? {
if x == y {
return nil
}
var currentMin = x
var currentMax = y
if y < x {
currentMin = y
currentMax = x
}
var r = Ret(min:currentMin, max:currentMax, min2:currentMin, max2:currentMax, min3:currentMin, max3:currentMax)
return r
}
// Passing struct: Int8, MyPoint x 10, MySize * 10
// CHECK-LABEL: define hidden swiftcc double @_TF8test_v7k8testRet5{{.*}}(%V8test_v7k7MyRect3* noalias nocapture dereferenceable(328))
// V7K-LABEL: __TF8test_v7k8testRet5
// V7K: ldrb [[TMP1:r[0-9]+]], [r0]
// V7K: vldr [[REG1:d[0-9]+]], [r0, #8]
// V7K: vldr [[REG2:d[0-9]+]], [r0]
// V7K: sxtb r0, [[TMP1]]
// V7K: vmov [[TMP2:s[0-9]+]], r0
// V7K: vcvt.f64.s32 [[INTPART:d[0-9]+]], [[TMP2]]
// V7K: vadd.f64 [[TMP3:d[0-9]+]], [[INTPART]], [[REG1]]
// V7K: vadd.f64 d0, [[TMP3]], [[REG2]]
struct MyRect3 {
var t: Int8
var p: MyPoint
var p2: MyPoint
var s: MySize
var s2: MySize
var p3: MyPoint
var p4: MyPoint
var s3: MySize
var s4: MySize
var p5: MyPoint
var p6: MyPoint
var s5: MySize
var s6: MySize
var p7: MyPoint
var p8: MyPoint
var s7: MySize
var s8: MySize
var p9: MyPoint
var p10: MyPoint
var s9: MySize
var s10: MySize
}
func testRet5(r: MyRect3) -> Double {
return Double(r.t) + r.p.x + r.s9.w
}
|
apache-2.0
|
b7d5e744c2508b1d8b83e153b97f9a15
| 27.349333 | 151 | 0.602201 | 2.644527 | false | true | false | false |
brave/browser-ios
|
brave/src/frontend/popups/AlertPopupView.swift
|
1
|
3737
|
/* 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 UIKit
class AlertPopupView: PopupView {
fileprivate var dialogImage: UIImageView?
fileprivate var titleLabel: UILabel!
fileprivate var messageLabel: UILabel!
fileprivate var containerView: UIView!
fileprivate let kAlertPopupScreenFraction: CGFloat = 0.8
fileprivate let kPadding: CGFloat = 20.0
init(image: UIImage?, title: String, message: String) {
super.init(frame: CGRect.zero)
overlayDismisses = false
defaultShowType = .normal
defaultDismissType = .noAnimation
presentsOverWindow = true
containerView = UIView(frame: CGRect.zero)
containerView.autoresizingMask = [.flexibleWidth]
if let image = image {
let di = UIImageView(image: image)
containerView.addSubview(di)
dialogImage = di
}
titleLabel = UILabel(frame: CGRect.zero)
titleLabel.textColor = BraveUX.GreyJ
titleLabel.textAlignment = .center
titleLabel.font = UIFont.systemFont(ofSize: 24, weight: UIFont.Weight.bold)
titleLabel.text = title
titleLabel.numberOfLines = 0
containerView.addSubview(titleLabel)
messageLabel = UILabel(frame: CGRect.zero)
messageLabel.textColor = BraveUX.GreyH
messageLabel.textAlignment = .center
messageLabel.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.regular)
messageLabel.text = message
messageLabel.numberOfLines = 0
containerView.addSubview(messageLabel)
updateSubviews()
setPopupContentView(view: containerView)
setStyle(popupStyle: .dialog)
setDialogColor(color: BraveUX.PopupDialogColorLight)
}
func updateSubviews() {
let width: CGFloat = dialogWidth
var imageFrame: CGRect = dialogImage?.frame ?? CGRect.zero
if let dialogImage = dialogImage {
imageFrame.origin.x = (width - imageFrame.width) / 2.0
imageFrame.origin.y = kPadding * 2.0
dialogImage.frame = imageFrame
}
let titleLabelSize: CGSize = titleLabel.sizeThatFits(CGSize(width: width - kPadding * 3.0, height: CGFloat.greatestFiniteMagnitude))
var titleLabelFrame: CGRect = titleLabel.frame
titleLabelFrame.size = titleLabelSize
titleLabelFrame.origin.x = rint((width - titleLabelSize.width) / 2.0)
titleLabelFrame.origin.y = imageFrame.maxY + kPadding
titleLabel.frame = titleLabelFrame
let messageLabelSize: CGSize = messageLabel.sizeThatFits(CGSize(width: width - kPadding * 4.0, height: CGFloat.greatestFiniteMagnitude))
var messageLabelFrame: CGRect = messageLabel.frame
messageLabelFrame.size = messageLabelSize
messageLabelFrame.origin.x = rint((width - messageLabelSize.width) / 2.0)
messageLabelFrame.origin.y = rint(titleLabelFrame.maxY + kPadding * 1.5 / 2.0)
messageLabel.frame = messageLabelFrame
var containerViewFrame: CGRect = containerView.frame
containerViewFrame.size.width = width
containerViewFrame.size.height = messageLabelFrame.maxY + kPadding * 1.5
containerView.frame = containerViewFrame
}
override func layoutSubviews() {
super.layoutSubviews()
updateSubviews()
}
required init(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mpl-2.0
|
4120d7eb83fb682e29ad93b016a64429
| 37.927083 | 144 | 0.656409 | 5.147383 | false | false | false | false |
PaddlerApp/paddler-ios
|
Paddler/View Controllers/ProfileViewController.swift
|
1
|
2338
|
//
// ProfileViewController.swift
// Paddler
//
// Created by YingYing Zhang on 10/10/17.
// Copyright © 2017 Paddler. All rights reserved.
//
import UIKit
import Firebase
import GoogleSignIn
class ProfileViewController: UIViewController {
@IBOutlet weak var profileImageView: UIImageView!
@IBOutlet weak var playerNameLabel: UILabel!
@IBOutlet weak var playerWinsLabel: UILabel!
@IBOutlet weak var playerLossesLabel: UILabel!
@IBOutlet weak var logoutButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
//print(PaddlerUser.current!.firstName!)
let currentUser = PaddlerUser.current!
let fullName = currentUser.fullName!
let winCount = currentUser.winCount!
let lossCount = currentUser.lossCount!
if let url = currentUser.profileURL {
profileImageView.setImageWith(url)
} else {
profileImageView.image = UIImage(named: Constants.placeholderImageString)
}
profileImageView.layer.cornerRadius = profileImageView.frame.size.width / 2
profileImageView.clipsToBounds = true
profileImageView.layer.borderWidth = 5
profileImageView.layer.borderColor = UIColor.white.cgColor
playerNameLabel.text = fullName
playerWinsLabel.text = "\(winCount)"
playerLossesLabel.text = "\(lossCount)"
logoutButton.layer.cornerRadius = Constants.buttonCornerRadius
logoutButton.layer.shadowColor = UIColor(red:1.00, green:0.80, blue:0.50, alpha:1.0).cgColor
logoutButton.layer.shadowOffset = CGSize(width: 0, height: 0)
logoutButton.layer.shadowRadius = 1
logoutButton.layer.shadowOpacity = 1.0
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func logOut(_ sender: UIButton) {
GIDSignIn.sharedInstance().signOut()
PaddlerUser.current = nil
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let loginVC = storyboard.instantiateInitialViewController()
UIApplication.shared.keyWindow?.rootViewController = loginVC
}
}
|
apache-2.0
|
853d76423fd224d5ba61a72b51af9198
| 32.869565 | 100 | 0.671801 | 4.982942 | false | false | false | false |
alobanov/ALFormBuilder
|
Sources/FormBuilder/Vendors/extension/String+Regex.swift
|
1
|
2164
|
//
// String+Regex.swift
// Pulse
//
// Created by Aleksey Lobanov on 16.08.16.
// Copyright © 2016 Aleksey Lobanov All rights reserved.
//
import Foundation
extension String {
func regex(pattern: String) -> [String] {
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
let nsstr = self as NSString
let all = NSRange(location: 0, length: nsstr.length)
var matches: [String] = [String]()
regex
.enumerateMatches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: all) { (result: NSTextCheckingResult?, _, _) in
if let r = result {
let result = nsstr.substring(with: r.range) as String
matches.append(result)
}
}
return matches
} catch {
return [String]()
}
}
func regex(pattern: String, group: Int) -> [String] {
do {
let regex = try NSRegularExpression(pattern: pattern, options: NSRegularExpression.Options.caseInsensitive)
let nsstr = self as NSString
let all = NSRange(location: 0, length: nsstr.length)
var result: [String] = [String]()
let matches = regex.matches(in: self, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: all)
for match in matches as [NSTextCheckingResult] {
if match.numberOfRanges-1 > group {
return [String]()
}
let substring = nsstr.substring(with: match.rangeAt(group))
result.append(substring)
}
return result
} catch {
return [String]()
}
}
private func findStringBy(searchString: String, results: [NSTextCheckingResult]) -> String {
if !results.isEmpty {
let firstMatch = results[0]
if firstMatch.numberOfRanges >= 1 {
let range = firstMatch.rangeAt(1)
let newRange = searchString.index(searchString.startIndex, offsetBy: range.location) ..< searchString.index(searchString.startIndex, offsetBy: range.location + range.length)
let string = searchString.substring(with: newRange)
return string
}
return ""
}
return ""
}
}
|
mit
|
64d1eda8ee212d19059197d8daf7e112
| 29.464789 | 181 | 0.643551 | 4.423313 | false | false | false | false |
iCrany/iOSExample
|
iOSExample/Module/ResourceExample/ResourceExampleTableViewController.swift
|
1
|
2831
|
//
// ResourceExampleTableViewController.swift
// iOSExample
//
// Created by iCrany on 2017/7/25.
// Copyright (c) 2017 iCrany. All rights reserved.
//
import Foundation
import UIKit
import SnapKit
class ResourceExampleTableViewController: UIViewController {
struct Constant {
static let kTTFFontExample = "Icon Font Example"
}
private lazy var tableView: UITableView = {
let tableView = UITableView.init(frame: .zero, style: .plain)
tableView.tableFooterView = UIView.init()
tableView.delegate = self
tableView.dataSource = self
return tableView
}()
fileprivate var dataSource: [String] = []
init() {
super.init(nibName: nil, bundle: nil)
self.prepareDataSource()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.title = "Resource Example"
self.setupUI()
}
private func setupUI() {
self.view.addSubview(self.tableView)
self.tableView.snp.makeConstraints { maker in
maker.edges.equalTo(self.view)
}
self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: Constant.kTTFFontExample)
}
private func prepareDataSource() {
self.dataSource.append(Constant.kTTFFontExample)
}
}
extension ResourceExampleTableViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.dataSource.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let dataSourceStr: String = self.dataSource[indexPath.row]
let tableViewCell: UITableViewCell? = tableView.dequeueReusableCell(withIdentifier: dataSourceStr)
if let cell = tableViewCell {
cell.textLabel?.text = dataSourceStr
cell.textLabel?.textColor = UIColor.black
return cell
} else {
return UITableViewCell.init(style: .default, reuseIdentifier: "error")
}
}
}
extension ResourceExampleTableViewController: UITableViewDelegate {
public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 60
}
public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let selectedDataSourceStr = self.dataSource[indexPath.row]
switch selectedDataSourceStr {
case Constant.kTTFFontExample:
let vc: TTFFontExampleViewController = TTFFontExampleViewController.init()
self.navigationController?.pushViewController(vc, animated: true)
default:
break
}
}
}
|
mit
|
6ad5a9e710653edc845121bcbcd34ade
| 28.489583 | 106 | 0.67432 | 5.046346 | false | false | false | false |
lumenlunae/SwiftSpriter
|
SwiftSpriter/Classes/AnimationModel/ModelTimeline.swift
|
1
|
2156
|
//
// ModelTimeline.swift
// SwiftSpriter
//
// Created by Matt on 8/27/16.
// Copyright © 2016 BiminiRoad. All rights reserved.
//
import Foundation
class ModelTimeline {
var id: Int
var spatialsByTime = [ModelSpatial]()
init(spriterTimeline: SpriterTimeline) {
self.id = spriterTimeline.id
}
func spatial(forTime time: TimeInterval) -> ModelSpatial? {
guard spatialsByTime.count > 0 else {
return nil
}
var spatial: ModelSpatial?
var startIndex = 0
var endIndex = self.spatialsByTime.count - 1
while startIndex <= endIndex {
var midIndex = (startIndex + endIndex) / 2
var currentSpatial = self.spatialsByTime[midIndex]
if currentSpatial.equals(time: time) {
spatial = currentSpatial
while midIndex < endIndex {
midIndex += 1
currentSpatial = self.spatialsByTime[midIndex]
if currentSpatial.equals(time: time) {
spatial = currentSpatial
} else {
break
}
}
break
} else if currentSpatial.time < time {
startIndex = midIndex + 1
if startIndex > endIndex {
spatial = self.spatialsByTime[endIndex]
break
}
} else if currentSpatial.time > time {
endIndex = midIndex - 1
if startIndex > endIndex {
if startIndex == 0 {
spatial = self.spatialsByTime[0]
} else {
spatial = self.spatialsByTime[startIndex-1]
}
break
}
} else {
fatalError("Impossible state")
}
}
return spatial
}
}
extension ModelTimeline: CustomStringConvertible {
public var description: String {
return "Timeline \(self.id):\n\(self.spatialsByTime)"
}
}
|
mit
|
6cd43364fc864ea17fdd6554f99d317e
| 28.930556 | 67 | 0.492343 | 5.281863 | false | false | false | false |
treejames/firefox-ios
|
Client/Frontend/Reader/ReaderModeHandlers.swift
|
3
|
6384
|
/* 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
struct ReaderModeHandlers {
static func register(webServer: WebServer, profile: Profile) {
// Register our fonts and css, which we want to expose to web content that we present in the WebView
webServer.registerMainBundleResourcesOfType("ttf", module: "reader-mode/fonts")
webServer.registerMainBundleResource("Reader.css", module: "reader-mode/styles")
// Register a handler that simply lets us know if a document is in the cache or not. This is called from the
// reader view interstitial page to find out when it can stop showing the 'Loading...' page and instead load
// the readerized content.
webServer.registerHandlerForMethod("GET", module: "reader-mode", resource: "page-exists") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in
if let url = request.query["url"] as? String {
if let url = NSURL(string: url) {
if ReaderModeCache.sharedInstance.contains(url, error: nil) {
return GCDWebServerResponse(statusCode: 200)
} else {
return GCDWebServerResponse(statusCode: 404)
}
}
}
return GCDWebServerResponse(statusCode: 500)
}
// Register the handler that accepts /reader-mode/page?url=http://www.example.com requests.
webServer.registerHandlerForMethod("GET", module: "reader-mode", resource: "page") { (request: GCDWebServerRequest!) -> GCDWebServerResponse! in
if let url = request.query["url"] as? String {
if let url = NSURL(string: url) {
if let readabilityResult = ReaderModeCache.sharedInstance.get(url, error: nil) {
// We have this page in our cache, so we can display it. Just grab the correct style from the
// profile and then generate HTML from the Readability results.
var readerModeStyle = DefaultReaderModeStyle
if let dict = profile.prefs.dictionaryForKey(ReaderModeProfileKeyStyle) {
if let style = ReaderModeStyle(dict: dict) {
readerModeStyle = style
}
}
if let html = ReaderModeUtils.generateReaderContent(readabilityResult, initialStyle: readerModeStyle) {
let response = GCDWebServerDataResponse(HTML: html)
// Apply a Content Security Policy that disallows everything except images from anywhere and fonts and css from our internal server
response.setValue("default-src 'none'; img-src *; style-src http://localhost:*; font-src http://localhost:*", forAdditionalHeader: "Content-Security-Policy")
return response
}
} else {
// This page has not been converted to reader mode yet. This happens when you for example add an
// item via the app extension and the application has not yet had a change to readerize that
// page in the background.
//
// What we do is simply queue the page in the ReadabilityService and then show our loading
// screen, which will periodically call page-exists to see if the readerized content has
// become available.
ReadabilityService.sharedInstance.process(url)
if let readerViewLoadingPath = NSBundle.mainBundle().pathForResource("ReaderViewLoading", ofType: "html") {
if let readerViewLoading = NSMutableString(contentsOfFile: readerViewLoadingPath, encoding: NSUTF8StringEncoding, error: nil) {
if let absoluteString = url.absoluteString {
readerViewLoading.replaceOccurrencesOfString("%ORIGINAL-URL%", withString: absoluteString,
options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, readerViewLoading.length))
readerViewLoading.replaceOccurrencesOfString("%LOADING-TEXT%", withString: NSLocalizedString("Loading content…", comment: "Message displayed when the reader mode page is loading. This message will appear only when sharing to Firefox reader mode from another app."),
options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, readerViewLoading.length))
readerViewLoading.replaceOccurrencesOfString("%LOADING-FAILED-TEXT%", withString: NSLocalizedString("The page could not be displayed in Reader View.", comment: "Message displayed when the reader mode page could not be loaded. This message will appear only when sharing to Firefox reader mode from another app."),
options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, readerViewLoading.length))
readerViewLoading.replaceOccurrencesOfString("%LOAD-ORIGINAL-TEXT%", withString: NSLocalizedString("Load original page", comment: "Link for going to the non-reader page when the reader view could not be loaded. This message will appear only when sharing to Firefox reader mode from another app."),
options: NSStringCompareOptions.LiteralSearch, range: NSMakeRange(0, readerViewLoading.length))
}
return GCDWebServerDataResponse(HTML: readerViewLoading as String)
}
}
}
}
}
let errorString = NSLocalizedString("There was an error converting the page", comment: "Error displayed when reader mode cannot be enabled")
return GCDWebServerDataResponse(HTML: errorString) // TODO Needs a proper error page
}
}
}
|
mpl-2.0
|
8306c5d6e0648a85717cdc9a58bf2f77
| 78.7875 | 348 | 0.60843 | 6.101338 | false | false | false | false |
hejunbinlan/Carlos
|
Sample/MemoryWarningSampleViewController.swift
|
2
|
971
|
import Foundation
import UIKit
import Carlos
class MemoryWarningSampleViewController: BaseCacheViewController {
private var cache: BasicCache<NSURL, NSData>!
private var token: NSObjectProtocol?
override func fetchRequested() {
super.fetchRequested()
cache.get(NSURL(string: urlKeyField?.text ?? "")!)
}
override func titleForScreen() -> String {
return "Memory warnings"
}
override func setupCache() {
super.setupCache()
cache = simpleCache()
}
@IBAction func memoryWarningSwitchValueChanged(sender: UISwitch) {
if sender.on && token == nil {
token = listenToMemoryWarnings(cache)
} else if let token = token where !sender.on {
unsubscribeToMemoryWarnings(token)
self.token = nil
}
}
@IBAction func simulateMemoryWarning(sender: AnyObject) {
NSNotificationCenter.defaultCenter().postNotificationName(UIApplicationDidReceiveMemoryWarningNotification, object: nil)
}
}
|
mit
|
c714bc69c0dc567ad7191b13d64e3206
| 25.27027 | 124 | 0.712667 | 4.855 | false | false | false | false |
PiXeL16/SwiftMandrill
|
SwiftMandrill/Model/MandrillEmail.swift
|
1
|
2200
|
//
// MandrillEmail.swift
// SwiftMandrill
//
// Created by Christopher Jimenez on 1/18/16.
// Copyright © 2016 greenpixels. All rights reserved.
//
import Foundation
import ObjectMapper
//Email object to be send with the API
open class MandrillEmail: Mappable{
open var to :[MandrillTo]?
open var from :String?
open var fromName :String?
open var subject :String?
open var html :String?
open var text :String?
public required init?(map: Map) {}
public init(){}
/**
Constructor that receives an array of several to emails
- parameter from:
- parameter fromName: The name of the person sending the email
- parameter to:
- parameter subject:
- parameter html:
- parameter text:
- returns:
*/
public convenience init(from: String, fromName:String, to: [MandrillTo], subject: String, html: String?, text: String?)
{
self.init()
self.from = from
self.fromName = fromName
self.subject = subject
self.html = html
self.text = text
self.to = to
}
/**
Constructor to be used when sending to a single sender
- parameter from:
- parameter to:
- parameter subject:
- parameter html:
- parameter text:
- returns: <#return value description#>
*/
public convenience init(from: String, fromName:String, to: String, subject: String, html: String?, text: String?)
{
self.init()
self.from = from
self.fromName = fromName
self.subject = subject
self.html = html
self.text = text
let mandrillTo = MandrillTo(email: to)
self.to = [mandrillTo]
}
/**
Mapping functionality for serialization/deserialization
- parameter map: <#map description#>
*/
open func mapping(map: Map){
to <- map["to"]
from <- map["from_email"]
fromName <- map["from_name"]
subject <- map["subject"]
html <- map["html"]
text <- map["text"]
}
}
|
mit
|
ccb129fe329d1cd8a2c8c7680cef3f2c
| 22.902174 | 123 | 0.557981 | 4.415663 | false | false | false | false |
cdmx/MiniMancera
|
miniMancera/Model/Option/PollutedGarden/Bubble/Item/Abstract/MOptionPollutedGardenBubbleItem.swift
|
1
|
2016
|
import UIKit
class MOptionPollutedGardenBubbleItem:MGameUpdate<MOptionPollutedGarden>
{
weak var view:VOptionPollutedGardenBubble?
let colour:UIColor
let position:CGPoint
let radius:CGFloat
let mass:CGFloat
let scaleX:CGFloat
let angularVelocity:CGFloat
let velocityY:CGFloat
let velocityX:CGFloat
let velocityXExplosion:CGFloat
private(set) weak var texture:MGameTexture!
private var strategy:MGameStrategy<MOptionPollutedGardenBubbleItem, MOptionPollutedGarden>?
private static let kMaxVelocity:UInt32 = 100
private class func randomVelocity() -> CGFloat
{
let random:UInt32 = arc4random_uniform(kMaxVelocity)
let vectorVelocity:CGFloat = -CGFloat(random)
return vectorVelocity
}
init(
type:MOptionPollutedGardenBubbleItemType,
position:CGPoint)
{
texture = type.texture
colour = type.colour
radius = type.radius
mass = type.mass
scaleX = type.scaleX
angularVelocity = type.angularVelocity
velocityXExplosion = type.velocityXExplosion
velocityX = type.velocityX
velocityY = MOptionPollutedGardenBubbleItem.randomVelocity()
self.position = position
super.init()
strategy = MOptionPollutedGardenBubbleItemStrategyAlive(model:self)
}
override func update(
elapsedTime:TimeInterval,
scene:ViewGameScene<MOptionPollutedGarden>)
{
strategy?.update(
elapsedTime:elapsedTime,
scene:scene)
}
//MARK: public
func explode()
{
strategy = MOptionPollutedGardenBubbleItemStrategyExploded(model:self)
}
func alive() -> Bool
{
guard
let _:MOptionPollutedGardenBubbleItemStrategyAlive = strategy as? MOptionPollutedGardenBubbleItemStrategyAlive
else
{
return false
}
return true
}
}
|
mit
|
f7a1ff971b198ecca1eddaa367890ab2
| 25.88 | 122 | 0.65129 | 5.319261 | false | false | false | false |
SRGSSR/srglogger-ios
|
Sources/SRGLoggerSwift/SRGLogger.swift
|
1
|
2124
|
//
// Copyright (c) SRG SSR. All rights reserved.
//
// License information is available from the LICENSE file.
//
import SRGLogger
/**
* Log a given message at the verbose level.
*/
public func SRGLogVerbose(subsystem: String?, category : String?, message: String, file: String = #file, function: String = #function, line: UInt = #line) {
SRGLogger.logMessage({ () -> String in
return message
}, level: SRGLogLevel.verbose, subsystem: subsystem, category: category, file: file, function: function, line: line);
}
/**
* Log a given message at the debug level.
*/
public func SRGLogDebug(subsystem: String?, category : String?, message: String, file: String = #file, function: String = #function, line: UInt = #line) {
SRGLogger.logMessage({ () -> String in
return message
}, level: SRGLogLevel.debug, subsystem: subsystem, category: category, file: file, function: function, line: line);
}
/**
* Log a given message at the info level.
*/
public func SRGLogInfo(subsystem: String?, category : String?, message: String, file: String = #file, function: String = #function, line: UInt = #line) {
SRGLogger.logMessage({ () -> String in
return message
}, level: SRGLogLevel.info, subsystem: subsystem, category: category, file: file, function: function, line: line);
}
/**
* Log a given message at the warning level.
*/
public func SRGLogWarning(subsystem: String?, category : String?, message: String, file: String = #file, function: String = #function, line: UInt = #line) {
SRGLogger.logMessage({ () -> String in
return message
}, level: SRGLogLevel.warning, subsystem: subsystem, category: category, file: file, function: function, line: line);
}
/**
* Log a given message at the error level.
*/
public func SRGLogError(subsystem: String?, category : String?, message: String, file: String = #file, function: String = #function, line: UInt = #line) {
SRGLogger.logMessage({ () -> String in
return message
}, level: SRGLogLevel.error, subsystem: subsystem, category: category, file: file, function: function, line: line);
}
|
mit
|
e730406eaadce27360aeaeed568baaff
| 39.846154 | 156 | 0.682203 | 3.792857 | false | false | false | false |
gecko655/Swifter
|
Sources/String++.swift
|
1
|
2859
|
//
// String+Swifter.swift
// Swifter
//
// Copyright (c) 2014 Matt Donnelly.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import Foundation
extension String {
internal func indexOf(_ sub: String) -> Int? {
guard let range = self.range(of: sub), !range.isEmpty else {
return nil
}
return self.characters.distance(from: self.startIndex, to: range.lowerBound)
}
internal subscript (r: Range<Int>) -> String {
get {
let startIndex = self.characters.index(self.startIndex, offsetBy: r.lowerBound)
let endIndex = self.characters.index(startIndex, offsetBy: r.upperBound - r.lowerBound)
return self[startIndex..<endIndex]
}
}
func urlEncodedString(_ encodeAll: Bool = false) -> String {
var allowedCharacterSet: CharacterSet = .urlQueryAllowed
allowedCharacterSet.remove(charactersIn: "\n:#/?@!$&'()*+,;=")
if !encodeAll {
allowedCharacterSet.insert(charactersIn: "[]")
}
return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet)!
}
var queryStringParameters: Dictionary<String, String> {
var parameters = Dictionary<String, String>()
let scanner = Scanner(string: self)
var key: NSString?
var value: NSString?
while !scanner.isAtEnd {
key = nil
scanner.scanUpTo("=", into: &key)
scanner.scanString("=", into: nil)
value = nil
scanner.scanUpTo("&", into: &value)
scanner.scanString("&", into: nil)
if let key = key as? String, let value = value as? String {
parameters.updateValue(value, forKey: key)
}
}
return parameters
}
}
|
mit
|
9504881243d24efbb851512a13e5fffe
| 34.296296 | 99 | 0.649878 | 4.663948 | false | false | false | false |
MBKwon/TestAppStore
|
TestAppStore/TestAppStore/AppListCell.swift
|
1
|
1571
|
//
// AppListCell.swift
// TestAppStore
//
// Created by Moonbeom KWON on 2017. 4. 17..
// Copyright © 2017년 Kyle. All rights reserved.
//
import Foundation
import UIKit
import SDWebImage
class AppListCell: UITableViewCell {
@IBOutlet weak var numLabel: UILabel!
@IBOutlet weak var titleLabel: UILabel!
@IBOutlet weak var appImageView: UIImageView!
var iconUrl: String = ""
func resetInfo() {
numLabel.text = ""
titleLabel.text = ""
appImageView.image = nil
}
func setInfo(_ itemInfo: AppListModel?, rank: Int) {
numLabel.text = "\(rank)"
guard let appInfoModel = itemInfo else {
return
}
titleLabel.text = appInfoModel.title
if let iconUrl = appInfoModel.iconUrl {
self.iconUrl = iconUrl
appImageView.sd_setImage(with: URL(string: iconUrl), completed: { [unowned self] (iconImage, error, cacheType, url) in
if self.iconUrl == url?.absoluteString {
self.appImageView.image = iconImage
}
})
}
}
}
extension AppListCell {
override func layoutSubviews() {
super.layoutSubviews()
appImageView.layer.masksToBounds = true
appImageView.layer.borderWidth = 1/UIScreen.main.scale
appImageView.layer.borderColor = UIColor(white: 0.7, alpha: 1.0).cgColor
appImageView.layer.cornerRadius = appImageView.frame.size.width*0.2
}
}
|
mit
|
c00621ae699b9d67f667f10536bd6c65
| 25.133333 | 130 | 0.58801 | 4.571429 | false | false | false | false |
J-Mendes/Bliss-Assignement
|
Bliss-Assignement/Bliss-Assignement/Core Layer/Network/HTTP Manager/BaseHTTPManager.swift
|
1
|
3388
|
//
// BaseHTTPManager.swift
// Bliss-Assignement
//
// Created by Jorge Mendes on 12/10/16.
// Copyright © 2016 Jorge Mendes. All rights reserved.
//
import Foundation
import Alamofire
class BaseHTTPManager {
static let networkReachable: String = "com.jm.Bliss-Assignement.BaseHTTPManager.Reachable"
static let networkUnreachable: String = "com.jm.Bliss-Assignement.BaseHTTPManager.Unreachable"
internal var manager: Manager?
private var networkManager: NetworkReachabilityManager?
private var request: Request?
init() {
self.networkManager = NetworkReachabilityManager()
self.networkManager?.listener = {
switch $0 {
case .Reachable:
NSNotificationCenter.defaultCenter().postNotificationName(BaseHTTPManager.networkReachable, object: self)
break
default:
self.request?.cancel()
NSNotificationCenter.defaultCenter().postNotificationName(BaseHTTPManager.networkUnreachable, object: self)
break
}
}
self.networkManager?.startListening()
}
internal func GET(URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request {
self.request = self.manager?.request(.GET, URLString, parameters: parameters, encoding: encoding, headers: headers)
return self.request!.debugLog().validate()
}
internal func HEAD(URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request {
self.request = self.manager?.request(.HEAD, URLString, parameters: parameters, encoding: encoding, headers: headers)
return self.request!.debugLog().validate()
}
internal func POST(URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request {
self.request = self.manager?.request(.POST, URLString, parameters: parameters, encoding: encoding, headers: headers)
return self.request!.debugLog().validate()
}
internal func PUT(URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request {
self.request = self.manager?.request(.PUT, URLString, parameters: parameters, encoding: encoding, headers: headers)
return self.request!.debugLog().validate()
}
internal func PATCH(URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request {
self.request = self.manager?.request(.PATCH, URLString, parameters: parameters, encoding: encoding, headers: headers)
return self.request!.debugLog().validate()
}
internal func DELETE(URLString: URLStringConvertible, parameters: [String: AnyObject]? = nil, encoding: ParameterEncoding = .URL, headers: [String: String]? = nil) -> Request {
self.request = self.manager?.request(.DELETE, URLString, parameters: parameters, encoding: encoding, headers: headers)
return self.request!.debugLog().validate()
}
}
|
lgpl-3.0
|
135056c0f7126065a6002f390471256f
| 46.704225 | 180 | 0.677 | 4.817923 | false | false | false | false |
wtshm/YHImageViewer
|
Pod/Classes/YHImageViewer.swift
|
1
|
9247
|
//
// YHImageViewer.swift
// YHImageViewer
//
// Created by yuyahirayama on 2015/07/19.
// Copyright (c) 2015年 Yuya Hirayama. All rights reserved.
//
import UIKit
public class YHImageViewer: NSObject {
private var window:UIWindow!
private var backgroundView:UIView!
private var imageView:UIImageView!
private var startFrame:CGRect!
private var completion:(()->Void)!
public var backgroundColor:UIColor?
public var fadeAnimationDuration:NSTimeInterval = 0.15
public func show(targetImageView:UIImageView) {
// Create UIWindow
let window = UIWindow()
window.frame = UIScreen.mainScreen().bounds
window.backgroundColor = UIColor.clearColor()
window.windowLevel = UIWindowLevelAlert
let windowTapRecognizer = UITapGestureRecognizer(target: self, action: Selector("windowTapped:"))
window.addGestureRecognizer(windowTapRecognizer)
self.window = window
window.makeKeyAndVisible()
// Initialize background view
let backgroundView = UIView()
if let color = self.backgroundColor {
backgroundView.backgroundColor = color
} else {
backgroundView.backgroundColor = UIColor.blackColor()
}
backgroundView.frame = self.window.bounds
backgroundView.alpha = 0
self.window.addSubview(backgroundView)
self.backgroundView = backgroundView
// Initialize UIImageView
let image = targetImageView.image
if image == nil {
fatalError("UIImageView is not initialized correctly.")
}
let imageView = UIImageView(image: image)
imageView.contentMode = targetImageView.contentMode
self.imageView = imageView
let startFrame = targetImageView.convertRect(targetImageView.bounds, toView: self.backgroundView)
self.startFrame = startFrame
imageView.frame = startFrame
self.backgroundView.addSubview(imageView)
// Initialize drag gesture recognizer
let imageDragRecognizer = UIPanGestureRecognizer(target: self, action: Selector("imageDragged:"))
self.imageView.userInteractionEnabled = true
self.imageView.addGestureRecognizer(imageDragRecognizer)
// Initialize pinch gesture recognizer
let imagePinchRecognizer = UIPinchGestureRecognizer(target: self, action: Selector("imagePinched:"))
self.imageView.userInteractionEnabled = true
self.imageView.addGestureRecognizer(imagePinchRecognizer)
// Start animation
UIView.animateWithDuration(self.fadeAnimationDuration, delay: 0, options: [], animations: { () -> Void in
backgroundView.alpha = 1
}) { (_) -> Void in
self.moveImageToCenter()
}
}
public func show(targetImageView:UIImageView, completion: () -> Void) {
self.completion = completion
self.show(targetImageView)
}
func moveImageToCenter() {
if let imageView = self.imageView {
UIView.animateWithDuration(0.2, delay: 0, options: [], animations: { () -> Void in
let width = self.window.bounds.size.width
let height = width / imageView.image!.size.width * imageView.image!.size.height
self.imageView.frame.size = CGSizeMake(width, height)
self.imageView.center = self.window.center
}) { (_) -> Void in
self.adjustBoundsAndTransform(self.imageView)
}
}
}
func windowTapped(recognizer:UIGestureRecognizer) {
self.moveToFirstFrame { () -> Void in
self.close()
}
// self.debug()
}
func imageDragged(recognizer:UIPanGestureRecognizer) {
switch (recognizer.state) {
case .Changed:
// Move target view
if let targetView = recognizer.view {
let variation = recognizer.translationInView(targetView)
targetView.center = CGPointMake(targetView.center.x + variation.x * targetView.transform.a, targetView.center.y + variation.y * targetView.transform.a)
let velocity = recognizer.velocityInView(targetView)
}
recognizer.setTranslation(CGPointZero, inView: recognizer.view)
case .Ended:
// Check velocity
if let targetView = recognizer.view {
let variation = recognizer.translationInView(targetView)
let velocity = recognizer.velocityInView(targetView)
let straightVelocity = sqrt(velocity.x * velocity.x + velocity.y * velocity.y)
let velocityThreshold = 1000
let goalPointRate = 5000.0
if straightVelocity > 1000 {
let radian = atan2(velocity.y, velocity.x)
let goalPoint = CGPointMake(cos(radian) * CGFloat(goalPointRate), sin(radian) * CGFloat(goalPointRate))
UIView.animateWithDuration(0.4, delay: 0, options: [], animations: { () -> Void in
targetView.center = goalPoint
}, completion: { (_) -> Void in
self.close()
})
} else {
self.adjustImageViewFrame()
}
}
default:
_ = 0
}
self.debug()
}
func imagePinched(recognizer:UIPinchGestureRecognizer) {
let targetView = recognizer.view!
let scale = recognizer.scale
let velocity = recognizer.velocity
let point = recognizer.locationInView(targetView)
switch (recognizer.state) {
case .Changed:
let transform = targetView.transform.a
targetView.transform = CGAffineTransformMakeScale(scale, scale)
case .Ended , .Cancelled:
let center = targetView.center
self.adjustBoundsAndTransform(targetView)
self.adjustImageViewFrame()
default:
_ = 0
}
self.debug()
}
func close() {
UIView.animateWithDuration(self.fadeAnimationDuration, delay: 0, options: [], animations: { () -> Void in
self.backgroundView.alpha = 0
}) { (_) -> Void in
self.window = nil
}
if var completionFunction = self.completion {
completion()
}
}
func moveToFirstFrame(completion: () -> Void) {
UIView.animateWithDuration(0.2, delay: 0, options: [], animations: { () -> Void in
self.imageView.frame = self.startFrame
}) { (_) -> Void in
completion()
}
}
func debug() {
// println("frame: \(self.imageView.frame) bounds: \(self.imageView.bounds) center: \(self.imageView.center) transform: \(self.imageView.transform.a)")
}
func adjustBoundsAndTransform(view: UIView) {
let center = view.center
let scale = view.transform.a
view.bounds.size = CGSizeMake(view.bounds.size.width * scale, view.bounds.size.height * scale)
view.transform = CGAffineTransformMakeScale(1.0, 1.0)
view.center = center
}
func isImageSmallerThanScreen() -> Bool {
let imageWidth = self.imageView.frame.size.width
let imageHeight = self.imageView.frame.size.height
let screenWidth = self.window.bounds.size.width
let screenHeight = self.window.bounds.size.height
return imageWidth <= screenWidth && imageHeight <= screenHeight
}
func adjustImageViewFrame() {
if self.isImageSmallerThanScreen() {
self.moveImageToCenter()
return
}
let targetView = self.imageView
var originX:CGFloat = targetView.frame.origin.x
var originY:CGFloat = targetView.frame.origin.y
var animateX = true
var animateY = true
if (targetView.frame.origin.x > 0) {
originX = 0
} else if (targetView.frame.origin.x < self.window.bounds.width - targetView.bounds.size.width) {
originX = self.window.bounds.width - targetView.bounds.size.width
}else {
animateX = false
}
if (targetView.bounds.size.height < self.window.bounds.size.height) {
originY = (self.window.bounds.size.height - targetView.bounds.size.height)/2
} else if targetView.frame.origin.y > 0{
originY = 0
} else if targetView.frame.origin.y + targetView.bounds.size.height < self.window.bounds.height {
originY = self.window.bounds.size.height - targetView.bounds.size.height
}
else {
animateY = false
}
if animateX || animateY {
UIView.animateWithDuration(0.2, animations: { () -> Void in
targetView.frame = CGRectMake(originX, originY, targetView.bounds.size.width, targetView.bounds.size.height)
}, completion: { (_) -> Void in
})
}
}
}
|
mit
|
b606c7b0e7fb33f174c0483632e9f2dc
| 37.360996 | 167 | 0.596647 | 5.127565 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.