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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
shorlander/firefox-ios | Shared/AsyncReducer.swift | 11 | 4371 | /* 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 Deferred
private let DefaultDispatchQueue = DispatchQueue.global(qos: DispatchQoS.default.qosClass)
public func asyncReducer<T, U>(_ initialValue: T, combine: @escaping (T, U) -> Deferred<Maybe<T>>) -> AsyncReducer<T, U> {
return AsyncReducer(initialValue: initialValue, combine: combine)
}
/**
* A appendable, async `reduce`.
*
* The reducer starts empty. New items need to be `append`ed.
*
* The constructor takes an `initialValue`, a `dispatch_queue_t`, and a `combine` function.
*
* The reduced value can be accessed via the `reducer.terminal` `Deferred<Maybe<T>>`, which is
* run once all items have been combined.
*
* The terminal will never be filled if no items have been appended.
*
* Once the terminal has been filled, no more items can be appended, and `append` methods will error.
*/
open class AsyncReducer<T, U> {
// T is the accumulator. U is the input value. The returned T is the new accumulated value.
public typealias Combine = (T, U) -> Deferred<Maybe<T>>
fileprivate let lock = NSRecursiveLock()
private let dispatchQueue: DispatchQueue
private let combine: Combine
private let initialValueDeferred: Deferred<Maybe<T>>
open let terminal: Deferred<Maybe<T>> = Deferred()
private var queuedItems: [U] = []
private var isStarted: Bool = false
/**
* Has this task queue finished?
* Once the task queue has finished, it cannot have more tasks appended.
*/
open var isFilled: Bool {
lock.lock()
defer { lock.unlock() }
return terminal.isFilled
}
public convenience init(initialValue: T, queue: DispatchQueue = DefaultDispatchQueue, combine: @escaping Combine) {
self.init(initialValue: deferMaybe(initialValue), queue: queue, combine: combine)
}
public init(initialValue: Deferred<Maybe<T>>, queue: DispatchQueue = DefaultDispatchQueue, combine: @escaping Combine) {
self.dispatchQueue = queue
self.combine = combine
self.initialValueDeferred = initialValue
}
// This is always protected by a lock, so we don't need to
// take another one.
fileprivate func ensureStarted() {
if self.isStarted {
return
}
func queueNext(_ deferredValue: Deferred<Maybe<T>>) {
deferredValue.uponQueue(dispatchQueue, block: continueMaybe)
}
func nextItem() -> U? {
// Because popFirst is only available on array slices.
// removeFirst is fine for range-replaceable collections.
return queuedItems.isEmpty ? nil : queuedItems.removeFirst()
}
func continueMaybe(_ res: Maybe<T>) {
lock.lock()
defer { lock.unlock() }
if res.isFailure {
self.queuedItems.removeAll()
self.terminal.fill(Maybe(failure: res.failureValue!))
return
}
let accumulator = res.successValue!
guard let item = nextItem() else {
self.terminal.fill(Maybe(success: accumulator))
return
}
let combineItem = deferDispatchAsync(dispatchQueue) { _ in
return self.combine(accumulator, item)
}
queueNext(combineItem)
}
queueNext(self.initialValueDeferred)
self.isStarted = true
}
/**
* Append one or more tasks onto the end of the queue.
*
* @throws AlreadyFilled if the queue has finished already.
*/
open func append(_ items: U...) throws -> Deferred<Maybe<T>> {
return try append(items)
}
/**
* Append a list of tasks onto the end of the queue.
*
* @throws AlreadyFilled if the queue has already finished.
*/
open func append(_ items: [U]) throws -> Deferred<Maybe<T>> {
lock.lock()
defer { lock.unlock() }
if terminal.isFilled {
throw ReducerError.alreadyFilled
}
queuedItems.append(contentsOf: items)
ensureStarted()
return terminal
}
}
enum ReducerError: Error {
case alreadyFilled
}
| mpl-2.0 | 57f4322f11ef30ac6ceda2e8cb84ef86 | 30.446043 | 124 | 0.631206 | 4.557873 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Reader/ReaderCommentAction.swift | 1 | 821 | /// Encapsulates a command to navigate to a post's comments
final class ReaderCommentAction {
func execute(post: ReaderPost,
origin: UIViewController,
promptToAddComment: Bool = false,
navigateToCommentID: Int? = nil,
source: ReaderCommentsSource) {
guard let postInMainContext = ReaderActionHelpers.postInMainContext(post),
let controller = ReaderCommentsViewController(post: postInMainContext, source: source) else {
return
}
controller.navigateToCommentID = navigateToCommentID as NSNumber?
controller.promptToAddComment = promptToAddComment
controller.trackCommentsOpened()
origin.navigationController?.pushViewController(controller, animated: true)
}
}
| gpl-2.0 | 33fa7bedc0ec34cb3cb03b1b695ab3d3 | 44.611111 | 107 | 0.667479 | 5.78169 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/PaymentMethods/Views/PaymentMethodsFooterView.swift | 1 | 1863 | import Library
import Prelude
import UIKit
public protocol PaymentMethodsFooterViewDelegate: AnyObject {
func paymentMethodsFooterViewDidTapAddNewCardButton(_ footerView: PaymentMethodsFooterView)
}
public final class PaymentMethodsFooterView: UIView, NibLoading {
public weak var delegate: PaymentMethodsFooterViewDelegate?
@IBOutlet private var addCardButton: UIButton!
@IBOutlet private var separatorView: UIView!
@IBOutlet private var loadingIndicator: UIActivityIndicatorView!
public override func bindStyles() {
super.bindViewModel()
_ = self.addCardButton
|> \.titleEdgeInsets .~ UIEdgeInsets(left: Styles.grid(4))
|> \.imageEdgeInsets .~ UIEdgeInsets(left: Styles.grid(2))
|> \.tintColor .~ .ksr_create_700
|> UIButton.lens.backgroundColor(for: .normal) .~ .ksr_white
|> UIButton.lens.titleColor(for: .normal) .~ .ksr_create_700
|> UIButton.lens.titleColor(for: .highlighted) .~ .ksr_create_700
|> UIButton.lens.title(for: .normal) %~ { _ in Strings.Add_new_card() }
_ = self.addCardButton.imageView
?|> \.tintColor .~ .ksr_create_700
_ = self
|> \.backgroundColor .~ .ksr_white
_ = self.separatorView
|> separatorStyle
}
@IBAction func addNewCardButtonTapped(_: Any) {
if featureSettingsPaymentSheetEnabled() {
self.loadingIndicator.startAnimating()
self.addCardButton.isHidden = true
}
self.addCardButton.isUserInteractionEnabled = false
self.delegate?.paymentMethodsFooterViewDidTapAddNewCardButton(self)
}
}
extension PaymentMethodsFooterView: PaymentMethodsViewControllerDelegate {
func cancelLoadingPaymentMethodsViewController(
_: PaymentMethodsViewController) {
self.addCardButton.isHidden = false
self.addCardButton.isUserInteractionEnabled = true
self.loadingIndicator.stopAnimating()
}
}
| apache-2.0 | a0e5be44dfb00460113c0b7d995ab03c | 32.872727 | 93 | 0.732689 | 4.954787 | false | false | false | false |
marsal-silveira/Tonight | Tonight/src/Controllers/ClubListTableViewController.swift | 1 | 8118 | //
// ClubListTableViewController.swift
// Tonight
//
// Created by Marsal on 29/02/16.
// Copyright © 2016 Marsal Silveira. All rights reserved.
//
import UIKit
import Firebase
class ClubListTableViewController : UITableViewController, UIPickerViewDataSource, UIPickerViewDelegate
{
// ****************************** //
// MARK: Properties
// ****************************** //
private var _clubs: [Club] = [Club]()
private var _selectedClub: Club!
// *********************************** //
// MARK: <UIViewController> Lifecycle
// *********************************** //
override func viewDidLoad()
{
super.viewDidLoad()
// update selected filter and fetch data from server
_selectedFilter = _pickerData[0]
self.fetchDataFromCity(_selectedFilter!)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?)
{
if (segue.identifier == Segue_ListToDetail) {
let viewController = segue.destinationViewController as! ClubDetailsTableViewController
viewController.club = _selectedClub
}
}
func updateTitle()
{
self.navigationItem.title = "\(_selectedFilter!)"
}
// *********************************** //
// MARK: <UITableViewDataSource>
// *********************************** //
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return _clubs.count
}
// *********************************** //
// MARK: <UITableViewDelegate>
// *********************************** //
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
var result: ClubListTableViewCell!
if let cell = tableView.dequeueReusableCellWithIdentifier(Cell_Identifier_ClubListCell) as? ClubListTableViewCell {
result = cell
}
else {
result = ClubListTableViewCell()
}
result.configureCell(_clubs[indexPath.row])
return result
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
_selectedClub = _clubs[indexPath.row]
performSegueWithIdentifier(Segue_ListToDetail, sender: self)
}
// *********************************** //
// MARK: Load Data
// *********************************** //
@IBAction func btnChangeFilterTap(sender: UIBarButtonItem)
{
self.showPickerInActionSheet()
}
private func fetchDataFromCity(city: String)
{
// wait until Firebase send data or occurs some event
FirebaseApp.sharedInstance().fetchClubsWithFilter(city, completionBlock: { clubs in
// update clubs list and refresh table data with new values
self._clubs = clubs
self.tableView.reloadData()
}, failBlock: { error in
Logger.log("Errro fetching data. Error: \(error.localizedDescription)")
// create and configure alert to ask user confirmation to do logout
let alert = UIAlertController(title: "Tonight!", message: "Error fetching data.", preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
})
// finally update title with selected filter
self.updateTitle()
}
// *************************************************************** //
// MARK: Filter Controller
// *************************************************************** //
private let _pickerData = [Filter_All_Places, Filter_Palhoca, Filter_Santo_Amaro_da_Imperatriz, Filter_Sao_Jose, Filter_Florianopolis]
private var _selectedFilter: String?
// PickerView inside AlertController
private func showPickerInActionSheet()
{
let title = ""
let message = "\n\n\n\n\n\n\n\n\n\n"
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.ActionSheet)
alert.modalInPopover = true
// create a frame (placeholder/wrapper) for the picker and then create the picker... so add the picker to alert controller
let picker: UIPickerView = UIPickerView(frame: CGRectMake(17, 52, 270, 100))
picker.delegate = self
picker.dataSource = self
alert.view.addSubview(picker)
// configure picker position
if (UIDevice.currentDevice().userInterfaceIdiom == .Phone) {
picker.center.x = self.view.center.x
}
if (UIDevice.currentDevice().userInterfaceIdiom == .Pad) {
alert.popoverPresentationController?.sourceView = self.view
// alert.popoverPresentationController?.sourceRect = picker.bounds
}
// set selected filter as selected value in picker view
picker.selectRow(_pickerData.indexOf(_selectedFilter!)!, inComponent: 0, animated: true)
// create the toolbar view - the view witch will hold our 2 buttons
let toolView: UIView = UIView(frame: CGRectMake(17, 5, 270, 45))
// add cancel button to alert
let buttonCancel: UIButton = UIButton(frame: CGRectMake(0, 7, 100, 30))
buttonCancel.setTitle("Cancel", forState: UIControlState.Normal)
buttonCancel.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
buttonCancel.addTarget(self, action: "btnCancelTap:", forControlEvents: UIControlEvents.TouchDown);
toolView.addSubview(buttonCancel)
// add select button to alert
let buttonSelect: UIButton = UIButton(frame: CGRectMake(170, 7, 100, 30));
buttonSelect.setTitle("Select", forState: UIControlState.Normal);
buttonSelect.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal);
buttonSelect.addTarget(self, action: "btnFilterTap:", forControlEvents: UIControlEvents.TouchDown);
toolView.addSubview(buttonSelect);
//add the toolbar to the alert controller
alert.view.addSubview(toolView);
self.presentViewController(alert, animated: true, completion: nil);
}
func btnCancelTap(sender: UIButton)
{
self.dismissViewControllerAnimated(true, completion: nil);
}
func btnFilterTap(sender: UIButton)
{
// close ui and refresh data
self.dismissViewControllerAnimated(true, completion: nil);
self.fetchDataFromCity(_selectedFilter!)
}
// *************************************************************** //
// MARK: <UIPickerViewDataSource>
// *************************************************************** //
func numberOfComponentsInPickerView(pickerView: UIPickerView) -> Int
{
return 1
}
func pickerView(pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int
{
return _pickerData.count
}
// *************************************************************** //
// MARK: <UIPickerViewDelegate>
// *************************************************************** //
func pickerView(pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String?
{
return _pickerData[row]
}
func pickerView(pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int)
{
_selectedFilter = _pickerData[row]
}
func pickerView(pickerView: UIPickerView, attributedTitleForRow row: Int, forComponent component: Int) -> NSAttributedString?
{
let titleData = _pickerData[row]
let myTitle = NSAttributedString(string: titleData, attributes: [NSFontAttributeName:UIFont(name: "Georgia", size: 26.0)!,NSForegroundColorAttributeName:UIColor.blueColor()])
return myTitle
}
} | mit | ffdd590b87841987fd102c4dee5f1f29 | 37.292453 | 182 | 0.586054 | 5.578694 | false | false | false | false |
DevaLee/LYCSwiftDemo | LYCSwiftDemo/Classes/Main/Other/LYCMainViewModel.swift | 1 | 1293 | //
// LYCMainViewModel.swift
// LYCSwiftDemo
//
// Created by 李玉臣 on 2017/6/10.
// Copyright © 2017年 zsc. All rights reserved.
//
import UIKit
class LYCMainViewModel: NSObject {
var anchors : [LYCAnchorTypeModel] = []
}
extension LYCMainViewModel {
func loadMainData(methodType : MethodType , urlString : String , parameter : [String : Any]? , finishCallBack : @escaping()->() ){
LYCNetworkTool.loadData(type: methodType, urlString: urlString, parameter: parameter) { (result : Any) -> Void in
// 确保 result 为字典形式
guard let resultDict = result as? [String : Any] else{
return
}
guard let messageDict = resultDict["message"] as? [String : Any] else {
return
}
// 确保 dataArray 为存放字典的数组
guard let dataArray = messageDict["anchors"] as? [[String : Any]] else{
return
}
for(i , anchorDict) in dataArray.enumerated() {
let anchorModel = LYCAnchorTypeModel.init(dict : anchorDict)
anchorModel.isEvenIndex = i % 2 == 0
self.anchors.append(anchorModel)
}
finishCallBack()
}
}
}
| mit | 92cb3546b16acb4c476fdca9fb6216c7 | 31.051282 | 134 | 0.5608 | 4.401408 | false | false | false | false |
y0ke/actor-platform | actor-sdk/sdk-core-ios/ActorSDK/Sources/Utils/Categories/AACustomPresentationController.swift | 2 | 2755 | //
// Copyright (c) 2014-2016 Actor LLC. <https://actor.im>
//
import UIKit
class AACustomPresentationController: UIPresentationController {
lazy var dimmingView :UIView = {
let view = UIView(frame: self.containerView!.bounds)
view.backgroundColor = UIColor(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.5)
view.alpha = 0.0
return view
}()
override func presentationTransitionWillBegin() {
// Add the dimming view and the presented view to the heirarchy
self.dimmingView.frame = self.containerView!.bounds
self.containerView!.addSubview(self.dimmingView)
self.containerView!.addSubview(self.presentedView()!)
// Fade in the dimming view alongside the transition
if let transitionCoordinator = self.presentingViewController.transitionCoordinator() {
transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.dimmingView.alpha = 1.0
}, completion:nil)
}
}
override func presentationTransitionDidEnd(completed: Bool) {
// If the presentation didn't complete, remove the dimming view
if !completed {
self.dimmingView.removeFromSuperview()
}
}
override func dismissalTransitionWillBegin() {
// Fade out the dimming view alongside the transition
if let transitionCoordinator = self.presentingViewController.transitionCoordinator() {
transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.dimmingView.alpha = 0.0
}, completion:nil)
}
}
override func dismissalTransitionDidEnd(completed: Bool) {
// If the dismissal completed, remove the dimming view
if completed {
self.dimmingView.removeFromSuperview()
}
}
override func frameOfPresentedViewInContainerView() -> CGRect {
// We don't want the presented view to fill the whole container view, so inset it's frame
var frame = self.containerView!.bounds;
frame = CGRectInset(frame, 0.0, 0.0)
return frame
}
// ---- UIContentContainer protocol methods
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator transitionCoordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: transitionCoordinator)
transitionCoordinator.animateAlongsideTransition({(context: UIViewControllerTransitionCoordinatorContext!) -> Void in
self.dimmingView.frame = self.containerView!.bounds
}, completion:nil)
}
}
| agpl-3.0 | d5b238f2904bcb459e0080d746f45f66 | 37.263889 | 146 | 0.68784 | 5.812236 | false | false | false | false |
lvdaqian/Stone | Stone/Action.swift | 1 | 1950 | //
// Action.swift
// Stone
//
// Created by Darwin Lv on 17/3/21.
// Copyright © 2017年 cn.lvdaqian. All rights reserved.
//
public protocol Action {
var actionId: String { get }
}
public protocol RequestAction:Action {
var path: String { get }
var queryParams: [String: Any] { get }
var headerParams: [String: String] { get }
var payload:PayloadType { get }
var method:String { get }
static var authorization:AuthorizationType? { get }
}
public protocol ResponseAction:Action {
}
public protocol ResponseActionBuilder {
associatedtype contentType
func createResponseAction(_ content:contentType, for request:RequestAction) -> ResponseAction
}
public struct DefaultResponseAction:ResponseAction {
public var actionId: String
public let payload:Any?
public init(_ actionId:String, _ payload:Any?) {
self.actionId = actionId
self.payload = payload
}
}
extension Action {
var actionType:String {
get {
return "\(type(of:self))"
}
}
}
extension RequestAction {
public func toJSON() -> Any {
var jsonObject:[String:Any] = [:]
jsonObject["actionId"] = actionId
jsonObject["actionType"] = actionType
jsonObject["path"] = path
jsonObject["queryParams"] = queryParams
jsonObject["headerParams"] = headerParams
jsonObject["payload"] = payload.toJSON()
jsonObject["method"] = method
return jsonObject
}
public func toJSONString() -> String? {
do {
let jsonObject = toJSON()
let data = try JSONSerialization.data(withJSONObject: jsonObject, options: .prettyPrinted)
let jsonString = String(data: data, encoding: .utf8)
return jsonString
} catch {
return nil
}
}
}
| mit | 63346cc5bcae7e2d7c86d83c86ef5474 | 21.905882 | 102 | 0.596302 | 4.657895 | false | false | false | false |
blg-andreasbraun/ProcedureKit | Sources/Cloud/CKDatabaseOperation.swift | 2 | 4831 | //
// ProcedureKit
//
// Copyright © 2016 ProcedureKit. All rights reserved.
//
import CloudKit
/**
A generic protocol which exposes the types and properties used by
Apple's CloudKit Database Operation types.
*/
public protocol CKDatabaseOperationProtocol: CKOperationProtocol {
/// The type of the CloudKit Database
associatedtype Database
/// - returns: the CloudKit Database
var database: Database? { get set }
}
/// An extension to make CKDatabaseOperation to conform to the CKDatabaseOperationProtocol.
extension CKDatabaseOperation: CKDatabaseOperationProtocol {
/// The Database is a CKDatabase
public typealias Database = CKDatabase
}
extension CKProcedure where T: CKDatabaseOperationProtocol {
public var database: T.Database? {
get { return operation.database }
set { operation.database = newValue }
}
}
extension CloudKitProcedure where T: CKDatabaseOperationProtocol {
/// - returns: the CloudKit database
public var database: T.Database? {
get { return current.database }
set {
current.database = newValue
appendConfigureBlock { $0.database = newValue }
}
}
}
// MARK: - CKPreviousServerChangeToken
/**
A generic protocol which exposes the types and properties used by
Apple's CloudKit Operation's which return the previous sever change
token.
*/
public protocol CKPreviousServerChangeToken: CKOperationProtocol {
/// - returns: the previous sever change token
var previousServerChangeToken: ServerChangeToken? { get set }
}
extension CKProcedure where T: CKPreviousServerChangeToken {
public var previousServerChangeToken: T.ServerChangeToken? {
get { return operation.previousServerChangeToken }
set { operation.previousServerChangeToken = newValue }
}
}
extension CloudKitProcedure where T: CKPreviousServerChangeToken {
/// - returns: the previous server change token
public var previousServerChangeToken: T.ServerChangeToken? {
get { return current.previousServerChangeToken }
set {
current.previousServerChangeToken = newValue
appendConfigureBlock { $0.previousServerChangeToken = newValue }
}
}
}
// MARK: - CKResultsLimit
/// A generic protocol which exposes the properties used by Apple's CloudKit Operation's which return a results limit.
public protocol CKResultsLimit: CKOperationProtocol {
/// - returns: the results limit
var resultsLimit: Int { get set }
}
extension CKProcedure where T: CKResultsLimit {
public var resultsLimit: Int {
get { return operation.resultsLimit }
set { operation.resultsLimit = newValue }
}
}
extension CloudKitProcedure where T: CKResultsLimit {
/// - returns: the results limit
public var resultsLimit: Int {
get { return current.resultsLimit }
set {
current.resultsLimit = newValue
appendConfigureBlock { $0.resultsLimit = newValue }
}
}
}
// MARK: - CKMoreComing
/// A generic protocol which exposes the properties used by Apple's CloudKit Operation's which return a flag for more coming.
public protocol CKMoreComing: CKOperationProtocol {
/// - returns: whether there are more results on the server
var moreComing: Bool { get }
}
extension CKProcedure where T: CKMoreComing {
public var moreComing: Bool {
return operation.moreComing
}
}
extension CloudKitProcedure where T: CKMoreComing {
/// - returns: a flag to indicate whether there are more results on the server
public var moreComing: Bool {
return current.moreComing
}
}
// MARK: - CKDesiredKeys
/// A generic protocol which exposes the properties used by Apple's CloudKit Operation's which have desired keys.
public protocol CKDesiredKeys: CKOperationProtocol {
/// - returns: the desired keys to fetch or fetched.
var desiredKeys: [String]? { get set }
}
extension CKProcedure where T: CKDesiredKeys {
public var desiredKeys: [String]? {
get { return operation.desiredKeys }
set { operation.desiredKeys = newValue }
}
}
extension CloudKitProcedure where T: CKDesiredKeys {
/// - returns: the desired keys
public var desiredKeys: [String]? {
get { return current.desiredKeys }
set {
current.desiredKeys = newValue
appendConfigureBlock { $0.desiredKeys = newValue }
}
}
}
/// A protocol typealias which exposes the properties used by Apple's CloudKit batched operation types.
public typealias CKBatchedOperation = CKResultsLimit & CKMoreComing
/// A protocol typealias which exposes the properties used by Apple's CloudKit fetched operation types.
public typealias CKFetchOperation = CKPreviousServerChangeToken & CKBatchedOperation
| mit | 91f3c996cff1e893cbf4948db27b82ec | 27.75 | 125 | 0.709317 | 5.261438 | false | false | false | false |
skedgo/tripkit-ios | Sources/TripKit/model/TKSegment+TKTripSegment.swift | 1 | 12101 | //
// TKSegment+TKTripSegment.swift
// TripKit
//
// Created by Adrian Schönig on 23.07.20.
// Copyright © 2020 SkedGo Pty Ltd. All rights reserved.
//
import Foundation
import MapKit
// MARK: - TKUITripSegmentDisplayable
extension TKSegment {
public var tripSegmentAccessibilityLabel: String? {
titleWithoutTime
}
@objc
public var tripSegmentModeTitle: String? {
if let service = service {
return service.number
} else if let descriptor = modeInfo?.descriptor, !descriptor.isEmpty {
return descriptor
} else if !trip.isMixedModal(ignoreWalking: false), let distance = distanceInMetres {
return MKDistanceFormatter().string(fromDistance: distance.doubleValue)
} else {
return nil
}
}
public var tripSegmentModeSubtitle: String? {
func friendliness() -> String? {
guard let friendly = distanceInMetresFriendly, let total = distanceInMetres else { return nil }
let formatter = NumberFormatter()
formatter.numberStyle = .percent
guard let percentage = formatter.string(from: NSNumber(value: friendly.doubleValue / total.doubleValue)) else {
return nil
}
if isCycling {
return Loc.PercentCycleFriendly(percentage)
} else if isWheelchair {
return Loc.PercentWheelchairFriendly(percentage)
} else {
return nil
}
}
if timesAreRealTime {
return isPublicTransport ? Loc.RealTime : Loc.LiveTraffic
} else if let friendliness = friendliness() {
return friendliness
} else if !isPublicTransport, template?.hideExactTimes != true {
let final = finalSegmentIncludingContinuation()
let duration = final.arrivalTime.timeIntervalSince(departureTime)
if duration > 10 * 60 || !trip.isMixedModal(ignoreWalking: false) {
return final.arrivalTime.durationSince(departureTime)
} else {
return nil
}
} else {
return nil
}
}
public var tripSegmentTimeZone: TimeZone? { timeZone }
public var tripSegmentModeImage: TKImage? { image() }
public var tripSegmentInstruction: String {
guard let rawString = template?.miniInstruction?.instruction else { return "" }
let (instruction, _) = fillTemplates(input: rawString, inTitle: true, includingTime: true, includingPlatform: true)
return instruction
}
/// A short detail expanding on `tripSegmentInstruction`.
public var tripSegmentDetail: String? {
guard let rawString = template?.miniInstruction?.detail else { return nil }
let (instruction, _) = fillTemplates(input: rawString, inTitle: true, includingTime: true, includingPlatform: true)
return instruction
}
public var tripSegmentTimesAreRealTime: Bool {
return timesAreRealTime
}
public var tripSegmentWheelchairAccessibility: TKWheelchairAccessibility {
return self.wheelchairAccessibility ?? .unknown
}
public var tripSegmentFixedDepartureTime: Date? {
if isPublicTransport {
if let frequency = frequency?.intValue, frequency > 0 {
return nil
} else {
return departureTime
}
} else {
return nil
}
}
public var tripSegmentModeColor: TKColor? {
// These are only used in segment views. We only want to
// colour public transport there.
guard isPublicTransport else { return nil }
// Prefer service colour over that of the mode itself.
return service?.color ?? modeInfo?.color
}
public var tripSegmentModeImageURL: URL? {
return imageURL(for: .listMainMode)
}
public var tripSegmentModeImageIsTemplate: Bool {
guard let modeInfo = modeInfo else { return false }
return modeInfo.remoteImageIsTemplate || modeInfo.identifier.map(TKRegionManager.shared.remoteImageIsTemplate) ?? false
}
public var tripSegmentModeImageIsBranding: Bool {
return modeInfo?.remoteImageIsBranding ?? false
}
public var tripSegmentModeInfoIconType: TKInfoIconType {
let modeAlerts = alerts
.filter { $0.isForMode }
.sorted { $0.alertSeverity.rawValue > $1.alertSeverity.rawValue }
return modeAlerts.first?.infoIconType ?? .none
}
public var tripSegmentSubtitleIconType: TKInfoIconType {
let nonModeAlerts = alerts
.filter { !$0.isForMode }
.sorted { $0.alertSeverity.rawValue > $1.alertSeverity.rawValue }
return nonModeAlerts.first?.infoIconType ?? .none
}
}
// MARK: - Visits
extension TKSegment {
func buildSegmentVisits() -> [String: Bool]? {
guard let service = service else { return [:] } // Don't ask again
guard service.hasServiceData else { return nil } // Ask again later
let untravelledEachSide = 5
var output: [String: Bool] = [:]
var unvisited: [String] = []
var isTravelled = false
var isEnd = false
var target = scheduledStartStopCode
for visit in service.sortedVisits {
guard let current = visit.stop?.stopCode else { continue }
if target == current {
if !isTravelled {
// found start
target = scheduledEndStopCode ?? ""
} else {
isEnd = true
target = nil
}
isTravelled.toggle()
output[current] = true
} else {
// on the way
output[current] = isTravelled
if !isTravelled {
unvisited.append(current)
if isEnd, unvisited.count >= untravelledEachSide {
break // added enough
}
}
}
// remove unvisited from the start if we have to
if isTravelled, !unvisited.isEmpty {
if unvisited.count > untravelledEachSide {
let toRemove = unvisited.reversed().suffix(from: untravelledEachSide)
toRemove.forEach { output.removeValue(forKey: $0) }
}
unvisited.removeAll()
}
}
return output
}
}
// MARK: - Content builder
extension TKSegment {
func buildPrimaryLocationString() -> String? {
guard order == .regular else { return nil }
if isStationary || isContinuation {
let departure = (start?.title ?? nil) ?? ""
return departure.isEmpty ? nil : departure
} else if isPublicTransport {
let departure = (start?.title ?? nil) ?? ""
return departure.isEmpty ? nil : Loc.From(location: departure)
} else {
let destination = (finalSegmentIncludingContinuation().end?.title ?? nil) ?? ""
return destination.isEmpty ? nil : Loc.To(location: destination)
}
}
func buildSingleLineInstruction(includingTime: Bool, includingPlatform: Bool) -> (String, Bool) {
switch order {
case .start:
let isTimeDependent = includingTime && trip.departureTimeIsFixed
let name: String?
if let named = trip.request.fromLocation.name {
name = named
} else if isPublicTransport, let next = (next?.start?.title ?? nil) {
name = next
} else {
name = trip.request.fromLocation.address ?? (next?.start?.title ?? nil)
}
if matchesQuery() {
let time = isTimeDependent ? TKStyleManager.timeString(departureTime, for: timeZone) : nil
return (Loc.LeaveFromLocation(name, at: time), isTimeDependent)
} else {
return (Loc.LeaveNearLocation(name), isTimeDependent)
}
case .regular:
guard let raw = _rawAction else { return ("", false) }
return fillTemplates(input: raw, inTitle: true, includingTime: includingTime, includingPlatform: includingPlatform)
case .end:
let isTimeDependent = includingTime && trip.departureTimeIsFixed
let name: String?
if let named = trip.request.toLocation.name {
name = named
} else if isPublicTransport, let next = (previous?.end?.title ?? nil) {
name = next
} else {
name = trip.request.toLocation.address ?? (previous?.end?.title ?? nil)
}
if matchesQuery() {
let time = isTimeDependent ? TKStyleManager.timeString(arrivalTime, for: timeZone) : nil
return (Loc.ArriveAtLocation(name, at: time), isTimeDependent)
} else {
return (Loc.ArriveNearLocation(name), isTimeDependent)
}
}
}
func fillTemplates(input: String, inTitle: Bool, includingTime: Bool, includingPlatform: Bool) -> (String, Bool) {
var isDynamic = false
var output = input
output["<NUMBER>"] = scheduledServiceNumber.nonEmpty ?? tripSegmentModeTitle
output["<LINE_NAME>"] = service?.lineName
output["<DIRECTION>"] = service?.direction.map { Loc.Direction + ": " + $0 }
output["<LOCATIONS>"] = nil // we show these as stationary segments
output["<PLATFORM>"] = includingPlatform ? scheduledStartPlatform : nil
output["<STOPS>"] = Loc.Stops(numberOfStopsIncludingContinuation())
if includingTime, let range = output.range(of: "<TIME>") {
let timeString = TKStyleManager.timeString(departureTime, for: timeZone)
let prepend = range.lowerBound != output.startIndex && output[output.index(range.lowerBound, offsetBy: -1)] != "\n"
output["<TIME>"] = prepend ? Loc.SomethingAt(time: timeString) : timeString
isDynamic = true
} else {
output["<TIME>"] = nil
}
if let range = output.range(of: "<DURATION>") {
let durationString = finalSegmentIncludingContinuation().arrivalTime.durationSince(departureTime)
let prepend = inTitle && range.lowerBound != output.startIndex
output["<DURATION>"] = prepend ? " " + Loc.SomethingFor(duration: durationString) : durationString
isDynamic = true
} else {
output["<DURATION>"] = nil
}
if output.contains("<TRAFFIC>") {
output["<TRAFFIC>"] = durationStringWithoutTraffic()
isDynamic = true // even though the "duration without traffic" itself isn't time dependent, whether it is visible or not IS time dependent
} else {
output["<TRAFFIC>"] = nil
}
// replace empty lead-in
output.replace("^: ", with: "", regex: true)
output.replace("([\\n^])[ ]*⋅[ ]*", with: "$1", regex: true)
// replace empty lead-out
output.replace("[ ]*⋅[ ]*$", with: "", regex: true)
// replace empty stuff between dots
output.replace("⋅[ ]*⋅", with: "⋅", regex: true)
// replace empty lines
output.replace("^\\n*", with: "", regex: true)
output.replace(" ", with: " ")
while let range = output.range(of: "\n\n") {
output.replaceSubrange(range, with: "\n")
}
output.replace("\\n*$", with: "")
return (output, isDynamic)
}
private func numberOfStopsIncludingContinuation() -> Int {
var stops = 0
var candidate: TKSegment? = self
while let segment = candidate {
stops += segment.scheduledServiceStops
candidate = (segment.next?.isContinuation == true) ? segment.next : nil
}
return stops
}
private func durationStringWithoutTraffic() -> String? {
guard durationWithoutTraffic > 0 else { return nil }
let withTraffic = arrivalTime.timeIntervalSince(departureTime)
if withTraffic > durationWithoutTraffic + 60 {
let durationString = Date.durationString(forMinutes: Int(durationWithoutTraffic) / 60)
return Loc.DurationWithoutTraffic(durationString)
} else {
return nil
}
}
}
extension String {
subscript(template: String) -> String? {
get { assertionFailure(); return nil }
set {
if let range = range(of: template) {
replaceSubrange(range, with: newValue ?? "")
}
}
}
mutating func replace(_ this: String, with that: String, regex: Bool = false) {
let mutable = NSMutableString(string: self)
mutable.replaceOccurrences(of: this, with: that, options: regex ? .regularExpression : .literal, range: NSRange(location: 0, length: mutable.length))
self = mutable as String
}
}
extension Alert {
fileprivate var isForMode: Bool {
if idService != nil {
return true
} else if location != nil {
return false
} else {
return idStopCode != nil
}
}
}
| apache-2.0 | 510cd461e8d19d5d7f0da90dce496d04 | 31.410188 | 153 | 0.647779 | 4.556728 | false | false | false | false |
mxclove/compass | 毕业设计_指南针最新3.2/毕业设计_指南针/MapViewController.swift | 1 | 12718 | //
// ViewController.swift
// 毕业设计_指南针
//
// Created by 马超 on 15/10/26.
// Copyright © 2015年 马超. All rights reserved.
//
import UIKit
import MapKit
import CoreData
import CoreLocation
var myLongitude = ""
var myLatitude = ""
var myAddress = ""
protocol MapViewControllerDelegate {
func updataSelfLabels(controller: MapViewController)
}
class MapViewController: UIViewController, CLLocationManagerDelegate,MKMapViewDelegate, SwitchCellMapDelegate {
var map = MKMapView()
// var locationManager = CLLocationManager()
var longitudeLabel = UILabel()
var latitudeLabel = UILabel()
var addressLabel = UILabel()
var messageLabel = UILabel()
let getUserLocationBTn = UIButton(type: UIButtonType.Custom)
var currentLocation:CLLocation!
var delegate : MapViewControllerDelegate?
var updatingLocation = false
let MATLABImageView = UIImageView()
// 反地理编码管理器
let geocorder = CLGeocoder()
// 存储翻译过来的地址信息。(街道、门牌号等)
var placemark: CLPlacemark?
// 存储翻译时的错误
var lastGeocodingError: NSError?
// 判断是否正在执行反地理编码
var performingReverseGeocoding = false
// 存储NSError的对象
var locationError: NSError?
override func viewDidLoad() {
super.viewDidLoad()
map.frame = self.view.frame
map.height(deviceHeight * 0.8)
map.showsUserLocation = true
map.mapType = MKMapType.Standard
map.userTrackingMode = MKUserTrackingMode.FollowWithHeading
map.delegate = self
configureMapShouldDisplay()
longitudeLabel.frame = CGRect(x: deviceWidth * 0.1, y: deviceHeight * 0.9, width: deviceWidth * 0.4, height: 30)
// longitudeLabel.contentMode = UIViewContentMode.Left
longitudeLabel.textAlignment = NSTextAlignment.Left
longitudeLabel.textColor = UIColor.whiteColor()
longitudeLabel.text = "0"
latitudeLabel.frame = CGRect(x: deviceWidth * 0.5, y: deviceHeight * 0.9, width: deviceWidth * 0.4, height: 30)
// latitudeLabel.contentMode = UIViewContentMode.Right
latitudeLabel.textAlignment = NSTextAlignment.Right
latitudeLabel.textColor = UIColor.whiteColor()
latitudeLabel.text = "0"
addressLabel.frame = CGRect(x: deviceWidth * 0.05, y: deviceHeight * 0.82, width: deviceWidth * 0.5, height: 30)
addressLabel.textColor = UIColor.whiteColor()
addressLabel.numberOfLines = 0
// addressLabel.adjustsFontSizeToFitWidth = true
addressLabel.lineBreakMode = NSLineBreakMode.ByTruncatingMiddle
addressLabel.text = "0"
messageLabel.frame = CGRect(x: deviceWidth * 0.55, y: deviceHeight * 0.82, width: deviceWidth * 0.41, height: 30)
messageLabel.textAlignment = NSTextAlignment.Right
messageLabel.textColor = UIColor.whiteColor()
messageLabel.text = "0"
// MATLABImageView.frame = CGRect(x: deviceWidth - deviceWidth * 0.14 , y: 20, width: deviceWidth * 0.14, height: deviceWidth * 0.14)
// MATLABImageView.image = UIImage(named: "MNT3")
getUserLocationBTn.frame = CGRect(x: deviceWidth * 0.9, y: map.bounds.height * 0.85, width: deviceWidth * 0.1, height: deviceWidth * 0.1)
getUserLocationBTn.addTarget(self, action: "showCurrectLocation", forControlEvents: UIControlEvents.TouchUpInside)
getUserLocationBTn.setImage(UIImage(named: "icon_map"), forState: UIControlState.Normal)
getUserLocationBTn.setImage(UIImage(named: "icon_map_highlighted"), forState: UIControlState.Highlighted)
if modelStr == "iPhone" {
longitudeLabel.font = UIFont.systemFontOfSize(17.0)
latitudeLabel.font = UIFont.systemFontOfSize(17.0)
addressLabel.font = UIFont.systemFontOfSize(20.0)
messageLabel.font = UIFont.systemFontOfSize(13.0)
addressLabel.adjustsFontSizeToFitWidth = true
messageLabel.adjustsFontSizeToFitWidth = true
} else if modelStr == "iPad" {
longitudeLabel.font = UIFont.systemFontOfSize(25.0)
latitudeLabel.font = UIFont.systemFontOfSize(25.0)
addressLabel.font = UIFont.systemFontOfSize(32.0)
messageLabel.font = UIFont.systemFontOfSize(20.0)
addressLabel.adjustsFontSizeToFitWidth = false
} else {
longitudeLabel.font = UIFont.systemFontOfSize(17.0)
latitudeLabel.font = UIFont.systemFontOfSize(17.0)
addressLabel.font = UIFont.systemFontOfSize(20.0)
messageLabel.font = UIFont.systemFontOfSize(13.0)
addressLabel.adjustsFontSizeToFitWidth = true
messageLabel.adjustsFontSizeToFitWidth = true
}
// self.view.addSubview(MATLABImageView)
self.view.addSubview(longitudeLabel)
self.view.addSubview(latitudeLabel)
self.view.addSubview(addressLabel)
self.view.addSubview(messageLabel)
self.map.addSubview(getUserLocationBTn)
// locationManager.delegate = self
//
// locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
// locationManager.startUpdatingLocation()
}
func configureMapShouldDisplay() {
if trafficProtection == true && IJReachability.isConnectedToNetworkOfType() == .WWAN {
self.map.removeFromSuperview()
} else {
self.view.addSubview(map)
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
showCurrectLocation()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
// currentLocation = locations.last
// latitudeLabel.text = "纬度:"+String(format: "%.1fº",Float (currentLocation.coordinate.latitude))
//
// longitudeLabel.text = "经度:"+String(format: "%.1fº",Float (currentLocation.coordinate.longitude))
currentLocation = CLLocation(latitude: map.userLocation.coordinate.latitude, longitude: map.userLocation.coordinate.longitude)
updateLabels()
}
// MARK: - CLLocationManagerDelegate Methods
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {
// 处理地址信息获取错误的信息
locationError = NSError(domain: "MyLocationError", code: 1, userInfo: nil)
// 如果错误是地址不可知,则继续取地址信息
if error.code == CLError.LocationUnknown.rawValue {
return
}
locationError = error
// print("location fail: \(error)")
updateLabels()
}
func mapViewDidFailLoadingMap(mapView: MKMapView, withError error: NSError) {
updatingLocation = false
locationError = NSError(domain: "MyLocationError", code: 1, userInfo: nil)
messageLabel.text = "DidFailLoadingMap"
updateLabels()
}
func mapViewWillStartLoadingMap(mapView: MKMapView) {
messageLabel.text = "WillStartLoadingMap"
updateLabels()
}
func mapViewDidFinishLoadingMap(mapView: MKMapView) {
messageLabel.text = "DidFinishLoadingMap"
updateLabels()
}
func mapViewWillStartLocatingUser(mapView: MKMapView) {
messageLabel.text = "WillStartLocatingUser"
updateLabels()
}
// func mapView(mapView: MKMapView, regionDidChangeAnimated animated: Bool) {
// self.map.removeFromSuperview()
// self.view.addSubview(map)
// }
func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation) {
// 得到以用户位置为中心的一片区域
// latitudeLabel.text = "经度:"+"\(map.userLocation.coordinate.longitude)"
// longitudeLabel.text = "纬度:"+"\(map.userLocation.coordinate.latitude)"
messageLabel.text = "didUpdateUserLocation"
currentLocation = CLLocation(latitude: map.userLocation.coordinate.latitude, longitude: map.userLocation.coordinate.longitude)
let reigon = MKCoordinateRegionMakeWithDistance(map.userLocation.coordinate, 1000, 1000)
map.setRegion(reigon, animated: true)
geocorderDoWork()
updateLabels()
}
func showCurrectLocation() {
// 得到以用户位置为中心的一片区域
let reigon = MKCoordinateRegionMakeWithDistance(map.userLocation.coordinate, 1000, 1000)
map.setRegion(reigon, animated: true)
currentLocation = CLLocation(latitude: map.userLocation.coordinate.latitude, longitude: map.userLocation.coordinate.longitude)
updateLabels()
}
func showAlert() {
let alert = UIAlertController(title: "授权", message: "请在设置中授权本软件获取您的位置信息", preferredStyle: UIAlertControllerStyle.Alert)
let action = UIAlertAction(title: "好", style: UIAlertActionStyle.Default, handler: nil)
alert.addAction(action)
presentViewController(alert, animated: true, completion: nil)
}
private func showPlacemark(placemark: CLPlacemark) -> String {
var line1 = ""
line1.addText(placemark.subThoroughfare)
line1.addText(placemark.thoroughfare)
var line2 = ""
// line2.addText(placemark.locality)
line2.addText(placemark.locality, withseparator: " ")
line2.addText(placemark.administrativeArea, withseparator: " ")
line2.addText(placemark.postalCode, withseparator: " ")
if line1.isEmpty {
return line2
} else {
return line1 + line2
}
}
func geocorderDoWork() {
if !performingReverseGeocoding {
performingReverseGeocoding = true
geocorder.reverseGeocodeLocation(currentLocation!, completionHandler: { (placemarks, error) -> Void in
self.lastGeocodingError = error
if error == nil && !placemarks!.isEmpty {
self.placemark = placemarks!.last
}
else {
self.placemark = nil
}
self.performingReverseGeocoding = false
self.updateLabels()
})
}
}
private func updateLabels() {
if let location = currentLocation {
let long = String(format: "经度:%.5f ", location.coordinate.longitude)
let lati = String(format: "纬度:%.5f", location.coordinate.latitude)
longitudeLabel.text = long
latitudeLabel.text = lati
myLongitude = long
myLatitude = lati
addressLabel.text = ""
if let placemark = placemark {
let addr = showPlacemark(placemark)
addressLabel.text = addr
}
else if performingReverseGeocoding {
addressLabel.text = "搜寻地址中..."
}
else if lastGeocodingError != nil {
addressLabel.text = "地址有错误"
geocorderDoWork()
}
else {
addressLabel.text = "没有这个地址"
}
if let str = addressLabel.text {
myAddress = str
}
}
else {
longitudeLabel.text = ""
latitudeLabel.text = ""
addressLabel.text = ""
var tempMessage = ""
if let error = locationError {
if error.domain == kCLErrorDomain && error.code == CLError.Denied.rawValue {
tempMessage = "地址服务不可用"
}
else {
tempMessage = "地址获取错误"
}
}
else if !CLLocationManager.locationServicesEnabled() {
tempMessage = "地址服务不可用"
}
else if updatingLocation {
tempMessage = "搜寻中..."
}
else {
tempMessage = "搜寻结束"
}
messageLabel.text = tempMessage
}
delegate?.updataSelfLabels(self)
}
}
| apache-2.0 | f0b71d955323eda863ab1f12d7433c51 | 33.923295 | 145 | 0.610673 | 5.115689 | false | false | false | false |
kz56cd/ios_sandbox_animate | IosSandboxAnimate/Utils/UIColor+Util.swift | 1 | 2771 | //
// UIColor+Util.swift
// e-park
//
// Created by KaiKeima on 2015/12/21.
// Copyright © 2015年 OHAKO,inc. All rights reserved.
//
import UIKit
extension UIColor {
class func color(hex: Int, alpha: Double = 1.0) -> UIColor {
let red = Double((hex & 0xFF0000) >> 16) / 255.0
let green = Double((hex & 0xFF00) >> 8) / 255.0
let blue = Double((hex & 0xFF)) / 255.0
return UIColor(red: CGFloat(red), green: CGFloat(green), blue: CGFloat(blue), alpha: CGFloat(alpha))
}
class func hexStr (var hexStr : NSString, alpha : CGFloat) -> UIColor {
hexStr = hexStr.stringByReplacingOccurrencesOfString("#", withString: "")
let scanner = NSScanner(string: hexStr as String)
var color: UInt32 = 0
if scanner.scanHexInt(&color) {
let r = CGFloat((color & 0xFF0000) >> 16) / 255.0
let g = CGFloat((color & 0x00FF00) >> 8) / 255.0
let b = CGFloat((color & 0x0000FF) ) / 255.0
return UIColor(red: r, green: g, blue: b, alpha: alpha)
}else {
return UIColor.whiteColor()
}
}
class func mainColor(alpha: Double = 1.0) -> UIColor {
return UIColor.color(0x1db0d0, alpha: alpha)
}
class func sectionColor(alpha: Double = 1.0) -> UIColor {
return UIColor.color(0xeeeef2, alpha: alpha)
}
class func textColor(alpha: Double = 1.0) -> UIColor {
return UIColor.color(0x333333, alpha: alpha)
}
class func highlightedColor(alpha: Double = 1.0) -> UIColor {
return UIColor.color(0xf4f4f8, alpha: alpha)
}
func transitionColor(nextColor nextColor: UIColor, portion: CGFloat) -> UIColor {
if portion >= 1.0 {
return nextColor
}
if portion <= 0.0 {
return self
}
var preRed = CGFloat(0.0)
var preGreen = CGFloat(0.0)
var preBlue = CGFloat(0.0)
var preAlpha = CGFloat(0.0)
self.getRed(&preRed, green: &preGreen, blue: &preBlue, alpha: &preAlpha)
var nextRed = CGFloat(0.0)
var nextGreen = CGFloat(0.0)
var nextBlue = CGFloat(0.0)
var nextAlpha = CGFloat(0.0)
nextColor.getRed(&nextRed, green: &nextGreen, blue: &nextBlue, alpha: &nextAlpha)
let currentRed = ( 1.0 - portion) * preRed + portion * nextRed
let currentGreen = ( 1.0 - portion) * preGreen + portion * nextGreen
let currentBlue = ( 1.0 - portion) * preBlue + portion * nextBlue
let currentAlpha = ( 1.0 - portion) * preAlpha + portion * nextAlpha
return UIColor(red: currentRed, green: currentGreen, blue: currentBlue, alpha: currentAlpha)
}
} | mit | 653a31572cedade7e29012b2862a333b | 34.050633 | 108 | 0.577312 | 3.750678 | false | false | false | false |
floriankrueger/Manuscript | Manuscript-iOSTests/TestHelper.swift | 1 | 4005 | //
// TestHelper.swift
// Manuscript
//
// Created by Florian Krüger on 06/05/15.
// Copyright (c) 2015 projectserver.org. 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
import UIKit
import XCTest
struct Helper {
static func checkConstraint(
_ constraint: NSLayoutConstraint,
item: UIView,
attribute: NSLayoutAttribute,
relation: NSLayoutRelation,
relatedItem: UIView? = nil,
relatedAttribute: NSLayoutAttribute = .notAnAttribute,
multiplier: CGFloat = 1.0,
constant: CGFloat)
{
XCTAssertNotNil(constraint, "constraint must not be nil")
XCTAssertEqual(constraint.firstItem as? UIView, item, "")
XCTAssertEqual(constraint.firstAttribute, attribute, "")
XCTAssertEqual(constraint.relation, relation, "")
if let strongRelatedItem = relatedItem {
XCTAssertEqual(constraint.secondItem as? UIView, strongRelatedItem, "")
} else {
XCTAssertNil(constraint.secondItem, "")
}
XCTAssertEqual(constraint.secondAttribute, relatedAttribute, "")
XCTAssertEqualWithAccuracy(constraint.multiplier, multiplier, accuracy: CGFloat(Float.ulpOfOne), "")
XCTAssertEqual(constraint.constant, constant, "")
}
static func randomFloat(_ min: CGFloat = 0.0, max: CGFloat) -> CGFloat {
let random = CGFloat(arc4random()) / CGFloat(UInt32.max)
return random * (max - min) + min
}
static func firstConstraint(_ view: UIView, withAttribute optionalAttribute: NSLayoutAttribute? = nil) -> NSLayoutConstraint? {
if view.constraints.count > 0 {
for constraint in view.constraints {
if let attribute = optionalAttribute {
if constraint.firstAttribute == attribute {
return constraint
}
} else {
return constraint
}
}
}
return nil
}
}
extension NSLayoutAttribute : CustomStringConvertible {
public var description: String {
switch self {
case .left:
return "Left"
case .right:
return "Right"
case .top:
return "Top"
case .bottom:
return "Bottom"
case .leading:
return "Leading"
case .trailing:
return "Trailing"
case .width:
return "Width"
case .height:
return "Height"
case .centerX:
return "CenterX"
case .centerY:
return "CenterY"
case .lastBaseline:
return "Baseline"
case .firstBaseline:
return "FirstBaseline"
case .leftMargin:
return "LeftMargin"
case .rightMargin:
return "RightMargin"
case .topMargin:
return "TopMargin"
case .bottomMargin:
return "BottomMargin"
case .leadingMargin:
return "LeadingMargin"
case .trailingMargin:
return "TrailingMargin"
case .centerXWithinMargins:
return "CenterXWithinMargins"
case .centerYWithinMargins:
return "CenterYWithinMargins"
case .notAnAttribute:
return "NotAnAttribute"
}
}
}
| mit | a5db04ef0e1e66f2590270bc4e2a1406 | 31.032 | 129 | 0.68981 | 4.661234 | false | false | false | false |
blstream/TOZ_iOS | TOZ_iOS/CalendarViewController.swift | 1 | 4836 | //
// CalendarViewController.swift
// TOZ_iOS
// Copyright © 2017 intive. All rights reserved.
//
import UIKit
import Foundation
class CalendarViewController: UIViewController {
@IBOutlet weak var prevButton: UIButton!
@IBOutlet weak var nextButton: UIButton!
@IBOutlet weak var currentDateLabel: UILabel!
var pageController: UIPageViewController!
var weekPages = [WeekViewController]()
private var indexPage = 0
var reservations: [ReservationItem] = []
var calendarHelper = CalendarHelper()
var weekScheduleOperation: GetScheduleWeekOperation!
var currentWeekController: WeekViewController!
var weekdayArray: [WeekdayItem]! {
didSet {
if weekdayArray.isEmpty {
currentDateLabel.text = ""
} else {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM"
let month = dateFormatter.monthSymbols[Int(weekdayArray[0].month)! - 1]
currentDateLabel.text = month + " " + weekdayArray[0].year
}
}
}
@IBAction func nextWeek(_ sender: Any) {
weekdayArray = calendarHelper.nextWeek()
currentWeekController = nextWeekController()
retrieveReservationsinWeek(when: .forward)
}
@IBAction func previousWeek(_ sender: Any) {
weekdayArray = calendarHelper.previousWeek()
currentWeekController = nextWeekController()
retrieveReservationsinWeek(when: .reverse)
}
func nextWeekController() -> WeekViewController {
indexPage -= 1
indexPage = abs(indexPage)
return weekPages[indexPage]
}
override func viewDidLoad() {
super.viewDidLoad()
pageController.dataSource = self
// swiftlint:disable:next force_cast
let weekAfter: WeekViewController = self.storyboard?.instantiateViewController(withIdentifier: "WeekViewController") as! WeekViewController
// swiftlint:disable:next force_cast
let weekBefore: WeekViewController = self.storyboard?.instantiateViewController(withIdentifier: "WeekViewController") as! WeekViewController
weekPages.append(weekBefore)
weekPages.append(weekAfter)
weekBefore.delegate = self
weekAfter.delegate = self
weekdayArray = calendarHelper.weekdayItemArray()
currentWeekController = weekBefore
retrieveReservationsinWeek(when: .forward)
}
override func viewDidLayoutSubviews() {
prevButton.setTitleColor(Color.Calendar.PreviousButton.text, for: .normal)
prevButton.backgroundColor = Color.Calendar.PreviousButton.background
nextButton.setTitleColor(Color.Calendar.NextButton.text, for: .normal)
nextButton.backgroundColor = Color.Calendar.NextButton.background
prevButton.layer.cornerRadius = prevButton.bounds.height * 0.5
nextButton.layer.cornerRadius = nextButton.bounds.height * 0.5
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// swiftlint:disable:next force_cast
pageController = segue.destination as! UIPageViewController
}
func retrieveReservationsinWeek(when direction: UIPageViewControllerNavigationDirection?, refreshOnly: Bool = false) {
weekScheduleOperation = GetScheduleWeekOperation(fromDate: weekdayArray[0].dataLabel, toDate: weekdayArray[6].dataLabel)
weekScheduleOperation.resultCompletion = { result in
switch result {
case .success(let listOfReservation):
DispatchQueue.main.async {
self.currentWeekController.weekdayArray = self.weekdayArray
self.currentWeekController.reservations = listOfReservation
if refreshOnly == false {
self.pageController.setViewControllers([self.currentWeekController], direction: direction!, animated: false)
}
}
case .failure(let error):
print ("\(error)")
}
}
weekScheduleOperation.start()
}
}
extension CalendarViewController: WeekViewControllerDelegate {
func weekViewController(_ controller: WeekViewController, didUpdate reservations: [ReservationItem]) {
self.reservations = controller.reservations
retrieveReservationsinWeek(when: nil, refreshOnly: true)
}
}
extension CalendarViewController: UIPageViewControllerDataSource {
func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
return nil
}
func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {
return nil
}
}
| apache-2.0 | b1b59a4a621a7e8cfa2f3f64a363fa6b | 36.48062 | 149 | 0.686039 | 5.681551 | false | false | false | false |
HarrisLee/SwiftBook | Swift-ZhihuDaily-master/view/HomeViewController.swift | 1 | 9909 | //
// HomeViewController.swift
// testSwift
//
// Created by XuDong Jin on 14-6-10.
// Copyright (c) 2014年 XuDong Jin. All rights reserved.
//
import UIKit
let WINDOW_HEIGHT = UIScreen.mainScreen().bounds.size.height
let WINDOW_WIDTH = UIScreen.mainScreen().bounds.size.width
let identifier = "cell"
let url = "http://news-at.zhihu.com/api/4/stories/latest?client=0"
let continueUrl = "http://news-at.zhihu.com/api/4/stories/before/"
let launchImgUrl = "https://news-at.zhihu.com/api/4/start-image/640*1136?client=0"
let kImageHeight:Float = 400
let kInWindowHeight:Float = 200
class HomeViewController: UIViewController,SlideScrollViewDelegate {
@IBOutlet var tableView : UITableView!
var dataKey = NSMutableArray()
var dataFull = NSMutableDictionary() //date as key, above
var slideArray = NSMutableArray()
var slideImgArray = NSMutableArray()
var slideTtlArray = NSMutableArray()
var bloading = false;
var dateString = ""
//MARK:-
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.title = "今日热闻"
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.whiteColor()
var nib = UINib(nibName:"HomeViewCell", bundle: nil)
self.tableView?.registerNib(nib, forCellReuseIdentifier: identifier)
self.edgesForExtendedLayout = UIRectEdge.Top
showLauchImage()
loadData()
}
func loadData()
{
if(bloading){
return;
}
self.bloading = true;
var curUrl = url;
if(dateString.lengthOfBytesUsingEncoding(NSUTF8StringEncoding) > 0){
curUrl = continueUrl.stringByAppendingString(dateString);
}
YRHttpRequest.requestWithURL(curUrl,completionHandler:{ data in
self.bloading = false;
if data as! NSObject == NSNull()
{
UIView.showAlertView("提示",message:"加载失败")
return
}
if(self.dateString.isEmpty){
let topArr = data["top_stories"] as! NSArray
self.slideArray = NSMutableArray(array:topArr)
for topData : AnyObject in topArr
{
let dic = topData as! NSDictionary
let imgUrl = dic["image"] as! String
self.slideImgArray.addObject(imgUrl)
let title = dic["title"] as! String
self.slideTtlArray.addObject(title)
}
}
self.dateString = data["date"] as! String
let arr = data["stories"] as! NSArray
self.dataKey.addObject(self.dateString);
self.dataFull.addEntriesFromDictionary([self.dateString : arr])
self.tableView!.reloadData()
})
}
func showLauchImage () {
YRHttpRequest.requestWithURL(launchImgUrl,completionHandler:{ data in
if data as! NSObject == NSNull()
{
return
}
let imgUrl = data["img"] as! String
let height = UIScreen.mainScreen().bounds.size.height
let width = UIScreen.mainScreen().bounds.size.width
let img = UIImageView(frame:CGRectMake(0, 0, width, height))
img.backgroundColor = UIColor.blackColor()
img.contentMode = UIViewContentMode.ScaleAspectFit
let window = UIApplication.sharedApplication().keyWindow
window!.addSubview(img)
img.setImage(imgUrl,placeHolder:nil)
let lbl = UILabel(frame:CGRectMake(0,height-50,width,20))
lbl.backgroundColor = UIColor.clearColor()
lbl.text = data["text"] as? String
lbl.textColor = UIColor.lightGrayColor()
lbl.textAlignment = NSTextAlignment.Center
lbl.font = UIFont.systemFontOfSize(14)
window!.addSubview(lbl)
UIView.animateWithDuration(3,animations:{
let height = UIScreen.mainScreen().bounds.size.height
let rect = CGRectMake(-100,-100,width+200,height+200)
img.frame = rect
},completion:{
(Bool completion) in
if completion {
UIView.animateWithDuration(1,animations:{
img.alpha = 0
lbl.alpha = 0
},completion:{
(Bool completion) in
if completion {
img.removeFromSuperview()
lbl.removeFromSuperview()
}
})
}
})
})
}
//MARK:
//MARK: -------tableView delegate&datasource
func numberOfSectionsInTableView(tableView: UITableView!) -> Int{
return 1 + self.dataKey.count
}
func tableView(tableView: UITableView?, numberOfRowsInSection section: Int) -> Int {
if section==0{
return 1
}
else
{
let array1 = self.dataFull[self.dataKey[section-1] as! String] as! NSArray
return array1.count
}
}
func tableView(tableView: UITableView!, heightForRowAtIndexPath indexPath: NSIndexPath!) -> CGFloat
{
if indexPath.section==0{
return CGFloat(kInWindowHeight)
}
else{
return 106
}
}
func tableView(tableView: UITableView?, cellForRowAtIndexPath indexPath: NSIndexPath?) -> UITableViewCell? {
var cell:UITableViewCell
if indexPath!.section==0{
cell = UITableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: nil)
cell.backgroundColor = UIColor.clearColor()
cell.contentView.backgroundColor = UIColor.clearColor()
cell.selectionStyle = UITableViewCellSelectionStyle.None
cell.clipsToBounds = true
if self.slideImgArray.count > 0{
let width = UIScreen.mainScreen().bounds.size.height
let slideRect = CGRect(origin:CGPoint(x:0,y:0),size:CGSize(width:width,height:CGFloat(kImageHeight)))
let slideView = SlideScrollView(frame: slideRect)
slideView.delegate = self
slideView.initWithFrameRect(slideRect,imgArr:self.slideImgArray,titArr:self.slideTtlArray)
// self.view.addSubview(slideView)
// self.tableView.tableHeaderView = slideView
cell.addSubview(slideView)
}
}
else{
let c = tableView?.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath!) as? HomeViewCell
let index = indexPath!.row
let array1 = self.dataFull[self.dataKey[(indexPath?.section)!-1] as! String] as! NSArray
let data = array1[index] as! NSDictionary
c!.data = data
cell = c!
}
return cell
}
func tableView(tableView: UITableView!, didSelectRowAtIndexPath indexPath: NSIndexPath!)
{
if indexPath!.section==0 {return}
tableView.deselectRowAtIndexPath(indexPath!,animated: true)
let index = indexPath!.row
let array1 = self.dataFull[self.dataKey[(indexPath?.section)!-1] as! String] as! NSArray
let data = array1[index] as! NSDictionary
let detailCtrl = DetailViewController(nibName :"DetailViewController", bundle: nil)
detailCtrl.aid = data["id"] as! Int
detailCtrl.title = data["title"] as? String;
self.navigationController!.pushViewController(detailCtrl, animated: true)
}
func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat
{
if(section <= 1)
{
return 0
}
return 30 //NavigationBar Height
}
func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView?
{
let lbl = UILabel(frame:CGRectMake(0,0,320,30))
lbl.backgroundColor = UIColor.lightGrayColor()
if(section > 0){
lbl.text = self.dataKey[section-1] as? String
}
lbl.textColor = UIColor.whiteColor()
lbl.textAlignment = NSTextAlignment.Center
lbl.font = UIFont.systemFontOfSize(14)
return lbl;
}
//MARK:
//MARK:------slidescroll delegate
func scrollViewDidScroll(scrollView: UIScrollView){
if(scrollView.contentSize.height - scrollView.contentOffset.y - scrollView.frame.height < scrollView.frame.height/3){
loadData()
}
}
func SlideScrollViewDidClicked(index:Int)
{
if index == 0 {return} // when you click scrollview too soon after the view is presented
let data = self.slideArray[index-1] as! NSDictionary
let detailCtrl = DetailViewController(nibName :"DetailViewController", bundle: nil)
detailCtrl.aid = data["id"] as! Int
self.navigationController!.pushViewController(detailCtrl, animated: true)
}
//MARK:
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| mit | ead38beabfc2ff20327376b667c2bdfd | 33.449477 | 125 | 0.574289 | 5.187303 | false | false | false | false |
practicalswift/swift | test/IRGen/class_field_other_module.swift | 13 | 1233 | // RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -emit-module -emit-module-path=%t/other_class.swiftmodule %S/Inputs/other_class.swift
// RUN: %target-swift-frontend -I %t -emit-ir -O -enforce-exclusivity=unchecked %s | %FileCheck %s -DINT=i%target-ptrsize
import other_class
// CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc i32 @"$s24class_field_other_module12getSubclassXys5Int32V0c1_A00F0CF"(%T11other_class8SubclassC* nocapture readonly)
// CHECK-NEXT: entry:
// CHECK-NEXT: %._value = getelementptr inbounds %T11other_class8SubclassC, %T11other_class8SubclassC* %0, [[INT]] 0, i32 1, i32 0
// CHECK-NEXT: %1 = load i32, i32* %._value
// CHECK-NEXT: ret i32 %1
public func getSubclassX(_ o: Subclass) -> Int32 {
return o.x
}
// CHECK-LABEL: define {{(protected )?}}{{(dllexport )?}}swiftcc i32 @"$s24class_field_other_module12getSubclassYys5Int32V0c1_A00F0CF"(%T11other_class8SubclassC* nocapture readonly)
// CHECK-NEXT: entry:
// CHECK-NEXT: %._value = getelementptr inbounds %T11other_class8SubclassC, %T11other_class8SubclassC* %0, [[INT]] 0, i32 2, i32 0
// CHECK-NEXT: %1 = load i32, i32* %._value
// CHECK-NEXT: ret i32 %1
public func getSubclassY(_ o: Subclass) -> Int32 {
return o.y
}
| apache-2.0 | b7f6de9a6367d0e8ae62d75a36879bc6 | 50.375 | 181 | 0.712895 | 2.971084 | false | false | false | false |
bkmunar/firefox-ios | Storage/SQL/SQLitePasswords.swift | 1 | 6378 | /* 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
private class PasswordsTable<T>: GenericTable<Password> {
override var name: String { return "logins" }
override var version: Int { return 1 }
override var rows: String { return "id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"hostname TEXT NOT NULL, " +
"httpRealm TEXT NOT NULL, " +
"formSubmitUrl TEXT NOT NULL, " +
"usernameField TEXT NOT NULL, " +
"passwordField TEXT NOT NULL, " +
"guid TEXT NOT NULL UNIQUE, " +
"timeCreated REAL NOT NULL, " +
"timeLastUsed REAL NOT NULL, " +
"timePasswordChanged REAL NOT NULL, " +
"username TEXT NOT NULL, " +
"password TEXT NOT NULL" }
override func getInsertAndArgs(inout item: Password) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
if item.guid == nil {
item.guid = NSUUID().UUIDString
}
args.append(item.hostname)
args.append(item.httpRealm)
args.append(item.formSubmitUrl)
args.append(item.usernameField)
args.append(item.passwordField)
args.append(item.guid)
args.append(item.timeCreated)
args.append(item.timeLastUsed)
args.append(item.timePasswordChanged)
args.append(item.username)
args.append(item.password)
return ("INSERT INTO \(name) (hostname, httpRealm, formSubmitUrl, usernameField, passwordField, guid, timeCreated, timeLastUsed, timePasswordChanged, username, password) VALUES (?,?,?,?,?,?,?,?,?,?,?)", args)
}
override func getUpdateAndArgs(inout item: Password) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
args.append(item.httpRealm)
args.append(item.formSubmitUrl)
args.append(item.usernameField)
args.append(item.passwordField)
args.append(item.timeCreated)
args.append(item.timeLastUsed)
args.append(item.timePasswordChanged)
args.append(item.password)
args.append(item.hostname)
args.append(item.username)
return ("UPDATE \(name) SET httpRealm = ?, formSubmitUrl = ?, usernameField = ?, passwordField = ?, timeCreated = ?, timeLastUsed = ?, timePasswordChanged = ?, password = ? WHERE hostname = ? AND username = ?", args)
}
override func getDeleteAndArgs(inout item: Password?) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
if let pw = item {
args.append(pw.hostname)
args.append(pw.username)
return ("DELETE FROM \(name) WHERE hostname = ? AND username = ?", args)
}
return ("DELETE FROM \(name)", args)
}
override var factory: ((row: SDRow) -> Password)? {
return { row -> Password in
let hostname = row["hostname"] as? String ?? ""
let pw = Password(hostname: hostname, username: row["username"] as? String ?? "", password: row["password"] as? String ?? "")
pw.httpRealm = row["httpRealm"] as? String ?? ""
pw.formSubmitUrl = row["formSubmitUrl"] as? String ?? ""
pw.usernameField = row["usernameField"] as? String ?? ""
pw.passwordField = row["passwordField"] as? String ?? ""
pw.guid = row["guid"] as? String
pw.timeCreated = NSDate(timeIntervalSince1970: row["timeCreated"] as? Double ?? 0)
pw.timeLastUsed = NSDate(timeIntervalSince1970: row["timeLastUsed"] as? Double ?? 0)
pw.timePasswordChanged = NSDate(timeIntervalSince1970: row["timePasswordChanged"] as? Double ?? 0)
return pw
}
}
override func getQueryAndArgs(options: QueryOptions?) -> (String, [AnyObject?])? {
var args = [AnyObject?]()
if let filter: AnyObject = options?.filter {
args.append(filter)
return ("SELECT * FROM \(name) WHERE hostname = ?", args)
}
return ("SELECT * FROM \(name)", args)
}
}
public class SQLitePasswords: Passwords {
private let table = PasswordsTable<Password>()
private let db: BrowserDB
public init(db: BrowserDB) {
self.db = db
db.createOrUpdate(table)
}
public func get(options: QueryOptions, complete: (cursor: Cursor<Password>) -> Void) {
var err: NSError? = nil
let cursor = db.withReadableConnection(&err, callback: { (connection, err) -> Cursor<Password> in
return self.table.query(connection, options: options)
})
dispatch_async(dispatch_get_main_queue()) { _ in
complete(cursor: cursor)
}
}
public func add(password: Password, complete: (success: Bool) -> Void) {
var err: NSError? = nil
var success = false
let updated = db.withWritableConnection(&err) { (connection, inout err: NSError?) -> Int in
return self.table.update(connection, item: password, err: &err)
}
if updated == 0 {
let inserted = db.withWritableConnection(&err) { (connection, inout err: NSError?) -> Int in
return self.table.insert(connection, item: password, err: &err)
}
if inserted > -1 {
success = true
}
} else {
success = true
}
dispatch_async(dispatch_get_main_queue()) { _ in
complete(success: success)
return
}
}
public func remove(password: Password, complete: (success: Bool) -> Void) {
var err: NSError? = nil
let deleted = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in
return self.table.delete(conn, item: password, err: &err)
}
dispatch_async(dispatch_get_main_queue()) { _ in
complete(success: deleted > -1)
}
}
public func removeAll(complete: (success: Bool) -> Void) {
var err: NSError? = nil
let deleted = db.withWritableConnection(&err) { (conn, inout err: NSError?) -> Int in
return self.table.delete(conn, item: nil, err: &err)
}
dispatch_async(dispatch_get_main_queue()) { _ in
complete(success: deleted > -1)
}
}
}
| mpl-2.0 | 33feac768a3902ee1912dabeaa085b55 | 38.128834 | 224 | 0.593603 | 4.413841 | false | false | false | false |
Argas/10923748 | SOADemo/3. CoreLayer/Networking/Requests/LastFMTracksRequest.swift | 1 | 1172 | //
// LastFMTracksRequest.swift
// SOADemo
//
// Created by Alex Zverev on 15.04.17.
// Copyright © 2017 a.y.zverev. All rights reserved.
//
import Foundation
// https//ws.audioscrobbler.com/2.0/?method=chart.gettoptracks&api_key=d2fc8ba489c03df1a0f1eba71dea6fd9&format=json
class LastFMTopTracksRequest: IRequest {
private var baseUrl: String = "https://ws.audioscrobbler.com/"
private var apiVersion: String = "2.0/"
private var command: String = "chart.gettoptracks"
private let apiKey: String
private var getParameters: [String : String] {
return ["method" : command,
"api_key": apiKey,
"format" : "json"]
}
private var urlString: String {
let getParams = getParameters.flatMap({ "\($0.key)=\($0.value)"}).joined(separator: "&")
return baseUrl + apiVersion + "?" + getParams
}
// MARK: - IRequest
var urlRequest: URLRequest? {
if let url = URL(string: urlString) {
return URLRequest(url: url)
}
return nil
}
// MARK: - Initialization
init(apiKey: String) {
self.apiKey = apiKey
}
}
| mit | 1bc05bb6fc37ce4e7d98e11f75678073 | 26.880952 | 115 | 0.608881 | 3.625387 | false | false | false | false |
DrabWeb/Azusa | Source/Yui/Yui/Objects/Logger.swift | 1 | 3053 | //
// Logger.swift
// Yui
//
// Created by Ushio on 2/11/17.
//
import Foundation
public enum LoggingLevel: Int {
case none, regular, high, full
}
public struct Logger {
// MARK: - Properties
// MARK: Public Properties
public static var level : LoggingLevel = LoggingLevel.regular {
didSet {
Logger.log("Logger: Changed logging level to \(self.level)");
}
};
// MARK: Private Properties
private static var log : String = "";
// MARK: - Methods
// MARK: Public Methods
/// Logs the given object, with the given level
///
/// - Parameters:
/// - object: The object to log
/// - level: The level this print should be
public static func log(_ object : Any, level : LoggingLevel = .regular) {
let timestampDateFormatter : DateFormatter = DateFormatter();
timestampDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss.SSS";
let timestamp : String = timestampDateFormatter.string(from: Date());
let message = "\(timestamp) Yui: \(object)";
log.append("\(message)\n");
// Only print if we are in a debug build
#if DEBUG
if(level.rawValue <= self.level.rawValue) {
print(message);
}
#endif
}
/// Shows an error alert with the given message and logs it
///
/// - Parameter object: The object to log
public static func logError(_ object : Any) {
Logger.log(object);
let alert = NSAlert();
alert.messageText = "An error has occured";
alert.informativeText = "\(object)";
alert.icon = NSImage(named: "NSCaution");
alert.addButton(withTitle: "Report");
alert.addButton(withTitle: "OK");
if alert.runModal() == NSAlertFirstButtonReturn {
if (Logger.promptSave()) {
NSWorkspace.shared().open(URL(string: "https://github.com/DrabWeb/Azusa/issues/new")!);
}
}
}
/// Prompts the user for a place to save the log
public static func promptSave() -> Bool {
var p = NSSavePanel();
p.title = "Save Log";
p.nameFieldStringValue = "azusa.txt";
if p.runModal() == NSModalResponseOK {
Logger.saveTo(file: p.url!.absoluteString.removingPercentEncoding!.replacingOccurrences(of: "file://", with: ""));
return true;
}
return false;
}
/// Writes all the log output to the given file
///
/// - Parameter file: The file to write the output to
public static func saveTo(file : String) {
Logger.log("Logger: Saving all log output to \"\(file)\"");
do {
try log.write(toFile: file, atomically: true, encoding: String.Encoding.utf8);
}
catch let error as NSError {
Logger.logError("Logger: Error saving log file to \"\(file)\", \(error.localizedDescription)");
}
}
}
| gpl-3.0 | 3a662d169ed126494877b9589f5ac5ad | 28.640777 | 126 | 0.56207 | 4.618759 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/CryptoAssets/Sources/EthereumKit/Account/EthereumReceiveAddress.swift | 1 | 1170 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import MoneyKit
import PlatformKit
import RxSwift
struct EthereumReceiveAddress: CryptoReceiveAddress, QRCodeMetadataProvider {
var asset: CryptoCurrency {
eip681URI.cryptoCurrency
}
var address: String {
eip681URI.method.destination ?? eip681URI.address
}
var qrCodeMetadata: QRCodeMetadata {
QRCodeMetadata(content: address, title: address)
}
let label: String
let onTxCompleted: TxCompleted
let eip681URI: EIP681URI
init(
eip681URI: EIP681URI,
label: String,
onTxCompleted: @escaping TxCompleted
) {
self.eip681URI = eip681URI
self.label = label
self.onTxCompleted = onTxCompleted
}
init?(
address: String,
label: String,
network: EVMNetwork,
onTxCompleted: @escaping TxCompleted
) {
guard let eip681URI = EIP681URI(address: address, cryptoCurrency: network.cryptoCurrency) else {
return nil
}
self.eip681URI = eip681URI
self.label = label
self.onTxCompleted = onTxCompleted
}
}
| lgpl-3.0 | 455f55d4a9bd20f0258c85c5e5a2377c | 23.354167 | 104 | 0.650128 | 4.566406 | false | false | false | false |
swiftgurmeet/LocuEx | LocuEx/LocuExViewController.swift | 1 | 5395 | //
// LocuExViewController.swift
// LocuEx
//
//The MIT License (MIT)
//
//Copyright (c) 2015 swiftgurmeet
//
//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 MapKit
class LocuExViewController: UIViewController, MKMapViewDelegate {
var initialLocationUpdated = false
var location: CLLocation! {
didSet {
if !initialLocationUpdated {
moveMapToLocation(location.coordinate)
requestLocuData()
initialLocationUpdated = true
}
}
}
var service:LocuData!
func requestLocuData()
{
service = LocuData()
// Async request for Locu Data
service.request(self.location!.coordinate) {
(response) in
self.locuData = response
}
}
var locationManager = LocationManager()
var error: NSError?
var venues = [Venue]()
var locuData = [:]
{
didSet {
if mapView != nil {
updateMap(mapView)
}
}
}
func moveMapToLocation(loc:CLLocationCoordinate2D) {
mapView.centerCoordinate = loc
let region = MKCoordinateRegionMakeWithDistance(loc, 2000, 2000)
mapView.setRegion(region, animated: true)
}
func updateMap(mapView:MKMapView){
mapView.removeAnnotations(self.venues)
self.venues = Venue.venueListFromDict(self.locuData)
mapView.addAnnotations(self.venues)
mapView.showAnnotations(self.venues, animated: false)
}
@IBOutlet weak var mapView: MKMapView! {
didSet {
mapView.delegate = self
mapView.mapType = .Standard
mapView.rotateEnabled = false
}
}
@IBAction func moveToCurrentLocation(sender: UIBarButtonItem) {
initialLocationUpdated = false
requestCurrentLocation()
}
@IBAction func refresh(sender: UIBarButtonItem) {
if initialLocationUpdated {
location = CLLocation(latitude: mapView.centerCoordinate.latitude, longitude: mapView.centerCoordinate.longitude)
requestLocuData()
}
}
private struct Constants {
static let ShowVenueSegue = "Show Venue"
}
func mapView(mapView: MKMapView!, viewForAnnotation annotation: MKAnnotation!) -> MKAnnotationView! {
var view = mapView.dequeueReusableAnnotationViewWithIdentifier("AnnotationReuseIdentifier")
if view == nil {
view = MKPinAnnotationView(annotation: annotation, reuseIdentifier: "AnnotationReuseIdentifier")
view.canShowCallout = true
} else {
view.annotation = annotation
}
view.leftCalloutAccessoryView = nil
view.rightCalloutAccessoryView = nil
view.rightCalloutAccessoryView = UIButton.buttonWithType(UIButtonType.DetailDisclosure) as! UIButton
return view
}
func mapView(mapView: MKMapView!, annotationView view: MKAnnotationView!, calloutAccessoryControlTapped control: UIControl!) {
if (control as? UIButton)?.buttonType == UIButtonType.DetailDisclosure {
mapView.deselectAnnotation(view.annotation, animated: false)
performSegueWithIdentifier(Constants.ShowVenueSegue, sender: view)
}
}
// MARK: - Navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == Constants.ShowVenueSegue {
if let venue = (sender as? MKAnnotationView)?.annotation as? Venue {
if let ivc = segue.destinationViewController.contentViewController as? VenueTableViewController {
ivc.venue = venue
}
}
}
}
func requestCurrentLocation() {
// Async request for current location
locationManager.request {
(location, error) in
self.location = location
self.error = error
}
}
override func viewDidLoad() {
super.viewDidLoad()
requestCurrentLocation()
}
}
extension UIViewController {
var contentViewController: UIViewController {
if let nc = self as? UINavigationController {
return nc.visibleViewController
} else {
return self
}
}
}
| mit | f3aa13edcfa737a2f34bf9bdbd82a4e5 | 31.305389 | 130 | 0.649676 | 5.373506 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureSettings/Sources/FeatureSettingsUI/SettingsServices/Email/Switch/EmailSwitchViewPresenter.swift | 1 | 1742 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import AnalyticsKit
import DIKit
import PlatformKit
import PlatformUIKit
import RxCocoa
import RxRelay
import RxSwift
import ToolKit
final class EmailSwitchViewPresenter: SwitchViewPresenting {
// MARK: - Types
private typealias AccessibilityID = Accessibility.Identifier.Settings.SwitchView
private typealias AnalyticsEvent = AnalyticsEvents.Settings
// MARK: - Public
let viewModel = SwitchViewModel.primary(accessibilityId: AccessibilityID.twoFactorSwitchView)
// MARK: - Private
private let interactor: SwitchViewInteracting
private let disposeBag = DisposeBag()
init(
service: EmailNotificationSettingsServiceAPI,
analyticsRecording: AnalyticsEventRecorderAPI = resolve()
) {
interactor = EmailSwitchViewInteractor(service: service)
viewModel.isSwitchedOnRelay
.bindAndCatch(to: interactor.switchTriggerRelay)
.disposed(by: disposeBag)
viewModel.isSwitchedOnRelay
.bind {
analyticsRecording.record(events: [
AnalyticsEvent.settingsEmailNotifSwitch(value: $0),
AnalyticsEvents.New.Settings.notificationPreferencesUpdated(emailEnabled: $0, smsEnabled: nil)
])
}
.disposed(by: disposeBag)
interactor.state
.compactMap(\.value)
.map(\.isEnabled)
.bindAndCatch(to: viewModel.isEnabledRelay)
.disposed(by: disposeBag)
interactor.state
.compactMap(\.value)
.map(\.isOn)
.bindAndCatch(to: viewModel.isOnRelay)
.disposed(by: disposeBag)
}
}
| lgpl-3.0 | 46b2300519b691711888a318f945adae | 28.508475 | 114 | 0.663412 | 5.423676 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/FeatureKYC/Sources/FeatureKYCUI/Views/ValidationFields/ValidationDateField/ValidationDateField.swift | 1 | 1843 | // Copyright © Blockchain Luxembourg S.A. All rights reserved.
import UIKit
/// `ValidationDateField` is a `ValidationTextField`
/// that presents a `UIDatePicker` instead of a keyboard.
/// It does not support manual date entry.
/// Ideally this would be a `UIPickerView` with its own dataSource
/// but due to time constraints I am using a `UIDatePicker`.
class ValidationDateField: ValidationTextField {
lazy var pickerView: UIDatePicker = {
var picker = UIDatePicker()
picker.datePickerMode = .date
picker.preferredDatePickerStyle = .wheels
picker.sizeToFit()
return picker
}()
var selectedDate: Date {
get {
pickerView.date
}
set {
pickerView.date = newValue
datePickerUpdated(pickerView)
}
}
var maximumDate: Date? {
get {
pickerView.maximumDate
}
set {
pickerView.maximumDate = newValue
}
}
override func awakeFromNib() {
super.awakeFromNib()
textFieldInputView = pickerView
pickerView.addTarget(self, action: #selector(datePickerUpdated(_:)), for: .valueChanged)
}
@objc func datePickerUpdated(_ sender: UIDatePicker) {
text = DateFormatter.medium.string(from: sender.date)
}
override func textFieldDidEndEditing(_ textField: UITextField) {
super.textFieldDidEndEditing(textField)
pickerView.isHidden = true
}
override func textFieldDidBeginEditing(_ textField: UITextField) {
super.textFieldDidBeginEditing(textField)
pickerView.isHidden = false
}
override func textField(
_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String
) -> Bool {
false
}
}
| lgpl-3.0 | 829f9785a835727b179b526f28fe8afe | 26.909091 | 96 | 0.640065 | 5.385965 | false | false | false | false |
PekanMmd/Pokemon-XD-Code | GoDToolOSX/Views/GoDMetalView.swift | 1 | 15522 | //
// GoDMetalView.swift
// GoDToolCL
//
// Created by The Steez on 03/09/2018.
//
#if canImport(Cocoa) && canImport(Metal) && canImport(GLKit)
import Cocoa
import Metal
let metalManager = GoDMetalManager()
class GoDMetalManager : NSObject {
var device : MTLDevice!
var metalLayer : CAMetalLayer!
var pipelineState : MTLRenderPipelineState!
var depthState : MTLDepthStencilState!
var commandQueue : MTLCommandQueue!
var uniformBuffer: MTLBuffer!
var vertexBuffer: MTLBuffer!
var vertexCount = 0
var interactionIndexToHighlight = -1 {
didSet {
createUniformBuffer()
}
}
var sectionIndexToHighlight = -1 {
didSet {
createUniformBuffer()
}
}
var projectionMatrix = GoDMatrix4() {
didSet {
createUniformBuffer()
}
}
var cameraPosition = Vector3(v0: 0.0, v1: 0.0, v2: 0.0) {
didSet {
createUniformBuffer()
}
}
var cameraOrientation = Vector3(v0: 0.0, v1: 0.0, v2: 0.0) {
didSet {
createUniformBuffer()
}
}
var viewMatrix : GoDMatrix4 {
let m = GoDMatrix4()
m.translate(vector: cameraPosition)
m.rotate(vector_degrees: cameraOrientation)
return m
}
var lightPosition : Vector3 = Vector3(v0: 0.0, v1: -1.0, v2: -0.3)
var ambientLight : Float = 0.35
var specular : Float = 1.0
var shininess : Float = 32
var clearColour = GoDDesign.isDarkModeEnabled ? GoDDesign.colourDarkGrey().NSColour : GoDDesign.colourLightGrey().NSColour
override init() {
super.init()
device = MTLCreateSystemDefaultDevice()
metalLayer = CAMetalLayer()
metalLayer.device = device
metalLayer.pixelFormat = .bgra8Unorm
metalLayer.framebufferOnly = true
let defaultLibrary = device.makeDefaultLibrary()!
let vertexProgram = defaultLibrary.makeFunction(name: "shader_vertex")
let fragmentProgram = defaultLibrary.makeFunction(name: "shader_fragment")
let pipelineStateDescriptor = MTLRenderPipelineDescriptor()
pipelineStateDescriptor.vertexFunction = vertexProgram
pipelineStateDescriptor.fragmentFunction = fragmentProgram
pipelineStateDescriptor.colorAttachments[0].pixelFormat = .bgra8Unorm
pipelineStateDescriptor.depthAttachmentPixelFormat = .depth32Float
self.pipelineState = try! device.makeRenderPipelineState(descriptor: pipelineStateDescriptor)
let depth = MTLDepthStencilDescriptor()
depth.isDepthWriteEnabled = true
depth.depthCompareFunction = .less
self.depthState = self.device.makeDepthStencilState(descriptor: depth)
self.commandQueue = device.makeCommandQueue()
}
func createVertexBuffer(collisionData data: XGCollisionData) {
let vertexData = data.rawVertexBuffer as [Float]
guard vertexData.count > 0 else {
vertexCount = 0
return
}
let dataSize = vertexData.count * MemoryLayout.size(ofValue: vertexData[0])
vertexBuffer = device.makeBuffer(bytes: vertexData, length: dataSize, options: [])
vertexCount = data.vertexes.count
}
func createUniformBuffer() {
let uniformData = projectionMatrix.rawArray() + viewMatrix.rawArray() + [Float(interactionIndexToHighlight)] + [Float(sectionIndexToHighlight)]
// hard code because either compiler is being dumb or I'm being dumb
let dataSize = 148 //uniformData.count * MemoryLayout.size(ofValue: uniformData[0])
uniformBuffer = device.makeBuffer(bytes: uniformData, length: dataSize, options: [])
}
func render() {
if let drawable = metalLayer.nextDrawable() {
self.render(commandQueue: commandQueue, pipelineState: pipelineState, drawable: drawable, clearColor: nil)
}
}
func render(commandQueue: MTLCommandQueue, pipelineState: MTLRenderPipelineState, drawable: CAMetalDrawable, clearColor: MTLClearColor?){
guard vertexBuffer != nil else {
return
}
let renderPassDescriptor = MTLRenderPassDescriptor()
renderPassDescriptor.colorAttachments[0].texture = drawable.texture
renderPassDescriptor.colorAttachments[0].loadAction = .clear
renderPassDescriptor.colorAttachments[0].clearColor = MTLClearColor(red: Double(self.clearColour.redComponent), green: Double(self.clearColour.greenComponent), blue: Double(self.clearColour.blueComponent), alpha: 1.0)
renderPassDescriptor.colorAttachments[0].storeAction = .store
let depth = MTLTextureDescriptor.texture2DDescriptor(pixelFormat: .depth32Float, width: Int(metalLayer.frame.width), height: Int(metalLayer.frame.height), mipmapped: false)
depth.resourceOptions = .storageModePrivate
depth.usage = .renderTarget
renderPassDescriptor.depthAttachment.clearDepth = 1
renderPassDescriptor.depthAttachment.loadAction = .clear
renderPassDescriptor.depthAttachment.storeAction = .store
renderPassDescriptor.depthAttachment.texture = self.device.makeTexture(descriptor: depth)
let commandBuffer = commandQueue.makeCommandBuffer()!
let renderEncoder = commandBuffer.makeRenderCommandEncoder(descriptor: renderPassDescriptor)!
renderEncoder.setRenderPipelineState(self.pipelineState)
renderEncoder.setDepthStencilState(self.depthState)
// renderEncoder.setCullMode(MTLCullMode.front)
renderEncoder.setVertexBuffer(vertexBuffer , offset: 0, index: 0)
renderEncoder.setVertexBuffer(uniformBuffer, offset: 0, index: 1)
renderEncoder.drawPrimitives(type: .triangle, vertexStart: 0, vertexCount: vertexCount,
instanceCount: vertexCount/3)
renderEncoder.endEncoding()
commandBuffer.present(drawable)
commandBuffer.commit()
}
}
class GoDMetalView: NSView {
var file : XGFiles? {
didSet {
if let f = file {
let data = f.collisionData
metalManager.createVertexBuffer(collisionData: data)
self.interactionIndexes = data.interactableIndexes
self.sectionIndexes = data.sectionIndexes
setDefaultPositions()
metalManager.interactionIndexToHighlight = -1
metalManager.sectionIndexToHighlight = -1
}
}
}
required init?(coder decoder: NSCoder) {
super.init(coder: decoder)
}
var popup = GoDPopUpButton()
var interactionIndexes : [Int]! {
didSet {
var titles = ["-"]
for i in interactionIndexes {
titles.append("interactable region \(i)")
}
popup.setTitles(values: titles)
}
}
var popup2 = GoDPopUpButton()
var sectionIndexes : [Int]! {
didSet {
var titles = ["-"]
for i in sectionIndexes {
titles.append("section \(i)")
}
popup2.setTitles(values: titles)
}
}
var dictionaryOfKeys : [KeyCodeName : Bool] = KeyCodeName.dictionaryOfKeys
override var acceptsFirstResponder: Bool { return true }
var timer: Timer?
var previousTime : Float = 0
var cameraSpeed : Float = 1.0
var defaultProjectionMatrix : GoDMatrix4 {
return GoDMatrix4.makePerspective(angleRad: GoDMatrix4.degreesToRadians(85.0), aspectRatio: Float(self.frame.size.width / self.frame.size.height), nearZ: 0.001, farZ: 1000.0)
}
var zoomedProjectionMatrix : GoDMatrix4 {
return GoDMatrix4.makePerspective(angleRad: GoDMatrix4.degreesToRadians(45.0), aspectRatio: Float(self.frame.size.width / self.frame.size.height), nearZ: 0.001, farZ: 1000.0)
}
var defaultCameraPosition : Vector3 {
return Vector3(v0: 0.0, v1: -0.3, v2: -2.0)
}
var defaultCameraOrientation : Vector3 {
return Vector3(v0: 0.0, v1: 0.0, v2: 0.0)
}
var defaultLightPosition : Vector3 {
return Vector3(v0: 0.0, v1: -1.0, v2: -0.5)
}
func setDefaultPositions() {
metalManager.projectionMatrix = defaultProjectionMatrix
metalManager.cameraPosition = defaultCameraPosition
metalManager.cameraOrientation = defaultCameraOrientation
metalManager.lightPosition = defaultLightPosition
}
var isSetup: Bool = false
func startTimer() {
guard timer == nil else { return }
previousTime = Float(CACurrentMediaTime())
let fps : TimeInterval = 12.0
let frameTime = TimeInterval(1.0) / fps
timer = Timer.scheduledTimer(timeInterval: frameTime, target: self, selector: #selector(render), userInfo: nil, repeats: true)
}
func stopTimer() {
timer?.invalidate()
timer = nil
}
func setup() {
self.wantsLayer = true
self.layer!.frame = NSMakeRect(0.0, 0.0, self.frame.width, self.frame.height)
metalManager.metalLayer.frame = self.layer!.frame
self.layer!.addSublayer(metalManager.metalLayer)
setDefaultPositions()
startTimer()
popup.setTitles(values: ["Interactable Region Picker"])
popup.action = #selector(setInteraction)
popup.target = self
popup.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(popup)
self.addConstraintAlignTopEdges(view1: self, view2: popup)
self.addConstraintAlignLeftEdges(view1: self, view2: popup)
self.addConstraintSize(view: popup, height: 20, width: 120)
popup2.setTitles(values: ["Section Picker"])
popup2.action = #selector(setSection)
popup2.target = self
popup2.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(popup2)
self.addConstraintAlignTopEdges(view1: self, view2: popup2)
self.addConstraintAlignRightEdges(view1: self, view2: popup2)
self.addConstraintSize(view: popup2, height: 20, width: 120)
isSetup = true
}
override func viewDidEndLiveResize() {
super.viewDidEndLiveResize()
self.wantsLayer = true
self.layer!.frame = NSMakeRect(0.0, 0.0, self.frame.width, self.frame.height)
metalManager.metalLayer.frame = self.layer!.frame
setDefaultPositions()
}
@objc func setInteraction(sender: GoDPopUpButton) {
let index = sender.indexOfSelectedItem - 1
metalManager.interactionIndexToHighlight = index == -1 ? index : interactionIndexes[index]
metalManager.render()
}
@objc func setSection(sender: GoDPopUpButton) {
let index = sender.indexOfSelectedItem - 1
metalManager.sectionIndexToHighlight = index == -1 ? index : sectionIndexes[index]
metalManager.render()
}
@objc func render() {
if file != nil {
let time = Float(CACurrentMediaTime())
updateViewMatrix(atTime: time)
previousTime = time
}
}
var isRendering = false
func updateViewMatrix(atTime time: Float) {
guard !isRendering else {
return
}
isRendering = true
// The speed at which we desire to update
let timeDelta = time - previousTime
let amplitude = cameraSpeed * timeDelta
let rotationAmp = amplitude * 10_000
for key in dictionaryOfKeys {
switch key {
// Update camera position
case (KeyCodeName.W, true):
metalManager.cameraPosition.v2 += amplitude
case (KeyCodeName.S, true):
metalManager.cameraPosition.v2 -= amplitude
case (KeyCodeName.A, true):
metalManager.cameraPosition.v0 += amplitude
case (KeyCodeName.D, true):
metalManager.cameraPosition.v0 -= amplitude
case (KeyCodeName.up, true):
metalManager.cameraPosition.v1 -= amplitude
case (KeyCodeName.down, true):
metalManager.cameraPosition.v1 += amplitude
// reset camera position and orientation
case (KeyCodeName.space, true):
setDefaultPositions()
case (KeyCodeName.enter, true):
metalManager.projectionMatrix = zoomedProjectionMatrix
// set interactable region to highlight
case (KeyCodeName.zero, true):
metalManager.interactionIndexToHighlight = 0
self.popup.selectItem(at: 1)
case (KeyCodeName.one, true):
metalManager.interactionIndexToHighlight = 1
self.popup.selectItem(at: 2)
case (KeyCodeName.two, true):
metalManager.interactionIndexToHighlight = 2
self.popup.selectItem(at: 3)
case (KeyCodeName.three, true):
metalManager.interactionIndexToHighlight = 3
self.popup.selectItem(at: 4)
case (KeyCodeName.four, true):
metalManager.interactionIndexToHighlight = 4
self.popup.selectItem(at: 5)
case (KeyCodeName.five, true):
metalManager.interactionIndexToHighlight = 5
self.popup.selectItem(at: 6)
case (KeyCodeName.six, true):
metalManager.interactionIndexToHighlight = 6
self.popup.selectItem(at: 7)
case (KeyCodeName.seven, true):
metalManager.interactionIndexToHighlight = 7
self.popup.selectItem(at: 8)
case (KeyCodeName.eight, true):
metalManager.interactionIndexToHighlight = 8
self.popup.selectItem(at: 9)
case (KeyCodeName.nine, true):
metalManager.interactionIndexToHighlight = 9
self.popup.selectItem(at: 10)
// change camera speed
case (KeyCodeName.plus, true):
cameraSpeed *= 1.33
case (KeyCodeName.minus, true):
cameraSpeed /= 1.33
// rotate camera
case (KeyCodeName.left, true):
rotateCamera(pitch_degrees: 0.0, yaw_degrees: rotationAmp, roll_degrees: 0.0)
case (KeyCodeName.right, true):
rotateCamera(pitch_degrees: 0.0, yaw_degrees: -rotationAmp, roll_degrees: 0.0)
case (KeyCodeName.morethan, true):
rotateCamera(pitch_degrees: -rotationAmp, yaw_degrees: 0.0, roll_degrees: 0.0)
case (KeyCodeName.lessthan, true):
rotateCamera(pitch_degrees: rotationAmp, yaw_degrees: 0.0, roll_degrees: 0.0)
case (KeyCodeName.tab, true):
rotateCamera(pitch_degrees: 0.0, yaw_degrees: 0.0, roll_degrees: rotationAmp)
case (KeyCodeName.delete, true):
rotateCamera(pitch_degrees: 0.0, yaw_degrees: 0.0, roll_degrees: -rotationAmp)
default:
break;
}
}
if dictionaryOfKeys.values.contains(true) {
metalManager.render()
}
isRendering = false
}
func mouseEvent(deltaX x: Float, deltaY y: Float) {
guard !isRendering else {
return
}
isRendering = true
circumnavigate(x: -x/100 * cameraSpeed, y: y/100 * cameraSpeed)
metalManager.render()
isRendering = false
}
func circumnavigate(x: Float, y: Float) {
let oldPosition = metalManager.cameraPosition
// x^2 + y^2 + z^2 = r^2
let r2 = oldPosition.v0.raisedToPower(2) + oldPosition.v1.raisedToPower(2) + oldPosition.v2.raisedToPower(2)
let zIsNegative = metalManager.cameraPosition.v2 < 0
let newX = oldPosition.v0 + x
let newY = oldPosition.v1 + y
var newZ = (r2 - (newX.raisedToPower(2) + newY.raisedToPower(2))).squareRoot()
newZ = zIsNegative ? -newZ : newZ
let dx = abs(x)
let dy = abs(y)
let dz = abs(oldPosition.v2 - newZ)
let dxz = (dx.raisedToPower(2) + dz.raisedToPower(2)).squareRoot()
let dyz = (dy.raisedToPower(2) + dz.raisedToPower(2)).squareRoot()
let rxz = (oldPosition.v0.raisedToPower(2) + oldPosition.v2.raisedToPower(2)).squareRoot()
let ryz = (oldPosition.v1.raisedToPower(2) + oldPosition.v2.raisedToPower(2)).squareRoot()
// sohcahtoa
// needs fixing
let sinthetaxz = (dxz / 2) / rxz
let sinthetayz = (dyz / 2) / ryz
var anglexz = asin(sinthetaxz) * 2 * (x < 0 ? -1 : 1)
var angleyz = asin(sinthetayz) * 2 * (x < 0 ? -1 : 1)
if y == 0 { angleyz = 0}
if x == 0 { anglexz = 0}
metalManager.cameraPosition = Vector3(v0: newX, v1: newY, v2: newZ)
rotateCamera(pitch_degrees: angleyz * degreesPerRadian, yaw_degrees: anglexz * degreesPerRadian, roll_degrees: 0.0)
}
func rotateCamera(pitch_degrees: Float, yaw_degrees: Float, roll_degrees: Float) {
// in degrees
var roll = metalManager.cameraOrientation.v0 - GoDMatrix4.degreesToRadians(roll_degrees)
var yaw = metalManager.cameraOrientation.v1 - GoDMatrix4.degreesToRadians(yaw_degrees)
var pitch = metalManager.cameraOrientation.v2 - GoDMatrix4.degreesToRadians(pitch_degrees)
roll = roll > Float(M_2_PI) ? roll - Float(M_2_PI) : (roll < 0 ? roll + Float(M_2_PI) : roll)
yaw = yaw > Float(M_2_PI) ? yaw - Float(M_2_PI) : (yaw < 0 ? yaw + Float(M_2_PI) : yaw)
pitch = pitch > Float(M_2_PI) ? pitch - Float(M_2_PI) : (pitch < 0 ? pitch + Float(M_2_PI) : pitch)
metalManager.cameraOrientation.v0 = roll
metalManager.cameraOrientation.v1 = yaw
metalManager.cameraOrientation.v2 = pitch
}
}
#endif
| gpl-2.0 | 3391120b60ea1e34b6284dab991179d2 | 31.27027 | 219 | 0.726839 | 3.68431 | false | false | false | false |
googlearchive/science-journal-ios | ScienceJournal/Users/AccountUserManager.swift | 1 | 5084 | /*
* Copyright 2019 Google LLC. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
/// Manages user data for a single account based user.
class AccountUserManager: UserManager {
// MARK: - Properties
let metadataManager: MetadataManager
let preferenceManager: PreferenceManager
let sensorDataManager: SensorDataManager
let assetManager: UserAssetManager
var driveSyncManager: DriveSyncManager?
let experimentDataDeleter: ExperimentDataDeleter
let documentManager: DocumentManager
var exportType: UserExportType {
// If an account has sharing restrictions, it can only save to files. Otherwise, full share.
return account.isShareRestricted ? .saveToFiles : .share
}
var isDriveSyncEnabled: Bool {
return driveSyncManager != nil
}
/// The root URL under which all user data is stored.
let rootURL: URL
/// The user account.
let account: AuthAccount
private let fileSystemLayout: FileSystemLayout
// MARK: - Public
/// Designated initializer.
///
/// - Parameters:
/// - fileSystemLayout: The file system layout.
/// - account: A user account.
/// - driveConstructor: The drive constructor.
/// - networkAvailability: Network availability.
/// - sensorController: The sensor controller.
/// - analyticsReporter: An analytics reporter.
init(fileSystemLayout: FileSystemLayout,
account: AuthAccount,
driveConstructor: DriveConstructor,
networkAvailability: NetworkAvailability,
sensorController: SensorController,
analyticsReporter: AnalyticsReporter) {
self.fileSystemLayout = fileSystemLayout
self.account = account
// Create a root URL for this account.
rootURL = fileSystemLayout.accountURL(for: account.ID)
// Create the directory if needed.
do {
try FileManager.default.createDirectory(at: rootURL,
withIntermediateDirectories: true,
attributes: nil)
} catch {
print("[AccountUserManager] Error creating rootURL: \(error.localizedDescription)")
}
// Configure preference manager with account ID.
preferenceManager = PreferenceManager(accountID: account.ID)
// Configure Core Data store.
sensorDataManager = SensorDataManager(rootURL: rootURL)
// Configure metadata manager.
metadataManager = MetadataManager(rootURL: rootURL,
deletedRootURL: rootURL,
preferenceManager: preferenceManager,
sensorController: sensorController,
sensorDataManager: sensorDataManager)
// Configure experiment data deleter.
experimentDataDeleter = ExperimentDataDeleter(accountID: account.ID,
metadataManager: metadataManager,
sensorDataManager: sensorDataManager)
documentManager = DocumentManager(experimentDataDeleter: experimentDataDeleter,
metadataManager: metadataManager,
sensorDataManager: sensorDataManager)
// Configure drive sync.
if let authorization = account.authorization {
driveSyncManager =
driveConstructor.driveSyncManager(withAuthorization: authorization,
experimentDataDeleter: experimentDataDeleter,
metadataManager: metadataManager,
networkAvailability: networkAvailability,
preferenceManager: preferenceManager,
sensorDataManager: sensorDataManager,
analyticsReporter: analyticsReporter)
}
// Configure user asset manager.
assetManager = UserAssetManager(driveSyncManager: driveSyncManager,
metadataManager: metadataManager,
sensorDataManager: sensorDataManager)
}
func tearDown() {
metadataManager.tearDown()
assetManager.tearDown()
driveSyncManager?.tearDown()
}
/// Deletes the user's data and preferences.
func deleteAllUserData() throws {
// TODO: Fix SQLite warning b/132878667
try AccountDeleter(fileSystemLayout: fileSystemLayout, accountID: account.ID).deleteData()
}
}
| apache-2.0 | bb42f97fb80004cbe3034d1c9523a18b | 37.225564 | 96 | 0.641424 | 6.095923 | false | false | false | false |
robrix/Madness | Madness/SourcePos.swift | 1 | 2013 | // Copyright (c) 2014 Josh Vera. All rights reserved.
public typealias Line = Int
public typealias Column = Int
var DefaultTabWidth = 8
public struct SourcePos<Index: Comparable> {
public let line: Line
public let column: Column
public let index: Index
public init(index: Index) {
line = 1
column = 1
self.index = index
}
public init(line: Line, column: Column, index: Index) {
self.line = line
self.column = column
self.index = index
}
}
extension SourcePos: Equatable {
/// Returns whether two SourcePos are equal.
public static func ==(first: SourcePos, other: SourcePos) -> Bool {
return first.line == other.line && first.column == other.column && first.index == other.index
}
}
extension SourcePos {
/// Returns a new SourcePos advanced by the given index.
public func advanced(to index: Index) -> SourcePos {
return SourcePos(line: line, column: column, index: index)
}
/// Returns a new SourcePos advanced by `count`.
public func advanced<C: Collection>(by distance: C.IndexDistance, from input: C) -> SourcePos where C.Index == Index {
return advanced(to: input.index(index, offsetBy: distance))
}
}
extension SourcePos where Index == String.Index {
/// Returns a new SourcePos with its line, column, and index advanced by the given character.
public func advanced(by char: Character, from input: String.CharacterView) -> SourcePos {
let nextIndex = input.index(after: index)
if char == "\n" {
return SourcePos(line: line + 1, column: 0, index: nextIndex)
} else if char == "\t" {
return SourcePos(line: line, column: column + DefaultTabWidth - ((column - 1) % DefaultTabWidth), index: nextIndex)
} else {
return SourcePos(line: line, column: column + 1, index: nextIndex)
}
}
/// Returns a new SourcePos with its line, column, and index advanced by the given string.
func advanced(by string: String, from input: String.CharacterView) -> SourcePos {
return string.characters.reduce(self) { $0.advanced(by: $1, from: input) }
}
}
| mit | 788f626a2d1f85fe30ec599e7f9295ec | 30.952381 | 119 | 0.703428 | 3.581851 | false | false | false | false |
sudeepag/Phobia | Phobia/Data.swift | 1 | 427 | //
// Data.swift
// Phobia
//
// Created by Sudeep Agarwal on 11/21/15.
// Copyright © 2015 Sudeep Agarwal. All rights reserved.
//
import Foundation
class Data {
var word: Word!
var time: Double!
var isCorrect: Bool!
init(word: Word, time: Double, colorSelected: ColorType) {
self.word = word
self.time = time
self.isCorrect = (word.color == colorSelected)
}
} | mit | df158a58e941011683f58fb2b01c1eb7 | 17.565217 | 62 | 0.600939 | 3.579832 | false | false | false | false |
sufan/dubstepocto | Shared/Models/TVObserverable.swift | 1 | 1009 | //
// TestStoreModel.swift
// Potpourri
//
// Created by sufan on 8/12/20.
//
import Alamofire
import SwiftUI
class TVObserverable: ObservableObject {
enum Source {
case server
case preview
}
@Published var schedules = [TVScheduleModel]()
private let apiPath = "/schedule"
init(source: Source = .server) {
switch source {
case .server:
fetchCharacters()
case .preview:
fetchPreview()
}
}
private func fetchPreview() {
self.schedules = testSchedules
}
private func fetchCharacters() {
AF.request(TVEndPoints.baseURL + apiPath)
.validate()
.responseDecodable(of: [TVScheduleModel].self) { response in
guard let schedules = response.value else {
debugPrint(response)
return
}
self.schedules = schedules
}
}
}
| mit | 15bf3fc2a2aa810f9e2b93a280a93156 | 20.934783 | 72 | 0.526264 | 4.99505 | false | false | false | false |
shyn/cs193p | Psychologist/Psychologist/DiagnosedHappinessViewController.swift | 1 | 1811 | //
// File.swift
// Psychologist
//
// Created by deepwind on 5/1/17.
// Copyright © 2017 deepwind. All rights reserved.
//
import UIKit
// to get HappinessViewController untouched we dedrived it.
// keep faceView generatic
class DiagnosedHappinessViewController: HappinessViewController, UIPopoverPresentationControllerDelegate
{
override var happiness: Int {
didSet {
diagnosticHistory += [happiness]
}
}
private let defaults = UserDefaults.standard
var diagnosticHistory: [Int] {
get {
return defaults.object(forKey: History.DefaultsKey) as? [Int] ?? [] // must do cast and set [] avoiding return nil
}
set {
defaults.set(newValue, forKey: History.DefaultsKey)
}
}
private struct History {
static let SegueIdentifier = "Show Diagnostic History"
static let DefaultsKey = "DiagnosedHappinessViewController.History" // Infact you can set anything here
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let identifier = segue.identifier {
switch identifier {
case History.SegueIdentifier:
if let hvc = segue.destination as? TextViewController {
if let ppc = hvc.popoverPresentationController {
ppc.delegate = self
}
hvc.text = "\(diagnosticHistory)"
}
default:
break
}
}
}
// prevent popover to adape the screen (medal)
func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
return .none
}
}
| mit | f3dba7e7d631783aa23ec3b6201a7b0d | 29.677966 | 128 | 0.582873 | 5.552147 | false | false | false | false |
PureSwift/Bluetooth | Sources/BluetoothHCI/HCILEDataLengthChange.swift | 1 | 3228 | //
// HCILEDataLengthChange.swift
// Bluetooth
//
// Created by Alsey Coleman Miller on 6/14/18.
// Copyright © 2018 PureSwift. All rights reserved.
//
import Foundation
/// LE Data Length Change Event
///
/// event notifies the Host of a change to either the maximum Payload length or the maximum transmission time of packets
/// in either direction. The values reported are the maximum that will actually be used on the connection following the change,
/// except that on the LE Coded PHY a packet taking up to 2704 μs to transmit may be sent even though the corresponding
/// parameter has a lower value.
@frozen
public struct HCILEDataLengthChange: HCIEventParameter {
public static let event = LowEnergyEvent.dataLengthChange // 0x07
public static let length: Int = 10
public let handle: UInt16 // Connection_Handle
/// The maximum number of payload octets in a Link Layer packet that the local Controller will send on this connection
/// (connEffectiveMaxTxOctets defined in [Vol 6] Part B, Section 4.5.10).
/// onnInitialMaxTxOctets - the value of connMaxTxOctets that the Controller will use for a new connection.
/// Range 0x001B-0x00FB (all other values reserved for future use)
public let maxTxOctets: UInt16
/// The maximum time that the local Controller will take to send a Link Layer packet on this connection
/// (connEffectiveMaxTxTime defined in [Vol 6] Part B, Section 4.5.10).
/// connEffectiveMaxTxTime - equal to connEffectiveMaxTxTimeUncoded while the connection is on an LE Uncoded PHY
/// and equal to connEffectiveMaxTxTimeCoded while the connection is on the LE Coded PHY.
public let maxTxTime: UInt16
/// The maximum number of payload octets in a Link Layer packet that the local Controller expects to receive on
/// this connection (connEffectiveMaxRxOctets defined in [Vol 6] Part B, Section 4.5.10).
/// connEffectiveMaxRxOctets - the lesser of connMaxRxOctets and connRemoteMaxTxOctets.
public let maxRxOctets: UInt16
/// The maximum time that the local Controller expects to take to receive a Link Layer packet on this
/// connection (connEffectiveMaxRxTime defined in [Vol 6] Part B, Section 4.5.10).
/// connEffectiveMaxRxTime - equal to connEffectiveMaxRxTimeUncoded while the connection is on an LE Uncoded PHY
/// and equal to connEffectiveMaxRxTimeCoded while the connection is on the LE Coded PHY.
public let maxRxTime: UInt16
public init?(data: Data) {
guard data.count == type(of: self).length
else { return nil }
let handle = UInt16(littleEndian: UInt16(bytes: (data[0], data[1])))
let maxTxOctets = UInt16(littleEndian: UInt16(bytes: (data[2], data[3])))
let maxTxTime = UInt16(littleEndian: UInt16(bytes: (data[4], data[5])))
let maxRxOctets = UInt16(littleEndian: UInt16(bytes: (data[6], data[7])))
let maxRxTime = UInt16(littleEndian: UInt16(bytes: (data[8], data[9])))
self.handle = handle
self.maxTxOctets = maxTxOctets
self.maxTxTime = maxTxTime
self.maxRxOctets = maxRxOctets
self.maxRxTime = maxRxTime
}
}
| mit | 59d8591f78466387cbc179d673b2f68c | 47.878788 | 127 | 0.708617 | 4.455801 | false | false | false | false |
mani95lisa/VFLToolbox | VFLToolbox/VFL/Array+Subscript.swift | 3 | 1588 | import UIKit
public extension Array {
public subscript(target: UILayoutSupport) -> [VFLConstraint] {
return get(target)
}
public subscript(target: UIView) -> [VFLConstraint] {
return get(target)
}
private func get(target: AnyObject) -> [VFLConstraint] {
if isEmpty || count > 1 {
assert(false, "Should not reach here")
return []
}
switch self[0] {
case let view as UIView:
let sibling = Sibling(item: view)
let constraint = SiblingConstraint(sibling: sibling, item: target)
return [constraint]
case let constraint as VFLConstraint:
//NOTE: This is the reason we don't declare VFLConstraint as a protocol
var result: [VFLConstraint] = self.map({ return $0 as VFLConstraint })
let sibling = Sibling(item: constraint.target)
let siblingConstraint = SiblingConstraint(sibling: sibling, item: target)
result.append(siblingConstraint)
return result
//This one is questionable, unfortunately we can't cast to UILayoutSupport as it's not @objc protocol
case let guide as NSObject:
var result: [VFLConstraint] = self.map({ return $0 as VFLConstraint })
let sibling = Sibling(item: guide)
let constraint = SiblingConstraint(sibling: sibling, item: target)
result.append(constraint)
return result
default:
assert(false, "Should not reach here")
return []
}
}
}
| mit | 0c3009129f02e0b785b9498fc164f951 | 32.083333 | 109 | 0.601385 | 4.841463 | false | false | false | false |
tinypass/piano-sdk-for-ios | Sources/Composer/Composer/Models/FailureEventParams.swift | 1 | 578 | import Foundation
@objcMembers
public class FailureEventParams: NSObject {
public let moduleId: String
public let moduleType: String
public let moduleName: String
public let errorMessage: String
init?(dict: [String: Any]?) {
if dict == nil {
return nil
}
moduleId = dict!["moduleId"] as? String ?? ""
moduleType = dict!["moduleType"] as? String ?? ""
moduleName = dict!["moduleName"] as? String ?? ""
errorMessage = dict!["errorMessage"] as? String ?? ""
}
}
| apache-2.0 | 7649277f99073a1c3a7108c999e4d8d3 | 23.083333 | 61 | 0.565744 | 4.982759 | false | false | false | false |
neetsdkasu/Paiza-POH-MyAnswers | POH7/SantaFuku/Answer.swift | 1 | 411 | // Try POH
// author: Leonardone @ NEETSDKASU
var readInts={readLine()!.utf8.split{$0==32}.map{Int(String($0))!}}
var xyzn=readInts(),xs=[0,xyzn[0]],ys=[0,xyzn[1]]
for _ in 1...xyzn[3]{
let da=readInts()
if da[0]==0{xs+=[da[1]]}else{ys+=[da[1]]}
}
func mn(a:[Int])->Int{
var m = a[a.count-1]
for i in 1..<a.count{m=min(m,a[i]-a[i-1])}
return m
}
print(xyzn[2]*mn(xs.sort())*mn(ys.sort()))
| mit | 6a1a26258e43670db2fede518536e65d | 24.6875 | 67 | 0.564477 | 2.151832 | false | false | false | false |
Noders/NodersCL-App | StrongLoopForiOS/EventosViewController.swift | 1 | 4582 | //
// EventosViewController.swift
// Noders
//
// Created by Jose Vildosola on 22-05-15.
// Copyright (c) 2015 DevIn. All rights reserved.
//
import UIKit
import MBProgressHUD
import SpinKit
import SIAlertView
class EventosViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
@IBOutlet weak var eventosTableView: UITableView!
@IBOutlet weak var menuButton: UIBarButtonItem!
var dataLoaded = false
var hud: MBProgressHUD?
var eventosArray:NSArray = []
override func viewDidLoad() {
super.viewDidLoad()
self.eventosTableView.separatorStyle = UITableViewCellSeparatorStyle.None
if self.revealViewController() != nil {
menuButton.target = self.revealViewController()
menuButton.action = "revealToggle:"
self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer())
}
self.eventosTableView.delegate = self
self.eventosTableView.dataSource = self
self.eventosTableView.registerClass(EventoTableViewCell.self, forCellReuseIdentifier: "cell")
self.eventosTableView.registerNib(UINib(nibName: "EventoCellView", bundle: nil), forCellReuseIdentifier: "cell")
let adapter = (UIApplication.sharedApplication().delegate as! AppDelegate).adapter
let eventosRepo = adapter?.repositoryWithClass(EventoRepository.self) as! EventoRepository
let spinner:RTSpinKitView = RTSpinKitView(style: RTSpinKitViewStyle.Style9CubeGrid)
hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud!.labelText = "Cargando"
hud!.mode = MBProgressHUDMode.CustomView
hud!.customView = spinner
eventosRepo.allWithSuccess({ (results) -> Void in
self.eventosArray = results
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.eventosTableView.separatorStyle = UITableViewCellSeparatorStyle.SingleLine
MBProgressHUD.hideHUDForView(self.view, animated: true)
self.dataLoaded = true
self.numberOfSectionsInTableView(self.eventosTableView)
self.eventosTableView.reloadData();
self.eventosTableView.tableFooterView = UIView(frame: CGRectZero)
})
}, failure: { (error) -> Void in
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.hud!.hide(true)
let alert:SCLAlertView = SCLAlertView()
alert.showError("Eventos", subTitle: "Hubo un error al recuperar la lista de eventos", closeButtonTitle: "Aceptar", duration: 0.0)
})
})
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("cell") as! EventoTableViewCell
var evento = eventosArray.objectAtIndex(indexPath.row) as! EventoModel
cell.eventoTitle.text = evento.name
let formatter:NSDateFormatter = NSDateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let eventDate = formatter.dateFromString(evento.fechainicio)
formatter.dateFormat = "EEEE d 'de' MMMM 'de' yyyy"
cell.eventoDate.text = formatter.stringFromDate(eventDate!)
return cell
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
tableView.layoutMargins = UIEdgeInsetsZero;
cell.layoutMargins = UIEdgeInsetsZero;
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
if dataLoaded {
return 1;
}
return 0;
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.eventosArray.count
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 95;
}
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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-2.0 | d7dfc13f605e256a9e139db4789a00c5 | 40.279279 | 146 | 0.676779 | 5.248568 | false | false | false | false |
wheerd/swift-parser | Sources/helpers.swift | 1 | 7116 | private let zero: UnicodeScalar = "0"
private let lowerA: UnicodeScalar = "a"
private let upperA: UnicodeScalar = "A"
extension UnicodeScalar {
var isIdentifierHead: Bool {
get {
if self.isASCII {
switch self {
case "a"..."z", "A"..."Z", "_":
return true
default:
return false
}
}
switch self {
case "\u{00A8}", "\u{00AA}", "\u{00AD}", "\u{00AF}", "\u{00B2}"..."\u{00B5}", "\u{00B7}"..."\u{00BA}",
"\u{00BC}"..."\u{00BE}", "\u{00C0}"..."\u{00D6}", "\u{00D8}"..."\u{00F6}", "\u{00F8}"..."\u{00FF}",
"\u{0100}"..."\u{02FF}", "\u{0370}"..."\u{167F}", "\u{1681}"..."\u{180D}", "\u{180F}"..."\u{1DBF}",
"\u{1E00}"..."\u{1FFF}",
"\u{200B}"..."\u{200D}", "\u{202A}"..."\u{202E}", "\u{203F}"..."\u{2040}", "\u{2054}", "\u{2060}"..."\u{206F}",
"\u{2070}"..."\u{20CF}", "\u{2100}"..."\u{218F}", "\u{2460}"..."\u{24FF}", "\u{2776}"..."\u{2793}",
"\u{2C00}"..."\u{2DFF}", "\u{2E80}"..."\u{2FFF}",
"\u{3004}"..."\u{3007}", "\u{3021}"..."\u{302F}", "\u{3031}"..."\u{303F}", "\u{3040}"..."\u{D7FF}",
"\u{F900}"..."\u{FD3D}", "\u{FD40}"..."\u{FDCF}", "\u{FDF0}"..."\u{FE1F}", "\u{FE30}"..."\u{FE44}",
"\u{FE47}"..."\u{FFFD}",
"\u{10000}"..."\u{1FFFD}", "\u{20000}"..."\u{2FFFD}", "\u{30000}"..."\u{3FFFD}", "\u{40000}"..."\u{4FFFD}",
"\u{50000}"..."\u{5FFFD}", "\u{60000}"..."\u{6FFFD}", "\u{70000}"..."\u{7FFFD}", "\u{80000}"..."\u{8FFFD}",
"\u{90000}"..."\u{9FFFD}", "\u{A0000}"..."\u{AFFFD}", "\u{B0000}"..."\u{BFFFD}", "\u{C0000}"..."\u{CFFFD}",
"\u{D0000}"..."\u{DFFFD}", "\u{E0000}"..."\u{EFFFD}":
return true
default:
return false
}
}
}
var isIdentifierBody: Bool {
get {
if self.isIdentifierHead {
return true
}
switch self {
case "0"..."9",
"\u{0300}", "\u{036F}", "\u{1DC0}"..."\u{1DFF}", "\u{20D0}"..."\u{20FF}", "\u{FE20}"..."\u{FE2F}":
return true
default:
return false
}
}
}
var isOperatorHead: Bool {
get {
if self.isASCII {
switch self {
case "/", "=", "-", "+", "!", "*", "%", "<",
">", "&", "|", "^", "~", "?", ".":
return true
default:
return false
}
}
switch self {
case "\u{00A1}"..."\u{00A7}", "\u{00A9}", "\u{00AB}", "\u{00AC}",
"\u{00AE}", "\u{00B0}"..."\u{00B1}", "\u{00B6}", "\u{00BB}",
"\u{00BF}", "\u{00D7}", "\u{00F7}", "\u{2016}"..."\u{2017}",
"\u{2020}"..."\u{2027}", "\u{2030}"..."\u{203E}",
"\u{2041}"..."\u{2053}", "\u{2055}"..."\u{205E}",
"\u{2190}"..."\u{23FF}", "\u{2500}"..."\u{2775}",
"\u{2794}"..."\u{2BFF}", "\u{2E00}"..."\u{2E7F}",
"\u{3001}"..."\u{3003}", "\u{3008}"..."\u{3030}":
return true
default:
return false
}
}
}
var isOperatorBody: Bool {
get {
if self.isOperatorHead {
return true
}
switch self {
case "\u{0300}"..."\u{036F}",
"\u{1DC0}"..."\u{1DFF}",
"\u{20D0}"..."\u{20FF}",
"\u{FE00}"..."\u{FE0F}",
"\u{FE20}"..."\u{FE2F}",
"\u{E0100}"..."\u{E01EF}":
return true
default:
return false
}
}
}
var isDigit: Bool {
get {
switch self {
case "0"..."9":
return true
default:
return false
}
}
}
var isHexDigit: Bool {
get {
switch self {
case "0"..."9", "a"..."f", "A"..."F":
return true
default:
return false
}
}
}
var decimalValue: UInt32? {
get {
return self.isDigit ? ((self.value - zero.value) as UInt32?) : nil
}
}
var hexValue: UInt32? {
get {
switch self {
case "0"..."9":
return self.value - zero.value
case "a"..."f":
return 10 + self.value - lowerA.value
case "A"..."F":
return 10 + self.value - upperA.value
default:
return nil
}
}
}
}
func * (str: String, times: Int) -> String {
return (0..<times).reduce("") { $0.0 + str }
}
extension String {
var literalString: String {
get {
return "\"" + self.characters.map {
switch $0 {
case "\n":
return "\\n"
case "\r":
return "\\r"
case "\t":
return "\\t"
case "\"":
return "\\\""
case "\\":
return "\\\\"
default:
return String($0)
}
}.joined(separator: "") + "\""
}
}
}
extension String.UnicodeScalarView {
func getCount(range: Range<String.UnicodeScalarView.Index>) -> Int {
var count: Int = 0
var index = range.lowerBound
while index != range.upperBound {
index = self.index(after: index)
count += 1
}
return count
}
}
func clamp<T: Comparable>(_ value: T, lower: T, upper: T) -> T {
return min(max(value, lower), upper)
}
extension String {
var length: Int {
return self.characters.count
}
subscript(i: Int) -> Character {
return self.characters[index(startIndex, offsetBy: i)]
}
subscript(range: Range<Int>) -> String {
let startOffset = clamp(range.lowerBound, lower: 0, upper: length)
let endOffset = clamp(range.upperBound, lower: 0, upper: length)
let start = index(startIndex, offsetBy: startOffset)
let end = index(start, offsetBy: endOffset - startOffset)
return self[start ..< end]
}
}
| mit | 2af3444c3b96db6b1eedbf7ea0aedfeb | 31.252336 | 132 | 0.348791 | 4.176056 | false | false | false | false |
sonsongithub/reddift | test/LinksTest.swift | 1 | 38693 | //
// LinksTest.swift
// reddift
//
// Created by sonson on 2015/05/09.
// Copyright (c) 2015年 sonson. All rights reserved.
//
import Foundation
import XCTest
class LinksTest: SessionTestSpec {
/// Default contents to be used by test
var testLinkId = "3r2pih"
var testCommentId = "cw05r44"
let nsfwTestLinkId = "35ljt6"
override func setUp() {
super.setUp()
getTestLinkID()
getTestCommentID()
}
func getTestCommentID() {
let documentOpenExpectation = self.expectation(description: "getTestCommentID")
let link = Link(id: self.testLinkId)
do {
try self.session?.getArticles(link, sort: .new, comments: nil, completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error)
case .success(let (_, listing1)):
for obj in listing1.children {
if let comment = obj as? Comment {
self.testCommentId = comment.id
}
break
}
}
documentOpenExpectation.fulfill()
})
} catch { print(error) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
func getTestLinkID() {
let subreddit = Subreddit(subreddit: "sandboxtest")
let documentOpenExpectation = self.expectation(description: "getTestLinkID")
do {
try self.session?.getList(Paginator(), subreddit: subreddit, sort: .new, timeFilterWithin: .week, completion: { (result) in
switch result {
case .failure(let error):
print(error)
case .success(let listing):
for obj in listing.children {
if let link = obj as? Link {
if link.numComments > 0 {
self.testLinkId = link.id
break
}
}
}
}
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
func test_deleteCommentOrLink(_ thing: Thing) {
let documentOpenExpectation = self.expectation(description: "test_deleteCommentOrLink")
var isSucceeded = false
do {
try self.session?.deleteCommentOrLink(thing.name, completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to delete the last posted comment.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
func testPostingCommentToExistingLink() {
print("Test posting a comment to existing link")
do {
var comment: Comment? = nil
print ("Check whether the comment is posted as a child of the specified link")
do {
do {
let name = "t3_" + self.testLinkId
let documentOpenExpectation = self.expectation(description: "Check whether the comment is posted as a child of the specified link")
try self.session?.postComment("test comment2", parentName: name, completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let postedComment):
comment = postedComment
}
XCTAssert(comment != nil, "Check whether the comment is posted as a child of the specified link")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print ("Test to delete the last posted comment.")
do {
if let comment = comment {
self.test_deleteCommentOrLink(comment)
}
}
}
}
func testParsingErrorObjectWhenPostingCommentToTooOldComment() {
print("Test whether Parse class can parse returned JSON object when posting a comment to the too old comment")
do {
do {
do {
let name = "t1_cw05r44" // old comment object ID
let documentOpenExpectation = self.expectation(description: "Test whether Parse class can parse returned JSON object when posting a comment to the too old comment")
try self.session?.postComment("test comment3", parentName: name, completion: { (result) -> Void in
switch result {
case .failure(let error):
XCTAssert(error.code == ReddiftError.commentJsonObjectIsMalformed.rawValue)
case .success(let postedComment):
print(postedComment)
XCTFail("")
}
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
}
}
func testPostingCommentToExistingComment() {
print("Test posting a comment to existing comment")
do {
var comment: Comment? = nil
print("the comment is posted as a child of the specified comment")
do {
do {
let name = "t1_" + self.testCommentId
let documentOpenExpectation = self.expectation(description: "the comment is posted as a child of the specified comment")
try self.session?.postComment("test comment3", parentName: name, completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let postedComment):
comment = postedComment
}
XCTAssert(comment != nil, "the comment is posted as a child of the specified comment")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print("Test to delete the last posted comment.")
do {
if let comment = comment {
self.test_deleteCommentOrLink(comment)
}
}
}
}
func testSetNSFW() {
print("Test to make specified Link NSFW.")
do {
var isSucceeded = false
let link = Link(id: nsfwTestLinkId)
let documentOpenExpectation = self.expectation(description: "Test to make specified Link NSFW.")
do {
try self.session?.setNSFW(true, thing: link, completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to make specified Link NSFW.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is NSFW.")
do {
let link = Link(id: nsfwTestLinkId)
let documentOpenExpectation = self.expectation(description: "Check whether the specified Link is NSFW.")
do {
try self.session?.getInfo([link.name], completion: { (result) -> Void in
var isSucceeded = false
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
isSucceeded = listing.children
.compactMap({(thing: Thing) -> Link? in
if let obj = thing as? Link {if obj.name == link.name { return obj }}
return nil
})
.reduce(true) {(a: Bool, link: Link) -> Bool in
return (a && link.over18)
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is NSFW.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print("Test to make specified Link NOT NSFW.")
do {
var isSucceeded = false
let link = Link(id: nsfwTestLinkId)
let documentOpenExpectation = self.expectation(description: "Test to make specified Link NOT NSFW.")
do {
try self.session?.setNSFW(false, thing: link, completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to make specified Link NOT NSFW.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is NOT NSFW.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectation(description: "Test to make specified Link NOT NSFW.")
let link = Link(id: nsfwTestLinkId)
do {
try self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && !incommingLink.over18)
}
}
}
XCTAssert(isSucceeded, "Test to make specified Link NOT NSFW.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
}
func testToSaveLink() {
print("Test to save specified Link.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectation(description: "Test to save specified Link.")
let link = Link(id: self.testLinkId)
do {
try self.session?.setSave(true, name: link.name, category: "", completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to save specified Link.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is saved.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectation(description: "Check whether the specified Link is saved.")
let link = Link(id: self.testLinkId)
do {
try self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && incommingLink.saved)
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is saved.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print("Test to unsave specified Link.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectation(description: "Test to unsave specified Link.")
let link = Link(id: self.testLinkId)
do {
try self.session?.setSave(false, name: link.name, category: "", completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to unsave specified Link.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is unsaved.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectation(description: "Check whether the specified Link is unsaved.")
let link = Link(id: self.testLinkId)
do {
try self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && !incommingLink.saved)
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is unsaved.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
}
func testToSaveComment() {
print("Test to save specified Comment.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectation(description: "Test to save specified Comment.")
let comment = Comment(id: self.testCommentId)
do {
try self.session?.setSave(true, name: comment.name, category: "", completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to save specified Comment.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print("Check whether the specified Comment is saved.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectation(description: "Check whether the specified Comment is saved.")
let comment = Comment(id: self.testCommentId)
do {
try self.session?.getInfo([comment.name], completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
for obj in listing.children {
if let incommingComment = obj as? Comment {
isSucceeded = (incommingComment.name == comment.name && incommingComment.saved)
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Comment is saved.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print("Test to unsave specified Comment.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectation(description: "Test to unsave specified Comment.")
let comment = Comment(id: self.testCommentId)
do {
try self.session?.setSave(false, name: comment.name, category: "", completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to unsave specified Comment.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print("Check whether the specified Comment is unsaved.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectation(description: "Check whether the specified Comment is unsaved.")
let comment = Comment(id: self.testCommentId)
do {
try self.session?.getInfo([comment.name], completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
for obj in listing.children {
if let incommingComment = obj as? Comment {
isSucceeded = (incommingComment.name == comment.name && !incommingComment.saved)
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Comment is unsaved.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
}
func testToHideLink() {
print("Test to hide the specified Link.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectation(description: "Test to hide the specified Link.")
let link = Link(id: self.testLinkId)
do {
try self.session?.setHide(true, name: link.name, completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to hide the specified Link.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is hidden.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectation(description: "Check whether the specified Link is hidden.")
let link = Link(id: self.testLinkId)
do {
try self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && incommingLink.hidden)
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is hidden.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print("Test to show the specified Link.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectation(description: "Test to show the specified Link.")
let link = Link(id: self.testLinkId)
do {
try self.session?.setHide(false, name: link.name, completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to show the specified Link.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
print("Check whether the specified Link is not hidden.")
do {
var isSucceeded = false
let documentOpenExpectation = self.expectation(description: "Check whether the specified Link is not hidden.")
let link = Link(id: self.testLinkId)
do {
try self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && !incommingLink.hidden)
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is not hidden.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
}
func testToVoteLink() {
print("Test to upvote the specified Link.")
do {
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectation(description: "Test to upvote the specified Link.")
do {
try self.session?.setVote(.up, name: link.name, completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to upvote the specified Link.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
Thread.sleep(forTimeInterval: testInterval)
print("Check whether the specified Link is gave upvote.")
do {
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectation(description: "Check whether the specified Link is gave upvote.")
do {
try self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && incommingLink.likes == .up)
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is gave upvote.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
Thread.sleep(forTimeInterval: testInterval)
print("Test to give a downvote to the specified Link.")
do {
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectation(description: "Test to give a downvote to the specified Link.")
do {
try self.session?.setVote(.down, name: link.name, completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to give a downvote to the specified Link.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
Thread.sleep(forTimeInterval: testInterval)
print("Check whether the specified Link is gave downvote.")
do {
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectation(description: "Check whether the specified Link is gave downvote.")
do {
try self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && incommingLink.likes == .down)
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is gave downvote.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
Thread.sleep(forTimeInterval: testInterval)
print("Test to revoke voting to the specified Link.")
do {
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectation(description: "Test to revoke voting to the specified Link.")
do {
try self.session?.setVote(.none, name: link.name, completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to revoke voting to the specified Link.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
Thread.sleep(forTimeInterval: testInterval)
print("Check whether the downvote to the specified Link has been revoked.")
do {
var isSucceeded = false
let link = Link(id: self.testLinkId)
let documentOpenExpectation = self.expectation(description: "Check whether the downvote to the specified Link has been revoked.")
do {
try self.session?.getInfo([link.name], completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
for obj in listing.children {
if let incommingLink = obj as? Link {
isSucceeded = (incommingLink.name == link.name && (incommingLink.likes == .none))
}
}
}
XCTAssert(isSucceeded, "Check whether the downvote to the specified Link has been revoked.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
}
func testToVoteComment() {
print("Test to upvote the specified Comment.")
do {
var isSucceeded = false
let comment = Comment(id: self.testCommentId)
let documentOpenExpectation = self.expectation(description: "Test to upvote the specified Comment.")
do {
try self.session?.setVote(VoteDirection.up, name: comment.name, completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to upvote the specified comment.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
Thread.sleep(forTimeInterval: testInterval)
print("Check whether the specified Comment is gave upvote.")
do {
var isSucceeded = false
let comment = Comment(id: self.testCommentId)
let documentOpenExpectation = self.expectation(description: "Check whether the specified Comment is gave upvote.")
do {
try self.session?.getInfo([comment.name], completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
for obj in listing.children {
if let incommingComment = obj as? Comment {
isSucceeded = (incommingComment.name == comment.name && (incommingComment.likes == .up))
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Comment is gave upvote.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
Thread.sleep(forTimeInterval: testInterval)
print("Test to give a downvote to the specified Comment.")
do {
var isSucceeded = false
let comment = Comment(id: self.testCommentId)
let documentOpenExpectation = self.expectation(description: "Test to give a downvote to the specified Link.")
do {
try self.session?.setVote(VoteDirection.down, name: comment.name, completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to give a downvote to the specified Link.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
Thread.sleep(forTimeInterval: testInterval)
print("Check whether the specified Comment is gave downvote.")
do {
var isSucceeded = false
let comment = Comment(id: self.testCommentId)
let documentOpenExpectation = self.expectation(description: "Check whether the specified Comment is gave downvote.")
do {
try self.session?.getInfo([comment.name], completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
for obj in listing.children {
if let incommingComment = obj as? Comment {
isSucceeded = (incommingComment.name == comment.name && (incommingComment.likes == .down))
}
}
}
XCTAssert(isSucceeded, "Check whether the specified Link is gave downvote.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
Thread.sleep(forTimeInterval: testInterval)
print("Test to revoke voting to the specified Comment.")
do {
var isSucceeded = false
let comment = Comment(id: self.testCommentId)
let documentOpenExpectation = self.expectation(description: "Test to revoke voting to the specified Comment.")
do {
try self.session?.setVote(.none, name: comment.name, completion: { (result) -> Void in
switch result {
case .failure:
print(result.error!.description)
case .success:
isSucceeded = true
}
XCTAssert(isSucceeded, "Test to revoke voting to the specified Comment.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
Thread.sleep(forTimeInterval: testInterval)
print("Check whether the downvote to the specified Comment has been revoked.")
do {
var isSucceeded = false
let comment = Comment(id: self.testCommentId)
let documentOpenExpectation = self.expectation(description: "Check whether the downvote to the specified Comment has been revoked.")
do {
try self.session?.getInfo([comment.name], completion: { (result) -> Void in
switch result {
case .failure(let error):
print(error.description)
case .success(let listing):
for obj in listing.children {
if let incommingComment = obj as? Comment {
isSucceeded = (incommingComment.name == comment.name && (incommingComment.likes == .none))
}
}
}
XCTAssert(isSucceeded, "Check whether the downvote to the specified Comment has been revoked.")
documentOpenExpectation.fulfill()
})
} catch { XCTFail((error as NSError).description) }
self.waitForExpectations(timeout: self.timeoutDuration, handler: nil)
}
}
}
| mit | 5851b165b434cd51e1d181cc3bdb4c58 | 45.671894 | 184 | 0.511566 | 6.003258 | false | true | false | false |
thehung111/ViSearchSwiftSDK | Example/Example/Lib/ImageLoader/ImageLoader.swift | 3 | 2730 | //
// ImageLoader.swift
// ImageLoader
//
// Created by Hirohisa Kawasaki on 10/16/14.
// Copyright © 2014 Hirohisa Kawasaki. All rights reserved.
//
import Foundation
import UIKit
public protocol URLLiteralConvertible {
var imageLoaderURL: URL { get }
}
extension URL: URLLiteralConvertible {
public var imageLoaderURL: URL {
return self
}
}
extension URLComponents: URLLiteralConvertible {
public var imageLoaderURL: URL {
return url!
}
}
extension String: URLLiteralConvertible {
public var imageLoaderURL: URL {
if let string = addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) {
return URL(string: string)!
}
return URL(string: self)!
}
}
// MARK: Cache
/**
Cache for `ImageLoader` have to implement methods.
find data in Cache before sending a request and set data into cache after receiving.
*/
public protocol ImageLoaderCache: class {
subscript (aKey: URL) -> Data? {
get
set
}
}
public typealias CompletionHandler = (URL, UIImage?, Error?, CacheType) -> Void
class Block {
let identifier: Int
let completionHandler: CompletionHandler
init(identifier: Int, completionHandler: @escaping CompletionHandler) {
self.identifier = identifier
self.completionHandler = completionHandler
}
}
extension Block: Equatable {}
func ==(lhs: Block, rhs: Block) -> Bool {
return lhs.identifier == rhs.identifier
}
/**
Use to check state of loaders that manager has.
Ready: The manager have no loaders
Running: The manager has loaders
*/
public enum State {
case ready
case running
}
/**
Use to check where image is loaded from.
None: fetching from network
Cache: getting from `ImageCache`
*/
public enum CacheType {
case none
case cache
}
// MARK: singleton instance
public let sharedInstance = Manager()
/**
Creates `Loader` object using the shared manager instance for the specified URL.
*/
public func load(_ url: URLLiteralConvertible) -> Loader {
return sharedInstance.load(url)
}
/**
Suspends `Loader` object using the shared manager instance for the specified URL.
*/
public func suspend(_ url: URLLiteralConvertible) -> Loader? {
return sharedInstance.suspend(url)
}
/**
Cancels `Loader` object using the shared manager instance for the specified URL.
*/
public func cancel(_ url: URLLiteralConvertible) {
sharedInstance.cancel(url)
}
public var state: State {
return sharedInstance.state
}
func dispatch_main(_ block: @escaping (Void) -> Void) {
if Thread.isMainThread {
block()
} else {
DispatchQueue.main.async(execute: block)
}
}
| mit | 87e03a24743b8ee2ae6e7d433aa4e601 | 20.832 | 88 | 0.681935 | 4.423015 | false | false | false | false |
tkremenek/swift | libswift/Sources/Optimizer/FunctionPasses/MergeCondFails.swift | 2 | 3459 | //===--- MergeCondFail.swift - Merge cond_fail instructions --------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SIL
let mergeCondFailsPass = FunctionPass(name: "merge-cond_fails", runMergeCondFails)
/// Return true if the operand of the cond_fail instruction looks like
/// the overflow bit of an arithmetic instruction.
private func hasOverflowConditionOperand(_ cfi: CondFailInst) -> Bool {
if let tei = cfi.condition as? TupleExtractInst {
return tei.tuple is BuiltinInst
}
return false
}
/// Merge cond_fail instructions.
///
/// We can merge cond_fail instructions if there is no side-effect or memory
/// write in between them.
/// This pass merges cond_fail instructions by building the disjunction of
/// their operands.
private func runMergeCondFails(function: Function, context: FunctionPassContext) {
// Merge cond_fail instructions if there is no side-effect or read in
// between them.
for block in function.blocks {
// Per basic block list of cond_fails to merge.
var condFailToMerge = StackList<CondFailInst>(context)
for inst in block.instructions {
if let cfi = inst as? CondFailInst {
// Do not process arithmetic overflow checks. We typically generate more
// efficient code with separate jump-on-overflow.
if !hasOverflowConditionOperand(cfi) &&
(condFailToMerge.isEmpty || cfi.message == condFailToMerge.first!.message) {
condFailToMerge.push(cfi)
}
} else if inst.mayHaveSideEffects || inst.mayReadFromMemory {
// Stop merging at side-effects or reads from memory.
mergeCondFails(&condFailToMerge, context: context)
}
}
// Process any remaining cond_fail instructions in the current basic
// block.
mergeCondFails(&condFailToMerge, context: context)
}
}
/// Try to merge the cond_fail instructions. Returns true if any could
/// be merge.
private func mergeCondFails(_ condFailToMerge: inout StackList<CondFailInst>,
context: FunctionPassContext) {
guard let lastCFI = condFailToMerge.last else {
return
}
var mergedCond: Value? = nil
var didMerge = false
let builder = Builder(at: lastCFI.next!, location: lastCFI.location, context)
// Merge conditions and remove the merged cond_fail instructions.
for cfi in condFailToMerge {
if let prevCond = mergedCond {
mergedCond = builder.createBuiltinBinaryFunction(name: "or",
operandType: prevCond.type,
resultType: prevCond.type,
arguments: [prevCond, cfi.condition])
didMerge = true
} else {
mergedCond = cfi.condition
}
}
if !didMerge {
condFailToMerge.removeAll()
return
}
// Create a new cond_fail using the merged condition.
_ = builder.createCondFail(condition: mergedCond!,
message: lastCFI.message)
while let cfi = condFailToMerge.pop() {
context.erase(instruction: cfi)
}
}
| apache-2.0 | 6bc6c16e31d7db3467ad349a4bc05f1b | 35.797872 | 87 | 0.65915 | 4.72541 | false | false | false | false |
CocoaFlow/Engine | EngineTests/OutPortSpec.swift | 1 | 934 | import Quick
import Nimble
import Engine
class OutPortSpec: QuickSpec {
override func spec() {
describe("OutPort") {
var process: BareComponent!
beforeEach {
let network = Network()
process = BareComponent(network)
}
it("should belong to a process") {
let outPort = OutPort<Int>(process)
let processId = ObjectIdentifier(process).hashValue
let outPortProcessId = ObjectIdentifier(outPort.process).hashValue
expect(outPortProcessId).to(equal(processId))
}
it("should have a unique ID") {
let firstOutPort = OutPort<Int>(process)
let secondOutPort = OutPort<Int>(process)
expect(firstOutPort.id).toNot(equal(secondOutPort.id))
}
}
}
}
| apache-2.0 | 54f333e708533f09335e365d2f6f3715 | 30.133333 | 82 | 0.524625 | 5.247191 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/RxCocoa/RxCocoa/RxCocoa.swift | 19 | 4825 | //
// RxCocoa.swift
// RxCocoa
//
// Created by Krunoslav Zaher on 2/21/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import class Foundation.NSNull
// Importing RxCocoa also imports RxRelay
@_exported import RxRelay
import RxSwift
#if os(iOS)
import UIKit
#endif
/// RxCocoa errors.
public enum RxCocoaError
: Swift.Error
, CustomDebugStringConvertible {
/// Unknown error has occurred.
case unknown
/// Invalid operation was attempted.
case invalidOperation(object: Any)
/// Items are not yet bound to user interface but have been requested.
case itemsNotYetBound(object: Any)
/// Invalid KVO Path.
case invalidPropertyName(object: Any, propertyName: String)
/// Invalid object on key path.
case invalidObjectOnKeyPath(object: Any, sourceObject: AnyObject, propertyName: String)
/// Error during swizzling.
case errorDuringSwizzling
/// Casting error.
case castingError(object: Any, targetType: Any.Type)
}
// MARK: Debug descriptions
extension RxCocoaError {
/// A textual representation of `self`, suitable for debugging.
public var debugDescription: String {
switch self {
case .unknown:
return "Unknown error occurred."
case let .invalidOperation(object):
return "Invalid operation was attempted on `\(object)`."
case let .itemsNotYetBound(object):
return "Data source is set, but items are not yet bound to user interface for `\(object)`."
case let .invalidPropertyName(object, propertyName):
return "Object `\(object)` doesn't have a property named `\(propertyName)`."
case let .invalidObjectOnKeyPath(object, sourceObject, propertyName):
return "Unobservable object `\(object)` was observed as `\(propertyName)` of `\(sourceObject)`."
case .errorDuringSwizzling:
return "Error during swizzling."
case let .castingError(object, targetType):
return "Error casting `\(object)` to `\(targetType)`"
}
}
}
// MARK: Error binding policies
func bindingError(_ error: Swift.Error) {
let error = "Binding error: \(error)"
#if DEBUG
rxFatalError(error)
#else
print(error)
#endif
}
/// Swift does not implement abstract methods. This method is used as a runtime check to ensure that methods which intended to be abstract (i.e., they should be implemented in subclasses) are not called directly on the superclass.
func rxAbstractMethod(message: String = "Abstract method", file: StaticString = #file, line: UInt = #line) -> Swift.Never {
rxFatalError(message, file: file, line: line)
}
func rxFatalError(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) -> Swift.Never {
// The temptation to comment this line is great, but please don't, it's for your own good. The choice is yours.
fatalError(lastMessage(), file: file, line: line)
}
func rxFatalErrorInDebug(_ lastMessage: @autoclosure () -> String, file: StaticString = #file, line: UInt = #line) {
#if DEBUG
fatalError(lastMessage(), file: file, line: line)
#else
print("\(file):\(line): \(lastMessage())")
#endif
}
// MARK: casts or fatal error
// workaround for Swift compiler bug, cheers compiler team :)
func castOptionalOrFatalError<T>(_ value: Any?) -> T? {
if value == nil {
return nil
}
let v: T = castOrFatalError(value)
return v
}
func castOrThrow<T>(_ resultType: T.Type, _ object: Any) throws -> T {
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
func castOptionalOrThrow<T>(_ resultType: T.Type, _ object: AnyObject) throws -> T? {
if NSNull().isEqual(object) {
return nil
}
guard let returnValue = object as? T else {
throw RxCocoaError.castingError(object: object, targetType: resultType)
}
return returnValue
}
func castOrFatalError<T>(_ value: AnyObject!, message: String) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
rxFatalError(message)
}
return result
}
func castOrFatalError<T>(_ value: Any!) -> T {
let maybeResult: T? = value as? T
guard let result = maybeResult else {
rxFatalError("Failure converting from \(String(describing: value)) to \(T.self)")
}
return result
}
// MARK: Error messages
let dataSourceNotSet = "DataSource not set"
let delegateNotSet = "Delegate not set"
// MARK: Shared with RxSwift
func rxFatalError(_ lastMessage: String) -> Never {
// 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 | feb76673204f75ccedc4b958530cafa1 | 30.122581 | 230 | 0.672264 | 4.393443 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/Kingfisher/Sources/Views/AnimatedImageView.swift | 4 | 19450 | //
// AnimatableImageView.swift
// Kingfisher
//
// Created by bl4ckra1sond3tre on 4/22/16.
//
// The AnimatableImageView, AnimatedFrame and Animator is a modified version of
// some classes from kaishin's Gifu project (https://github.com/kaishin/Gifu)
//
// The MIT License (MIT)
//
// Copyright (c) 2019 Reda Lemeden.
//
// 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.
//
// The name and characters used in the demo of this software are property of their
// respective owners.
import UIKit
import ImageIO
/// Protocol of `AnimatedImageView`.
public protocol AnimatedImageViewDelegate: AnyObject {
/// Called after the animatedImageView has finished each animation loop.
///
/// - Parameters:
/// - imageView: The `AnimatedImageView` that is being animated.
/// - count: The looped count.
func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt)
/// Called after the `AnimatedImageView` has reached the max repeat count.
///
/// - Parameter imageView: The `AnimatedImageView` that is being animated.
func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView)
}
extension AnimatedImageViewDelegate {
public func animatedImageView(_ imageView: AnimatedImageView, didPlayAnimationLoops count: UInt) {}
public func animatedImageViewDidFinishAnimating(_ imageView: AnimatedImageView) {}
}
#if swift(>=4.2)
let KFRunLoopModeCommon = RunLoop.Mode.common
#else
let KFRunLoopModeCommon = RunLoopMode.commonModes
#endif
/// Represents a subclass of `UIImageView` for displaying animated image.
/// Different from showing animated image in a normal `UIImageView` (which load all frames at one time),
/// `AnimatedImageView` only tries to load several frames (defined by `framePreloadCount`) to reduce memory usage.
/// It provides a tradeoff between memory usage and CPU time. If you have a memory issue when using a normal image
/// view to load GIF data, you could give this class a try.
///
/// Kingfisher supports setting GIF animated data to either `UIImageView` and `AnimatedImageView` out of box. So
/// it would be fairly easy to switch between them.
open class AnimatedImageView: UIImageView {
/// Proxy object for preventing a reference cycle between the `CADDisplayLink` and `AnimatedImageView`.
class TargetProxy {
private weak var target: AnimatedImageView?
init(target: AnimatedImageView) {
self.target = target
}
@objc func onScreenUpdate() {
target?.updateFrameIfNeeded()
}
}
/// Enumeration that specifies repeat count of GIF
public enum RepeatCount: Equatable {
case once
case finite(count: UInt)
case infinite
public static func ==(lhs: RepeatCount, rhs: RepeatCount) -> Bool {
switch (lhs, rhs) {
case let (.finite(l), .finite(r)):
return l == r
case (.once, .once),
(.infinite, .infinite):
return true
case (.once, .finite(let count)),
(.finite(let count), .once):
return count == 1
case (.once, _),
(.infinite, _),
(.finite, _):
return false
}
}
}
// MARK: - Public property
/// Whether automatically play the animation when the view become visible. Default is `true`.
public var autoPlayAnimatedImage = true
/// The count of the frames should be preloaded before shown.
public var framePreloadCount = 10
/// Specifies whether the GIF frames should be pre-scaled to the image view's size or not.
/// If the downloaded image is larger than the image view's size, it will help to reduce some memory use.
/// Default is `true`.
public var needsPrescaling = true
/// The animation timer's run loop mode. Default is `RunLoop.Mode.common`.
/// Set this property to `RunLoop.Mode.default` will make the animation pause during UIScrollView scrolling.
public var runLoopMode = KFRunLoopModeCommon {
willSet {
guard runLoopMode == newValue else { return }
stopAnimating()
displayLink.remove(from: .main, forMode: runLoopMode)
displayLink.add(to: .main, forMode: newValue)
startAnimating()
}
}
/// The repeat count. The animated image will keep animate until it the loop count reaches this value.
/// Setting this value to another one will reset current animation.
///
/// Default is `.infinite`, which means the animation will last forever.
public var repeatCount = RepeatCount.infinite {
didSet {
if oldValue != repeatCount {
reset()
setNeedsDisplay()
layer.setNeedsDisplay()
}
}
}
/// Delegate of this `AnimatedImageView` object. See `AnimatedImageViewDelegate` protocol for more.
public weak var delegate: AnimatedImageViewDelegate?
// MARK: - Private property
/// `Animator` instance that holds the frames of a specific image in memory.
private var animator: Animator?
// Dispatch queue used for preloading images.
private lazy var preloadQueue: DispatchQueue = {
return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
}()
// A flag to avoid invalidating the displayLink on deinit if it was never created, because displayLink is so lazy.
private var isDisplayLinkInitialized: Bool = false
// A display link that keeps calling the `updateFrame` method on every screen refresh.
private lazy var displayLink: CADisplayLink = {
isDisplayLinkInitialized = true
let displayLink = CADisplayLink(
target: TargetProxy(target: self), selector: #selector(TargetProxy.onScreenUpdate))
displayLink.add(to: .main, forMode: runLoopMode)
displayLink.isPaused = true
return displayLink
}()
// MARK: - Override
override open var image: Image? {
didSet {
if image != oldValue {
reset()
}
setNeedsDisplay()
layer.setNeedsDisplay()
}
}
deinit {
if isDisplayLinkInitialized {
displayLink.invalidate()
}
}
override open var isAnimating: Bool {
if isDisplayLinkInitialized {
return !displayLink.isPaused
} else {
return super.isAnimating
}
}
/// Starts the animation.
override open func startAnimating() {
guard !isAnimating else { return }
if animator?.isReachMaxRepeatCount ?? false {
return
}
displayLink.isPaused = false
}
/// Stops the animation.
override open func stopAnimating() {
super.stopAnimating()
if isDisplayLinkInitialized {
displayLink.isPaused = true
}
}
override open func display(_ layer: CALayer) {
if let currentFrame = animator?.currentFrameImage {
layer.contents = currentFrame.cgImage
} else {
layer.contents = image?.cgImage
}
}
override open func didMoveToWindow() {
super.didMoveToWindow()
didMove()
}
override open func didMoveToSuperview() {
super.didMoveToSuperview()
didMove()
}
// This is for back compatibility that using regular `UIImageView` to show animated image.
override func shouldPreloadAllAnimation() -> Bool {
return false
}
// Reset the animator.
private func reset() {
animator = nil
if let imageSource = image?.kf.imageSource {
let targetSize = bounds.scaled(UIScreen.main.scale).size
let animator = Animator(
imageSource: imageSource,
contentMode: contentMode,
size: targetSize,
framePreloadCount: framePreloadCount,
repeatCount: repeatCount,
preloadQueue: preloadQueue)
animator.delegate = self
animator.needsPrescaling = needsPrescaling
animator.prepareFramesAsynchronously()
self.animator = animator
}
didMove()
}
private func didMove() {
if autoPlayAnimatedImage && animator != nil {
if let _ = superview, let _ = window {
startAnimating()
} else {
stopAnimating()
}
}
}
/// Update the current frame with the displayLink duration.
private func updateFrameIfNeeded() {
guard let animator = animator else {
return
}
guard !animator.isFinished else {
stopAnimating()
delegate?.animatedImageViewDidFinishAnimating(self)
return
}
let duration: CFTimeInterval
// CA based display link is opt-out from ProMotion by default.
// So the duration and its FPS might not match.
// See [#718](https://github.com/onevcat/Kingfisher/issues/718)
// By setting CADisableMinimumFrameDuration to YES in Info.plist may
// cause the preferredFramesPerSecond being 0
if displayLink.preferredFramesPerSecond == 0 {
duration = displayLink.duration
} else {
// Some devices (like iPad Pro 10.5) will have a different FPS.
duration = 1.0 / Double(displayLink.preferredFramesPerSecond)
}
animator.shouldChangeFrame(with: duration) { [weak self] hasNewFrame in
if hasNewFrame {
self?.layer.setNeedsDisplay()
}
}
}
}
protocol AnimatorDelegate: AnyObject {
func animator(_ animator: AnimatedImageView.Animator, didPlayAnimationLoops count: UInt)
}
extension AnimatedImageView: AnimatorDelegate {
func animator(_ animator: Animator, didPlayAnimationLoops count: UInt) {
delegate?.animatedImageView(self, didPlayAnimationLoops: count)
}
}
extension AnimatedImageView {
// Represents a single frame in a GIF.
struct AnimatedFrame {
// The image to display for this frame. Its value is nil when the frame is removed from the buffer.
let image: UIImage?
// The duration that this frame should remain active.
let duration: TimeInterval
// A placeholder frame with no image assigned.
// Used to replace frames that are no longer needed in the animation.
var placeholderFrame: AnimatedFrame {
return AnimatedFrame(image: nil, duration: duration)
}
// Whether this frame instance contains an image or not.
var isPlaceholder: Bool {
return image == nil
}
// Returns a new instance from an optional image.
//
// - parameter image: An optional `UIImage` instance to be assigned to the new frame.
// - returns: An `AnimatedFrame` instance.
func makeAnimatedFrame(image: UIImage?) -> AnimatedFrame {
return AnimatedFrame(image: image, duration: duration)
}
}
}
extension AnimatedImageView {
// MARK: - Animator
class Animator {
private let size: CGSize
private let maxFrameCount: Int
private let imageSource: CGImageSource
private let maxRepeatCount: RepeatCount
private let maxTimeStep: TimeInterval = 1.0
private var animatedFrames = [AnimatedFrame]()
private var frameCount = 0
private var timeSinceLastFrameChange: TimeInterval = 0.0
private var currentRepeatCount: UInt = 0
var isFinished: Bool = false
var needsPrescaling = true
weak var delegate: AnimatorDelegate?
// Total duration of one animation loop
var loopDuration: TimeInterval = 0
// Current active frame image
var currentFrameImage: UIImage? {
return frame(at: currentFrameIndex)
}
// Current active frame duration
var currentFrameDuration: TimeInterval {
return duration(at: currentFrameIndex)
}
// The index of the current GIF frame.
var currentFrameIndex = 0 {
didSet {
previousFrameIndex = oldValue
}
}
var previousFrameIndex = 0 {
didSet {
preloadQueue.async {
self.updatePreloadedFrames()
}
}
}
var isReachMaxRepeatCount: Bool {
switch maxRepeatCount {
case .once:
return currentRepeatCount >= 1
case .finite(let maxCount):
return currentRepeatCount >= maxCount
case .infinite:
return false
}
}
var isLastFrame: Bool {
return currentFrameIndex == frameCount - 1
}
var preloadingIsNeeded: Bool {
return maxFrameCount < frameCount - 1
}
var contentMode = UIView.ContentMode.scaleToFill
private lazy var preloadQueue: DispatchQueue = {
return DispatchQueue(label: "com.onevcat.Kingfisher.Animator.preloadQueue")
}()
/// Creates an animator with image source reference.
///
/// - Parameters:
/// - source: The reference of animated image.
/// - mode: Content mode of the `AnimatedImageView`.
/// - size: Size of the `AnimatedImageView`.
/// - count: Count of frames needed to be preloaded.
/// - repeatCount: The repeat count should this animator uses.
init(imageSource source: CGImageSource,
contentMode mode: UIView.ContentMode,
size: CGSize,
framePreloadCount count: Int,
repeatCount: RepeatCount,
preloadQueue: DispatchQueue) {
self.imageSource = source
self.contentMode = mode
self.size = size
self.maxFrameCount = count
self.maxRepeatCount = repeatCount
self.preloadQueue = preloadQueue
}
func frame(at index: Int) -> Image? {
return animatedFrames[safe: index]?.image
}
func duration(at index: Int) -> TimeInterval {
return animatedFrames[safe: index]?.duration ?? .infinity
}
func prepareFramesAsynchronously() {
frameCount = Int(CGImageSourceGetCount(imageSource))
animatedFrames.reserveCapacity(frameCount)
preloadQueue.async { [weak self] in
self?.setupAnimatedFrames()
}
}
func shouldChangeFrame(with duration: CFTimeInterval, handler: (Bool) -> Void) {
incrementTimeSinceLastFrameChange(with: duration)
if currentFrameDuration > timeSinceLastFrameChange {
handler(false)
} else {
resetTimeSinceLastFrameChange()
incrementCurrentFrameIndex()
handler(true)
}
}
private func setupAnimatedFrames() {
resetAnimatedFrames()
var duration: TimeInterval = 0
(0..<frameCount).forEach { index in
let frameDuration = GIFAnimatedImage.getFrameDuration(from: imageSource, at: index)
duration += min(frameDuration, maxTimeStep)
animatedFrames += [AnimatedFrame(image: nil, duration: frameDuration)]
if index > maxFrameCount { return }
animatedFrames[index] = animatedFrames[index].makeAnimatedFrame(image: loadFrame(at: index))
}
self.loopDuration = duration
}
private func resetAnimatedFrames() {
animatedFrames = []
}
private func loadFrame(at index: Int) -> UIImage? {
guard let image = CGImageSourceCreateImageAtIndex(imageSource, index, nil) else {
return nil
}
let scaledImage: CGImage
if needsPrescaling, size != .zero {
scaledImage = image.kf.resize(to: size, for: contentMode)
} else {
scaledImage = image
}
return Image(cgImage: scaledImage)
}
private func updatePreloadedFrames() {
guard preloadingIsNeeded else {
return
}
animatedFrames[previousFrameIndex] = animatedFrames[previousFrameIndex].placeholderFrame
preloadIndexes(start: currentFrameIndex).forEach { index in
let currentAnimatedFrame = animatedFrames[index]
if !currentAnimatedFrame.isPlaceholder { return }
animatedFrames[index] = currentAnimatedFrame.makeAnimatedFrame(image: loadFrame(at: index))
}
}
private func incrementCurrentFrameIndex() {
currentFrameIndex = increment(frameIndex: currentFrameIndex)
if isReachMaxRepeatCount && isLastFrame {
isFinished = true
} else if currentFrameIndex == 0 {
currentRepeatCount += 1
delegate?.animator(self, didPlayAnimationLoops: currentRepeatCount)
}
}
private func incrementTimeSinceLastFrameChange(with duration: TimeInterval) {
timeSinceLastFrameChange += min(maxTimeStep, duration)
}
private func resetTimeSinceLastFrameChange() {
timeSinceLastFrameChange -= currentFrameDuration
}
private func increment(frameIndex: Int, by value: Int = 1) -> Int {
return (frameIndex + value) % frameCount
}
private func preloadIndexes(start index: Int) -> [Int] {
let nextIndex = increment(frameIndex: index)
let lastIndex = increment(frameIndex: index, by: maxFrameCount)
if lastIndex >= nextIndex {
return [Int](nextIndex...lastIndex)
} else {
return [Int](nextIndex..<frameCount) + [Int](0...lastIndex)
}
}
}
}
extension Array {
subscript(safe index: Int) -> Element? {
return indices ~= index ? self[index] : nil
}
}
| mit | 3716fe142b1380ee9176844754087a18 | 33.856631 | 118 | 0.616195 | 5.593903 | false | false | false | false |
belatrix/iOSAllStarsRemake | AllStars/AllStars/iPhone/Classes/Profile/AddSkillsViewController.swift | 1 | 8115 | //
// AddSkillsViewController.swift
// AllStars
//
// Created by Ricardo Hernan Herrera Valle on 8/8/16.
// Copyright © 2016 Belatrix SF. All rights reserved.
//
import Foundation
class AddSkillsViewController: UIViewController, UISearchBarDelegate {
// MARK: - IBOutlets
@IBOutlet weak var backButton : UIButton!
@IBOutlet weak var tableView : UITableView!
@IBOutlet weak var titleLabel : UILabel!
@IBOutlet weak var viewHeader : UIView!
@IBOutlet weak var searchSkills : UISearchBar!
@IBOutlet weak var viewLoading : UIView!
@IBOutlet weak var lblErrorMessage : UILabel!
@IBOutlet weak var acitivitySkills : UIActivityIndicatorView!
@IBOutlet weak var actUpdating : UIActivityIndicatorView!
// MARK: - Properties
var isDownload = false
var arraySkills = NSMutableArray()
var allSkills = NSMutableArray()
var searchText : String = ""
var shouldAddNew = false
var delegate: UserSkillsViewControllerDelegate?
// MAKR: - Initialization
override func viewDidLoad() {
super.viewDidLoad()
setViewsStyle()
setTexts()
listAllSkills()
}
// MARK: - UI Style
func setViewsStyle() {
viewHeader.layer.shadowOffset = CGSizeMake(0, 0)
viewHeader.layer.shadowRadius = 2
viewHeader.layer.masksToBounds = false
viewHeader.layer.shadowOpacity = 1
viewHeader.layer.shadowColor = UIColor.orangeColor().CGColor
viewHeader.backgroundColor = UIColor.colorPrimary()
self.searchSkills.backgroundImage = UIImage()
self.searchSkills.backgroundColor = .clearColor()
self.searchSkills.barTintColor = .clearColor()
self.searchSkills.tintColor = .whiteColor()
}
func setTexts() {
self.titleLabel.text = "add_skill".localized
}
// MARK: - UISearchBarDelegate
func searchBarCancelButtonClicked(searchBar: UISearchBar) {
self.searchSkills.text = ""
shouldAddNew = false
self.listAllSkills()
self.searchSkills.resignFirstResponder()
}
func searchBarSearchButtonClicked(searchBar: UISearchBar) {
searchSkills.resignFirstResponder()
}
func searchBar(searchBar: UISearchBar, textDidChange searchText: String) {
self.searchText = searchText.characters.count > 0 ? searchText : ""
if self.searchText.characters.count == 0 {
self.listAllSkills()
}else{
self.listSkillsWithSearchText()
}
}
func searchBarTextDidBeginEditing(searchBar: UISearchBar) {
searchBar.showsCancelButton = true
}
func searchBarTextDidEndEditing(searchBar: UISearchBar) {
searchBar.showsCancelButton = false
}
// MARK: - UITableViewDelegate, UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return (shouldAddNew == true) ? 1 : self.arraySkills.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
if shouldAddNew {
let cell = UITableViewCell(style: .Default, reuseIdentifier: "AddSkillCell")
cell.textLabel?.textAlignment = .Center
cell.textLabel?.text = "Add " + searchText + " as a new Skill"
cell.textLabel?.textColor = UIColor.colorAccent()
return cell
}
let cellIdentifier = "SkillTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! TagTableViewCell
let skill = self.arraySkills[indexPath.row] as! KeywordBE
cell.lblNameTag.text = skill.keyword_name
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let cell = tableView.cellForRowAtIndexPath(indexPath)
cell?.setSelected(false, animated: true)
// The searched skill wasn't found
if shouldAddNew {
self.addSkillToUser(searchText)
return
}
let skill = self.arraySkills[indexPath.row] as! KeywordBE
let alert = UIAlertController(title: "app_name".localized , message: "Do you want to add " + skill.keyword_name! + " as a new Skill?", preferredStyle: .Alert)
let addAction = UIAlertAction(title: "yes".localized, style: .Default) { (action) in
self.actUpdating.startAnimating()
self.addSkillToUser(skill.keyword_name!)
}
let cancelAction = UIAlertAction(title: "no".localized, style: .Cancel, handler: nil)
alert.addAction(addAction)
alert.addAction(cancelAction)
self.presentViewController(alert, animated: true, completion: nil)
}
// MARK: - User Interaction
@IBAction func btnBackTUI(sender: UIButton) {
self.view.endEditing(true)
self.navigationController?.popViewControllerAnimated(true)
}
func listSkillsWithSearchText() {
let resultPredicate = NSPredicate(format: "SELF.keyword_name contains[cd] %@", searchText)
self.arraySkills.removeAllObjects()
self.arraySkills.addObjectsFromArray(self.allSkills as [AnyObject])
let filteredSkills = self.arraySkills.filteredArrayUsingPredicate(resultPredicate)
self.arraySkills.removeAllObjects()
self.arraySkills.addObjectsFromArray(filteredSkills)
self.shouldAddNew = (self.arraySkills.count == 0)
self.tableView.reloadData()
}
// MARK: - WebServices
func listAllSkills() {
if (!self.isDownload && allSkills.count == 0) {
self.isDownload = true
self.acitivitySkills.startAnimating()
self.viewLoading.alpha = CGFloat(!Bool(self.arraySkills.count))
self.lblErrorMessage.text = "Loading skills"
RecommendBC.listKeyWordsWithCompletion({ (arrayKeywords) in
self.arraySkills = NSMutableArray(array: arrayKeywords)
self.allSkills = NSMutableArray(array: arrayKeywords)
self.tableView.reloadData()
self.acitivitySkills.stopAnimating()
self.viewLoading.alpha = CGFloat(!Bool(self.arraySkills.count))
self.lblErrorMessage.text = "skills not found"
self.isDownload = false
})
} else {
self.arraySkills.removeAllObjects()
self.arraySkills.addObjectsFromArray(self.allSkills as [AnyObject])
self.tableView.reloadData()
}
}
func addSkillToUser(skillName: String) {
self.actUpdating.startAnimating()
self.view.userInteractionEnabled = false
ProfileBC.addUserSkill(skillName) { (skills, successful) in
self.view.userInteractionEnabled = true
self.actUpdating.stopAnimating()
if successful {
self.delegate?.newSkillAdded()
let alert = UIAlertController(title: "app_name".localized , message: skillName + " added", preferredStyle: .Alert)
let acceptAction = UIAlertAction(title: "got_it".localized, style: .Cancel, handler: nil)
alert.addAction(acceptAction)
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
} | mit | c5b70a2aae6260e7883638b9b42a41ad | 33.828326 | 166 | 0.604511 | 5.538567 | false | false | false | false |
DanielAsher/VIPER-SWIFT | Carthage/Checkouts/RxSwift/RxExample/RxDataSources/DataSources+Rx/UISectionedViewType+RxAnimatedDataSource.swift | 2 | 1542 | //
// UISectionedViewType+RxAnimatedDataSource.swift
// RxExample
//
// Created by Krunoslav Zaher on 11/14/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import UIKit
#if !RX_NO_MODULE
import RxSwift
import RxCocoa
#endif
extension UITableView {
public func rx_itemsAnimatedWithDataSource<
DataSource: protocol<RxTableViewDataSourceType, UITableViewDataSource>,
O: ObservableConvertibleType,
Section: AnimatableSectionModelType
where
DataSource.Element == [Changeset<Section>],
O.E == [Section]
>
(dataSource: DataSource)
-> (source: O)
-> Disposable {
return { source in
let differences = source.differentiateForSectionedView()
return self.rx_itemsWithDataSource(dataSource)(source: differences)
}
}
}
extension UICollectionView {
public func rx_itemsAnimatedWithDataSource<
DataSource: protocol<RxCollectionViewDataSourceType, UICollectionViewDataSource>,
O: ObservableConvertibleType,
Section: AnimatableSectionModelType
where
DataSource.Element == [Changeset<Section>],
O.E == [Section]
>
(dataSource: DataSource)
-> (source: O)
-> Disposable {
return { source in
let differences = source.differentiateForSectionedView()
return self.rx_itemsWithDataSource(dataSource)(source: differences)
}
}
} | mit | f7845d235bc12b9394656b7a27bd33c3 | 28.653846 | 93 | 0.640493 | 5.259386 | false | false | false | false |
jacobwhite/firefox-ios | Client/Frontend/Settings/SettingsContentViewController.swift | 1 | 6399 | /* 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 Shared
import SnapKit
import UIKit
import WebKit
let DefaultTimeoutTimeInterval = 10.0 // Seconds. We'll want some telemetry on load times in the wild.
private var TODOPageLoadErrorString = NSLocalizedString("Could not load page.", comment: "Error message that is shown in settings when there was a problem loading")
/**
* A controller that manages a single web view and provides a way for
* the user to navigate back to Settings.
*/
class SettingsContentViewController: UIViewController, WKNavigationDelegate {
let interstitialBackgroundColor: UIColor
var settingsTitle: NSAttributedString?
var url: URL!
var timer: Timer?
var isLoaded: Bool = false {
didSet {
if isLoaded {
UIView.transition(from: interstitialView, to: webView,
duration: 0.5,
options: .transitionCrossDissolve,
completion: { finished in
self.interstitialView.removeFromSuperview()
self.interstitialSpinnerView.stopAnimating()
})
}
}
}
fileprivate var isError: Bool = false {
didSet {
if isError {
interstitialErrorView.isHidden = false
UIView.transition(from: interstitialSpinnerView, to: interstitialErrorView,
duration: 0.5,
options: .transitionCrossDissolve,
completion: { finished in
self.interstitialSpinnerView.removeFromSuperview()
self.interstitialSpinnerView.stopAnimating()
})
}
}
}
// The view shown while the content is loading in the background web view.
fileprivate var interstitialView: UIView!
fileprivate var interstitialSpinnerView: UIActivityIndicatorView!
fileprivate var interstitialErrorView: UILabel!
// The web view that displays content.
var webView: WKWebView!
fileprivate func startLoading(_ timeout: Double = DefaultTimeoutTimeInterval) {
if self.isLoaded {
return
}
if timeout > 0 {
self.timer = Timer.scheduledTimer(timeInterval: timeout, target: self, selector: #selector(didTimeOut), userInfo: nil, repeats: false)
} else {
self.timer = nil
}
self.webView.load(URLRequest(url: url))
self.interstitialSpinnerView.startAnimating()
}
init(backgroundColor: UIColor = UIColor.white, title: NSAttributedString? = nil) {
interstitialBackgroundColor = backgroundColor
settingsTitle = title
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
// This background agrees with the web page background.
// Keeping the background constant prevents a pop of mismatched color.
view.backgroundColor = interstitialBackgroundColor
self.webView = makeWebView()
view.addSubview(webView)
self.webView.snp.remakeConstraints { make in
make.edges.equalTo(self.view)
}
// Destructuring let causes problems.
let ret = makeInterstitialViews()
self.interstitialView = ret.0
self.interstitialSpinnerView = ret.1
self.interstitialErrorView = ret.2
view.addSubview(interstitialView)
self.interstitialView.snp.remakeConstraints { make in
make.edges.equalTo(self.view)
}
startLoading()
}
func makeWebView() -> WKWebView {
let config = WKWebViewConfiguration()
let webView = WKWebView(
frame: CGRect(width: 1, height: 1),
configuration: config
)
webView.allowsLinkPreview = false
webView.navigationDelegate = self
return webView
}
fileprivate func makeInterstitialViews() -> (UIView, UIActivityIndicatorView, UILabel) {
let view = UIView()
// Keeping the background constant prevents a pop of mismatched color.
view.backgroundColor = interstitialBackgroundColor
let spinner = UIActivityIndicatorView(activityIndicatorStyle: .gray)
view.addSubview(spinner)
let error = UILabel()
if let _ = settingsTitle {
error.text = TODOPageLoadErrorString
error.textColor = UIColor.red // Firefox Orange!
error.textAlignment = .center
}
error.isHidden = true
view.addSubview(error)
spinner.snp.makeConstraints { make in
make.center.equalTo(view)
return
}
error.snp.makeConstraints { make in
make.center.equalTo(view)
make.left.equalTo(view.snp.left).offset(20)
make.right.equalTo(view.snp.right).offset(-20)
make.height.equalTo(44)
return
}
return (view, spinner, error)
}
@objc func didTimeOut() {
self.timer = nil
self.isError = true
}
func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
// If this is a request to our local web server, use our private credentials.
if challenge.protectionSpace.host == "localhost" && challenge.protectionSpace.port == Int(WebServer.sharedInstance.server.port) {
completionHandler(.useCredential, WebServer.sharedInstance.credentials)
return
}
completionHandler(.performDefaultHandling, nil)
}
func webView(_ webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: Error) {
didTimeOut()
}
func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
didTimeOut()
}
func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
self.timer?.invalidate()
self.timer = nil
self.isLoaded = true
}
}
| mpl-2.0 | 46e437e4c2141bf15c876832115e125a | 34.353591 | 182 | 0.636349 | 5.422881 | false | false | false | false |
PokeMapCommunity/PokeMap-iOS | Pods/NSObject+Rx/NSObject+Rx.swift | 3 | 1047 | import Foundation
import RxSwift
import ObjectiveC
public extension NSObject {
private struct AssociatedKeys {
static var DisposeBag = "rx_disposeBag"
}
private func doLocked(closure: () -> Void) {
objc_sync_enter(self); defer { objc_sync_exit(self) }
closure()
}
var rx_disposeBag: DisposeBag {
get {
var disposeBag: DisposeBag!
doLocked {
let lookup = objc_getAssociatedObject(self, &AssociatedKeys.DisposeBag) as? DisposeBag
if let lookup = lookup {
disposeBag = lookup
} else {
let newDisposeBag = DisposeBag()
self.rx_disposeBag = newDisposeBag
disposeBag = newDisposeBag
}
}
return disposeBag
}
set {
doLocked {
objc_setAssociatedObject(self, &AssociatedKeys.DisposeBag, newValue, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
}
}
| mit | 3341a27e029f0ede9a77000e1fbdd954 | 27.297297 | 120 | 0.537727 | 5.629032 | false | false | false | false |
Paladinfeng/Weibo-Swift | Weibo/Weibo/Classes/Tools/Extension/UIBarButtonItem+extension.swift | 1 | 1387 | //
// UIBarButtonItem+extension.swift
// Weibo
//
// Created by Paladinfeng on 15/12/5.
// Copyright © 2015年 Paladinfeng. All rights reserved.
//
import UIKit
//默认字体颜色
let itemColor: UIColor = UIColor(white: 80 / 255, alpha: 1)
//默认字号
let itemFontSize: CGFloat = 14
extension UIBarButtonItem{
//真机测试,位置有问题
convenience init(imgName: String? = nil, title: String? = nil,target: AnyObject?, action: Selector) {
self.init()
let btn = UIButton()
btn.addTarget(target, action: action, forControlEvents: .TouchUpInside)
if let img = imgName {
btn.setImage(UIImage(named: img), forState: .Normal)
btn.setImage(UIImage(named: "\(img)_highlighted"), forState: .Highlighted)
}
if let t = title {
btn.setTitle(t, forState: .Normal)
//颜色
btn.setTitleColor(itemColor, forState: .Normal)
btn.setTitleColor(UIColor.orangeColor(), forState: .Highlighted)
//字号
btn.titleLabel?.font = UIFont.systemFontOfSize(itemFontSize)
btn.imageEdgeInsets = UIEdgeInsets(top: 0, left: -8, bottom: 0, right: 8)
}
btn.sizeToFit()
customView = btn
}
}
| mit | 189aae5a8413ee92eef1be01c6b327e1 | 24.730769 | 105 | 0.560538 | 4.415842 | false | false | false | false |
alexzatsepin/omim | iphone/Maps/Categories/UIView+Snapshot.swift | 9 | 669 | import UIKit
extension UIView {
@objc var snapshot: UIView {
guard let contents = layer.contents else {
return snapshotView(afterScreenUpdates: true)!
}
let snapshot: UIView
if let view = self as? UIImageView {
snapshot = UIImageView(image: view.image)
snapshot.bounds = view.bounds
} else {
snapshot = UIView(frame: frame)
snapshot.layer.contents = contents
snapshot.layer.bounds = layer.bounds
}
snapshot.layer.cornerRadius = layer.cornerRadius
snapshot.layer.masksToBounds = layer.masksToBounds
snapshot.contentMode = contentMode
snapshot.transform = transform
return snapshot
}
}
| apache-2.0 | 8c272554a2311fda53223e31de7df2a7 | 28.086957 | 54 | 0.692078 | 4.711268 | false | false | false | false |
Snail93/iOSDemos | SnailSwiftDemos/Pods/SQLite.swift/Sources/SQLite/Typed/CoreFunctions.swift | 4 | 27242 | //
// SQLite.swift
// https://github.com/stephencelis/SQLite.swift
// Copyright © 2014-2015 Stephen Celis.
//
// 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 ExpressionType where UnderlyingType : Number {
/// Builds a copy of the expression wrapped with the `abs` function.
///
/// let x = Expression<Int>("x")
/// x.absoluteValue
/// // abs("x")
///
/// - Returns: A copy of the expression wrapped with the `abs` function.
public var absoluteValue : Expression<UnderlyingType> {
return "abs".wrap(self)
}
}
extension ExpressionType where UnderlyingType : _OptionalType, UnderlyingType.WrappedType : Number {
/// Builds a copy of the expression wrapped with the `abs` function.
///
/// let x = Expression<Int?>("x")
/// x.absoluteValue
/// // abs("x")
///
/// - Returns: A copy of the expression wrapped with the `abs` function.
public var absoluteValue : Expression<UnderlyingType> {
return "abs".wrap(self)
}
}
extension ExpressionType where UnderlyingType == Double {
/// Builds a copy of the expression wrapped with the `round` function.
///
/// let salary = Expression<Double>("salary")
/// salary.round()
/// // round("salary")
/// salary.round(2)
/// // round("salary", 2)
///
/// - Returns: A copy of the expression wrapped with the `round` function.
public func round(_ precision: Int? = nil) -> Expression<UnderlyingType> {
guard let precision = precision else {
return wrap([self])
}
return wrap([self, Int(precision)])
}
}
extension ExpressionType where UnderlyingType == Double? {
/// Builds a copy of the expression wrapped with the `round` function.
///
/// let salary = Expression<Double>("salary")
/// salary.round()
/// // round("salary")
/// salary.round(2)
/// // round("salary", 2)
///
/// - Returns: A copy of the expression wrapped with the `round` function.
public func round(_ precision: Int? = nil) -> Expression<UnderlyingType> {
guard let precision = precision else {
return wrap(self)
}
return wrap([self, Int(precision)])
}
}
extension ExpressionType where UnderlyingType : Value, UnderlyingType.Datatype == Int64 {
/// Builds an expression representing the `random` function.
///
/// Expression<Int>.random()
/// // random()
///
/// - Returns: An expression calling the `random` function.
public static func random() -> Expression<UnderlyingType> {
return "random".wrap([])
}
}
extension ExpressionType where UnderlyingType == Data {
/// Builds an expression representing the `randomblob` function.
///
/// Expression<Int>.random(16)
/// // randomblob(16)
///
/// - Parameter length: Length in bytes.
///
/// - Returns: An expression calling the `randomblob` function.
public static func random(_ length: Int) -> Expression<UnderlyingType> {
return "randomblob".wrap([])
}
/// Builds an expression representing the `zeroblob` function.
///
/// Expression<Int>.allZeros(16)
/// // zeroblob(16)
///
/// - Parameter length: Length in bytes.
///
/// - Returns: An expression calling the `zeroblob` function.
public static func allZeros(_ length: Int) -> Expression<UnderlyingType> {
return "zeroblob".wrap([])
}
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let data = Expression<NSData>("data")
/// data.length
/// // length("data")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int> {
return wrap(self)
}
}
extension ExpressionType where UnderlyingType == Data? {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let data = Expression<NSData?>("data")
/// data.length
/// // length("data")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int?> {
return wrap(self)
}
}
extension ExpressionType where UnderlyingType == String {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let name = Expression<String>("name")
/// name.length
/// // length("name")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int> {
return wrap(self)
}
/// Builds a copy of the expression wrapped with the `lower` function.
///
/// let name = Expression<String>("name")
/// name.lowercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `lower` function.
public var lowercaseString: Expression<UnderlyingType> {
return "lower".wrap(self)
}
/// Builds a copy of the expression wrapped with the `upper` function.
///
/// let name = Expression<String>("name")
/// name.uppercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `upper` function.
public var uppercaseString: Expression<UnderlyingType> {
return "upper".wrap(self)
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String>("email")
/// email.like("%@example.com")
/// // "email" LIKE '%@example.com'
/// email.like("99\\%@%", escape: "\\")
/// // "email" LIKE '99\%@%' ESCAPE '\'
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: String, escape character: Character? = nil) -> Expression<Bool> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)])
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String>("email")
/// let pattern = Expression<String>("pattern")
/// email.like(pattern)
/// // "email" LIKE "pattern"
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: Expression<String>, escape character: Character? = nil) -> Expression<Bool> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
let like: Expression<Bool> = "LIKE".infix(self, pattern, wrap: false)
return Expression("(\(like.template) ESCAPE ?)", like.bindings + [String(character)])
}
/// Builds a copy of the expression appended with a `GLOB` query against the
/// given pattern.
///
/// let path = Expression<String>("path")
/// path.glob("*.png")
/// // "path" GLOB '*.png'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `GLOB` query against
/// the given pattern.
public func glob(_ pattern: String) -> Expression<Bool> {
return "GLOB".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `MATCH` query against
/// the given pattern.
///
/// let title = Expression<String>("title")
/// title.match("swift AND programming")
/// // "title" MATCH 'swift AND programming'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `MATCH` query
/// against the given pattern.
public func match(_ pattern: String) -> Expression<Bool> {
return "MATCH".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `REGEXP` query against
/// the given pattern.
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `REGEXP` query
/// against the given pattern.
public func regexp(_ pattern: String) -> Expression<Bool> {
return "REGEXP".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `COLLATE` clause with
/// the given sequence.
///
/// let name = Expression<String>("name")
/// name.collate(.Nocase)
/// // "name" COLLATE NOCASE
///
/// - Parameter collation: A collating sequence.
///
/// - Returns: A copy of the expression appended with a `COLLATE` clause
/// with the given sequence.
public func collate(_ collation: Collation) -> Expression<UnderlyingType> {
return "COLLATE".infix(self, collation)
}
/// Builds a copy of the expression wrapped with the `ltrim` function.
///
/// let name = Expression<String>("name")
/// name.ltrim()
/// // ltrim("name")
/// name.ltrim([" ", "\t"])
/// // ltrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `ltrim` function.
public func ltrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `rtrim` function.
///
/// let name = Expression<String>("name")
/// name.rtrim()
/// // rtrim("name")
/// name.rtrim([" ", "\t"])
/// // rtrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `rtrim` function.
public func rtrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `trim` function.
///
/// let name = Expression<String>("name")
/// name.trim()
/// // trim("name")
/// name.trim([" ", "\t"])
/// // trim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `trim` function.
public func trim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap([self])
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `replace` function.
///
/// let email = Expression<String>("email")
/// email.replace("@mac.com", with: "@icloud.com")
/// // replace("email", '@mac.com', '@icloud.com')
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - replacement: The replacement string.
///
/// - Returns: A copy of the expression wrapped with the `replace` function.
public func replace(_ pattern: String, with replacement: String) -> Expression<UnderlyingType> {
return "replace".wrap([self, pattern, replacement])
}
public func substring(_ location: Int, length: Int? = nil) -> Expression<UnderlyingType> {
guard let length = length else {
return "substr".wrap([self, location])
}
return "substr".wrap([self, location, length])
}
public subscript(range: Range<Int>) -> Expression<UnderlyingType> {
return substring(range.lowerBound, length: range.upperBound - range.lowerBound)
}
}
extension ExpressionType where UnderlyingType == String? {
/// Builds a copy of the expression wrapped with the `length` function.
///
/// let name = Expression<String?>("name")
/// name.length
/// // length("name")
///
/// - Returns: A copy of the expression wrapped with the `length` function.
public var length: Expression<Int?> {
return wrap(self)
}
/// Builds a copy of the expression wrapped with the `lower` function.
///
/// let name = Expression<String?>("name")
/// name.lowercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `lower` function.
public var lowercaseString: Expression<UnderlyingType> {
return "lower".wrap(self)
}
/// Builds a copy of the expression wrapped with the `upper` function.
///
/// let name = Expression<String?>("name")
/// name.uppercaseString
/// // lower("name")
///
/// - Returns: A copy of the expression wrapped with the `upper` function.
public var uppercaseString: Expression<UnderlyingType> {
return "upper".wrap(self)
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String?>("email")
/// email.like("%@example.com")
/// // "email" LIKE '%@example.com'
/// email.like("99\\%@%", escape: "\\")
/// // "email" LIKE '99\%@%' ESCAPE '\'
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: String, escape character: Character? = nil) -> Expression<Bool?> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
return Expression("(\(template) LIKE ? ESCAPE ?)", bindings + [pattern, String(character)])
}
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = Expression<String>("email")
/// let pattern = Expression<String>("pattern")
/// email.like(pattern)
/// // "email" LIKE "pattern"
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: Expression<String>, escape character: Character? = nil) -> Expression<Bool?> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
let like: Expression<Bool> = "LIKE".infix(self, pattern, wrap: false)
return Expression("(\(like.template) ESCAPE ?)", like.bindings + [String(character)])
}
/// Builds a copy of the expression appended with a `GLOB` query against the
/// given pattern.
///
/// let path = Expression<String?>("path")
/// path.glob("*.png")
/// // "path" GLOB '*.png'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `GLOB` query against
/// the given pattern.
public func glob(_ pattern: String) -> Expression<Bool?> {
return "GLOB".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `MATCH` query against
/// the given pattern.
///
/// let title = Expression<String?>("title")
/// title.match("swift AND programming")
/// // "title" MATCH 'swift AND programming'
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `MATCH` query
/// against the given pattern.
public func match(_ pattern: String) -> Expression<Bool> {
return "MATCH".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `REGEXP` query against
/// the given pattern.
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression appended with a `REGEXP` query
/// against the given pattern.
public func regexp(_ pattern: String) -> Expression<Bool?> {
return "REGEXP".infix(self, pattern)
}
/// Builds a copy of the expression appended with a `COLLATE` clause with
/// the given sequence.
///
/// let name = Expression<String?>("name")
/// name.collate(.Nocase)
/// // "name" COLLATE NOCASE
///
/// - Parameter collation: A collating sequence.
///
/// - Returns: A copy of the expression appended with a `COLLATE` clause
/// with the given sequence.
public func collate(_ collation: Collation) -> Expression<UnderlyingType> {
return "COLLATE".infix(self, collation)
}
/// Builds a copy of the expression wrapped with the `ltrim` function.
///
/// let name = Expression<String?>("name")
/// name.ltrim()
/// // ltrim("name")
/// name.ltrim([" ", "\t"])
/// // ltrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `ltrim` function.
public func ltrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `rtrim` function.
///
/// let name = Expression<String?>("name")
/// name.rtrim()
/// // rtrim("name")
/// name.rtrim([" ", "\t"])
/// // rtrim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `rtrim` function.
public func rtrim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `trim` function.
///
/// let name = Expression<String?>("name")
/// name.trim()
/// // trim("name")
/// name.trim([" ", "\t"])
/// // trim("name", ' \t')
///
/// - Parameter characters: A set of characters to trim.
///
/// - Returns: A copy of the expression wrapped with the `trim` function.
public func trim(_ characters: Set<Character>? = nil) -> Expression<UnderlyingType> {
guard let characters = characters else {
return wrap(self)
}
return wrap([self, String(characters)])
}
/// Builds a copy of the expression wrapped with the `replace` function.
///
/// let email = Expression<String?>("email")
/// email.replace("@mac.com", with: "@icloud.com")
/// // replace("email", '@mac.com', '@icloud.com')
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - replacement: The replacement string.
///
/// - Returns: A copy of the expression wrapped with the `replace` function.
public func replace(_ pattern: String, with replacement: String) -> Expression<UnderlyingType> {
return "replace".wrap([self, pattern, replacement])
}
/// Builds a copy of the expression wrapped with the `substr` function.
///
/// let title = Expression<String?>("title")
/// title.substr(-100)
/// // substr("title", -100)
/// title.substr(0, length: 100)
/// // substr("title", 0, 100)
///
/// - Parameters:
///
/// - location: The substring’s start index.
///
/// - length: An optional substring length.
///
/// - Returns: A copy of the expression wrapped with the `substr` function.
public func substring(_ location: Int, length: Int? = nil) -> Expression<UnderlyingType> {
guard let length = length else {
return "substr".wrap([self, location])
}
return "substr".wrap([self, location, length])
}
/// Builds a copy of the expression wrapped with the `substr` function.
///
/// let title = Expression<String?>("title")
/// title[0..<100]
/// // substr("title", 0, 100)
///
/// - Parameter range: The character index range of the substring.
///
/// - Returns: A copy of the expression wrapped with the `substr` function.
public subscript(range: Range<Int>) -> Expression<UnderlyingType> {
return substring(range.lowerBound, length: range.upperBound - range.lowerBound)
}
}
extension Collection where Iterator.Element : Value, IndexDistance == Int {
/// Builds a copy of the expression prepended with an `IN` check against the
/// collection.
///
/// let name = Expression<String>("name")
/// ["alice", "betty"].contains(name)
/// // "name" IN ('alice', 'betty')
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression prepended with an `IN` check against
/// the collection.
public func contains(_ expression: Expression<Iterator.Element>) -> Expression<Bool> {
let templates = [String](repeating: "?", count: count).joined(separator: ", ")
return "IN".infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue }))
}
/// Builds a copy of the expression prepended with an `IN` check against the
/// collection.
///
/// let name = Expression<String?>("name")
/// ["alice", "betty"].contains(name)
/// // "name" IN ('alice', 'betty')
///
/// - Parameter pattern: A pattern to match.
///
/// - Returns: A copy of the expression prepended with an `IN` check against
/// the collection.
public func contains(_ expression: Expression<Iterator.Element?>) -> Expression<Bool?> {
let templates = [String](repeating: "?", count: count).joined(separator: ", ")
return "IN".infix(expression, Expression<Void>("(\(templates))", map { $0.datatypeValue }))
}
}
extension String {
/// Builds a copy of the expression appended with a `LIKE` query against the
/// given pattern.
///
/// let email = "[email protected]"
/// let pattern = Expression<String>("pattern")
/// email.like(pattern)
/// // '[email protected]' LIKE "pattern"
///
/// - Parameters:
///
/// - pattern: A pattern to match.
///
/// - escape: An (optional) character designated for escaping
/// pattern-matching characters (*i.e.*, the `%` and `_` characters).
///
/// - Returns: A copy of the expression appended with a `LIKE` query against
/// the given pattern.
public func like(_ pattern: Expression<String>, escape character: Character? = nil) -> Expression<Bool> {
guard let character = character else {
return "LIKE".infix(self, pattern)
}
let like: Expression<Bool> = "LIKE".infix(self, pattern, wrap: false)
return Expression("(\(like.template) ESCAPE ?)", like.bindings + [String(character)])
}
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let name = Expression<String?>("name")
/// name ?? "An Anonymous Coward"
/// // ifnull("name", 'An Anonymous Coward')
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback value for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V : Value>(optional: Expression<V?>, defaultValue: V) -> Expression<V> {
return "ifnull".wrap([optional, defaultValue])
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let nick = Expression<String?>("nick")
/// let name = Expression<String>("name")
/// nick ?? name
/// // ifnull("nick", "name")
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback expression for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V : Value>(optional: Expression<V?>, defaultValue: Expression<V>) -> Expression<V> {
return "ifnull".wrap([optional, defaultValue])
}
/// Builds a copy of the given expressions wrapped with the `ifnull` function.
///
/// let nick = Expression<String?>("nick")
/// let name = Expression<String?>("name")
/// nick ?? name
/// // ifnull("nick", "name")
///
/// - Parameters:
///
/// - optional: An optional expression.
///
/// - defaultValue: A fallback expression for when the optional expression is
/// `nil`.
///
/// - Returns: A copy of the given expressions wrapped with the `ifnull`
/// function.
public func ??<V : Value>(optional: Expression<V?>, defaultValue: Expression<V?>) -> Expression<V> {
return "ifnull".wrap([optional, defaultValue])
}
| apache-2.0 | 879ec7766abbb73360328f66276129a8 | 34.746719 | 110 | 0.589486 | 4.295695 | false | false | false | false |
shamanskyh/Precircuiter | Precircuiter/Main/Views/ConnectionView.swift | 1 | 6659 | //
// ConnectionView.swift
// Precircuiter
//
// Created by Harry Shamansky on 9/2/15.
// Copyright © 2015 Harry Shamansky. All rights reserved.
//
import Cocoa
/// Relative position of dimmer to light
enum RelativePosition {
case quadrantI
case quadrantII
case quadrantIII
case quadrantIV
}
class ConnectionView: NSView {
init(light: Instrument, dimmer: Instrument) {
self.light = light
self.dimmer = dimmer
super.init(frame: NSZeroRect)
}
required init?(coder: NSCoder) {
// Note that these keys aren't actually in use yet
self.light = coder.decodeObject(forKey: "light") as! Instrument
self.dimmer = coder.decodeObject(forKey: "dimmer") as! Instrument
super.init(coder: coder)
}
/// The dimmer that the ConnectionView is connecting
var dimmer: Instrument {
willSet {
assert(newValue.deviceType == .power, "Dimmer must be of type .Power")
}
}
/// The light that the ConnectionView is connecting
var light: Instrument {
willSet {
assert(newValue.deviceType == .light || newValue.deviceType == .movingLight || newValue.deviceType == .practical, "Light must be of type .Light, .MovingLight, or .Practical")
}
}
/// The CGPoint representing the dimmer in the PlotView
var dimmerPoint: CGPoint {
return CGPoint(x: dimmer.viewRepresentation.frame.midX, y: dimmer.viewRepresentation.frame.midY)
}
/// The CGPoint representing the light in the PlotView
var lightPoint: CGPoint {
return CGPoint(x: light.viewRepresentation.frame.midX, y: light.viewRepresentation.frame.midY)
}
/// Returns the relative position of the dimmer to the light
private var relativePositioning: RelativePosition {
if dimmerPoint.x >= lightPoint.x && dimmerPoint.y >= lightPoint.y {
return .quadrantI
} else if dimmerPoint.x >= lightPoint.x && dimmerPoint.y < lightPoint.y {
return .quadrantIV
} else if dimmerPoint.x < lightPoint.x && dimmerPoint.y >= lightPoint.y {
return .quadrantII
}
return .quadrantIII
}
/// Automatically sets the ConnectionView's frame to be in its pre-animation state
func sizeToAnimate() {
self.frame = CGRect(x: lightPoint.x, y: lightPoint.y, width: 0.0, height: 0.0)
}
/// Animate the ConnectionView's frame change
func animateIn() {
NSAnimationContext.runAnimationGroup({ (context: NSAnimationContext) -> Void in
context.duration = Random.within(kMinAnimationDuration...kMaxAnimationDuration)
context.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
context.allowsImplicitAnimation = true
self.sizeToConnect()
}, completionHandler: nil)
}
/// Automatically sets the ConnectionView's frame based on its light and dimmer
func sizeToConnect() {
let width = abs(dimmerPoint.x - lightPoint.x)
let height = abs(dimmerPoint.y - lightPoint.y)
let x: CGFloat
let y: CGFloat
switch (self.relativePositioning) {
case .quadrantI:
x = lightPoint.x
y = lightPoint.y
case .quadrantII:
x = dimmerPoint.x
y = lightPoint.y
case .quadrantIII:
x = dimmerPoint.x
y = dimmerPoint.y
case .quadrantIV:
x = lightPoint.x
y = dimmerPoint.y
}
self.frame = CGRect(x: x, y: y, width: max(kConnectionStrokeWidth, width), height: max(kConnectionStrokeWidth, height))
}
override func draw(_ dirtyRect: NSRect) {
super.draw(dirtyRect)
NSBezierPath.defaultLineWidth = kConnectionStrokeWidth
NSColor.darkGray.setStroke()
let line = NSBezierPath()
if Preferences.cutCorners {
if relativePositioning == .quadrantI || relativePositioning == .quadrantIII {
line.move(to: dirtyRect.origin)
line.line(to: NSPoint(x: dirtyRect.maxX, y: dirtyRect.maxY))
} else {
line.move(to: NSPoint(x: dirtyRect.minX, y: dirtyRect.maxY))
line.line(to: NSPoint(x: dirtyRect.maxX, y: dirtyRect.minY))
}
} else {
let kConnectionViewInset: CGFloat = kDimmerStrokeWidth;
if relativePositioning == .quadrantI || relativePositioning == .quadrantIII {
if dirtyRect.width > dirtyRect.height {
line.move(to: NSPoint(x: dirtyRect.minX + kConnectionViewInset, y: dirtyRect.minY + kConnectionViewInset))
line.line(to: NSPoint(x: dirtyRect.minX + kConnectionViewInset, y: dirtyRect.midY))
line.line(to: NSPoint(x: dirtyRect.maxX - kConnectionViewInset, y: dirtyRect.midY))
line.line(to: NSPoint(x: dirtyRect.maxX - kConnectionViewInset, y: dirtyRect.maxY - kConnectionViewInset))
} else {
line.move(to: NSPoint(x: dirtyRect.minX + kConnectionViewInset, y: dirtyRect.minY + kConnectionViewInset))
line.line(to: NSPoint(x: dirtyRect.midX, y: dirtyRect.minY + kConnectionViewInset))
line.line(to: NSPoint(x: dirtyRect.midX, y: dirtyRect.maxY - kConnectionViewInset))
line.line(to: NSPoint(x: dirtyRect.maxX - kConnectionViewInset, y: dirtyRect.maxY - kConnectionViewInset))
}
} else {
if dirtyRect.width > dirtyRect.height {
line.move(to: NSPoint(x: dirtyRect.minX + kConnectionViewInset, y: dirtyRect.maxY - kConnectionViewInset))
line.line(to: NSPoint(x: dirtyRect.minX + kConnectionViewInset, y: dirtyRect.midY))
line.line(to: NSPoint(x: dirtyRect.maxX - kConnectionViewInset, y: dirtyRect.midY))
line.line(to: NSPoint(x: dirtyRect.maxX - kConnectionViewInset, y: dirtyRect.minY + kConnectionViewInset))
} else {
line.move(to: NSPoint(x: dirtyRect.minX + kConnectionViewInset, y: dirtyRect.maxY - kConnectionViewInset))
line.line(to: NSPoint(x: dirtyRect.midX, y: dirtyRect.maxY - kConnectionViewInset))
line.line(to: NSPoint(x: dirtyRect.midX, y: dirtyRect.minY + kConnectionViewInset))
line.line(to: NSPoint(x: dirtyRect.maxX - kConnectionViewInset, y: dirtyRect.minY + kConnectionViewInset))
}
}
}
line.stroke()
}
}
| mit | 763aa2b0ef26db58f8aafe1badb9161b | 42.233766 | 186 | 0.617603 | 4.759114 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/WordPressTest/PostListTableViewHandlerTests.swift | 2 | 1945 | import UIKit
import XCTest
@testable import WordPress
class PostListTableViewHandlerTests: XCTestCase {
func testReturnAResultsControllerForViewingAndOtherWhenSearching() {
let postListHandlerMock = PostListHandlerMock()
let postListHandler = PostListTableViewHandler()
postListHandler.delegate = postListHandlerMock
let defaultResultsController = postListHandler.resultsController
postListHandler.isSearching = true
XCTAssertNotEqual(defaultResultsController, postListHandler.resultsController)
}
}
class PostListHandlerMock: NSObject, WPTableViewHandlerDelegate {
func managedObjectContext() -> NSManagedObjectContext {
return setUpInMemoryManagedObjectContext()
}
func fetchRequest() -> NSFetchRequest<NSFetchRequestResult> {
let a = NSFetchRequest<NSFetchRequestResult>(entityName: String(describing: Post.self))
a.sortDescriptors = [NSSortDescriptor(key: BasePost.statusKeyPath, ascending: true)]
return a
}
func configureCell(_ cell: UITableViewCell, at indexPath: IndexPath) { }
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { }
private func setUpInMemoryManagedObjectContext() -> NSManagedObjectContext {
let managedObjectModel = NSManagedObjectModel.mergedModel(from: [Bundle.main])!
let persistentStoreCoordinator = NSPersistentStoreCoordinator(managedObjectModel: managedObjectModel)
do {
try persistentStoreCoordinator.addPersistentStore(ofType: NSInMemoryStoreType, configurationName: nil, at: nil, options: nil)
} catch {
print("Adding in-memory persistent store failed")
}
let managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = persistentStoreCoordinator
return managedObjectContext
}
}
| gpl-2.0 | ab8380d430987af4e04038977a452d7b | 37.137255 | 137 | 0.752185 | 6.683849 | false | true | false | false |
syoung-smallwisdom/ResearchUXFactory-iOS | ResearchUXFactory/SBATrackedDataSelectionResult.swift | 1 | 3883 | //
// SBATrackedDataResult.swift
// ResearchUXFactory
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import UIKit
open class SBATrackedDataSelectionResult: ORKQuestionResult {
open var selectedItems: [SBATrackedDataObject]?
override init() {
super.init()
}
public override init(identifier: String) {
super.init(identifier: identifier)
self.questionType = .multipleChoice
}
open override var answer: Any? {
get { return selectedItems }
set {
guard let items = newValue as? [SBATrackedDataObject] else {
selectedItems = nil
return
}
selectedItems = items
}
}
// MARK: NSCoding
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.selectedItems = aDecoder.decodeObject(forKey: #keyPath(selectedItems)) as? [SBATrackedDataObject]
}
override open func encode(with aCoder: NSCoder) {
super.encode(with: aCoder)
aCoder.encode(self.selectedItems, forKey: #keyPath(selectedItems))
}
// MARK: NSCopying
override open func copy(with zone: NSZone? = nil) -> Any {
let copy = super.copy(with: zone)
guard let result = copy as? SBATrackedDataSelectionResult else { return copy }
result.selectedItems = self.selectedItems
return result
}
// MARK: Equality
open override func isEqual(_ object: Any?) -> Bool {
guard super.isEqual(object), let obj = object as? SBATrackedDataSelectionResult else { return false }
return SBAObjectEquality(self.selectedItems, obj.selectedItems)
}
override open var hash: Int {
return super.hash ^ SBAObjectHash(self.selectedItems)
}
}
extension SBATrackedDataSelectionResult {
public override func jsonSerializedAnswer() -> SBAAnswerKeyAndValue? {
// Always return a non-nil result for items
let selectedItems: NSArray? = self.selectedItems as NSArray?
let value = selectedItems?.jsonObject() ?? NSArray()
return SBAAnswerKeyAndValue(key: "items", value: value, questionType: .multipleChoice)
}
}
| bsd-3-clause | d0ac9644935605e2f2c871f32da9604b | 36.68932 | 110 | 0.696806 | 4.976923 | false | false | false | false |
kbeyer/Multipeer.Instrument | Multipeer.Instrument/EventLogger.swift | 2 | 1923 | //
// EventLogger.swift
// Multipeer.Instrument
//
// Created by Kyle Beyer on 6/10/14.
// Copyright (c) 2014 Kyle Beyer. All rights reserved.
//
import Foundation
let BASE_API_URL = "http://localhost:3000/"
class EventLogger{
init(){
}
class var shared : EventLogger {
get {
struct Static {
static var instance : EventLogger? = nil
static var token : dispatch_once_t = 0
}
dispatch_once(&Static.token) { Static.instance = EventLogger() }
return Static.instance!
}
}
/*
func log(msg: MPIMessage) {
persist(msg)
}
func persist(message: MPIMessage) {
if (message != nil) {
return //validation
}
// serialize as JSON dictionary
var jsonDict = MTLJSONAdapter.JSONDictionaryFromModel(message)
var messagesUrl = BASE_API_URL.stringByAppendingPathComponent("messages")
var request = NSMutableURLRequest(URL: messagesUrl)
request.HTTPMethod = "POST"
var jsonData = NSJSONSerialization(JSONObjectWithData:jsonDict, options:0, error:nil)
request.HTTPBody = data;
request.addValue("application/json", forHTTPHeaderField:"Content-Type")
var config = NSURLSessionConfiguration.defaultSessionConfiguration()
var urlSession = NSURLSession(configuration:config)
var dataTask = urlSession.dataTaskWithRequest(request, completionHandler:
{ data, response, error in
if (!error) {
var responseArray = NSJSONSerialization.JSONObjectWithData(data, options:0, error:NULL)
NSLog("recieved response")
}
})
dataTask.resume()
}*/
} | mit | 4896ae79a7f2520c06941643646b512a | 26.884058 | 107 | 0.561102 | 5.312155 | false | true | false | false |
Adorkable-forkable/SwiftRecord | Classes/SwiftRecord.swift | 1 | 25968 | //
// SwiftRecord.swift
//
// ark - http://www.arkverse.com
// Created by Zaid on 5/7/15.
//
//
import Foundation
import CoreData
public class SwiftRecord {
public static var generateRelationships = false
public static func setUpEntities(entities: [String:NSManagedObject.Type]) {
nameToEntities = entities
}
private static var nameToEntities: [String:NSManagedObject.Type] = [String:NSManagedObject.Type]()
}
public class CoreDataManager {
public let appName = NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String
public var databaseName: String {
get {
if let db = self._databaseName {
return db
} else {
return self.appName + ".sqlite"
}
}
set {
_databaseName = newValue
if _managedObjectContext != nil {
_managedObjectContext = nil
}
if _persistentStoreCoordinator != nil {
_persistentStoreCoordinator = nil
}
}
}
private var _databaseName: String?
public var modelName: String {
get {
if let model = _modelName {
return model
} else {
return appName
}
}
set {
_modelName = newValue
if _managedObjectContext != nil {
_managedObjectContext = nil
}
if _persistentStoreCoordinator != nil {
_persistentStoreCoordinator = nil
}
}
}
private var _modelName: String?
public var managedObjectContext: NSManagedObjectContext {
get {
if let context = _managedObjectContext {
return context
} else {
let c = NSManagedObjectContext(concurrencyType: NSManagedObjectContextConcurrencyType.MainQueueConcurrencyType)
c.persistentStoreCoordinator = persistentStoreCoordinator
_managedObjectContext = c
return c
}
}
set {
_managedObjectContext = newValue
}
}
private var _managedObjectContext: NSManagedObjectContext?
public var persistentStoreCoordinator: NSPersistentStoreCoordinator {
if let store = _persistentStoreCoordinator {
return store
} else {
let p = self.persistentStoreCoordinator(NSSQLiteStoreType, storeURL: self.sqliteStoreURL)
_persistentStoreCoordinator = p
return p
}
}
private var _persistentStoreCoordinator: NSPersistentStoreCoordinator?
public var managedObjectModel: NSManagedObjectModel {
if let m = _managedObjectModel {
return m
} else {
let modelURL = NSBundle.mainBundle().URLForResource(self.modelName, withExtension: "momd")
_managedObjectModel = NSManagedObjectModel(contentsOfURL: modelURL!)
return _managedObjectModel!
}
}
private var _managedObjectModel: NSManagedObjectModel?
public func useInMemoryStore() {
_persistentStoreCoordinator = self.persistentStoreCoordinator(NSInMemoryStoreType, storeURL: nil)
}
public func saveContext() -> Bool {
if !self.managedObjectContext.hasChanges {
return false
}
let error: NSErrorPointer = NSErrorPointer()
if (!self.managedObjectContext.save(error)) {
println("Unresolved error in saving context! " + error.debugDescription)
return false
}
return true
}
public func applicationDocumentsDirectory() -> NSURL {
return NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.DocumentDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last as! NSURL
}
public func applicationSupportDirectory() -> NSURL {
return (NSFileManager.defaultManager().URLsForDirectory(NSSearchPathDirectory.ApplicationSupportDirectory, inDomains: NSSearchPathDomainMask.UserDomainMask).last as! NSURL).URLByAppendingPathComponent(self.appName)
}
private var sqliteStoreURL: NSURL {
#if os(iOS)
let dir = self.applicationDocumentsDirectory()
#else
let dir = self.applicationSupportDirectory()
self.createApplicationSupportDirIfNeeded(dir)
#endif
return dir.URLByAppendingPathComponent(self.databaseName)
}
private func persistentStoreCoordinator(storeType: String, storeURL: NSURL?) -> NSPersistentStoreCoordinator {
let c = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let error = NSErrorPointer()
if c.addPersistentStoreWithType(storeType, configuration: nil, URL: storeURL, options: [NSMigratePersistentStoresAutomaticallyOption:true,NSInferMappingModelAutomaticallyOption:true], error: error) == nil {
println("ERROR WHILE CREATING PERSISTENT STORE COORDINATOR! " + error.debugDescription)
}
return c
}
private func createApplicationSupportDirIfNeeded(dir: NSURL) {
if NSFileManager.defaultManager().fileExistsAtPath(dir.absoluteString!) {
return
}
NSFileManager.defaultManager().createDirectoryAtURL(dir, withIntermediateDirectories: true, attributes: nil, error: nil)
}
// singleton
public static let sharedManager = CoreDataManager()
}
public extension NSManagedObjectContext {
public static var defaultContext: NSManagedObjectContext {
return CoreDataManager.sharedManager.managedObjectContext
}
}
public extension NSManagedObject {
//Querying
public static func all() -> [NSManagedObject] {
return self.all(context: NSManagedObjectContext.defaultContext)
}
public static func all(#sort: AnyObject) -> [NSManagedObject] {
return self.all(context: NSManagedObjectContext.defaultContext, withSort:sort)
}
public static func all(#context: NSManagedObjectContext) -> [NSManagedObject] {
return self.all(context: context, withSort: nil)
}
public static func all(#context: NSManagedObjectContext, withSort sort: AnyObject?) -> [NSManagedObject] {
return self.fetch(nil, context: context, sort: sort, limit: nil)
}
public static func findOrCreate(properties: [String:AnyObject]) -> NSManagedObject {
return self.findOrCreate(properties, context: NSManagedObjectContext.defaultContext)
}
public static func findOrCreate(properties: [String:AnyObject], context: NSManagedObjectContext) -> NSManagedObject {
let transformed = self.transformProperties(properties, context: context)
let existing: NSManagedObject? = self.query(transformed, context: context).first
return existing ?? self.create(transformed, context:context)
}
public static func find(condition: AnyObject, args: AnyObject...) -> NSManagedObject? {
let predicate: NSPredicate = self.predicate(condition, args: args);
return self.find(predicate, context: NSManagedObjectContext.defaultContext)
}
public static func find(condition: AnyObject, context: NSManagedObjectContext) -> NSManagedObject? {
return self.query(condition, context: context, sort:nil, limit:1).first
}
public static func query(condition: AnyObject, args: AnyObject...) -> [NSManagedObject] {
let predicate: NSPredicate = self.predicate(condition, args: args)
return self.query(predicate, context:NSManagedObjectContext.defaultContext)
}
public static func query(condition: AnyObject, sort: AnyObject) -> [NSManagedObject] {
return self.query(condition, context: NSManagedObjectContext.defaultContext, sort: sort)
}
public static func query(condition: AnyObject, limit: Int) -> [NSManagedObject] {
return self.query(condition, context: NSManagedObjectContext.defaultContext, sort:nil, limit: limit)
}
public static func query(condition: AnyObject, sort: AnyObject, limit: Int) -> [NSManagedObject] {
return self.query(condition, context: NSManagedObjectContext.defaultContext, sort: sort, limit: limit)
}
public static func query(condition: AnyObject, context: NSManagedObjectContext) -> [NSManagedObject] {
return self.query(condition, context: context, sort: nil, limit: nil)
}
public static func query(condition: AnyObject, context: NSManagedObjectContext, sort: AnyObject) -> [NSManagedObject] {
return self.query(condition, context: context, sort: sort, limit: nil)
}
public static func query(condition: AnyObject, context: NSManagedObjectContext, sort: AnyObject?, limit: Int?) -> [NSManagedObject] {
return self.fetch(condition, context: context, sort: sort, limit: limit)
}
// Aggregation
public static func count() -> Int {
return self.count(NSManagedObjectContext.defaultContext)
}
public static func count(#query: AnyObject, args: AnyObject...) -> Int {
let predicate = self.predicate(query, args: args)
return self.count(query: predicate, context:NSManagedObjectContext.defaultContext)
}
public static func count(context: NSManagedObjectContext) -> Int {
return self.countForFetch(nil, context: context)
}
public static func count(#query: AnyObject, context: NSManagedObjectContext) -> Int {
return self.countForFetch(self.predicate(query), context: context)
}
// Creation / Deletion
public static func create() -> NSManagedObject {
return self.create(context: NSManagedObjectContext.defaultContext)
}
public static func create(#context: NSManagedObjectContext) -> NSManagedObject {
let o = NSEntityDescription.insertNewObjectForEntityForName(self.entityName(), inManagedObjectContext: context) as! NSManagedObject
if let idprop = self.autoIncrementingId() {
o.setPrimitiveValue(NSNumber(integer: self.nextId()), forKey: idprop)
}
return o
}
public static func create(#properties: [String:AnyObject]) -> NSManagedObject {
return self.create(properties, context: NSManagedObjectContext.defaultContext)
}
public static func create(properties: [String:AnyObject], context: NSManagedObjectContext) -> NSManagedObject {
let newEntity: NSManagedObject = self.create(context: context)
newEntity.update(properties)
if let idprop = self.autoIncrementingId() {
if newEntity.primitiveValueForKey(idprop) == nil {
newEntity.setPrimitiveValue(NSNumber(integer: self.nextId()), forKey: idprop)
}
}
return newEntity
}
public static func autoIncrements() -> Bool {
return self.autoIncrementingId() != nil
}
public static func nextId() -> Int {
let key = "SwiftRecord-" + self.entityName() + "-ID"
if let idprop = self.autoIncrementingId() {
let id = NSUserDefaults.standardUserDefaults().integerForKey(key)
NSUserDefaults.standardUserDefaults().setInteger(id + 1, forKey: key)
return id
}
return 0
}
public func update(properties: [String:AnyObject]) {
if (properties.count == 0) {
return
}
let context = self.managedObjectContext ?? NSManagedObjectContext.defaultContext
let transformed = self.dynamicType.transformProperties(properties, context: context)
//Finish
for (key, value) in transformed {
self.willChangeValueForKey(key)
self.setSafeValue(value, forKey: key)
self.didChangeValueForKey(key)
}
}
public func save() -> Bool {
return self.saveTheContext()
}
public func delete() {
self.managedObjectContext!.deleteObject(self)
}
public static func deleteAll() {
self.deleteAll(NSManagedObjectContext.defaultContext)
}
public static func deleteAll(context: NSManagedObjectContext) {
for o in self.all(context: context) {
o.delete()
}
}
public class func autoIncrementingId() -> String? {
return nil
}
public static func entityName() -> String {
var name = NSStringFromClass(self)
if name.rangeOfString(".") != nil {
let comp = split(name) {$0 == "."}
if comp.count > 1 {
name = comp.last!
}
}
if name.rangeOfString("_") != nil {
var comp = split(name) {$0 == "_"}
var last: String = ""
var remove = -1
for (i,s) in enumerate(comp.reverse()) {
if last == s {
remove = i
}
last = s
}
if remove > -1 {
comp.removeAtIndex(remove)
name = "_".join(comp)
}
}
return name
}
//Private
private static func transformProperties(properties: [String:AnyObject], context: NSManagedObjectContext) -> [String:AnyObject]{
let entity = NSEntityDescription.entityForName(self.entityName(), inManagedObjectContext: context)!
let attrs = entity.attributesByName
let rels = entity.relationshipsByName
var transformed = [String:AnyObject]()
for (key, value) in properties {
let localKey = self.keyForRemoteKey(key, context: context)
if attrs[localKey] != nil {
transformed[localKey] = value
} else if let rel = rels[localKey] as? NSRelationshipDescription {
if SwiftRecord.generateRelationships {
if rel.toMany {
if let array = value as? [[String:AnyObject]] {
transformed[localKey] = self.generateSet(rel, array: array, context: context)
} else {
#if DEBUG
println("Invalid value for relationship generation in \(NSStringFromClass(self)).\(localKey)")
println(value)
#endif
}
} else if let dict = value as? [String:AnyObject] {
transformed[localKey] = self.generateObject(rel, dict: dict, context: context)
} else {
#if DEBUG
println("Invalid value for relationship generation in \(NSStringFromClass(self)).\(localKey)")
println(value)
#endif
}
}
}
}
return transformed
}
private static func predicate(properties: [String:AnyObject]) -> NSPredicate {
var preds = [NSPredicate]()
for (key, value) in properties {
preds.append(NSPredicate(format: "%K = %@", argumentArray: [key, value]))
}
return NSCompoundPredicate(type: NSCompoundPredicateType.AndPredicateType, subpredicates: preds)
}
private static func predicate(condition: AnyObject) -> NSPredicate {
return self.predicate(condition, args: nil)
}
private static func predicate(condition: AnyObject, args: [AnyObject]?) -> NSPredicate {
if condition is NSPredicate {
return condition as! NSPredicate
}
if condition is String {
return NSPredicate(format: condition as! String, argumentArray: args)
}
if let d = condition as? [String:AnyObject] {
return self.predicate(d)
}
return NSPredicate()
}
private static func sortDescriptor(o: AnyObject) -> NSSortDescriptor {
if let s = o as? String {
return self.sortDescriptor(o)
}
if let d = o as? NSSortDescriptor {
return d
}
if let d = o as? [String:AnyObject] {
return self.sortDescriptor(d)
}
return NSSortDescriptor()
}
private static func sortDescriptor(dict: [String:AnyObject]) -> NSSortDescriptor {
let isAscending = (dict.values.first as! String).uppercaseString != "DESC"
return NSSortDescriptor(key: dict.keys.first!, ascending: isAscending)
}
private static func sortDescriptor(string: String) -> NSSortDescriptor {
var key = string
let components = split(string) {$0 == " "}
var isAscending = true
if (components.count > 1) {
key = components[0]
isAscending = components[1] == "ASC"
}
return NSSortDescriptor(key: key, ascending: isAscending)
}
private static func sortDescriptors(d: AnyObject) -> [NSSortDescriptor] {
if let ds = d as? [NSSortDescriptor] {
return ds
}
if let s = d as? String {
return self.sortDescriptors(s)
}
if let dicts = d as? [[String:AnyObject]] {
return self.sortDescriptors(dicts)
}
return [self.sortDescriptor(d)]
}
private static func sortDescriptors(s: String) -> [NSSortDescriptor]{
let components = split(s) {$0 == ","}
var ds = [NSSortDescriptor]()
for sub in components {
ds.append(self.sortDescriptor(sub))
}
return ds
}
private static func sortDescriptors(ds: [NSSortDescriptor]) -> [NSSortDescriptor] {
return ds
}
private static func sortDescriptors(ds: [[String:AnyObject]]) -> [NSSortDescriptor] {
var ret = [NSSortDescriptor]()
for d in ds {
ret.append(self.sortDescriptor(d))
}
return ret
}
private static func createFetchRequest(context: NSManagedObjectContext) -> NSFetchRequest {
let request = NSFetchRequest()
request.entity = NSEntityDescription.entityForName(self.entityName(), inManagedObjectContext: context)
return request
}
private static func fetch(condition: AnyObject?, context: NSManagedObjectContext, sort: AnyObject?, limit: Int?) -> [NSManagedObject] {
let request = self.createFetchRequest(context)
if let cond: AnyObject = condition {
request.predicate = self.predicate(cond)
}
if let ord: AnyObject = sort {
request.sortDescriptors = self.sortDescriptors(ord)
}
if let lim = limit {
request.fetchLimit = lim
}
return context.executeFetchRequest(request, error: nil) as! [NSManagedObject]
}
private static func countForFetch(predicate: NSPredicate?, context: NSManagedObjectContext) -> Int {
let request = self.createFetchRequest(context)
request.predicate = predicate
return context.countForFetchRequest(request, error: nil)
}
private static func count(predicate: NSPredicate, context: NSManagedObjectContext) -> Int {
let request = self.createFetchRequest(context)
request.predicate = predicate
return context.countForFetchRequest(request, error: nil)
}
private func saveTheContext() -> Bool {
if self.managedObjectContext == nil || !self.managedObjectContext!.hasChanges {
return true
}
let error = NSErrorPointer()
let save = self.managedObjectContext!.save(error)
if (!save) {
println("Unresolved error in saving context for entity:")
println(self)
println("!\nError: " + error.debugDescription)
return false
}
return true
}
private func setSafeValue(value: AnyObject?, forKey key: String) {
if (value == nil) {
self.setNilValueForKey(key)
return
}
let val: AnyObject = value!
if let attr = self.entity.attributesByName[key] as? NSAttributeDescription {
let attrType = attr.attributeType
if attrType == NSAttributeType.StringAttributeType && value is NSNumber {
self.setPrimitiveValue((val as! NSNumber).stringValue, forKey: key)
} else if let s = val as? String {
if self.isIntegerAttributeType(attrType) {
self.setPrimitiveValue(NSNumber(integer: val.integerValue), forKey: key)
return
} else if attrType == NSAttributeType.BooleanAttributeType {
self.setPrimitiveValue(NSNumber(bool: val.boolValue), forKey: key)
return
} else if (attrType == NSAttributeType.FloatAttributeType) {
self.setPrimitiveValue(NSNumber(floatLiteral: val.doubleValue), forKey: key)
return
} else if (attrType == NSAttributeType.DateAttributeType) {
self.setPrimitiveValue(self.dynamicType.dateFormatter.dateFromString(s), forKey: key)
return
}
}
}
self.setPrimitiveValue(value, forKey: key)
}
private func isIntegerAttributeType(attrType: NSAttributeType) -> Bool {
return attrType == NSAttributeType.Integer16AttributeType || attrType == NSAttributeType.Integer32AttributeType || attrType == NSAttributeType.Integer64AttributeType
}
private static var dateFormatter: NSDateFormatter {
if _dateFormatter == nil {
_dateFormatter = NSDateFormatter()
_dateFormatter!.dateFormat = "yyyy-MM-dd HH:mm:ss z"
}
return _dateFormatter!
}
private static var _dateFormatter: NSDateFormatter?
}
public extension NSManagedObject {
public class func mappings() -> [String:String] {
return [String:String]()
}
public static func keyForRemoteKey(remote: String, context: NSManagedObjectContext) -> String {
if let s = cachedMappings[remote] {
return s
}
let entity = NSEntityDescription.entityForName(self.entityName(), inManagedObjectContext: context)!
let properties = entity.propertiesByName
if properties[entity.propertiesByName] != nil {
_cachedMappings![remote] = remote
return remote
}
let camelCased = remote.camelCase
if properties[camelCased] != nil {
_cachedMappings![remote] = camelCased
return camelCased
}
_cachedMappings![remote] = remote
return remote
}
private static var cachedMappings: [String:String] {
if let m = _cachedMappings {
return m
} else {
var m = [String:String]()
for (key, value) in mappings() {
m[value] = key
}
_cachedMappings = m
return m
}
}
private static var _cachedMappings: [String:String]?
private static func generateSet(rel: NSRelationshipDescription, array: [[String:AnyObject]], context: NSManagedObjectContext) -> NSSet {
var cls: NSManagedObject.Type?
if SwiftRecord.nameToEntities.count > 0 {
cls = SwiftRecord.nameToEntities[rel.destinationEntity!.managedObjectClassName]
}
if cls == nil {
cls = (NSClassFromString(rel.destinationEntity!.managedObjectClassName) as! NSManagedObject.Type)
} else {
println("Got class name from entity setup")
}
var set = NSMutableSet()
for d in array {
set.addObject(cls!.findOrCreate(d, context: context))
}
return set
}
private static func generateObject(rel: NSRelationshipDescription, dict: [String:AnyObject], context: NSManagedObjectContext) -> NSManagedObject {
var entity = rel.destinationEntity!
var cls: NSManagedObject.Type = NSClassFromString(entity.managedObjectClassName) as! NSManagedObject.Type
return cls.findOrCreate(dict, context: context)
}
public static func primaryKey() -> String {
NSException(name: "Primary key undefined in " + NSStringFromClass(self), reason: "Override primaryKey if you want to support automatic creation, otherwise disable this feature", userInfo: nil).raise()
return ""
}
}
private extension String {
var camelCase: String {
let spaced = self.stringByReplacingOccurrencesOfString("_", withString: " ", options: nil, range:Range<String.Index>(start: self.startIndex, end: self.endIndex))
let capitalized = spaced.capitalizedString
let spaceless = capitalized.stringByReplacingOccurrencesOfString(" ", withString: "", options:nil, range:Range<String.Index>(start:self.startIndex, end:self.endIndex))
return spaceless.stringByReplacingCharactersInRange(Range<String.Index>(start:spaceless.startIndex, end:spaceless.startIndex.successor()), withString: "\(spaceless[spaceless.startIndex])".lowercaseString)
}
}
extension NSObject {
// create a static method to get a swift class for a string name
class func swiftClassFromString(className: String) -> AnyClass! {
// get the project name
if var appName: String? = NSBundle.mainBundle().objectForInfoDictionaryKey("CFBundleName") as? String {
// generate the full name of your class (take a look into your "YourProject-swift.h" file)
let classStringName = "_TtC\(count(appName!.utf16))\(appName)\(count(className))\(className)"
// return the class!
return NSClassFromString(classStringName)
}
return nil;
}
} | mit | 46e87167a86b1689b41799255bc94077 | 37.817638 | 222 | 0.620764 | 5.493548 | false | false | false | false |
insidegui/WWDC | WWDC/ClipComposition.swift | 1 | 5514 | //
// ClipComposition.swift
// WWDC
//
// Created by Guilherme Rambo on 02/06/20.
// Copyright © 2020 Guilherme Rambo. All rights reserved.
//
import Cocoa
import AVFoundation
import CoreMedia
import CoreImage.CIFilterBuiltins
final class ClipComposition: AVMutableComposition {
private struct Constants {
static let minBoxWidth: CGFloat = 325
static let maxBoxWidth: CGFloat = 600
static let boxPadding: CGFloat = 42
}
let title: String
let subtitle: String
let video: AVAsset
let includeBanner: Bool
var videoComposition: AVMutableVideoComposition?
init(video: AVAsset, title: String, subtitle: String, includeBanner: Bool) throws {
self.video = video
self.title = title
self.subtitle = subtitle
self.includeBanner = includeBanner
super.init()
guard let newVideoTrack = addMutableTrack(withMediaType: .video, preferredTrackID: kCMPersistentTrackID_Invalid) else {
// Should this ever fail in real life? Who knows...
preconditionFailure("Failed to add video track to composition")
}
if let videoTrack = video.tracks(withMediaType: .video).first {
try newVideoTrack.insertTimeRange(CMTimeRange(start: .zero, duration: video.duration), of: videoTrack, at: .zero)
}
if let newAudioTrack = addMutableTrack(withMediaType: .audio, preferredTrackID: kCMPersistentTrackID_Invalid) {
if let audioTrack = video.tracks(withMediaType: .audio).first {
try newAudioTrack.insertTimeRange(CMTimeRange(start: .zero, duration: video.duration), of: audioTrack, at: .zero)
}
}
configureCompositionIfNeeded(videoTrack: newVideoTrack)
}
private func configureCompositionIfNeeded(videoTrack: AVMutableCompositionTrack) {
guard includeBanner else { return }
let mainInstruction = AVMutableVideoCompositionInstruction()
mainInstruction.timeRange = CMTimeRange(start: .zero, duration: video.duration)
let videolayerInstruction = AVMutableVideoCompositionLayerInstruction(assetTrack: videoTrack)
mainInstruction.layerInstructions = [videolayerInstruction]
videoComposition = AVMutableVideoComposition(propertiesOf: video)
videoComposition?.instructions = [mainInstruction]
composeTemplate(with: videoTrack.naturalSize)
}
private func composeTemplate(with renderSize: CGSize) {
guard let asset = CALayer.load(assetNamed: "ClipTemplate") else {
fatalError("Missing ClipTemplate asset")
}
guard let assetContainer = asset.sublayer(named: "container", of: CALayer.self) else {
fatalError("Missing container layer")
}
guard let box = assetContainer.sublayer(named: "box", of: CALayer.self) else {
fatalError("Missing box layer")
}
guard let titleLayer = box.sublayer(named: "sessionTitle", of: CATextLayer.self) else {
fatalError("Missing sessionTitle layer")
}
guard let subtitleLayer = box.sublayer(named: "eventName", of: CATextLayer.self) else {
fatalError("Missing sessionTitle layer")
}
guard let videoLayer = assetContainer.sublayer(named: "video", of: CALayer.self) else {
fatalError("Missing video layer")
}
if let iconLayer = box.sublayer(named: "appicon", of: CALayer.self) {
iconLayer.contents = NSApp.applicationIconImage
}
// Add a NSVisualEffectView-like blur to the box.
let blur = CIFilter.gaussianBlur()
blur.radius = 22
let saturate = CIFilter.colorControls()
saturate.setDefaults()
saturate.saturation = 1.5
box.backgroundFilters = [saturate, blur]
box.masksToBounds = true
// Set text on layers.
titleLayer.string = attributedTitle
subtitleLayer.string = attributedSubtitle
// Compute final box/title layer widths based on title.
let titleSize = attributedTitle.size()
if titleSize.width > titleLayer.bounds.width {
var boxFrame = box.frame
boxFrame.size.width = titleSize.width + Constants.boxPadding * 3
box.frame = boxFrame
var titleFrame = titleLayer.frame
titleFrame.size.width = titleSize.width
titleLayer.frame = titleFrame
}
let container = CALayer()
container.frame = CGRect(origin: .zero, size: renderSize)
container.addSublayer(assetContainer)
container.resizeLayer(assetContainer)
assetContainer.isGeometryFlipped = true
videoComposition?.animationTool = AVVideoCompositionCoreAnimationTool(postProcessingAsVideoLayer: videoLayer, in: container)
box.sublayers?.compactMap({ $0 as? CATextLayer }).forEach { layer in
layer.minificationFilter = .trilinear
// Workaround rdar://32718905
layer.display()
}
}
private lazy var attributedTitle: NSAttributedString = {
NSAttributedString.create(
with: title,
font: .wwdcRoundedSystemFont(ofSize: 16, weight: .medium),
color: .white
)
}()
private lazy var attributedSubtitle: NSAttributedString = {
NSAttributedString.create(
with: subtitle,
font: .systemFont(ofSize: 13, weight: .medium),
color: .white
)
}()
}
| bsd-2-clause | 210f12be8983fc4dbfcad98f1f877500 | 34.11465 | 132 | 0.657537 | 5.099907 | false | false | false | false |
themonki/onebusaway-iphone | Carthage/Checkouts/PromiseKit/Tests/CorePromise/03_WhenTests.swift | 3 | 7847 | import PromiseKit
import XCTest
class WhenTests: XCTestCase {
func testEmpty() {
let e = expectation(description: "")
let promises: [Promise<Void>] = []
when(fulfilled: promises).then { _ in
e.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testInt() {
let e1 = expectation(description: "")
let p1 = Promise(value: 1)
let p2 = Promise(value: 2)
let p3 = Promise(value: 3)
let p4 = Promise(value: 4)
when(fulfilled: [p1, p2, p3, p4]).then { (x: [Int])->() in
XCTAssertEqual(x[0], 1)
XCTAssertEqual(x[1], 2)
XCTAssertEqual(x[2], 3)
XCTAssertEqual(x[3], 4)
XCTAssertEqual(x.count, 4)
e1.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testDoubleTuple() {
let e1 = expectation(description: "")
let p1 = Promise(value: 1)
let p2 = Promise(value: "abc")
when(fulfilled: p1, p2).then{ x, y -> Void in
XCTAssertEqual(x, 1)
XCTAssertEqual(y, "abc")
e1.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testTripleTuple() {
let e1 = expectation(description: "")
let p1 = Promise(value: 1)
let p2 = Promise(value: "abc")
let p3 = Promise(value: 1.0)
when(fulfilled: p1, p2, p3).then { u, v, w -> Void in
XCTAssertEqual(1, u)
XCTAssertEqual("abc", v)
XCTAssertEqual(1.0, w)
e1.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testQuadrupleTuple() {
let e1 = expectation(description: "")
let p1 = Promise(value: 1)
let p2 = Promise(value: "abc")
let p3 = Promise(value: 1.0)
let p4 = Promise(value: true)
when(fulfilled: p1, p2, p3, p4).then { u, v, w, x -> Void in
XCTAssertEqual(1, u)
XCTAssertEqual("abc", v)
XCTAssertEqual(1.0, w)
XCTAssertEqual(true, x)
e1.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testQuintupleTuple() {
let e1 = expectation(description: "")
let p1 = Promise(value: 1)
let p2 = Promise(value: "abc")
let p3 = Promise(value: 1.0)
let p4 = Promise(value: true)
let p5 = Promise(value: "a" as Character)
when(fulfilled: p1, p2, p3, p4, p5).then { u, v, w, x, y -> Void in
XCTAssertEqual(1, u)
XCTAssertEqual("abc", v)
XCTAssertEqual(1.0, w)
XCTAssertEqual(true, x)
XCTAssertEqual("a" as Character, y)
e1.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testVoid() {
let e1 = expectation(description: "")
let p1 = Promise(value: 1).then { x -> Void in }
let p2 = Promise(value: 2).then { x -> Void in }
let p3 = Promise(value: 3).then { x -> Void in }
let p4 = Promise(value: 4).then { x -> Void in }
when(fulfilled: p1, p2, p3, p4).then(execute: e1.fulfill)
waitForExpectations(timeout: 1, handler: nil)
}
func testRejected() {
enum Error: Swift.Error { case dummy }
let e1 = expectation(description: "")
let p1 = after(interval: .milliseconds(100)).then{ true }
let p2 = after(interval: .milliseconds(200)).then{ throw Error.dummy }
let p3 = Promise(value: false)
when(fulfilled: p1, p2, p3).catch { _ in
e1.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testProgress() {
let ex = expectation(description: "")
XCTAssertNil(Progress.current())
let p1 = after(interval: .milliseconds(10))
let p2 = after(interval: .milliseconds(20))
let p3 = after(interval: .milliseconds(30))
let p4 = after(interval: .milliseconds(40))
let progress = Progress(totalUnitCount: 1)
progress.becomeCurrent(withPendingUnitCount: 1)
when(fulfilled: p1, p2, p3, p4).then { _ -> Void in
XCTAssertEqual(progress.completedUnitCount, 1)
ex.fulfill()
}
progress.resignCurrent()
waitForExpectations(timeout: 1, handler: nil)
}
func testProgressDoesNotExceed100Percent() {
let ex1 = expectation(description: "")
let ex2 = expectation(description: "")
XCTAssertNil(Progress.current())
let p1 = after(interval: .milliseconds(10))
let p2: Promise<Void> = after(interval: .milliseconds(20)).then { throw NSError(domain: "a", code: 1, userInfo: nil) }
let p3 = after(interval: .milliseconds(30))
let p4 = after(interval: .milliseconds(40))
let progress = Progress(totalUnitCount: 1)
progress.becomeCurrent(withPendingUnitCount: 1)
let promise: Promise<Void> = when(fulfilled: p1, p2, p3, p4)
progress.resignCurrent()
promise.catch { _ in
ex2.fulfill()
}
var x = 0
func finally() {
x += 1
if x == 4 {
XCTAssertLessThanOrEqual(1, progress.fractionCompleted)
XCTAssertEqual(progress.completedUnitCount, 1)
ex1.fulfill()
}
}
let q = DispatchQueue.main
p1.always(on: q, execute: finally)
p2.always(on: q, execute: finally)
p3.always(on: q, execute: finally)
p4.always(on: q, execute: finally)
waitForExpectations(timeout: 1, handler: nil)
}
func testUnhandledErrorHandlerDoesNotFire() {
enum Error: Swift.Error {
case test
}
InjectedErrorUnhandler = { error in
XCTFail()
}
let ex = expectation(description: "")
let p1 = Promise<Void>(error: Error.test)
let p2 = after(interval: .milliseconds(100))
when(fulfilled: p1, p2).then{ XCTFail() }.catch { error in
XCTAssertTrue(error as? Error == Error.test)
ex.fulfill()
}
waitForExpectations(timeout: 1, handler: nil)
}
func testUnhandledErrorHandlerDoesNotFireForStragglers() {
enum Error: Swift.Error {
case test
case straggler
}
InjectedErrorUnhandler = { error in
XCTFail()
}
let ex1 = expectation(description: "")
let ex2 = expectation(description: "")
let ex3 = expectation(description: "")
let p1 = Promise<Void>(error: Error.test)
let p2 = after(interval: .milliseconds(100)).then { throw Error.straggler }
let p3 = after(interval: .milliseconds(200)).then { throw Error.straggler }
when(fulfilled: p1, p2, p3).catch { error -> Void in
XCTAssertTrue(Error.test == error as? Error)
ex1.fulfill()
}
p2.always { after(interval: .milliseconds(100)).then(execute: ex2.fulfill) }
p3.always { after(interval: .milliseconds(100)).then(execute: ex3.fulfill) }
waitForExpectations(timeout: 1, handler: nil)
}
func testAllSealedRejectedFirstOneRejects() {
enum Error: Swift.Error {
case test1
case test2
case test3
}
let ex = expectation(description: "")
let p1 = Promise<Void>(error: Error.test1)
let p2 = Promise<Void>(error: Error.test2)
let p3 = Promise<Void>(error: Error.test3)
when(fulfilled: p1, p2, p3).catch { error in
XCTAssertTrue(error as? Error == Error.test1)
ex.fulfill()
}
waitForExpectations(timeout: 1)
}
}
| apache-2.0 | c4890f43e4faa34f8146169c0de22873 | 30.138889 | 126 | 0.554989 | 3.99949 | false | true | false | false |
rdm0423/Hydrate | Pods/IQKeyboardManagerSwift/IQKeyboardManagerSwift/IQTextView/IQTextView.swift | 16 | 4272 | //
// IQTextView.swift
// https://github.com/hackiftekhar/IQKeyboardManager
// Copyright (c) 2013-15 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
/** @abstract UITextView with placeholder support */
public class IQTextView : UITextView {
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshPlaceholder", name: UITextViewTextDidChangeNotification, object: self)
}
override init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshPlaceholder", name: UITextViewTextDidChangeNotification, object: self)
}
override public func awakeFromNib() {
super.awakeFromNib()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "refreshPlaceholder", name: UITextViewTextDidChangeNotification, object: self)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
private var placeholderLabel: UILabel?
/** @abstract To set textView's placeholder text. Default is ni. */
public var placeholder : String? {
get {
return placeholderLabel?.text
}
set {
if placeholderLabel == nil {
placeholderLabel = UILabel(frame: CGRectInset(self.bounds, 5, 0))
if let unwrappedPlaceholderLabel = placeholderLabel {
unwrappedPlaceholderLabel.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
unwrappedPlaceholderLabel.lineBreakMode = .ByWordWrapping
unwrappedPlaceholderLabel.numberOfLines = 0
unwrappedPlaceholderLabel.font = self.font
unwrappedPlaceholderLabel.backgroundColor = UIColor.clearColor()
unwrappedPlaceholderLabel.textColor = UIColor(white: 0.7, alpha: 1.0)
unwrappedPlaceholderLabel.alpha = 0
addSubview(unwrappedPlaceholderLabel)
}
}
placeholderLabel?.text = newValue
refreshPlaceholder()
}
}
private func refreshPlaceholder() {
if text.characters.count != 0 {
placeholderLabel?.alpha = 0
} else {
placeholderLabel?.alpha = 1
}
}
override public var text: String! {
didSet {
refreshPlaceholder()
}
}
override public var font : UIFont? {
didSet {
if let unwrappedFont = font {
placeholderLabel?.font = unwrappedFont
} else {
placeholderLabel?.font = UIFont.systemFontOfSize(12)
}
}
}
override public var delegate : UITextViewDelegate? {
get {
refreshPlaceholder()
return super.delegate
}
set {
}
}
}
| mit | 4ea72fbc1d72499cf5f06f2589310ce9 | 33.176 | 151 | 0.62617 | 5.876204 | false | false | false | false |
rchatham/PeerConnectivity | Sources/PeerConnectionResponder.swift | 1 | 3410 | //
// PeerConnectionResponder.swift
// PeerConnectivity
//
// Created by Reid Chatham on 12/25/15.
// Copyright © 2015 Reid Chatham. All rights reserved.
//
import Foundation
/**
Network events that can be responded to via PeerConnectivity.
*/
public enum PeerConnectionEvent {
/**
Event sent when the `PeerConnectionManager` is ready to start.
*/
case ready
/**
Signals the `PeerConnectionManager` was started succesfully.
*/
case started
/**
Devices changed event which returns the `Peer` that changed along with the connected `Peer`s. Check the passed `Peer`'s `Status` to see what changed.
*/
case devicesChanged(peer: Peer, connectedPeers: [Peer])
/**
Data received from `Peer`.
*/
case receivedData(peer: Peer, data: Data)
/**
Event received from `Peer`.
*/
case receivedEvent(peer: Peer, eventInfo: [String:Any])
/**
Data stream received from `Peer`.
*/
case receivedStream(peer: Peer, stream: Stream, name: String)
/**
Started receiving a resource from `Peer` with name and `NSProgress`.
*/
case startedReceivingResource(peer: Peer, name: String, progress: Progress)
/**
Finished receiving resource from `Peer` with name at url with optional error.
*/
case finishedReceivingResource(peer: Peer, name: String, url: URL, error: Error?)
/**
Received security certificate from `Peer` with handler.
*/
case receivedCertificate(peer: Peer, certificate: [Any]?, handler: (Bool)->Void)
/**
Received a `PeerConnectionError`.
*/
case error(Error)
/**
`PeerConnectionManager` was succesfully stopped.
*/
case ended
/**
Found nearby `Peer`.
*/
case foundPeer(peer: Peer)
/**
Lost nearby `Peer`.
*/
case lostPeer(peer: Peer)
/**
Nearby peers changed.
*/
case nearbyPeersChanged(foundPeers: [Peer])
/**
Received invitation from `Peer` with optional context data and invitation handler.
*/
case receivedInvitation(peer: Peer, withContext: Data?, invitationHandler: (Bool)->Void)
}
/**
Listener for responding to `PeerConnectionEvent`s.
*/
public typealias PeerConnectionEventListener = (PeerConnectionEvent)->Void
internal class PeerConnectionResponder {
fileprivate let peerEventObserver : MultiObservable<PeerConnectionEvent>
internal fileprivate(set) var listeners : [String:PeerConnectionEventListener] = [:]
internal init(observer: MultiObservable<PeerConnectionEvent>) {
peerEventObserver = observer
}
@discardableResult internal func addListener(_ listener: @escaping PeerConnectionEventListener, forKey key: String) -> PeerConnectionResponder {
listeners[key] = listener
peerEventObserver.addObserver(listener, key: key)
return self
}
@discardableResult internal func addListeners(_ listeners: [String:PeerConnectionEventListener]) -> PeerConnectionResponder {
listeners.forEach { addListener($0.1, forKey: $0.0) }
return self
}
internal func removeAllListeners() {
listeners = [:]
peerEventObserver.observers = [:]
}
internal func removeListenerForKey(_ key: String) {
listeners.removeValue(forKey: key)
peerEventObserver.observers.removeValue(forKey: key)
}
}
| mit | 65a8b5d91d2b1c48c22692fdea3852cc | 29.4375 | 154 | 0.665591 | 4.787921 | false | false | false | false |
kkolli/MathGame | client/Speedy/GameCircle.swift | 1 | 1777 | //
// GameCircle.swift
// Speedy
//
// Created by Edward Chiou on 2/14/15.
// Copyright (c) 2015 Krishna Kolli. All rights reserved.
//
import SpriteKit
struct GameCircleProperties {
static let nodeRadius: CGFloat = 23
static let nodeStrokeColor = UIColor.blackColor()
static let nodeTextFontSize: CGFloat = 16.0
static let nodeLineWidth: CGFloat = 1
static let nodeFillColor = UIColor(red: 62.0 / 255.0, green: 176.0 / 255.0, blue: 237.0 / 255.0, alpha: 1.0)
static let pickupScaleFactor: CGFloat = 1.2
}
class GameCircle: SKNode{
//var column: Int?
var shapeNode: SKShapeNode?
var neighbor: GameCircle?
var boardPos: Int?
override init() {
super.init()
setupNodes()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func setupNodes() {
shapeNode = SKShapeNode(circleOfRadius: GameCircleProperties.nodeRadius)
shapeNode!.strokeColor = GameCircleProperties.nodeStrokeColor
shapeNode!.lineWidth = GameCircleProperties.nodeLineWidth
shapeNode!.antialiased = true
shapeNode!.fillColor = GameCircleProperties.nodeFillColor
self.addChild(shapeNode!)
}
func setNeighbor(neighborNode: GameCircle){
neighbor = neighborNode
}
func hasNeighbor() -> Bool{
return self.neighbor != nil;
}
func getLeftAnchor() -> CGPoint {
return CGPoint(x: self.position.x - GameCircleProperties.nodeRadius, y: self.position.y)
}
func getRightAnchor() -> CGPoint {
return CGPoint(x: self.position.x + GameCircleProperties.nodeRadius, y: self.position.y)
}
func setBoardPosition(pos: Int) {
boardPos = pos
}
}
| gpl-2.0 | 44efcdd0ca988037ded97e810d2bf051 | 26.338462 | 112 | 0.648846 | 4.344743 | false | false | false | false |
yanagiba/swift-transform | Sources/Transform/Token+Operators.swift | 1 | 2290 | /*
Copyright 2017 Ryuichi Laboratories and the Yanagiba project contributors
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.
*/
public func +(left: Token?, right: Token?) -> [Token] {
var tokens: [Token] = []
if let left = left {
tokens.append(left)
}
if let right = right {
tokens.append(right)
}
return tokens
}
public func +(left: [Token]?, right: Token?) -> [Token] {
var tokens = left ?? []
if let right = right {
tokens.append(right)
}
return tokens
}
public func +(left: [Token]?, right: [Token]?) -> [Token] {
var tokens: [Token] = []
if let left = left {
tokens.append(contentsOf: left)
}
if let right = right {
tokens.append(contentsOf: right)
}
return tokens
}
public func +(left: Token?, right: [Token]?) -> [Token] {
var tokens: [Token] = []
if let left = left {
tokens.append(left)
}
if let right = right {
tokens.append(contentsOf: right)
}
return tokens
}
extension Collection where Iterator.Element == [Token] {
public func joined(token: Token) -> [Token] {
return Array(self.filter { !$0.isEmpty }.flatMap { $0 + token }.dropLast())
}
public func joined() -> [Token] {
return self.flatMap { $0 }
}
}
extension Collection where Iterator.Element == Token {
public func joinedValues() -> String {
return self.map { $0.value }.joined()
}
}
extension Array where Iterator.Element == Token {
public func prefix(with token: Token) -> [Token] {
guard !self.isEmpty else { return self }
return token + self
}
public func suffix(with token: Token) -> [Token] {
guard !self.isEmpty else { return self }
return self + token
}
}
| apache-2.0 | 4479a0acb64825dabcbac31fe8c402f2 | 26.261905 | 83 | 0.622271 | 4.038801 | false | false | false | false |
mbeloded/LoadingViewController | LoadingViewController/Classes/Views/LoadingViews/StrokeLoadingView.swift | 1 | 1396 | //
// StrokeLoadingView.swift
// LoadingControllerDemo
//
// Created by Sapozhnik Ivan on 28.06.16.
// Copyright © 2016 Sapozhnik Ivan. All rights reserved.
//
import UIKit
class StrokeLoadingView: LoadingView, Animatable {
var activity = StrokeActivityView()
override init(frame: CGRect) {
super.init(frame: frame)
defaultInitializer()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
defaultInitializer()
}
private func defaultInitializer() {
let size = CGSize(width: 34, height: 34)
activity.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
addSubview(activity)
}
override func layoutSubviews() {
super.layoutSubviews()
activity.center = CGPoint(x: bounds.midX, y: bounds.midY)
}
func startAnimating() {
let delay = 0.0 * Double(NSEC_PER_SEC)
#if swift(>=2.3)
let time = DispatchTime.now() + delay
DispatchQueue.main.asyncAfter(deadline: time) {
// your code here
self.activity.animating = true
}
#else
let time = DispatchTime.now(dispatch_time(DispatchTime.now(), Int64(delay)))
dispatch_after(time, DispatchQueue.main, {
self.activity.animating = true
})
#endif
}
func stopAnimating() {
activity.animating = false
}
}
| mit | 501c683a0d3c01032730960cdbfc0ad5 | 22.644068 | 88 | 0.622939 | 3.896648 | false | false | false | false |
touyou/Swingle | Swingle/SwingleChords.swift | 1 | 1696 | //
// SwingleChords.swift
// Swingle
//
// Created by 藤井陽介 on 2016/09/01.
// Copyright © 2016年 touyou. All rights reserved.
//
import Foundation
import APIKit
import Himotoki
import Result
public extension Swingle {
/**
GET song/chord.json
Example:
Swingle().getSongChordInfo("URL", success: { chords in
print("first chord: \(chords.chords?[0].name)")
})
*/
func getSongChordInfo(_ url: String, revision: Int? = nil, success: @escaping (Chords) -> Void, failure: ((SessionTaskError) -> Void)? = nil) {
let request = GetSongChordInfo(url: url, revision: revision)
Session.send(request) { result in
switch result {
case .success(let chords):
success(chords)
case .failure(let error):
failure?(error)
print("error: \(SwingleError(statusCode: error._code).message)")
}
}
}
/**
GET song/chord_revisions.json
Example:
Swingle().getChordRevisions("URL", success: { revisions in
print("first chord revision: \(revisions.revisions?[0].updatedAt)")
})
*/
func getChordRevisions(_ url: String, success: @escaping (Revisions) -> Void, failure: ((SessionTaskError) -> Void)? = nil) {
let request = GetChordRevisions(url: url)
Session.send(request) { result in
switch result {
case .success(let revisions):
success(revisions)
case .failure(let error):
failure?(error)
print("error: \(SwingleError(statusCode: error._code).message)")
}
}
}
}
| mit | 1639f0ec5f21212237987222f7fed5b8 | 27.083333 | 147 | 0.568546 | 4.265823 | false | false | false | false |
breadwallet/breadwallet-ios | breadwalletWidget/Extensions/CoinGecko+Extesions.swift | 1 | 1296 | //
// File.swift
// breadwallet
//
// Created by stringcode on 17/02/2021.
// Copyright © 2021 Breadwinner AG. All rights reserved.
//
// See the LICENSE file at the project root for license information.
//
import Foundation
import CoinGecko
extension Resources {
static func chart<MarketChart>(base: String, quote: String, interval: Interval, callback: @escaping Callback<MarketChart>) -> Resource<MarketChart> {
var params = [URLQueryItem(name: "vs_currency", value: quote),
URLQueryItem(name: "days", value: interval.queryVal())]
if interval == .daily {
params.append(URLQueryItem(name: "interval", value: "daily"))
}
return Resource(.coinsMarketChart, method: .GET, pathParam: base, params: params, completion: callback)
}
}
// MARK: - Interval
extension Resources {
enum Interval {
case daily
case minute
func queryVal() -> String {
return self == .daily ? "max" : "1"
}
}
}
// MARK: - IntervalOption
extension IntervalOption {
var resources: Resources.Interval {
switch self {
case .minute:
return .minute
default:
return .daily
}
}
}
| mit | d04abb733ca73b2f726542db75ad0abb | 22.545455 | 154 | 0.5861 | 4.331104 | false | false | false | false |
xusader/firefox-ios | Client/Frontend/Browser/URLBarView.swift | 2 | 23554 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import Shared
import Snap
private struct URLBarViewUX {
// The color shown behind the tabs count button, and underneath the (mostly transparent) status bar.
static let BackgroundColor = UIColor(red: 0.21, green: 0.23, blue: 0.25, alpha: 1)
static let TextFieldBorderColor = UIColor.blackColor().colorWithAlphaComponent(0.05)
static let TextFieldActiveBorderColor = UIColor(rgb: 0x4A90E2)
static let LocationLeftPadding = 5
static let LocationHeight = 30
static let TextFieldCornerRadius: CGFloat = 3
static let TextFieldBorderWidth: CGFloat = 1
// offset from edge of tabs button
static let URLBarCurveOffset: CGFloat = 14
// buffer so we dont see edges when animation overshoots with spring
static let URLBarCurveBounceBuffer: CGFloat = 8
}
protocol URLBarDelegate: class {
func urlBarDidPressTabs(urlBar: URLBarView)
func urlBarDidPressReaderMode(urlBar: URLBarView)
func urlBarDidLongPressReaderMode(urlBar: URLBarView)
func urlBarDidPressStop(urlBar: URLBarView)
func urlBarDidPressReload(urlBar: URLBarView)
func urlBarDidBeginEditing(urlBar: URLBarView)
func urlBarDidEndEditing(urlBar: URLBarView)
func urlBarDidLongPressLocation(urlBar: URLBarView)
func urlBar(urlBar: URLBarView, didEnterText text: String)
func urlBar(urlBar: URLBarView, didSubmitText text: String)
}
class URLBarView: UIView, BrowserLocationViewDelegate, AutocompleteTextFieldDelegate, BrowserToolbarProtocol {
weak var delegate: URLBarDelegate?
private var locationView: BrowserLocationView!
private var editTextField: ToolbarTextField!
private var locationContainer: UIView!
private var tabsButton: UIButton!
private var progressBar: UIProgressView!
private var cancelButton: UIButton!
private var curveShape: CurveView!
weak var browserToolbarDelegate: BrowserToolbarDelegate?
let shareButton = UIButton()
let bookmarkButton = UIButton()
let forwardButton = UIButton()
let backButton = UIButton()
let stopReloadButton = UIButton()
var helper: BrowserToolbarHelper?
var toolbarIsShowing = false
override init(frame: CGRect) {
super.init(frame: frame)
initViews()
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initViews()
}
private func initViews() {
curveShape = CurveView()
self.addSubview(curveShape);
locationContainer = UIView()
locationContainer.setTranslatesAutoresizingMaskIntoConstraints(false)
locationContainer.layer.borderColor = URLBarViewUX.TextFieldBorderColor.CGColor
locationContainer.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius
locationContainer.layer.borderWidth = URLBarViewUX.TextFieldBorderWidth
addSubview(locationContainer)
locationView = BrowserLocationView(frame: CGRectZero)
locationView.setTranslatesAutoresizingMaskIntoConstraints(false)
locationView.readerModeState = ReaderModeState.Unavailable
locationView.delegate = self
locationContainer.addSubview(locationView)
editTextField = ToolbarTextField()
editTextField.keyboardType = UIKeyboardType.WebSearch
editTextField.autocorrectionType = UITextAutocorrectionType.No
editTextField.autocapitalizationType = UITextAutocapitalizationType.None
editTextField.returnKeyType = UIReturnKeyType.Go
editTextField.clearButtonMode = UITextFieldViewMode.WhileEditing
editTextField.layer.backgroundColor = UIColor.whiteColor().CGColor
editTextField.autocompleteDelegate = self
editTextField.font = AppConstants.DefaultMediumFont
editTextField.layer.cornerRadius = URLBarViewUX.TextFieldCornerRadius
editTextField.layer.borderColor = URLBarViewUX.TextFieldActiveBorderColor.CGColor
editTextField.hidden = true
editTextField.accessibilityLabel = NSLocalizedString("Address and Search", comment: "Accessibility label for address and search field, both words (Address, Search) are therefore nouns.")
locationContainer.addSubview(editTextField)
self.progressBar = UIProgressView()
self.progressBar.trackTintColor = self.backgroundColor
self.progressBar.alpha = 0
self.progressBar.hidden = true
self.addSubview(progressBar)
tabsButton = InsetButton()
tabsButton.setTranslatesAutoresizingMaskIntoConstraints(false)
tabsButton.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Normal)
tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility Label for the urlbar tabs button")
tabsButton.titleLabel?.layer.backgroundColor = UIColor.whiteColor().CGColor
tabsButton.titleLabel?.layer.cornerRadius = 2
tabsButton.titleLabel?.font = AppConstants.DefaultSmallFontBold
tabsButton.titleLabel?.textAlignment = NSTextAlignment.Center
tabsButton.titleLabel?.snp_makeConstraints { make in
make.size.equalTo(18)
return
}
tabsButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: UIControlEvents.TouchUpInside)
tabsButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
tabsButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
self.addSubview(tabsButton)
cancelButton = InsetButton()
cancelButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
let cancelTitle = NSLocalizedString("Cancel", comment: "Button label to cancel entering a URL or search query")
cancelButton.setTitle(cancelTitle, forState: UIControlState.Normal)
cancelButton.titleLabel?.font = AppConstants.DefaultMediumFont
cancelButton.addTarget(self, action: "SELdidClickCancel", forControlEvents: UIControlEvents.TouchUpInside)
cancelButton.titleEdgeInsets = UIEdgeInsetsMake(10, 12, 10, 12)
cancelButton.setContentHuggingPriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
cancelButton.setContentCompressionResistancePriority(1000, forAxis: UILayoutConstraintAxis.Horizontal)
self.addSubview(cancelButton)
addSubview(self.shareButton)
addSubview(self.bookmarkButton)
addSubview(self.forwardButton)
addSubview(self.backButton)
addSubview(self.stopReloadButton)
self.helper = BrowserToolbarHelper(toolbar: self)
// Make sure we hide any views that shouldn't be showing in non-editing mode
finishEditingAnimation(false)
}
private func updateToolbarConstraints() {
if toolbarIsShowing {
backButton.snp_remakeConstraints { (make) -> () in
make.left.bottom.equalTo(self)
make.height.equalTo(AppConstants.ToolbarHeight)
make.width.equalTo(AppConstants.ToolbarHeight)
}
backButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
forwardButton.snp_remakeConstraints { (make) -> () in
make.left.equalTo(self.backButton.snp_right)
make.bottom.equalTo(self)
make.height.equalTo(AppConstants.ToolbarHeight)
make.width.equalTo(AppConstants.ToolbarHeight)
}
forwardButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
stopReloadButton.snp_remakeConstraints { (make) -> () in
make.left.equalTo(self.forwardButton.snp_right)
make.bottom.equalTo(self)
make.height.equalTo(AppConstants.ToolbarHeight)
make.width.equalTo(AppConstants.ToolbarHeight)
}
stopReloadButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
shareButton.snp_remakeConstraints { (make) -> () in
make.right.equalTo(self.bookmarkButton.snp_left)
make.bottom.equalTo(self)
make.height.equalTo(AppConstants.ToolbarHeight)
make.width.equalTo(AppConstants.ToolbarHeight)
}
shareButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
bookmarkButton.snp_remakeConstraints { (make) -> () in
make.right.equalTo(self.tabsButton.snp_left)
make.bottom.equalTo(self)
make.height.equalTo(AppConstants.ToolbarHeight)
make.width.equalTo(AppConstants.ToolbarHeight)
}
bookmarkButton.contentEdgeInsets = UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}
}
override func updateConstraints() {
updateToolbarConstraints()
progressBar.snp_remakeConstraints { make in
make.centerY.equalTo(self.snp_bottom)
make.width.equalTo(self)
}
locationView.snp_remakeConstraints { make in
make.edges.equalTo(self.locationContainer).insets(EdgeInsetsMake(URLBarViewUX.TextFieldBorderWidth,
URLBarViewUX.TextFieldBorderWidth,
URLBarViewUX.TextFieldBorderWidth,
URLBarViewUX.TextFieldBorderWidth))
return
}
tabsButton.snp_remakeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
make.width.height.equalTo(AppConstants.ToolbarHeight)
}
editTextField.snp_remakeConstraints { make in
make.edges.equalTo(self.locationContainer)
return
}
cancelButton.snp_remakeConstraints { make in
make.centerY.equalTo(self.locationContainer)
make.trailing.equalTo(self)
}
// Add an offset to the left for slide animation, and a bit of extra offset for spring bounces
let leftOffset = self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset + URLBarViewUX.URLBarCurveBounceBuffer
self.curveShape.snp_remakeConstraints { make in
make.edges.equalTo(self).offset(EdgeInsetsMake(0, -leftOffset, 0, -URLBarViewUX.URLBarCurveBounceBuffer))
return
}
updateLayoutForEditing(editing: isEditing, animated: false)
super.updateConstraints()
}
var isEditing: Bool {
get {
return !editTextField.hidden
}
}
func updateURL(url: NSURL?) {
locationView.url = url
}
// Ideally we'd split this implementation in two, one URLBarView with a toolbar and one without
// However, switching views dynamically at runtime is a difficult. For now, we just use one view
// that can show in either mode.
func setShowToolbar(shouldShow: Bool) {
toolbarIsShowing = shouldShow
setNeedsUpdateConstraints()
}
func currentURL() -> NSURL {
return locationView.url!
}
func updateURLBarText(text: String) {
delegate?.urlBarDidBeginEditing(self)
editTextField.text = text
editTextField.becomeFirstResponder()
updateLayoutForEditing(editing: true)
delegate?.urlBar(self, didEnterText: text)
}
func updateTabCount(count: Int) {
tabsButton.setTitle(count.description, forState: UIControlState.Normal)
tabsButton.accessibilityValue = count.description
tabsButton.accessibilityLabel = NSLocalizedString("Show Tabs", comment: "Accessibility label for the tabs button in the (top) browser toolbar")
}
func SELdidClickAddTab() {
delegate?.urlBarDidPressTabs(self)
}
func updateProgressBar(progress: Float) {
if progress == 1.0 {
self.progressBar.setProgress(progress, animated: true)
UIView.animateWithDuration(1.5, animations: {
self.progressBar.alpha = 0.0
}, completion: { _ in
self.progressBar.setProgress(0.0, animated: false)
})
} else {
self.progressBar.alpha = 1.0
self.progressBar.setProgress(progress, animated: (progress > progressBar.progress))
}
}
func updateReaderModeState(state: ReaderModeState) {
locationView.readerModeState = state
}
func browserLocationViewDidTapReaderMode(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReaderMode(self)
}
func browserLocationViewDidLongPressReaderMode(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidLongPressReaderMode(self)
}
func browserLocationViewDidTapLocation(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidBeginEditing(self)
editTextField.text = locationView.url?.absoluteString
editTextField.becomeFirstResponder()
updateLayoutForEditing(editing: true)
}
func browserLocationViewDidLongPressLocation(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidLongPressLocation(self)
}
func browserLocationViewDidTapReload(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressReload(self)
}
func browserLocationViewDidTapStop(browserLocationView: BrowserLocationView) {
delegate?.urlBarDidPressStop(self)
}
func autocompleteTextFieldShouldReturn(autocompleteTextField: AutocompleteTextField) -> Bool {
delegate?.urlBar(self, didSubmitText: editTextField.text)
return true
}
func autocompleteTextField(autocompleteTextField: AutocompleteTextField, didTextChange text: String) {
delegate?.urlBar(self, didEnterText: text)
}
func autocompleteTextFieldDidBeginEditing(autocompleteTextField: AutocompleteTextField) {
// Without the async dispatch below, text selection doesn't work
// intermittently and crashes on the iPhone 6 Plus (bug 1124310).
dispatch_async(dispatch_get_main_queue(), {
autocompleteTextField.selectedTextRange = autocompleteTextField.textRangeFromPosition(autocompleteTextField.beginningOfDocument, toPosition: autocompleteTextField.endOfDocument)
})
autocompleteTextField.layer.borderWidth = 1
locationContainer.layer.shadowOpacity = 0
}
func autocompleteTextFieldDidEndEditing(autocompleteTextField: AutocompleteTextField) {
locationContainer.layer.shadowOpacity = 0.05
autocompleteTextField.layer.borderWidth = 0
}
func autocompleteTextFieldShouldClear(autocompleteTextField: AutocompleteTextField) -> Bool {
delegate?.urlBar(self, didEnterText: "")
return true
}
func setAutocompleteSuggestion(suggestion: String?) {
editTextField.setAutocompleteSuggestion(suggestion)
}
func finishEditing() {
editTextField.resignFirstResponder()
updateLayoutForEditing(editing: false)
delegate?.urlBarDidEndEditing(self)
}
func prepareEditingAnimation(editing: Bool) {
// Make sure everything is showing during the transition (we'll hide it afterwards).
self.progressBar.hidden = editing
self.locationView.hidden = editing
self.editTextField.hidden = !editing
self.tabsButton.hidden = false
self.cancelButton.hidden = false
self.forwardButton.hidden = !self.toolbarIsShowing
self.backButton.hidden = !self.toolbarIsShowing
self.stopReloadButton.hidden = !self.toolbarIsShowing
self.shareButton.hidden = !self.toolbarIsShowing
self.bookmarkButton.hidden = !self.toolbarIsShowing
// Update the location bar's size. If we're animating, we'll call layoutIfNeeded in the Animation
// and transition to this.
if editing {
// In editing mode, we always show the location view full width
self.locationContainer.snp_remakeConstraints { make in
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.cancelButton.snp_leading)
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self).offset(AppConstants.StatusBarHeight / 2)
}
} else {
self.locationContainer.snp_remakeConstraints { make in
if self.toolbarIsShowing {
// If we are showing a toolbar, show the text field next to the forward button
make.left.equalTo(self.stopReloadButton.snp_right)
make.right.equalTo(self.shareButton.snp_left)
} else {
// Otherwise, left align the location view
make.leading.equalTo(self).offset(URLBarViewUX.LocationLeftPadding)
make.trailing.equalTo(self.tabsButton.snp_leading).offset(-14)
}
make.height.equalTo(URLBarViewUX.LocationHeight)
make.centerY.equalTo(self).offset(AppConstants.StatusBarHeight / 2)
}
}
}
func transitionToEditing(editing: Bool) {
self.cancelButton.alpha = editing ? 1 : 0
self.shareButton.alpha = editing ? 0 : 1
self.bookmarkButton.alpha = editing ? 0 : 1
if editing {
self.cancelButton.transform = CGAffineTransformIdentity
self.tabsButton.transform = CGAffineTransformMakeTranslation(self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset, 0)
self.curveShape.transform = CGAffineTransformMakeTranslation(self.tabsButton.frame.width + URLBarViewUX.URLBarCurveOffset + URLBarViewUX.URLBarCurveBounceBuffer, 0)
if self.toolbarIsShowing {
self.forwardButton.transform = CGAffineTransformMakeTranslation(-3 * AppConstants.ToolbarHeight, 0)
self.backButton.transform = CGAffineTransformMakeTranslation(-3 * AppConstants.ToolbarHeight, 0)
self.stopReloadButton.transform = CGAffineTransformMakeTranslation(-3 * AppConstants.ToolbarHeight, 0)
}
} else {
self.tabsButton.transform = CGAffineTransformIdentity
self.cancelButton.transform = CGAffineTransformMakeTranslation(self.cancelButton.frame.width, 0)
self.curveShape.transform = CGAffineTransformIdentity
if self.toolbarIsShowing {
self.forwardButton.transform = CGAffineTransformIdentity
self.backButton.transform = CGAffineTransformIdentity
self.stopReloadButton.transform = CGAffineTransformIdentity
}
}
}
func finishEditingAnimation(editing: Bool) {
self.tabsButton.hidden = editing
self.cancelButton.hidden = !editing
self.forwardButton.hidden = !self.toolbarIsShowing || editing
self.backButton.hidden = !self.toolbarIsShowing || editing
self.shareButton.hidden = !self.toolbarIsShowing || editing
self.bookmarkButton.hidden = !self.toolbarIsShowing || editing
self.stopReloadButton.hidden = !self.toolbarIsShowing || editing
}
func updateLayoutForEditing(#editing: Bool, animated: Bool = true) {
prepareEditingAnimation(editing)
if animated {
UIView.animateWithDuration(0.3, delay: 0.0, usingSpringWithDamping: 0.85, initialSpringVelocity: 0.0, options: nil, animations: { _ in
self.transitionToEditing(editing)
self.layoutIfNeeded()
}, completion: { _ in
self.finishEditingAnimation(editing)
})
} else {
finishEditingAnimation(editing)
}
}
func SELdidClickCancel() {
finishEditing()
}
override func accessibilityPerformEscape() -> Bool {
self.SELdidClickCancel()
return true
}
/* BrowserToolbarProtocol */
func updateBackStatus(canGoBack: Bool) {
backButton.enabled = canGoBack
}
func updateFowardStatus(canGoForward: Bool) {
forwardButton.enabled = canGoForward
}
func updateBookmarkStatus(isBookmarked: Bool) {
bookmarkButton.selected = isBookmarked
}
func updateReloadStatus(isLoading: Bool) {
if isLoading {
stopReloadButton.setImage(helper?.ImageStop, forState: .Normal)
stopReloadButton.setImage(helper?.ImageStopPressed, forState: .Highlighted)
} else {
stopReloadButton.setImage(helper?.ImageReload, forState: .Normal)
stopReloadButton.setImage(helper?.ImageReloadPressed, forState: .Highlighted)
}
}
}
/* Code for drawing the urlbar curve */
// Curve's aspect ratio
private let ASPECT_RATIO = 0.729
// Width multipliers
private let W_M1 = 0.343
private let W_M2 = 0.514
private let W_M3 = 0.49
private let W_M4 = 0.545
private let W_M5 = 0.723
// Height multipliers
private let H_M1 = 0.25
private let H_M2 = 0.5
private let H_M3 = 0.72
private let H_M4 = 0.961
/* Code for drawing the urlbar curve */
private class CurveView: UIView {
func getWidthForHeight(height: Double) -> Double {
return height * ASPECT_RATIO
}
func drawFromTop(path: UIBezierPath) {
let height: Double = Double(AppConstants.ToolbarHeight)
let width = getWidthForHeight(height)
var from = (Double(self.frame.width) - width * 2 - Double(URLBarViewUX.URLBarCurveOffset - URLBarViewUX.URLBarCurveBounceBuffer), Double(AppConstants.StatusBarHeight))
path.moveToPoint(CGPoint(x: from.0, y: from.1))
path.addCurveToPoint(CGPoint(x: from.0 + width * W_M2, y: from.1 + height * H_M2),
controlPoint1: CGPoint(x: from.0 + width * W_M1, y: from.1),
controlPoint2: CGPoint(x: from.0 + width * W_M3, y: from.1 + height * H_M1))
path.addCurveToPoint(CGPoint(x: from.0 + width, y: from.1 + height),
controlPoint1: CGPoint(x: from.0 + width * W_M4, y: from.1 + height * H_M3),
controlPoint2: CGPoint(x: from.0 + width * W_M5, y: from.1 + height * H_M4))
}
private func getPath() -> UIBezierPath {
let path = UIBezierPath()
self.drawFromTop(path)
path.addLineToPoint(CGPoint(x: self.frame.width, y: AppConstants.ToolbarHeight + AppConstants.StatusBarHeight))
path.addLineToPoint(CGPoint(x: self.frame.width, y: -10))
path.addLineToPoint(CGPoint(x: 0, y: -10))
path.addLineToPoint(CGPoint(x: 0, y: AppConstants.StatusBarHeight))
path.closePath()
return path
}
override class func layerClass() -> AnyClass {
return CAShapeLayer.self
}
override func layoutSubviews() {
super.layoutSubviews()
if let layer = layer as? CAShapeLayer {
layer.path = self.getPath().CGPath
layer.fillColor = URLBarViewUX.BackgroundColor.CGColor
}
}
}
private class ToolbarTextField: AutocompleteTextField {
override func textRectForBounds(bounds: CGRect) -> CGRect {
let rect = super.textRectForBounds(bounds)
return rect.rectByInsetting(dx: 5, dy: 5)
}
override func editingRectForBounds(bounds: CGRect) -> CGRect {
let rect = super.editingRectForBounds(bounds)
return rect.rectByInsetting(dx: 5, dy: 5)
}
}
| mpl-2.0 | 45004e0d7d724629d6b0c66e9a1ee3a6 | 40.762411 | 194 | 0.686423 | 5.417203 | false | false | false | false |
oskarpearson/rileylink_ios | MinimedKit/PumpEvents/BasalProfileStartPumpEvent.swift | 1 | 1454 | //
// BasalProfileStartPumpEvent.swift
// RileyLink
//
// Created by Pete Schwamb on 3/8/16.
// Copyright © 2016 Pete Schwamb. All rights reserved.
//
import Foundation
public struct BasalProfileStartPumpEvent: TimestampedPumpEvent {
public let length: Int
public let rawData: Data
public let timestamp: DateComponents
let rate: Double
let profileIndex: Int
let offset: Int
public init?(availableData: Data, pumpModel: PumpModel) {
length = 10
guard length <= availableData.count else {
return nil
}
rawData = availableData.subdata(in: 0..<length)
func d(_ idx:Int) -> Int {
return Int(availableData[idx] as UInt8)
}
timestamp = DateComponents(pumpEventData: availableData, offset: 2)
rate = Double(d(8)) / 40.0
profileIndex = d(1)
offset = d(7) * 30 * 1000 * 60
}
public var dictionaryRepresentation: [String: Any] {
return [
"_type": "BasalProfileStart",
"offset": offset,
"rate": rate,
"profileIndex": profileIndex,
]
}
public var description: String {
return String(format: NSLocalizedString("Basal Profile %1$@: %2$@ U/hour", comment: "The format string description of a BasalProfileStartPumpEvent. (1: The index of the profile)(2: The basal rate)"),profileIndex, rate)
}
}
| mit | f261e37a61261c6f05f53e90d3fe7ac7 | 27.490196 | 226 | 0.603579 | 4.484568 | false | false | false | false |
1457792186/JWSwift | 熊猫TV2/Pods/Kingfisher/Sources/ImageView+Kingfisher.swift | 40 | 13121 | //
// ImageView+Kingfisher.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/6.
//
// Copyright (c) 2016 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
// MARK: - Extension methods.
/**
* Set image to use from web.
*/
extension Kingfisher where Base: ImageView {
/**
Set an image with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
@discardableResult
public func setImage(with resource: Resource?,
placeholder: Image? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
guard let resource = resource else {
base.image = placeholder
completionHandler?(nil, nil, .none, nil)
return .empty
}
var options = options ?? KingfisherEmptyOptionsInfo
if !options.keepCurrentImageWhileLoading {
base.image = placeholder
}
let maybeIndicator = indicator
maybeIndicator?.startAnimatingView()
setWebURL(resource.downloadURL)
if base.shouldPreloadAllGIF() {
options.append(.preloadAllGIFData)
}
let task = KingfisherManager.shared.retrieveImage(
with: resource,
options: options,
progressBlock: { receivedSize, totalSize in
if let progressBlock = progressBlock {
progressBlock(receivedSize, totalSize)
}
},
completionHandler: {[weak base] image, error, cacheType, imageURL in
DispatchQueue.main.safeAsync {
guard let strongBase = base, imageURL == self.webURL else {
return
}
self.setImageTask(nil)
guard let image = image else {
maybeIndicator?.stopAnimatingView()
completionHandler?(nil, error, cacheType, imageURL)
return
}
guard let transitionItem = options.firstMatchIgnoringAssociatedValue(.transition(.none)),
case .transition(let transition) = transitionItem, ( options.forceTransition || cacheType == .none) else
{
maybeIndicator?.stopAnimatingView()
strongBase.image = image
completionHandler?(image, error, cacheType, imageURL)
return
}
#if !os(macOS)
UIView.transition(with: strongBase, duration: 0.0, options: [],
animations: { maybeIndicator?.stopAnimatingView() },
completion: { _ in
UIView.transition(with: strongBase, duration: transition.duration,
options: [transition.animationOptions, .allowUserInteraction],
animations: {
// Set image property in the animation.
transition.animations?(strongBase, image)
},
completion: { finished in
transition.completion?(finished)
completionHandler?(image, error, cacheType, imageURL)
})
})
#endif
}
})
setImageTask(task)
return task
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
public func cancelDownloadTask() {
imageTask?.downloadTask?.cancel()
}
}
// MARK: - Associated Object
private var lastURLKey: Void?
private var indicatorKey: Void?
private var indicatorTypeKey: Void?
private var imageTaskKey: Void?
extension Kingfisher where Base: ImageView {
/// Get the image URL binded to this image view.
public var webURL: URL? {
return objc_getAssociatedObject(base, &lastURLKey) as? URL
}
fileprivate func setWebURL(_ url: URL) {
objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
public var indicatorType: IndicatorType {
get {
let indicator = (objc_getAssociatedObject(base, &indicatorTypeKey) as? Box<IndicatorType?>)?.value
return indicator ?? .none
}
set {
switch newValue {
case .none:
indicator = nil
case .activity:
indicator = ActivityIndicator()
case .image(let data):
indicator = ImageIndicator(imageData: data)
case .custom(let anIndicator):
indicator = anIndicator
}
objc_setAssociatedObject(base, &indicatorTypeKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `indicatorType` is `.none`.
public fileprivate(set) var indicator: Indicator? {
get {
return (objc_getAssociatedObject(base, &indicatorKey) as? Box<Indicator?>)?.value
}
set {
// Remove previous
if let previousIndicator = indicator {
previousIndicator.view.removeFromSuperview()
}
// Add new
if var newIndicator = newValue {
newIndicator.view.frame = base.frame
newIndicator.viewCenter = CGPoint(x: base.bounds.midX, y: base.bounds.midY)
newIndicator.view.isHidden = true
base.addSubview(newIndicator.view)
}
// Save in associated object
objc_setAssociatedObject(base, &indicatorKey, Box(value: newValue), .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
fileprivate var imageTask: RetrieveImageTask? {
return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask
}
fileprivate func setImageTask(_ task: RetrieveImageTask?) {
objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
// MARK: - Deprecated. Only for back compatibility.
/**
* Set image to use from web. Deprecated. Use `kf` namespacing instead.
*/
extension ImageView {
/**
Set an image with a resource, a placeholder image, options, progress handler and completion handler.
- parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`.
- parameter placeholder: A placeholder image when retrieving the image at URL.
- parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more.
- parameter progressBlock: Called when the image downloading progress gets updated.
- parameter completionHandler: Called when the image retrieved and set.
- returns: A task represents the retrieving process.
- note: Both the `progressBlock` and `completionHandler` will be invoked in main thread.
The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.setImage` instead.", renamed: "kf.setImage")
@discardableResult
public func kf_setImage(with resource: Resource?,
placeholder: Image? = nil,
options: KingfisherOptionsInfo? = nil,
progressBlock: DownloadProgressBlock? = nil,
completionHandler: CompletionHandler? = nil) -> RetrieveImageTask
{
return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler)
}
/**
Cancel the image download task bounded to the image view if it is running.
Nothing will happen if the downloading has already finished.
*/
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.cancelDownloadTask` instead.", renamed: "kf.cancelDownloadTask")
public func kf_cancelDownloadTask() { kf.cancelDownloadTask() }
/// Get the image URL binded to this image view.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.webURL` instead.", renamed: "kf.webURL")
public var kf_webURL: URL? { return kf.webURL }
/// Holds which indicator type is going to be used.
/// Default is .none, means no indicator will be shown.
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicatorType` instead.", renamed: "kf.indicatorType")
public var kf_indicatorType: IndicatorType {
get { return kf.indicatorType }
set { kf.indicatorType = newValue }
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated. Use `imageView.kf.indicator` instead.", renamed: "kf.indicator")
/// Holds any type that conforms to the protocol `Indicator`.
/// The protocol `Indicator` has a `view` property that will be shown when loading an image.
/// It will be `nil` if `kf_indicatorType` is `.none`.
public private(set) var kf_indicator: Indicator? {
get { return kf.indicator }
set { kf.indicator = newValue }
}
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.imageTask")
fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setImageTask")
fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task) }
@available(*, deprecated, message: "Extensions directly on image views are deprecated.", renamed: "kf.setWebURL")
fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) }
}
extension ImageView {
func shouldPreloadAllGIF() -> Bool { return true }
}
| apache-2.0 | 6b09887637167b3968c946cbe376b9cd | 44.559028 | 173 | 0.603613 | 5.583404 | false | false | false | false |
50WDLARP/app | SonicIOS_class_demo_orig/SonicIOS/Extensions/CustomColors.swift | 4 | 2097 | //
// CustomColors.swift
// Cool Beans
//
// Created by Kyle on 11/13/14.
// Copyright (c) 2014 Kyle Weiner. All rights reserved.
//
extension UIColor {
// MARK: Temperature Colors
class func CBHotColor() -> UIColor {
return UIColor(rgba: "#FF2851")
}
class func CBWarmColor() -> UIColor {
return UIColor(rgba: "#FF9600")
}
class func CBCoolColor() -> UIColor {
return UIColor(rgba: "#FFCD00")
}
class func CBColdColor() -> UIColor {
return UIColor(rgba: "#54C7FC")
}
// MARK: Helpers
// Credit: https://github.com/yeahdongcn/UIColor-Hex-Swift/
convenience init(rgba: String) {
var red: CGFloat = 0.0
var green: CGFloat = 0.0
var blue: CGFloat = 0.0
var alpha: CGFloat = 1.0
if rgba.hasPrefix("#") {
let index = rgba.startIndex.advancedBy(1)
let hex = rgba.substringFromIndex(index)
let scanner = NSScanner(string: hex)
var hexValue: CUnsignedLongLong = 0
if scanner.scanHexLongLong(&hexValue) {
if hex.characters.count == 6 {
red = CGFloat((hexValue & 0xFF0000) >> 16) / 255.0
green = CGFloat((hexValue & 0x00FF00) >> 8) / 255.0
blue = CGFloat(hexValue & 0x0000FF) / 255.0
} else if hex.characters.count == 8 {
red = CGFloat((hexValue & 0xFF000000) >> 24) / 255.0
green = CGFloat((hexValue & 0x00FF0000) >> 16) / 255.0
blue = CGFloat((hexValue & 0x0000FF00) >> 8) / 255.0
alpha = CGFloat(hexValue & 0x000000FF) / 255.0
} else {
print("invalid rgb string, length should be 7 or 9", terminator: "")
}
} else {
print("scan hex error")
}
} else {
print("invalid rgb string, missing '#' as prefix", terminator: "")
}
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
} | mit | 7996bcfbecc1b9045423d9e7e55f3aa6 | 30.313433 | 88 | 0.517883 | 4.032692 | false | false | false | false |
zdima/ZDMatrixPopover | src/ZDMatrixPopoverController.swift | 1 | 9803 | //
// ZDMatrixPopoverController.swift
// ZDMatrixPopover
//
// Created by Dmitriy Zakharkin on 1/7/17.
// Copyright © 2017 Dmitriy Zakharkin. All rights reserved.
//
// swiftlint:disable variable_name force_cast
import Cocoa
extension ZDMatrixPopoverDelegate {
func getColumnAlignment(column: Int) -> NSTextAlignment {
return .left
}
}
class ZDMatrixPopoverController: NSObject,
NSCollectionViewDelegate,
NSCollectionViewDataSource,
NSCollectionViewDelegateFlowLayout {
private var owner: ZDMatrixPopover!
private var bundle: Bundle!
private var nib: NSNib!
private var lastTimer: Timer?
public required init(owner myOwner: ZDMatrixPopover! ) {
owner = myOwner
super.init()
bundle = Bundle(for: ZDMatrixPopover.self)
bundle.loadNibNamed("ZDMatrixPopover", owner: self, topLevelObjects: &objects)
nib = NSNib(nibNamed: "NSCollectionViewItem", bundle: bundle)
m_collectionView.register( nib, forItemWithIdentifier: "dataSourceItem")
m_collectionView.backgroundColors = [ NSColor.clear, NSColor.clear]
m_titleLabel.font = NSFont.titleBarFont(ofSize: owner.titleFontSize)
}
/// Delegate object of type ZDMatrixPopoverDelegate
/// Due to storyboard limitation we have to use AnyObject as type to allow storyboard binding.
///
/// Interface Builder
///
/// Interface Builder does not support connecting to an outlet in a Swift file
/// when the outlet’s type is a protocol. Declare the outlet's type as AnyObject
/// or NSObject, connect objects to the outlet using Interface Builder, then change
/// the outlet's type back to the protocol. (17023935)
///
@IBOutlet public weak var delegate: AnyObject? {
didSet {
m_delegate = delegate as? ZDMatrixPopoverDelegate
}
}
public func show(
data: [[Any]],
title: String,
relativeTo rect: NSRect,
of view: NSView,
preferredEdge: NSRectEdge) {
assert( m_popover != nil, "Failed to load 'ZDMatrixPopover'")
if m_popover.isShown {
if lastTimer != nil {
lastTimer!.invalidate()
}
lastTimer = Timer.scheduledTimer(timeInterval: 0.05, target: self, selector: Selector("timerShow:"), userInfo: [ "data": data, "title": title, "rect": rect, "view": view, "preferredEdge": preferredEdge], repeats: false)
return
}
m_titleLabel.stringValue = title
m_data = data
if !m_popover.contentViewController!.isViewLoaded {
m_popover.contentViewController!.loadView()
}
m_collectionView.collectionViewLayout!.prepare()
m_collectionView.reloadData()
let collectionSize = m_collectionView.collectionViewLayout!.collectionViewContentSize
collectionWidthConstraint.constant = collectionSize.width
collectionHeightConstraint.constant = collectionSize.height
m_collectionView.needsLayout = true
m_collectionView.superview?.layoutSubtreeIfNeeded()
m_collectionView.reloadData()
m_popover.contentViewController!.view.setFrameSize(m_popover.contentViewController!.view.fittingSize)
m_popover.contentSize = m_popover.contentViewController!.view.bounds.size
let mustSize = m_popover.contentSize
m_popover.show(relativeTo:rect, of: view, preferredEdge: preferredEdge)
}
func timerShow(_ arg: Any?) {
guard let timer = arg as? Timer else { return }
guard let userInfoMap = timer.userInfo as? [String: Any?] else { return }
DispatchQueue.main.async() {
self.m_titleLabel.stringValue = userInfoMap["title"] as! String
self.m_data = userInfoMap["data"] as! [[Any]]
// make sure layout manager has been updated
self.m_collectionView.collectionViewLayout!.prepare()
self.m_collectionView.reloadData()
let collectionSize = self.m_collectionView.collectionViewLayout!.collectionViewContentSize
self.collectionWidthConstraint.constant = collectionSize.width
self.collectionHeightConstraint.constant = collectionSize.height
self.m_popover.positioningRect = userInfoMap["rect"] as! NSRect
self.m_popover.contentViewController!.view.layoutSubtreeIfNeeded()
self.m_popover.contentSize = self.m_popover.contentViewController!.view.bounds.size
self.m_collectionView.reloadData()
}
}
public func close() {
assert( m_popover != nil, "Failed to load 'ZDMatrixPopover'")
m_popover.close()
}
public private(set) var isShown: Bool {
get {
if m_popover == nil {
return false
}
return m_popover.isShown
}
set {
}
}
internal weak var m_delegate: ZDMatrixPopoverDelegate?
internal var lastColumnCount: Int = -1
internal var lastRowCount: Int = -1
private var m_data: [[Any]] = [[]] {
didSet {
let colCount = m_data.reduce(0) { (r, a) in return max(r, a.count)}
let rowCount = m_data.count
lastColumnCount = colCount
lastRowCount = rowCount
m_formatter = [Formatter?].init(repeating: nil, count: colCount)
if m_delegate != nil {
for col in 0..<colCount {
if let formatter = m_delegate!.getColumnFormatter(column: col) {
m_formatter[col] = formatter
}
}
}
m_collectionView.reloadData()
}
}
@IBOutlet internal var m_popover: NSPopover!
@IBOutlet internal var m_popoverView: NSView!
@IBOutlet internal weak var m_titleLabel: NSTextField!
@IBOutlet internal weak var m_collectionView: NSCollectionView!
@IBOutlet internal weak var collectionHeightConstraint: NSLayoutConstraint!
@IBOutlet internal weak var collectionWidthConstraint: NSLayoutConstraint!
@IBOutlet internal var collectionBackgroundView: NSView!
private var objects: NSArray = []
private var m_formatter: [Formatter?] = []
private func setupCollectionView(columnCount: Int, rowCount: Int) {
lastColumnCount = columnCount
lastRowCount = rowCount
m_formatter = [Formatter?].init(repeating: nil, count: columnCount)
if m_delegate != nil {
for col in 0..<columnCount {
if let formatter = m_delegate!.getColumnFormatter(column: col) {
m_formatter[col] = formatter
}
}
}
}
internal func initCellValue( textField: NSTextField, row: Int, col: Int) {
textField.font = NSFont.labelFont(ofSize: owner.dataFontSize)
// Configure the item with an image from the app's data structures
if m_data.count <= row { return }
let rowData = m_data[row]
if rowData.count <= col { return }
let data = rowData[col]
var attributedString: NSAttributedString?
var string: String?
if m_delegate != nil {
textField.alignment = m_delegate!.getColumnAlignment(column: col)
}
if let formatter = m_formatter[col] {
attributedString = formatter.attributedString(for: data, withDefaultAttributes: [
"column": NSNumber(value: col),
"row": NSNumber(value: row),
"alignment": textField.alignment])
if attributedString != nil && m_delegate != nil {
let alignment = m_delegate!.getColumnAlignment(column: col)
if let mutableString = attributedString!.mutableCopy() as? NSMutableAttributedString {
let paragraph = NSMutableParagraphStyle()
paragraph.alignment = alignment
mutableString.addAttribute( NSParagraphStyleAttributeName, value: paragraph, range: NSMakeRange(0, mutableString.length))
attributedString = mutableString
}
}
string = formatter.string(for: data)
} else if let attributedStringData = data as? NSAttributedString {
attributedString = attributedStringData
} else if let stringData = data as? String {
string = stringData
} else {
string = ""
}
if attributedString != nil {
textField.attributedStringValue = attributedString!
} else if string != nil {
textField.stringValue = string!
}
}
public func collectionView(_ collectionView: NSCollectionView,
itemForRepresentedObjectAt indexPath: IndexPath) -> NSCollectionViewItem {
// Recycle or create an item.
guard let item = NSCollectionViewItem(nibName: "NSCollectionViewItem", bundle: bundle) else { return NSCollectionViewItem() }
item.loadView()
let row = Int( indexPath.item / lastColumnCount )
let col = Int( indexPath.item % lastColumnCount )
initCellValue(textField: item.textField!, row: row, col: col)
if let matrix = collectionView.collectionViewLayout as? ZDMatrixPopoverLayout,
let attr = matrix.layoutAttributesForItem(at: indexPath ) {
item.view.frame = attr.frame
}
return item
}
public func collectionView(_ collectionView: NSCollectionView, numberOfItemsInSection section: Int) -> Int {
if m_data.count == 0 {
return 0
}
return m_data.count * m_data[0].count
}
public func numberOfSections(in collectionView: NSCollectionView) -> Int {
return 1
}
}
| mit | c34a843156025bdf7b0f5208b91288ac | 36.121212 | 231 | 0.630714 | 5.125523 | false | false | false | false |
shralpmeister/shralptide2 | ShralpTide/Shared/Components/ContentView/PhoneContentView.swift | 1 | 4065 | //
// PhoneContentView.swift
// Shared
//
// Created by Michael Parlee on 7/12/20.
//
import SwiftUI
struct PhoneContentView: View {
@EnvironmentObject var appState: AppState
@EnvironmentObject var config: ConfigHelper
@State private var isFirstLaunch = true
@State private var showingFavorites = false
@State private var pageIndex: Int = 0
@State private var cursorLocation: CGPoint = .zero
@GestureState private var translation: CGFloat = 0
var body: some View {
return GeometryReader { proxy in
Rectangle()
.background(Color("background-color"))
if isFirstLaunch || proxy.size.width < proxy.size.height {
ZStack {
Image("background-gradient").resizable()
VStack(spacing: 0) {
HeaderView()
.frame(
minHeight: proxy.size.height / 3.5,
maxHeight: proxy.size.height / 2
)
.padding()
TideEventsPageView(pageIndex: $pageIndex)
.frame(minHeight: proxy.size.height / 1.8, maxHeight: proxy.size.height / 1.8)
HStack {
Button(action: {
UIApplication.shared.open(URL(string: UIApplication.openSettingsURLString)!)
}) {
Image(systemName: "gearshape")
.font(.system(size: 24))
}
.padding(.leading)
Spacer()
Button(action: { showingFavorites = true }) {
Image(systemName: "list.bullet")
.font(.system(size: 24))
}
.padding()
.sheet(isPresented: $showingFavorites) {
FavoritesListView(isShowing: $showingFavorites)
.environmentObject(self.appState)
.environmentObject(self.config)
}
}
.frame(
width: proxy.size.width,
height: proxy.size.height * 0.1
)
}
}
.ignoresSafeArea()
.frame(width: proxy.size.width, height: proxy.size.height)
.onAppear {
isFirstLaunch = false
}
} else {
let dragGesture = DragGesture(minimumDistance: 0)
.onChanged {
self.cursorLocation = $0.location
}
.onEnded { _ in
self.cursorLocation = .zero
}
let pressGesture = LongPressGesture(minimumDuration: 0.2)
let pressDrag = pressGesture.sequenced(before: dragGesture)
let swipeDrag = DragGesture()
.updating(self.$translation) { value, state, _ in
state = value.translation.width
}
.onEnded { value in
let offset = value.translation.width / proxy.size.width
let newIndex = offset > 0 ? pageIndex - 1 : pageIndex + 1
self.pageIndex = min(max(Int(newIndex), 0), appState.tidesForDays.count - 1)
}
let exclusive = pressDrag.exclusively(before: swipeDrag)
TideGraphView(pageIndex: $pageIndex, cursorLocation: $cursorLocation)
.gesture(exclusive)
.ignoresSafeArea()
}
}
.statusBar(hidden: false)
.accentColor(.white)
}
}
| gpl-3.0 | f5793b315e679497f49982bc1f303c81 | 40.060606 | 108 | 0.44182 | 5.925656 | false | false | false | false |
abunur/quran-ios | QuranTests/WordByWordIntegrationTests.swift | 1 | 3240 | //
// WordByWordIntegrationTests.swift
// Quran
//
// Created by Mohamed Afifi on 6/15/17.
// Copyright © 2017 Quran.com. All rights reserved.
//
import XCTest
@testable import Quran
import SQLite
import SQLitePersistence
import QuranFoundation
private struct Words {
static let table = Table("words")
struct Columns {
static let sura = Expression<Int>("sura")
static let ayah = Expression<Int>("ayah")
static let wordType = Expression<String>("word_type")
static let wordPosition = Expression<Int>("word_position")
static let textMadani = Expression<String?>("text_madani")
}
}
private struct Glyphs {
struct Columns {
static let id = Expression<Int>("glyph_id")
static let page = Expression<Int>("page_number")
static let sura = Expression<Int>("sura_number")
static let ayah = Expression<Int>("ayah_number")
static let line = Expression<Int>("line_number")
static let position = Expression<Int>("position")
static let minX = Expression<Int>("min_x")
static let maxX = Expression<Int>("max_x")
static let minY = Expression<Int>("min_y")
static let maxY = Expression<Int>("max_y")
}
static let table = Table("glyphs")
}
private enum WordType: String {
case word
case end
case pause
case sajdah
case rubHizb = "rub-el-hizb"
}
class WordByWordIntegrationTests: XCTestCase {
func testWordsAnyAyahInfoDatabasesMatchingPositionsCount() {
expectNotToThrow {
let wordsConnection = try Connection(Files.wordsTextPath, readonly: true)
let wordsQuery = Words.table.select(Words.Columns.sura,
Words.Columns.ayah,
Words.Columns.wordPosition.count)
let wordsRows = try wordsConnection.prepare(wordsQuery)
var wordsAyahs: [AyahNumber: Int] = [:]
for row in wordsRows {
let ayah = row[Words.Columns.ayah]
let sura = row[Words.Columns.sura]
let count = row[Words.Columns.wordPosition.count]
wordsAyahs[AyahNumber(sura: sura, ayah: ayah)] = count
}
let ayahInfoConnection = try Connection(Files.ayahInfoPath, readonly: true)
let ayahInfoQuery = Glyphs.table.select(Glyphs.Columns.sura,
Glyphs.Columns.ayah,
Glyphs.Columns.position.count)
let ayahInfoRows = try ayahInfoConnection.prepare(ayahInfoQuery)
var ayahInfoAyahs: [AyahNumber: Int] = [:]
for row in ayahInfoRows {
let ayah = row[Glyphs.Columns.ayah]
let sura = row[Glyphs.Columns.sura]
let count = row[Glyphs.Columns.position.count]
ayahInfoAyahs[AyahNumber(sura: sura, ayah: ayah)] = count
}
XCTAssertEqual(wordsAyahs.count, ayahInfoAyahs.count)
for (ayah, count) in wordsAyahs {
XCTAssertEqual(count, ayahInfoAyahs[ayah], "Position count mismatch in ayah: \(ayah)")
}
}
}
}
| gpl-3.0 | 7c6413ec3994b8841957f4c7535e02de | 36.229885 | 102 | 0.594319 | 4.58133 | false | true | false | false |
aiwalle/LiveProject | LiveProject/Discovery/LJDiscoveryController.swift | 1 | 3381 | //
// LJDiscoveryController.swift
// LiveProject
//
// Created by liang on 2017/7/28.
// Copyright © 2017年 liang. All rights reserved.
//
import UIKit
class LJDiscoveryController: UITableViewController {
fileprivate lazy var carouselView: LJCarouselView = LJCarouselView.loadFromNib()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
extension LJDiscoveryController {
fileprivate func setupUI() {
setupHeaderView()
setupFooterView()
tableView.rowHeight = kDeviceWidth * 1.4
}
fileprivate func setupHeaderView() {
let carouselViewH = kDeviceWidth * 0.4
carouselView.frame = CGRect(x: 0, y: 0, width: kDeviceWidth, height: carouselViewH)
tableView.tableHeaderView = carouselView
}
fileprivate func setupFooterView() {
let footerView = UIView(frame: CGRect(x: 0, y: 0, width: kDeviceWidth, height: 80))
let btn = UIButton(frame: CGRect.zero)
btn.frame.size = CGSize(width: kDeviceWidth * 0.5, height: 40)
btn.center = CGPoint(x: kDeviceWidth * 0.5, y: 40)
btn.setTitle("换一换", for: .normal)
btn.setTitleColor(UIColor.black, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 16.0)
btn.layer.cornerRadius = 5
btn.layer.borderColor = UIColor.orange.cgColor
btn.layer.borderWidth = 0.5
btn.addTarget(self, action: #selector(switchGuessAnchor), for: .touchUpInside)
footerView.addSubview(btn)
footerView.backgroundColor = UIColor(r: 250, g: 250, b: 250)
tableView.tableFooterView = footerView
}
fileprivate func setupSectionHeaderView() -> UIView {
let headerView = UIView(frame: CGRect(x: 0, y: 0, width: kDeviceWidth, height: 40))
let headerLabel = UILabel(frame: CGRect(x: 0, y: 0, width: kDeviceWidth, height: 40))
headerLabel.textAlignment = .center
headerLabel.text = "猜你喜欢"
headerLabel.textColor = UIColor.orange
headerView.addSubview(headerLabel)
headerView.backgroundColor = UIColor.white
return headerView
}
@objc private func switchGuessAnchor() {
let cell = tableView.visibleCells.first as? LJDiscoveryCell
cell?.reloadData()
let offset = CGPoint(x: 0, y: kDeviceWidth * 0.4 - 64)
tableView.setContentOffset(offset, animated: true)
}
}
extension LJDiscoveryController {
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = LJDiscoveryCell.cellWithTableView(tableView)
cell.cellDidSelected = { (anchor : AnchorModel) in
let liveVc = LJRoomController()
liveVc.anchor = anchor
self.navigationController?.pushViewController(liveVc, animated: true)
}
return cell
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
return setupSectionHeaderView()
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 40
}
}
| mit | 2823e6e601a5a611682500cc817f3dcc | 30.735849 | 109 | 0.64893 | 4.785206 | false | false | false | false |
icetime17/CSSwiftExtension | Sources/UIKit+CSExtension/UIView+CSExtension.swift | 1 | 6244 | //
// UIView+CSExtension.swift
// CSSwiftExtension
//
// Created by Chris Hu on 16/12/25.
// Copyright © 2016年 com.icetime17. All rights reserved.
//
import UIKit
// MARK: - UIView frame Related
public extension CSSwift where Base: UIView {
var left: CGFloat {
get {
return base.frame.minX
}
set {
base.frame.origin.x = newValue
}
}
var right: CGFloat {
get {
return base.frame.maxX
}
set {
base.frame.origin.x = newValue - base.frame.width
}
}
var top: CGFloat {
get {
return base.frame.minY
}
set {
base.frame.origin.y = newValue
}
}
var bottom: CGFloat {
get {
return base.frame.maxY
}
set {
base.frame.origin.y = newValue - base.frame.height
}
}
var width: CGFloat {
get {
return base.frame.width
}
set {
base.frame.size.width = newValue
}
}
var height: CGFloat {
get {
return base.frame.height
}
set {
base.frame.size.height = newValue
}
}
var size: CGSize {
get {
return base.frame.size
}
set {
base.frame.size = newValue
}
}
}
// MARK: -
public extension CSSwift where Base: UIView {
// when View does not care the UIViewControler it belongs to.
var currentViewController: UIViewController {
var responder: UIResponder = base.next!
while !responder.isKind(of: UIWindow.classForCoder()) {
if responder.isKind(of: UIViewController.classForCoder()) {
break
}
responder = responder.next!
}
return responder as! UIViewController
}
var snapshot: UIImage? {
UIGraphicsBeginImageContextWithOptions(base.layer.frame.size, false, 0)
defer {
UIGraphicsEndImageContext()
}
guard let context = UIGraphicsGetCurrentContext() else {
return nil
}
base.layer.render(in: context)
return UIGraphicsGetImageFromCurrentImageContext()
}
// add corner radius, may have `off-screen render` problem.
// aView.cs.setCornerRadius(corners: [.bottomLeft, .bottomRight], radius: 20)
func setCornerRadius(corners: UIRectCorner = .allCorners, radius: CGFloat) {
let maskPath = UIBezierPath(roundedRect: base.bounds, byRoundingCorners: corners, cornerRadii: CGSize(width: radius, height: radius))
let shape = CAShapeLayer()
shape.path = maskPath.cgPath
base.layer.mask = shape
}
}
public extension CSSwift where Base: UIView {
// init UIView from a nib file
// let aView = AView.cs.loadFromNib("AView") as? AView
static func loadFromNib(_ nibName: String, bundle: Bundle? = nil) -> UIView? {
return UINib(nibName: nibName, bundle: bundle).instantiate(withOwner: nil, options: nil).first as? UIView
}
}
// MARK: - Gesture
public extension CSSwift where Base: UIView {
func removeGestureRecognizers() {
base.gestureRecognizers?.forEach(base.removeGestureRecognizer)
}
}
// MARK: - Animation
public extension CSSwift where Base: UIView {
func popAnimation(duration: TimeInterval = 0.5, completion: CS_ClosureWithBool? = nil) {
base.alpha = 0
base.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
UIView.animate(withDuration: duration,
delay: 0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 1,
options: .layoutSubviews,
animations: {
self.base.alpha = 1
self.base.transform = .identity
},
completion: completion)
}
func raiseAnimation(duration: TimeInterval = 0.5, completion: CS_ClosureWithBool? = nil) {
let offsetY = CS_ScreenHeight - base.frame.minY
base.transform = CGAffineTransform(translationX: 0, y: offsetY)
UIView.animate(withDuration: duration,
delay: 0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 1,
options: .layoutSubviews,
animations: {
self.base.transform = .identity
},
completion: completion)
}
func dropAnimation(duration: TimeInterval = 0.5, completion: CS_ClosureWithBool? = nil) {
let offsetY = base.frame.maxY
base.transform = CGAffineTransform(translationX: 0, y: -offsetY)
UIView.animate(withDuration: duration,
delay: 0,
usingSpringWithDamping: 0.6,
initialSpringVelocity: 1,
options: .layoutSubviews,
animations: {
self.base.transform = .identity
},
completion: completion)
}
func breathAnimation() {
let animation = CAKeyframeAnimation(keyPath: "transform.scale")
animation.repeatCount = MAXFLOAT
animation.values = [1, 0.9, 1]
animation.keyTimes = [0, 0.5, 1]
animation.duration = 1.0
base.layer.add(animation, forKey: nil)
}
func hideAnimation(duration: TimeInterval = 3.0, completion: CS_ClosureWithBool? = nil) {
base.alpha = 1.0
UIView.animate(withDuration: duration, animations: {
self.base.alpha = 0.0
}, completion: completion)
}
}
/*
// MARK: - reuse
public protocol ReusableView {
}
public extension ReusableView where Self: UIView {
static var reuseIdentifier: String {
return String(describing: self)
}
}
// MARK: - nib
public protocol NibLoadable {
}
public extension NibLoadable where Self: UIView {
static var nibName: String {
return String(describing: self)
}
}
*/
| mit | 73afc62c4e6957b058f93196850f2fb8 | 26.861607 | 141 | 0.55584 | 4.856809 | false | false | false | false |
thedistance/TheDistanceCore | TDCore/Extensions/NSURL.swift | 1 | 1158 | //
// NSURL.swift
// TDCore
//
// Created by Josh Campion on 30/10/2015.
// Copyright © 2015 The Distance. All rights reserved.
//
import Foundation
public extension URL {
/**
Creates an `NSURL` for opening in Google Chrome app. The caller should check whether the current `UIApplication` can open the returned value before attempting to.
- note: As of iOS 9, `googlechrome` and `googlechromes` should be added to the `LSApplicationQueriesSchemes` key in `info.plist` in order to open the retuned Google Chrome URL.
- returns: An `NSURL` suitable for opening an `NSURL` in Google Chrome if the scheme of `self` is `http` or `https`. `nil` otherwise.
*/
public func googleChromeURL() -> URL? {
guard scheme == "http" || scheme == "https" else { return nil }
var urlComps = URLComponents(url: self, resolvingAgainstBaseURL: false)
if scheme == "http" {
urlComps?.scheme = "googlechrome"
}
if scheme == "https" {
urlComps?.scheme = "googlechromes"
}
return urlComps?.url
}
}
| mit | a99e1465773a026cf1a2661cd04115b1 | 29.447368 | 181 | 0.610199 | 4.222628 | false | false | false | false |
bravelocation/daysleft | daysleft/Model Extensions/Date+Helpers.swift | 1 | 4714 | //
// Date+Extensions.swift
// DaysLeft
//
// Created by John Pollard on 19/09/2022.
// Copyright © 2022 Brave Location Software. All rights reserved.
//
import Foundation
extension Date {
/// Returns the start of the day based on the current date
var startOfDay: Date {
return Calendar.current.startOfDay(for: self)
}
/// Adds a number of days to the current date
/// - Parameter daysToAdd: Number of days to add
/// - Returns: Date with days added
func addDays(_ daysToAdd: Int) -> Date {
return Calendar.current.date(byAdding: .day, value: daysToAdd, to: self)!
}
/// Number of days between two dates
/// - Parameters:
/// - startDate: Start date
/// - endDate: End date
/// - currentDate: Current date used in calulations
/// - weekdaysOnly: Should we use weekdays only in the calculations
/// - Returns: Number of days bwteen the dates
static func daysDifference(_ startDate: Date, endDate: Date, currentDate: Date? = nil, weekdaysOnly: Bool) -> Int {
let startOfStartDate = startDate.startOfDay
let startOfEndDate = endDate.startOfDay
// If want all days, just calculate the days difference and return it
if weekdaysOnly == false {
let components: DateComponents = Calendar.current.dateComponents([.day], from: startOfStartDate, to: startOfEndDate)
return components.day!
}
// If we are calculating weekdays only, first adjust the start or end date if on a weekend
var startDayOfWeek: Int = Calendar.current.component(.weekday, from: startOfStartDate)
var endDayOfWeek: Int = Calendar.current.component(.weekday, from: startOfEndDate)
var adjustedStartDate = startOfStartDate
var adjustedEndDate = startOfEndDate
// If start is a weekend, adjust to Monday
if startDayOfWeek == 7 {
// Saturday
adjustedStartDate = startOfStartDate.addDays(2)
} else if startDayOfWeek == 1 {
// Sunday
adjustedStartDate = startOfStartDate.addDays(1)
}
// If there is a current date, and the adjusted start date is after it, return -1) we haven't started yet)
if let currentDate = currentDate {
let startOfCurrentDate = currentDate.startOfDay
let startComparison = startOfCurrentDate.compare(adjustedStartDate)
if startComparison == ComparisonResult.orderedAscending {
return -1
}
}
// If end is a weekend, move it back to Friday
if endDayOfWeek == 7 {
// Saturday
adjustedEndDate = startOfEndDate.addDays(-1)
} else if endDayOfWeek == 1 {
// Sunday
adjustedEndDate = startOfEndDate.addDays(-2)
}
let adjustedComponents: DateComponents = Calendar.current.dateComponents([.day], from: adjustedStartDate, to: adjustedEndDate)
let adjustedTotalDays: Int = adjustedComponents.day!
let fullWeeks: Int = adjustedTotalDays / 7
// Now we need to take into account if the day of the start date is before or after the day of the end date
startDayOfWeek = Calendar.current.component(.weekday, from: adjustedStartDate)
endDayOfWeek = Calendar.current.component(.weekday, from: adjustedEndDate)
var daysOfWeekDifference = endDayOfWeek - startDayOfWeek
if daysOfWeekDifference < 0 {
daysOfWeekDifference += 5
}
// Finally return the number of weekdays
return (fullWeeks * 5) + daysOfWeekDifference
}
/// Returns the next Xmas
/// - Returns: Date of next Xmas
static func nextXmas() -> Date {
// If it is first run, initialise the model data to Christmas
let todayComponents = Calendar.current.dateComponents([.year, .month, .day], from: Date())
let todayDate = Calendar.current.date(from: todayComponents)!
var xmasComponents = DateComponents()
xmasComponents.day = 25
xmasComponents.month = 12
xmasComponents.year = todayComponents.year
var xmasDate: Date = Calendar.current.date(from: xmasComponents)!
if Date.daysDifference(todayDate, endDate: xmasDate, weekdaysOnly: false) <= 0 {
// If we're past Xmas in the year, set it to next year
xmasComponents.year = xmasComponents.year! + 1
xmasDate = Calendar.current.date(from: xmasComponents)!
}
return xmasDate
}
}
| mit | 095a320178d6e7510716d2519805df77 | 38.605042 | 134 | 0.623806 | 5.201987 | false | false | false | false |
SteeweGriffin/STWCollectionView | Example/Example/CollectionViewCell.swift | 1 | 1458 | //
// CollectionViewCell.swift
// STWCollectionView
//
// Created by Steewe MacBook Pro on 16/05/17.
// Copyright © 2017 Steewe. All rights reserved.
//
import UIKit
class CollectionViewCell: UICollectionViewCell {
private let label = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = .green
self.layer.shadowColor = UIColor.black.cgColor
self.layer.shadowOffset = CGSize(width:0, height:0)
self.layer.shadowRadius = 5
self.layer.shadowOpacity = 0.6
self.layer.cornerRadius = 10
self.label.translatesAutoresizingMaskIntoConstraints = false
self.label.textAlignment = .center
self.contentView.addSubview(self.label)
self.contentView.addConstraint(NSLayoutConstraint(item: self.label, attribute: .centerX, relatedBy: .equal, toItem: self.contentView, attribute: .centerX, multiplier: 1, constant: 0))
self.contentView.addConstraint(NSLayoutConstraint(item: self.label, attribute: .centerY, relatedBy: .equal, toItem: self.contentView, attribute: .centerY, multiplier: 1, constant: 0))
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func prepareForReuse() {
self.label.text = ""
}
func populate(_ string:String){
self.prepareForReuse()
self.label.text = string
}
}
| mit | 08fd601d0d894c625c142eb8adb91750 | 30 | 191 | 0.661633 | 4.469325 | false | false | false | false |
Brightify/DataMapper | Tests/JsonSerializer/JsonSerializerTest.swift | 1 | 2529 | //
// JsonSerializerTest.swift
// DataMapper
//
// Created by Filip Dolnik on 19.01.17.
// Copyright © 2017 Brightify. All rights reserved.
//
import Quick
import Nimble
import DataMapper
class JsonSerializerTest: QuickSpec {
override func spec() {
describe("JsonSerializer") {
let type: SupportedType = .dictionary([
"int": .intOrDouble(2),
"double": .double(1.1),
"bool": .intOrDouble(1),
"text": .string("A"),
"null": .null,
"array": .array([.intOrDouble(0), .intOrDouble(1), .intOrDouble(2), .null]),
"dictionary": .dictionary(["null": .null, "text": .string("B")])
])
describe("typed serialize and deserialize") {
it("serializes and deserializes to the same type") {
self.typedSerializeTest(for: .null)
self.typedSerializeTest(for: .string("a"))
self.typedSerializeTest(for: .intOrDouble(1))
self.typedSerializeTest(for: .array([.null]))
self.typedSerializeTest(for: .dictionary(["a": .null]))
self.typedSerializeTest(for: type)
}
}
describe("serialize and deserialize") {
it("serializes and deserializes to the same type") {
self.serializeTest(for: .null)
self.serializeTest(for: .string("a"))
self.serializeTest(for: .intOrDouble(1))
self.serializeTest(for: .array([.null]))
self.serializeTest(for: .dictionary(["a": .null]))
self.serializeTest(for: type)
}
}
}
}
private func typedSerializeTest(for type: SupportedType, file: String = #file, line: UInt = #line) {
let serializer = JsonSerializer()
let data = serializer.typedSerialize(type)
let actualType = serializer.typedDeserialize(data)
expect(actualType, file: file, line: line) == type
}
private func serializeTest(for type: SupportedType, file: String = #file, line: UInt = #line) {
let serializer = JsonSerializer()
let data = serializer.serialize(type)
let actualType = try! serializer.deserializeOrThrow(data)
expect(actualType, file: file, line: line) == type
}
}
| mit | 14d80225f4fb7ea24746c6fb985696a9 | 36.731343 | 104 | 0.529272 | 4.908738 | false | true | false | false |
kperryua/swift | test/SILGen/materializeForSet.swift | 2 | 28642 | // RUN: %target-swift-frontend -emit-silgen %s | %FileCheck %s
class Base {
var stored: Int = 0
// The ordering here is unfortunate: we generate the property
// getters and setters after we've processed the decl.
// CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet4Basem8computedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $Base):
// CHECK: [[ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[T0:%.*]] = function_ref @_TFC17materializeForSet4Baseg8computedSi
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: store [[T1]] to [[ADDR]] : $*Int
// CHECK: [[BUFFER:%.*]] = address_to_pointer [[ADDR]]
// CHECK: [[T0:%.*]] = function_ref @_TFFC17materializeForSet4Basem8computedSiU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> ()
// CHECK: [[T2:%.*]] = thin_function_to_pointer [[T0]]
// CHECK: [[T3:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T2]] : $Builtin.RawPointer
// CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[T3]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
// CHECK-LABEL: sil hidden [transparent] @_TFFC17materializeForSet4Basem8computedSiU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Base, @thick Base.Type) -> () {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Base, [[SELFTYPE:%.*]] : $@thick Base.Type):
// CHECK: [[T0:%.*]] = load [[SELF]]
// CHECK: [[T1:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[T2:%.*]] = load [[T1]] : $*Int
// CHECK: [[SETTER:%.*]] = function_ref @_TFC17materializeForSet4Bases8computedSi
// CHECK: apply [[SETTER]]([[T2]], [[T0]])
// CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet4Basem6storedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed Base) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $Base):
// CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.stored
// CHECK: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer
// CHECK: [[T2:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none
// CHECK: [[T3:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T2]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[T3]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
var computed: Int {
get { return 0 }
set(value) {}
}
var storedFunction: () -> Int = { 0 }
final var finalStoredFunction: () -> Int = { 0 }
var computedFunction: () -> Int {
get { return {0} }
set {}
}
static var staticFunction: () -> Int {
get { return {0} }
set {}
}
}
class Derived : Base {}
protocol Abstractable {
associatedtype Result
var storedFunction: () -> Result { get set }
var finalStoredFunction: () -> Result { get set }
var computedFunction: () -> Result { get set }
static var staticFunction: () -> Result { get set }
}
// Validate that we thunk materializeForSet correctly when there's
// an abstraction pattern present.
extension Derived : Abstractable {}
// CHECK: sil hidden [transparent] [thunk] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FS1_m14storedFunction
// CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived):
// CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int
// CHECK-NEXT: [[T0:%.*]] = load %2 : $*Derived
// CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $@callee_owned () -> Int
// CHECK-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!getter.1
// CHECK-NEXT: [[RESULT:%.*]] = apply [[FN]]([[SELF]])
// CHECK-NEXT: store [[RESULT]] to [[TEMP]]
// CHECK-NEXT: [[RESULT:%.*]] = load [[TEMP]]
// CHECK-NEXT: strong_retain [[RESULT]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__dSi_XFo__iSi_ : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int
// CHECK-NEXT: [[T1:%.*]] = partial_apply [[REABSTRACTOR]]([[RESULT]])
// CHECK-NEXT: store [[T1]] to [[RESULT_ADDR]]
// CHECK-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_TTWC17materializeForSet7DerivedS_12AbstractableS_FFS1_m14storedFunctionFT_wx6ResultU_T_
// CHECK-NEXT: [[T1:%.*]] = thin_function_to_pointer [[T0]]
// CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T1]]
// CHECK-NEXT: [[T0:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK-NEXT: destroy_addr [[TEMP]]
// CHECK-NEXT: dealloc_stack [[TEMP]]
// CHECK-NEXT: return [[T0]]
// CHECK: sil hidden [transparent] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FFS1_m14storedFunctionFT_wx6ResultU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Derived, @thick Derived.Type) -> ()
// CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived, %3 : $@thick Derived.Type):
// CHECK-NEXT: [[T0:%.*]] = load %2 : $*Derived
// CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int
// CHECK-NEXT: [[VALUE:%.*]] = load [[RESULT_ADDR]] : $*@callee_owned () -> @out Int
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__iSi_XFo__dSi_ : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int
// CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]])
// CHECK-NEXT: [[FN:%.*]] = class_method [[SELF]] : $Base, #Base.storedFunction!setter.1 : (Base) -> (@escaping () -> Int) -> ()
// CHECK-NEXT: apply [[FN]]([[NEWVALUE]], [[SELF]])
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK: sil hidden [transparent] [thunk] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FS1_m19finalStoredFunction
// CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived):
// CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int
// CHECK-NEXT: [[T0:%.*]] = load %2 : $*Derived
// CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction
// CHECK-NEXT: [[RESULT:%.*]] = load [[ADDR]]
// CHECK-NEXT: strong_retain [[RESULT]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__dSi_XFo__iSi_ : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int
// CHECK-NEXT: [[T1:%.*]] = partial_apply [[REABSTRACTOR]]([[RESULT]])
// CHECK-NEXT: store [[T1]] to [[RESULT_ADDR]]
// CHECK-NEXT: [[RESULT_PTR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_TTWC17materializeForSet7DerivedS_12AbstractableS_FFS1_m19finalStoredFunctionFT_wx6ResultU_T_
// CHECK-NEXT: [[T1:%.*]] = thin_function_to_pointer [[T0]]
// CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[T1]]
// CHECK-NEXT: [[T0:%.*]] = tuple ([[RESULT_PTR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK-NEXT: return [[T0]]
// CHECK: sil hidden [transparent] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FFS1_m19finalStoredFunctionFT_wx6ResultU_T_ :
// CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*Derived, %3 : $@thick Derived.Type):
// CHECK-NEXT: [[T0:%.*]] = load %2 : $*Derived
// CHECK-NEXT: [[SELF:%.*]] = upcast [[T0]] : $Derived to $Base
// CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int
// CHECK-NEXT: [[VALUE:%.*]] = load [[RESULT_ADDR]] : $*@callee_owned () -> @out Int
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__iSi_XFo__dSi_ : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int
// CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]])
// CHECK-NEXT: [[ADDR:%.*]] = ref_element_addr [[SELF]] : $Base, #Base.finalStoredFunction
// CHECK-NEXT: assign [[NEWVALUE]] to [[ADDR]]
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWC17materializeForSet7DerivedS_12AbstractableS_ZFS1_m14staticFunctionFT_wx6Result
// CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $@thick Derived.Type):
// CHECK-NEXT: [[RESULT_ADDR:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int
// CHECK-NEXT: [[SELF:%.*]] = upcast %2 : $@thick Derived.Type to $@thick Base.Type
// CHECK-NEXT: [[OUT:%.*]] = alloc_stack $@callee_owned () -> Int
// CHECK: [[GETTER:%.*]] = function_ref @_TZFC17materializeForSet4Baseg14staticFunctionFT_Si : $@convention(method) (@thick Base.Type) -> @owned @callee_owned () -> Int
// CHECK-NEXT: [[VALUE:%.*]] = apply [[GETTER]]([[SELF]]) : $@convention(method) (@thick Base.Type) -> @owned @callee_owned () -> Int
// CHECK-NEXT: store [[VALUE]] to [[OUT]] : $*@callee_owned () -> Int
// CHECK-NEXT: [[VALUE:%.*]] = load [[OUT]] : $*@callee_owned () -> Int
// CHECK-NEXT: strong_retain [[VALUE]] : $@callee_owned () -> Int
// CHECK: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__dSi_XFo__iSi_ : $@convention(thin) (@owned @callee_owned () -> Int) -> @out Int
// CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]])
// CHECK-NEXT: store [[NEWVALUE]] to [[RESULT_ADDR]] : $*@callee_owned () -> @out Int
// CHECK-NEXT: [[ADDR:%.*]] = address_to_pointer [[RESULT_ADDR]] : $*@callee_owned () -> @out Int to $Builtin.RawPointer
// CHECK: [[CALLBACK_FN:%.*]] = function_ref @_TTWC17materializeForSet7DerivedS_12AbstractableS_FZFS1_m14staticFunctionFT_wx6ResultU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout @thick Derived.Type, @thick Derived.Type.Type) -> ()
// CHECK-NEXT: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]] : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout @thick Derived.Type, @thick Derived.Type.Type) -> () to $Builtin.RawPointer
// CHECK-NEXT: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]] : $Builtin.RawPointer
// CHECK-NEXT: [[RESULT:%.*]] = tuple ([[ADDR]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK-NEXT: destroy_addr [[OUT]] : $*@callee_owned () -> Int
// CHECK-NEXT: dealloc_stack [[OUT]] : $*@callee_owned () -> Int
// CHECK-NEXT: return [[RESULT]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK-LABEL: sil hidden [transparent] @_TTWC17materializeForSet7DerivedS_12AbstractableS_FZFS1_m14staticFunctionFT_wx6ResultU_T_
// CHECK: bb0(%0 : $Builtin.RawPointer, %1 : $*Builtin.UnsafeValueBuffer, %2 : $*@thick Derived.Type, %3 : $@thick Derived.Type.Type):
// CHECK-NEXT: [[SELF:%.*]] = load %2 : $*@thick Derived.Type
// CHECK-NEXT: [[BASE_SELF:%.*]] = upcast [[SELF]] : $@thick Derived.Type to $@thick Base.Type
// CHECK-NEXT: [[BUFFER:%.*]] = pointer_to_address %0 : $Builtin.RawPointer to [strict] $*@callee_owned () -> @out Int
// CHECK-NEXT: [[VALUE:%.*]] = load [[BUFFER]] : $*@callee_owned () -> @out Int
// CHECK: [[REABSTRACTOR:%.*]] = function_ref @_TTRXFo__iSi_XFo__dSi_ : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int
// CHECK-NEXT: [[NEWVALUE:%.*]] = partial_apply [[REABSTRACTOR]]([[VALUE]]) : $@convention(thin) (@owned @callee_owned () -> @out Int) -> Int
// CHECK: [[SETTER_FN:%.*]] = function_ref @_TZFC17materializeForSet4Bases14staticFunctionFT_Si : $@convention(method) (@owned @callee_owned () -> Int, @thick Base.Type) -> ()
// CHECK-NEXT: apply [[SETTER_FN]]([[NEWVALUE]], [[BASE_SELF]]) : $@convention(method) (@owned @callee_owned () -> Int, @thick Base.Type) -> ()
// CHECK-NEXT: [[RESULT:%.*]] = tuple ()
// CHECK-NEXT: return [[RESULT]] : $()
protocol ClassAbstractable : class {
associatedtype Result
var storedFunction: () -> Result { get set }
var finalStoredFunction: () -> Result { get set }
var computedFunction: () -> Result { get set }
static var staticFunction: () -> Result { get set }
}
extension Derived : ClassAbstractable {}
protocol Signatures {
associatedtype Result
var computedFunction: () -> Result { get set }
}
protocol Implementations {}
extension Implementations {
var computedFunction: () -> Int {
get { return {0} }
set {}
}
}
class ImplementingClass : Implementations, Signatures {}
struct ImplementingStruct : Implementations, Signatures {
var ref: ImplementingClass?
}
class HasDidSet : Base {
override var stored: Int {
didSet {}
}
// CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet9HasDidSetm6storedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasDidSet):
// CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[T0:%.*]] = function_ref @_TFC17materializeForSet9HasDidSetg6storedSi
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: store [[T1]] to [[T2]] : $*Int
// CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]]
// CHECK: [[CALLBACK_FN:%.*]] = function_ref @_TFFC17materializeForSet9HasDidSetm6storedSiU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> ()
// CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]]
// CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]]
// CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
override var computed: Int {
get { return 0 }
set(value) {}
}
// CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet9HasDidSetm8computedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasDidSet):
// CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[T0:%.*]] = function_ref @_TFC17materializeForSet9HasDidSetg8computedSi
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: store [[T1]] to [[T2]] : $*Int
// CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]]
// CHECK: [[CALLBACK_FN:%.*]] = function_ref @_TFFC17materializeForSet9HasDidSetm8computedSiU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasDidSet, @thick HasDidSet.Type) -> ()
// CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]]
// CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]]
// CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
}
class HasStoredDidSet {
var stored: Int = 0 {
didSet {}
}
// CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet15HasStoredDidSetm6storedSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasStoredDidSet) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasStoredDidSet):
// CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[T0:%.*]] = function_ref @_TFC17materializeForSet15HasStoredDidSetg6storedSi
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: store [[T1]] to [[T2]] : $*Int
// CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]]
// CHECK: [[CALLBACK_FN:%.*]] = function_ref @_TFFC17materializeForSet15HasStoredDidSetm6storedSiU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasStoredDidSet, @thick HasStoredDidSet.Type) -> ()
// CHECK: [[CALLBACK_ADDR:%.*]] = thin_function_to_pointer [[CALLBACK_FN]]
// CHECK: [[CALLBACK:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.some!enumelt.1, [[CALLBACK_ADDR]]
// CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, [[CALLBACK]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
}
// CHECK-LABEL: sil hidden [transparent] @_TFFC17materializeForSet15HasStoredDidSetm6storedSiU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasStoredDidSet, @thick HasStoredDidSet.Type) -> () {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*HasStoredDidSet, [[METATYPE:%.*]] : $@thick HasStoredDidSet.Type):
// CHECK: [[SELF_VALUE:%.*]] = load [[SELF]] : $*HasStoredDidSet
// CHECK: [[BUFFER_ADDR:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Int
// CHECK: [[VALUE:%.*]] = load [[BUFFER_ADDR]] : $*Int
// CHECK: [[SETTER_FN:%.*]] = function_ref @_TFC17materializeForSet15HasStoredDidSets6storedSi : $@convention(method) (Int, @guaranteed HasStoredDidSet) -> ()
// CHECK: apply [[SETTER_FN]]([[VALUE]], [[SELF_VALUE]]) : $@convention(method) (Int, @guaranteed HasStoredDidSet) -> ()
// CHECK: return
// CHECK: }
class HasWeak {
weak var weakvar: HasWeak?
}
// CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet7HasWeakm7weakvarXwGSqS0__ : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @guaranteed HasWeak) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $HasWeak):
// CHECK: [[T2:%.*]] = pointer_to_address [[BUFFER]] : $Builtin.RawPointer to [strict] $*Optional<HasWeak>
// CHECK: [[T0:%.*]] = ref_element_addr [[SELF]] : $HasWeak, #HasWeak.weakvar
// CHECK: [[T1:%.*]] = load_weak [[T0]] : $*@sil_weak Optional<HasWeak>
// CHECK: store [[T1]] to [[T2]] : $*Optional<HasWeak>
// CHECK: [[BUFFER:%.*]] = address_to_pointer [[T2]]
// CHECK: [[T0:%.*]] = function_ref @_TFFC17materializeForSet7HasWeakm7weakvarXwGSqS0__U_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout HasWeak, @thick HasWeak.Type) -> ()
// CHECK: [[T4:%.*]] = tuple ([[BUFFER]] : $Builtin.RawPointer, {{.*}} : $Optional<Builtin.RawPointer>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
// rdar://22109071
// Test that we don't use materializeForSet from a protocol extension.
protocol Magic {}
extension Magic {
var hocus: Int {
get { return 0 }
set {}
}
}
struct Wizard : Magic {}
func improve(_ x: inout Int) {}
func improveWizard(_ wizard: inout Wizard) {
improve(&wizard.hocus)
}
// CHECK-LABEL: sil hidden @_TF17materializeForSet13improveWizardFRVS_6WizardT_
// CHECK: [[IMPROVE:%.*]] = function_ref @_TF17materializeForSet7improveFRSiT_ :
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Int
// Call the getter and materialize the result in the temporary.
// CHECK-NEXT: [[T0:%.*]] = load [[WIZARD:.*]] : $*Wizard
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[GETTER:%.*]] = function_ref @_TFE17materializeForSetPS_5Magicg5hocusSi
// CHECK-NEXT: [[WTEMP:%.*]] = alloc_stack $Wizard
// CHECK-NEXT: store [[T0]] to [[WTEMP]]
// CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]<Wizard>([[WTEMP]])
// CHECK-NEXT: store [[T0]] to [[TEMP]]
// Call improve.
// CHECK-NEXT: apply [[IMPROVE]]([[TEMP]])
// CHECK-NEXT: [[T0:%.*]] = load [[TEMP]]
// CHECK-NEXT: function_ref
// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_TFE17materializeForSetPS_5Magics5hocusSi
// CHECK-NEXT: apply [[SETTER]]<Wizard>([[T0]], [[WIZARD]])
// CHECK-NEXT: dealloc_stack [[WTEMP]]
// CHECK-NEXT: dealloc_stack [[TEMP]]
protocol Totalled {
var total: Int { get set }
}
struct Bill : Totalled {
var total: Int
}
// CHECK-LABEL: sil hidden [transparent] @_TFV17materializeForSet4Billm5totalSi : $@convention(method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Bill):
// CHECK: [[T0:%.*]] = struct_element_addr [[SELF]] : $*Bill, #Bill.total
// CHECK: [[T1:%.*]] = address_to_pointer [[T0]] : $*Int to $Builtin.RawPointer
// CHECK: [[T3:%.*]] = enum $Optional<Builtin.RawPointer>, #Optional.none!enumelt
// CHECK: [[T4:%.*]] = tuple ([[T1]] : $Builtin.RawPointer, [[T3]] : $Optional<Builtin.RawPointer>)
// CHECK: return [[T4]] : $(Builtin.RawPointer, Optional<Builtin.RawPointer>)
// CHECK: }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV17materializeForSet4BillS_8TotalledS_FS1_m5totalSi : $@convention(witness_method) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout Bill) -> (Builtin.RawPointer, Optional<Builtin.RawPointer>) {
// CHECK: bb0([[BUFFER:%.*]] : $Builtin.RawPointer, [[STORAGE:%.*]] : $*Builtin.UnsafeValueBuffer, [[SELF:%.*]] : $*Bill):
// CHECK: [[T0:%.*]] = function_ref @_TFV17materializeForSet4Billm5totalSi
// CHECK: [[T1:%.*]] = apply [[T0]]([[BUFFER]], [[STORAGE]], [[SELF]])
// CHECK: return [[T1]] :
protocol AddressOnlySubscript {
associatedtype Index
subscript(i: Index) -> Index { get set }
}
struct Foo<T>: AddressOnlySubscript {
subscript(i: T) -> T {
get { return i }
set { print("\(i) = \(newValue)") }
}
}
func increment(_ x: inout Int) { x += 1 }
// Test for materializeForSet vs static properties of structs.
protocol Beverage {
static var abv: Int { get set }
}
struct Beer : Beverage {
static var abv: Int {
get {
return 7
}
set { }
}
}
struct Wine<Color> : Beverage {
static var abv: Int {
get {
return 14
}
set { }
}
}
// Make sure we can perform an inout access of such a property too.
func inoutAccessOfStaticProperty<T : Beverage>(_ t: T.Type) {
increment(&t.abv)
}
// Test for materializeForSet vs static properties of classes.
class ReferenceBeer {
class var abv: Int {
get {
return 7
}
set { }
}
}
func inoutAccessOfClassProperty() {
increment(&ReferenceBeer.abv)
}
// Test for materializeForSet when Self is re-abstracted.
//
// We have to open-code the materializeForSelf witness, and not screw up
// the re-abstraction.
protocol Panda {
var x: (Self) -> Self { get set }
}
func id<T>(_ t: T) -> T { return t }
extension Panda {
var x: (Self) -> Self {
get { return id }
set { }
}
}
struct TuxedoPanda : Panda { }
// CHECK-LABEL: sil hidden [transparent] [thunk] @_TTWV17materializeForSet11TuxedoPandaS_5PandaS_FS1_m1xFxx
// Call the getter:
// CHECK: function_ref @_TFE17materializeForSetPS_5Pandag1xFxx : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@in_guaranteed τ_0_0) -> @owned @callee_owned (@in τ_0_0) -> @out τ_0_0
// Result of calling the getter is re-abstracted to the maximally substituted type
// by SILGenFunction::emitApply():
// CHECK: function_ref @_TTRXFo_iV17materializeForSet11TuxedoPanda_iS0__XFo_dS0__dS0__ : $@convention(thin) (TuxedoPanda, @owned @callee_owned (@in TuxedoPanda) -> @out TuxedoPanda) -> TuxedoPanda
// ... then we re-abstract to the requirement signature:
// FIXME: Peephole this away with the previous one since there's actually no
// abstraction change in this case.
// CHECK: function_ref @_TTRXFo_dV17materializeForSet11TuxedoPanda_dS0__XFo_iS0__iS0__ : $@convention(thin) (@in TuxedoPanda, @owned @callee_owned (TuxedoPanda) -> TuxedoPanda) -> @out TuxedoPanda
// The callback:
// CHECK: function_ref @_TTWV17materializeForSet11TuxedoPandaS_5PandaS_FFS1_m1xFxxU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> ()
// CHECK: }
// CHECK-LABEL: sil hidden [transparent] @_TTWV17materializeForSet11TuxedoPandaS_5PandaS_FFS1_m1xFxxU_T_ : $@convention(thin) (Builtin.RawPointer, @inout Builtin.UnsafeValueBuffer, @inout TuxedoPanda, @thick TuxedoPanda.Type) -> ()
// FIXME: Useless re-abstractions
// CHECK: function_ref @_TTRXFo_iV17materializeForSet11TuxedoPanda_iS0__XFo_dS0__dS0__ : $@convention(thin) (TuxedoPanda, @owned @callee_owned (@in TuxedoPanda) -> @out TuxedoPanda) -> TuxedoPanda
// CHECK: function_ref @_TFE17materializeForSetPS_5Pandas1xFxx : $@convention(method) <τ_0_0 where τ_0_0 : Panda> (@owned @callee_owned (@in τ_0_0) -> @out τ_0_0, @inout τ_0_0) -> ()
// CHECK: function_ref @_TTRXFo_dV17materializeForSet11TuxedoPanda_dS0__XFo_iS0__iS0__ : $@convention(thin) (@in TuxedoPanda, @owned @callee_owned (TuxedoPanda) -> TuxedoPanda) -> @out TuxedoPanda
// CHECK: }
// Test for materializeForSet vs lazy properties of structs.
struct LazyStructProperty {
lazy var cat: Int = 5
}
// CHECK-LABEL: sil hidden @_TF17materializeForSet31inoutAccessOfLazyStructPropertyFT1lRVS_18LazyStructProperty_T_
// CHECK: function_ref @_TFV17materializeForSet18LazyStructPropertyg3catSi
// CHECK: function_ref @_TFV17materializeForSet18LazyStructPropertys3catSi
func inoutAccessOfLazyStructProperty(l: inout LazyStructProperty) {
increment(&l.cat)
}
// Test for materializeForSet vs lazy properties of classes.
// CHECK-LABEL: sil hidden [transparent] @_TFC17materializeForSet17LazyClassPropertym3catSi
class LazyClassProperty {
lazy var cat: Int = 5
}
// CHECK-LABEL: sil hidden @_TF17materializeForSet30inoutAccessOfLazyClassPropertyFT1lRCS_17LazyClassProperty_T_
// CHECK: class_method {{.*}} : $LazyClassProperty, #LazyClassProperty.cat!materializeForSet.1
func inoutAccessOfLazyClassProperty(l: inout LazyClassProperty) {
increment(&l.cat)
}
// Test for materializeForSet vs lazy properties of final classes.
final class LazyFinalClassProperty {
lazy var cat: Int = 5
}
// CHECK-LABEL: sil hidden @_TF17materializeForSet35inoutAccessOfLazyFinalClassPropertyFT1lRCS_22LazyFinalClassProperty_T_
// CHECK: function_ref @_TFC17materializeForSet22LazyFinalClassPropertyg3catSi
// CHECK: function_ref @_TFC17materializeForSet22LazyFinalClassPropertys3catSi
func inoutAccessOfLazyFinalClassProperty(l: inout LazyFinalClassProperty) {
increment(&l.cat)
}
// Make sure the below doesn't crash SILGen
struct FooClosure {
var computed: (((Int) -> Int) -> Int)? {
get { return stored }
set {}
}
var stored: (((Int) -> Int) -> Int)? = nil
}
// CHECK-LABEL: _TF17materializeForSet22testMaterializedSetterFT_T_
func testMaterializedSetter() {
// CHECK: function_ref @_TFV17materializeForSet10FooClosureCfT_S0_
var f = FooClosure()
// CHECK: function_ref @_TFV17materializeForSet10FooClosureg8computedGSqFFSiSiSi_
// CHECK: function_ref @_TFV17materializeForSet10FooClosures8computedGSqFFSiSiSi_
f.computed = f.computed
}
// CHECK-LABEL: sil_witness_table hidden Bill: Totalled module materializeForSet {
// CHECK: method #Totalled.total!getter.1: @_TTWV17materializeForSet4BillS_8TotalledS_FS1_g5totalSi
// CHECK: method #Totalled.total!setter.1: @_TTWV17materializeForSet4BillS_8TotalledS_FS1_s5totalSi
// CHECK: method #Totalled.total!materializeForSet.1: @_TTWV17materializeForSet4BillS_8TotalledS_FS1_m5totalSi
// CHECK: }
| apache-2.0 | 45f124bf7450367714bbc24efbe72dd7 | 53.641221 | 276 | 0.665619 | 3.566073 | false | false | false | false |
BlurredSoftware/BSWInterfaceKit | Sources/BSWInterfaceKit/Views/AvatarView.swift | 1 | 3339 | //
// Created by Pierluigi Cifani on 28/04/16.
// Copyright © 2018 TheLeftBit SL. All rights reserved.
//
#if canImport(UIKit)
import UIKit
@objc(BSWAvatarView)
@available(iOS 13, *)
public class AvatarView: UIView {
public let size: Size
public var photo: Photo {
didSet {
updateImage()
}
}
private let imageView: UIImageView = {
let imageView = UIImageView()
imageView.contentMode = .scaleAspectFill
return imageView
}()
public var onTapOnAvatar: AvatarTouchHandler? {
didSet {
if let tapRecognizer = self.tapRecognizer {
self.removeGestureRecognizer(tapRecognizer)
self.tapRecognizer = nil
}
cameraImageView.removeFromSuperview()
if let _ = onTapOnAvatar {
self.isUserInteractionEnabled = true
tapRecognizer = UITapGestureRecognizer(target: self, action: #selector(onTap))
self.addGestureRecognizer(tapRecognizer!)
addAutolayoutSubview(cameraImageView)
cameraImageView.centerInSuperview()
NSLayoutConstraint.activate([
cameraImageView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 0.25),
cameraImageView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 0.25),
])
} else {
self.isUserInteractionEnabled = true
}
}
}
private var tapRecognizer: UITapGestureRecognizer?
private let cameraImageView: UIImageView = {
let imageView = UIImageView()
imageView.image = UIImage.init(systemName: "camera")
imageView.tintColor = .white
imageView.contentMode = .scaleAspectFit
return imageView
}()
// MARK: Initialization
public init(size: Size, photo: Photo) {
self.size = size
self.photo = photo
super.init(frame: .zero)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View setup
private func setup() {
layer.masksToBounds = true
addAutolayoutSubview(imageView)
imageView.pinToSuperview()
updateImage()
setContentHuggingPriority(.required, for: .horizontal)
setContentHuggingPriority(.required, for: .vertical)
setContentCompressionResistancePriority(.required, for: .horizontal)
setContentCompressionResistancePriority(.required, for: .vertical)
}
private func updateImage() {
imageView.setPhoto(photo)
}
// MARK: Layout
override public var intrinsicContentSize : CGSize {
return CGSize(width: size.rawValue, height: size.rawValue)
}
override public func layoutSubviews() {
super.layoutSubviews()
layer.cornerRadius = bounds.width / 2
}
// MARK: TapReco
@objc func onTap() {
onTapOnAvatar?(self)
}
// MARK: Types
public enum Size: CGFloat {
case smallest = 44
case normal = 60
case big = 80
case huge = 140
}
public typealias AvatarTouchHandler = (AvatarView) -> ()
}
#endif
| mit | aa54bcd549ca11f4d4bef65c675071bb | 27.05042 | 101 | 0.599461 | 5.481117 | false | false | false | false |
blinksh/blink | Blink/Subscriptions/Paywall/CheckmarkRow.swift | 1 | 2400 | ////////////////////////////////////////////////////////////////////////////////
//
// B L I N K
//
// Copyright (C) 2016-2019 Blink Mobile Shell Project
//
// This file is part of Blink.
//
// Blink 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.
//
// Blink 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 Blink. If not, see <http://www.gnu.org/licenses/>.
//
// In addition, Blink is also subject to certain additional terms under
// GNU GPL version 3 section 7.
//
// You should have received a copy of these additional terms immediately
// following the terms and conditions of the GNU General Public License
// which accompanied the Blink Source Code. If not, see
// <http://www.github.com/blinksh/blink>.
//
////////////////////////////////////////////////////////////////////////////////
import Foundation
import SwiftUI
struct CheckmarkRow: View {
let text: String
let checked: Bool
let failed: Bool
let failedIcon: String
let checkedIcon: String
let uncheckedIcon: String
let iconColor: Color
let iconFailedColor: Color
init(
text: String,
checked: Bool = true,
failed: Bool = false,
failedIcon: String = "exclamationmark.circle",
checkedIcon: String = "checkmark.circle.fill",
uncheckedIcon: String = "circle",
iconColor: Color = .green,
iconFailedColor: Color = .orange
) {
self.text = text
self.checked = checked
self.failed = failed
self.uncheckedIcon = uncheckedIcon
self.checkedIcon = checkedIcon
self.failedIcon = failedIcon
self.iconColor = iconColor
self.iconFailedColor = iconFailedColor
}
var body: some View {
HStack(alignment: .firstTextBaseline) {
Image(systemName: failed ? failedIcon : checked ? checkedIcon : uncheckedIcon)
.foregroundColor(failed ? iconFailedColor : iconColor)
.frame(maxWidth: 26)
Text(text).fixedSize(horizontal: false, vertical: true)
Spacer()
}
}
}
| gpl-3.0 | 6eb0655b398c7276de164cc0726bdbda | 30.578947 | 84 | 0.65875 | 4.469274 | false | false | false | false |
zjjzmw1/robot | robot/robot/Macro/ApiMacros.swift | 1 | 865 | //
// ApiMacros.swift
// SwiftCodeFragments
//
// Created by zhangmingwei on 2017/2/3.
// Copyright © 2017年 SpeedX. All rights reserved.
//
import Foundation
// -- swift 的api以 kS开头
// 域名
let kSDomain = ".niaoyutong.com"
// 请求的根url
let kSBase_url = ""
// 请求的key(暂时需要)
let kSRequest_key = ""
// 业务逻辑的具体API:
/// 阿凡达天气数据的接口
/// YY天气-7天的天气预报 + 城市名字例如:武汉
let kYYWeather_url = "http://api.avatardata.cn/Weather/Query?key=f06098f5db9f43fbbfe04aba61bb94fb&cityname=%@"
/// 百度新闻搜索json数据
let kBaidu_new_url = "http://www.baidu.com/s?wd=%@&pn=0&rn=3&tn=json"
/// 百度翻译的api
let kApi_baidu_fanyi = "http://api.fanyi.baidu.com/api/trans/vip/translate"
| mit | 64ed91aa6ee33132723c0e16a5354ed2 | 23.266667 | 122 | 0.616758 | 2.459459 | false | false | false | false |
chordsNcode/jsonperf | Pods/Genome/Packages/Node-0.7.1/Sources/Node/Extract/Node+Extract.swift | 2 | 7438 |
extension Dictionary {
func mapValues<T>(_ mapper: (_ value: Value) throws -> T)
rethrows -> Dictionary<Key, T> {
var mapped: [Key: T] = [:]
try forEach { key, value in
mapped[key] = try mapper(value)
}
return mapped
}
}
extension Node: NodeBacked {
public var node: Node {
get {
return self
}
set {
self = newValue
}
}
public init(_ node: Node) {
self = node
}
}
// MARK: Transforming
extension NodeBacked {
public func extract<T, InputType: NodeInitializable>(
_ path: PathIndex...,
transform: (InputType) throws -> T)
throws -> T {
return try extract(path: path, transform: transform)
}
public func extract<T, InputType: NodeInitializable>(
path: [PathIndex],
transform: (InputType) throws -> T)
throws -> T {
guard let value = node[path] else {
throw NodeError.unableToConvert(node: nil, expected: "\(T.self)")
}
let input = try InputType(node: value)
return try transform(input)
}
public func extract<T, InputType: NodeInitializable>(
_ path: PathIndex...,
transform: (InputType?) throws -> T)
throws -> T {
return try extract(path: path, transform: transform)
}
public func extract<T, InputType: NodeInitializable>(
path: [PathIndex],
transform: (InputType?) throws -> T)
throws -> T {
return try transform(extract(path))
}
}
// MARK: Non-Optional
extension NodeBacked {
public func extract<T : NodeInitializable>(
_ path: PathIndex...)
throws -> T {
return try extract(path)
}
public func extract<T : NodeInitializable>(
_ path: [PathIndex])
throws -> T {
guard let value = node[path] else {
throw NodeError.unableToConvert(node: nil, expected: "\(T.self)")
}
return try T(node: value)
}
public func extract<T : NodeInitializable>(
_ path: PathIndex...)
throws -> [T] {
return try extract(path)
}
public func extract<T : NodeInitializable>(
_ path: [PathIndex])
throws -> [T] {
guard let value = node[path] else {
throw NodeError.unableToConvert(node: nil, expected: "\([T].self)")
}
return try [T](node: value)
}
public func extract<T : NodeInitializable>(
_ path: PathIndex...)
throws -> [[T]] {
return try extract(path)
}
public func extract<T : NodeInitializable>(
_ path: [PathIndex])
throws -> [[T]] {
guard let initial = node[path] else {
throw NodeError.unableToConvert(node: nil, expected: "\([[T]].self)")
}
let array = initial.nodeArray ?? [initial]
return try array.map { try [T](node: $0) }
}
public func extract<T : NodeInitializable>(
_ path: PathIndex...)
throws -> [String : T] {
return try extract(path)
}
public func extract<T : NodeInitializable>(
_ path: [PathIndex])
throws -> [String : T] {
let value = node[path]
guard let object = value?.nodeObject else {
throw NodeError.unableToConvert(node: value, expected: "\([String: T].self)")
}
return try object.mapValues { return try T(node: $0) }
}
public func extract<T : NodeInitializable>(
_ path: PathIndex...)
throws -> [String : [T]] {
return try extract(path)
}
public func extract<T : NodeInitializable>(
_ path: [PathIndex])
throws -> [String : [T]] {
let value = node[path]
guard let object = value?.nodeObject else {
throw NodeError.unableToConvert(node: value, expected: "\([String: [T]].self)")
}
return try object.mapValues { return try [T](node: $0) }
}
public func extract<T : NodeInitializable>(
_ path: PathIndex...)
throws -> Set<T> {
return try extract(path)
}
public func extract<T : NodeInitializable>(
_ path: [PathIndex])
throws -> Set<T> {
guard let value = node[path] else {
throw NodeError.unableToConvert(node: nil, expected: "\(Set<T>.self)")
}
let array = try [T](node: value)
return Set(array)
}
}
// MARK: Optional Extractions
extension NodeBacked {
public func extract<T : NodeInitializable>(
_ path: PathIndex...)
throws -> T? {
return try extract(path)
}
public func extract<T : NodeInitializable>(
_ path: [PathIndex])
throws -> T? {
guard let node = node[path], node != .null else { return nil }
return try T(node: node)
}
public func extract<T : NodeInitializable>(
_ path: PathIndex...)
throws -> [T]? {
return try extract(path)
}
public func extract<T : NodeInitializable>(
_ path: [PathIndex])
throws -> [T]? {
guard let node = node[path], node != .null else { return nil }
return try [T](node: node)
}
public func extract<T : NodeInitializable>(
_ path: PathIndex...)
throws -> [[T]]? {
return try extract(path)
}
public func extract<T : NodeInitializable>(
_ path: [PathIndex])
throws -> [[T]]? {
guard let node = node[path], node != .null else { return nil }
let array = node.nodeArray ?? [node]
return try array.map { try [T](node: $0) }
}
public func extract<T : NodeInitializable>(
_ path: PathIndex...)
throws -> [String : T]? {
return try extract(path)
}
public func extract<T : NodeInitializable>(
_ path: [PathIndex])
throws -> [String : T]? {
guard let node = node[path], node != .null else { return nil }
guard let object = node.nodeObject else {
throw NodeError.unableToConvert(node: node, expected: "\([String: T].self)")
}
return try object.mapValues { return try T(node: $0) }
}
public func extract<T : NodeInitializable>(
_ path: PathIndex...)
throws -> [String : [T]]? {
return try extract(path)
}
public func extract<T : NodeInitializable>(
_ path: [PathIndex])
throws -> [String : [T]]? {
guard let node = node[path], node != .null else { return nil }
guard let object = node.nodeObject else {
throw NodeError.unableToConvert(node: node, expected: "\([String: [T]].self)")
}
return try object.mapValues { return try [T](node: $0) }
}
public func extract<T : NodeInitializable>(
_ path: PathIndex...)
throws -> Set<T>? {
return try extract(path)
}
public func extract<T : NodeInitializable>(
_ path: [PathIndex])
throws -> Set<T>? {
guard let node = node[path], node != .null else { return nil }
let array = try [T](node: node)
return Set(array)
}
}
| mit | 4b0cfcb373b2349cde286595a660a622 | 28.633466 | 95 | 0.52541 | 4.49426 | false | false | false | false |
yaslab/Harekaze-iOS | Harekaze/AppDelegate.swift | 1 | 13114 | /**
*
* AppDelegate.swift
* Harekaze
* Created by Yuki MIZUNO on 2016/06/22.
*
* Copyright (c) 2016-2017, Yuki MIZUNO
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
import CoreData
import Material
import RealmSwift
import Fabric
import Crashlytics
import APIKit
import CoreSpotlight
import DropDown
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let navigationDrawerController = NavigationDrawerController(rootViewController: (window?.rootViewController)!,
leftViewController: NavigationDrawerTableViewController())
window!.rootViewController = SnackbarController(rootViewController: navigationDrawerController)
// Global appearance configuration
UITabBar.appearance().tintColor = Material.Color.blue.darken1
UINavigationBar.appearance().backIndicatorImage = UIImage(named: "ic_arrow_back_white")
UINavigationBar.appearance().backIndicatorTransitionMaskImage = UIImage(named: "ic_arrow_back_white")
DropDown.appearance().backgroundColor = UIColor.white
DropDown.appearance().cellHeight = 48
DropDown.appearance().textFont = RobotoFont.regular(with: 16)
DropDown.appearance().cornerRadiusPreset = .cornerRadius1
DropDown.appearance().direction = .bottom
DropDown.appearance().animationduration = 0.2
// Realm configuration
let config = Realm.Configuration(inMemoryIdentifier: "InMemoryRealm")
Realm.Configuration.defaultConfiguration = config
// Crashlytics, Answers
Fabric.sharedSDK().debug = true
Fabric.with([Crashlytics.self])
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state.
// This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or
// when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers,
// and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive.
// If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// Launch with URL scheme
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
guard let host = url.host else {
return true // Only protocol type launching
}
switch host {
case "program":
let components = url.pathComponents
if components.count != 3 {
return false
}
let storyboard = UIStoryboard(name: "Main", bundle: nil)
switch components[1] {
case "view":
let request = ChinachuAPI.RecordingDetailRequest(id: components[2])
Session.send(request) { result in
switch result {
case .success(let data):
guard let programDetailViewController = storyboard.instantiateViewController(withIdentifier: "ProgramDetailTableViewController") as?
ProgramDetailTableViewController else {
return
}
programDetailViewController.program = data
guard let rootController = self.window?.rootViewController! as? RootController else {
return
}
guard let rootViewController = rootController.rootViewController as? NavigationDrawerController else {
return
}
guard let navigationController = rootViewController.rootViewController as? MainNavigationController else {
return
}
navigationController.pushViewController(programDetailViewController, animated: true)
case .failure(_):
return
}
}
case "watch":
let request = ChinachuAPI.RecordingDetailRequest(id: components[2])
Session.send(request) { result in
switch result {
case .success(let data):
guard let videoPlayViewController = storyboard.instantiateViewController(withIdentifier: "VideoPlayerViewController") as? VideoPlayerViewController else {
return
}
videoPlayViewController.program = data
videoPlayViewController.modalPresentationStyle = .custom
guard let rootController = self.window?.rootViewController! as? RootController else {
return
}
guard let rootViewController = rootController.rootViewController else {
return
}
rootViewController.present(videoPlayViewController, animated: true, completion: nil)
case .failure(_):
return
}
}
default:
return false
}
default:
return false
}
return true
}
// Launch with Quick Action
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Void) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
switch shortcutItem.type {
case "org.harekaze.Harekaze.search":
let searchNavigationController = storyboard.instantiateViewController(withIdentifier: "ProgramSearchResultTableViewController")
let searchBarController = SearchBarController(rootViewController: searchNavigationController)
searchBarController.modalTransitionStyle = .crossDissolve
guard let rootController = self.window?.rootViewController! as? RootController else {
return
}
guard let rootViewController = rootController.rootViewController as? NavigationDrawerController else {
return
}
rootViewController.present(SearchNavigationController(rootViewController: searchBarController), animated: true, completion: nil)
default:
return
}
}
// Launch from Spotlight search result
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
if userActivity.activityType != CSSearchableItemActionType {
return false
}
guard let identifier = userActivity.userInfo?[CSSearchableItemActivityIdentifier] as? String else {
return false
}
let request = ChinachuAPI.RecordingDetailRequest(id: identifier)
Session.send(request) { result in
switch result {
case .success(let data):
let storyboard = UIStoryboard(name: "Main", bundle: nil)
guard let programDetailViewController = storyboard.instantiateViewController(withIdentifier: "ProgramDetailTableViewController") as?
ProgramDetailTableViewController else {
return
}
programDetailViewController.program = data
guard let rootController = self.window?.rootViewController! as? RootController else {
return
}
guard let rootViewController = rootController.rootViewController as? NavigationDrawerController else {
return
}
guard let navigationController = rootViewController.rootViewController as? MainNavigationController else {
return
}
navigationController.pushViewController(programDetailViewController, animated: true)
case .failure(_):
return
}
}
return true
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: URL = {
// The directory the application uses to store the Core Data store file.
// This code uses a directory named "org.harekaze.Harekaze" in the application's documents Application Support directory.
let urls = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional.
// It is a fatal error for the application not to be able to find and load its model.
let modelURL = Bundle.main.url(forResource: "Harekaze", withExtension: "momd")!
return NSManagedObjectModel(contentsOf: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application.
// This implementation creates and returns a coordinator, having added the store for the application to it.
// This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.appendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStore(ofType: NSSQLiteStoreType, configurationName: nil, at: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" as AnyObject?
dict[NSLocalizedFailureReasonErrorKey] = failureReason as AnyObject?
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate.
// You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.)
// This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .mainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate.
// You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
| bsd-3-clause | f74f7742ad87b5d9ad55fddc8efe3ce7 | 42.138158 | 160 | 0.757892 | 4.913451 | false | false | false | false |
alexanderedge/Toolbelt | Toolbelt/Toolbelt/Foundation.swift | 1 | 2203 | //
// Foundation.swift
// Toolbelt
//
// Created by Alexander Edge on 27/08/2015.
// Copyright © 2015 Alexander Edge. All rights reserved.
//
import Foundation
extension Int {
public static func random(_ range: Range<Int>) -> Int {
var offset = 0
// allow negative ranges
if range.lowerBound < 0 {
offset = abs(range.lowerBound)
}
let mini = UInt32(range.lowerBound + offset)
let maxi = UInt32(range.upperBound + offset)
return Int(mini + arc4random_uniform(maxi - mini)) - offset
}
}
extension Bool {
public static func random() -> Bool {
return arc4random() < arc4random()
}
}
extension Collection {
public func shuffled() -> [Self.Iterator.Element] {
return sorted(){ lhs, rhs in
return Bool.random()
}
}
}
extension Collection where Self.Iterator.Element : Equatable {
public func except(_ element : Self.Iterator.Element) -> [Self.Iterator.Element] {
return self.filter({ (obj) -> Bool in
return obj != element
})
}
}
extension Collection where Index == Int, Self.Iterator.Element : Equatable {
public func any(_ count : Int) -> [Self.Iterator.Element] {
guard !self.isEmpty else {
return []
}
let indexes = 0..<self.endIndex
let shuffledIndexes = indexes.shuffled()
return stride(from: 0, to: count, by: 1).map({return self[shuffledIndexes[$0]]})
}
public func anyExcept(_ element : Self.Iterator.Element) -> Self.Iterator.Element? {
guard self.count >= 2 else {
return nil
}
var newElement = element
while newElement == element {
newElement = self.any!
}
return newElement
}
public var any: Self.Iterator.Element? {
guard !self.isEmpty else {
return nil
}
return self[Int.random(0..<self.endIndex)]
}
}
extension Dictionary {
public mutating func merge<K, V>(_ dict: [K: V]){
for (k, v) in dict {
self.updateValue(v as! Value, forKey: k as! Key)
}
}
}
| mit | 8ef812c80591b08c1957aad22381c0b1 | 24.604651 | 89 | 0.56812 | 4.170455 | false | false | false | false |
richardpiazza/GraphPoint | Tests/GraphPointTests/CartesianPlaneTests.swift | 1 | 3726 | import XCTest
@testable import GraphPoint
import Swift2D
class CartesianPlaneTests: XCTestCase {
func testCartesianOrigin() {
var plane = CartesianPlane(size: Size(width: 40, height: 20))
XCTAssertEqual(plane.cartesianOrigin.x, 20)
XCTAssertEqual(plane.cartesianOrigin.y, 10)
plane = CartesianPlane(axis: 6)
XCTAssertEqual(plane.cartesianOrigin.x, 6)
XCTAssertEqual(plane.cartesianOrigin.y, 6)
plane = CartesianPlane(radius: 45.0)
XCTAssertEqual(plane.cartesianOrigin.x, 45.0)
XCTAssertEqual(plane.cartesianOrigin.y, 45.0)
}
func testMinimumAxis() {
var plane = CartesianPlane(size: Size(width: 40, height: 20))
XCTAssertEqual(plane.minimumAxis, 10)
plane = CartesianPlane(axis: 6)
XCTAssertEqual(plane.minimumAxis, 6)
plane = CartesianPlane(radius: 45.0)
XCTAssertEqual(plane.minimumAxis, 45.0)
}
func testMaximumAxis() {
var plane = CartesianPlane(size: Size(width: 40, height: 20))
XCTAssertEqual(plane.maximumAxis, 20)
plane = CartesianPlane(axis: 6)
XCTAssertEqual(plane.maximumAxis, 6)
plane = CartesianPlane(radius: 45.0)
XCTAssertEqual(plane.maximumAxis, 45.0)
}
func testCartesianPointForPoint() {
// 100 x 100 rect {50 x 50} axes
let plane = CartesianPlane(radius: 50)
var point: Point
var cartesianPoint: CartesianPoint
point = .init(x: 20, y: 35)
cartesianPoint = plane.cartesianPoint(for: point)
XCTAssertEqual(cartesianPoint.x, -30)
XCTAssertEqual(cartesianPoint.y, 15)
point = .init(x: 80, y: 35)
cartesianPoint = plane.cartesianPoint(for: point)
XCTAssertEqual(cartesianPoint.x, 30)
XCTAssertEqual(cartesianPoint.y, 15)
point = .init(x: 20, y: 80)
cartesianPoint = plane.cartesianPoint(for: point)
XCTAssertEqual(cartesianPoint.x, -30)
XCTAssertEqual(cartesianPoint.y, -30)
point = .init(x: 80, y: 80)
cartesianPoint = plane.cartesianPoint(for: point)
XCTAssertEqual(cartesianPoint.x, 30)
XCTAssertEqual(cartesianPoint.y, -30)
}
func testPointForCartesianPoint() {
// 100 x 100 rect {50 x 50} axes
let plane = CartesianPlane(radius: 50)
var cartesianPoint: CartesianPoint
var point: Point
cartesianPoint = .init(x: -30, y: 15)
point = plane.point(for: cartesianPoint)
XCTAssertEqual(point.x, 20)
XCTAssertEqual(point.y, 35)
cartesianPoint = .init(x: 30, y: 15)
point = plane.point(for: cartesianPoint)
XCTAssertEqual(point.x, 80)
XCTAssertEqual(point.y, 35)
cartesianPoint = .init(x: -30, y: -30)
point = plane.point(for: cartesianPoint)
XCTAssertEqual(point.x, 20)
XCTAssertEqual(point.y, 80)
cartesianPoint = .init(x: 30, y: -30)
point = plane.point(for: cartesianPoint)
XCTAssertEqual(point.x, 80)
XCTAssertEqual(point.y, 80)
}
func testRectForCartesianFrame() {
// 100 x 100 rect {50 x 50} axes
let plane = CartesianPlane(radius: 50)
// {-25, 25}, {50, 50}
let cartesianFrame = CartesianFrame(origin: .init(x: -25, y: 25), size: .init(width: 50, height: 50))
let rect = plane.rect(for: cartesianFrame)
XCTAssertEqual(rect.x, 25)
XCTAssertEqual(rect.y, 25)
XCTAssertEqual(rect.width, 50)
XCTAssertEqual(rect.height, 50)
}
}
| mit | 3f5c162ebfd51856583b8b281f87577b | 32.872727 | 109 | 0.604402 | 4.307514 | false | true | false | false |
ruilin/RLMap | iphone/Maps/UI/PlacePage/PlacePageLayout/Content/ViatorCells/PPViatorCarouselCell.swift | 1 | 2320 | @objc(MWMPPViatorCarouselCell)
final class PPViatorCarouselCell: MWMTableViewCell {
@IBOutlet private weak var title: UILabel! {
didSet {
title.text = L("place_page_viator_title")
title.font = UIFont.bold14()
title.textColor = UIColor.blackSecondaryText()
}
}
@IBOutlet private weak var more: UIButton! {
didSet {
more.setTitle(L("placepage_more_button"), for: .normal)
more.titleLabel?.font = UIFont.regular17()
more.setTitleColor(UIColor.linkBlue(), for: .normal)
}
}
@IBOutlet private weak var collectionView: UICollectionView!
fileprivate var dataSource: [ViatorItemModel] = []
fileprivate let kMaximumNumberOfElements = 5
fileprivate var delegate: MWMPlacePageButtonsProtocol?
func config(with ds: [ViatorItemModel], delegate d: MWMPlacePageButtonsProtocol?) {
dataSource = ds
delegate = d
collectionView.contentOffset = .zero
collectionView.delegate = self
collectionView.dataSource = self
collectionView.register(cellClass: ViatorElement.self)
collectionView.reloadData()
isSeparatorHidden = true
backgroundColor = UIColor.clear
}
fileprivate func isLastCell(_ indexPath: IndexPath) -> Bool {
return indexPath.item == collectionView.numberOfItems(inSection: indexPath.section) - 1
}
@IBAction
func onMore() {
delegate?.openViatorURL(nil)
}
}
extension PPViatorCarouselCell: UICollectionViewDelegate, UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withCellClass: ViatorElement.self,
indexPath: indexPath) as! ViatorElement
cell.model = isLastCell(indexPath) ? nil : dataSource[indexPath.item]
cell.onMoreAction = { [weak self] in
self?.onMore()
}
return cell
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return min(dataSource.count + 1, kMaximumNumberOfElements)
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
let url: URL? = isLastCell(indexPath) ? nil : dataSource[indexPath.item].pageURL
delegate?.openViatorURL(url)
}
}
| apache-2.0 | 09dcbf574c182976fbcba4abbd214625 | 34.692308 | 119 | 0.719828 | 4.773663 | false | false | false | false |
abreis/swift-gissumo | tools/floatingCarDataXML2TSV/src/main.swift | 1 | 4235 | /* Andre Braga Reis, 2017
*/
import Foundation
/* Process command line options
*/
guard CommandLine.arguments.count == 2,
CommandLine.arguments[1].hasSuffix(".fcd.xml")
else {
print("ERROR: Please supply a .fcd.xml floating car data file.")
exit(EXIT_FAILURE)
}
/* Load floating car data from an XML file
*/
print("Loading floating car data... ", terminator: ""); fflush(stdout)
// See if the file exists
let fcdFile: String = CommandLine.arguments[1]
let fcdFileURL = URL(fileURLWithPath: fcdFile)
guard (fcdFileURL as NSURL).checkResourceIsReachableAndReturnError(nil) else {
print("\n","Error: Unable to open floating car data file.")
exit(EXIT_FAILURE)
}
// Parse XML Floating Car Data
guard let fcdData = try? Data(contentsOf: fcdFileURL, options: [.mappedIfSafe, .uncached] ) else {
print("\n","Error: Unable to memmap floating car data file.")
exit(EXIT_FAILURE)
}
// Create an XML indexer for the FCD data
let fcdXML = SWXMLHash.config {
config in
config.shouldProcessLazily = true
}.parse(fcdData)
print("okay")
// Extension to write strings to OutputStream
// Credit: stackoverflow rob & aleksey-timoshchenko
extension OutputStream {
/// Write `String` to `OutputStream`
///
/// - parameter string: The `String` to write.
/// - parameter encoding: The `String.Encoding` to use when writing the string. This will default to `.utf8`.
/// - parameter allowLossyConversion: Whether to permit lossy conversion when writing the string. Defaults to `false`.
///
/// - returns: Return total number of bytes written upon success. Return `-1` upon failure.
func write(_ string: String, encoding: String.Encoding = .utf8, allowLossyConversion: Bool = false) -> Int {
if let data = string.data(using: encoding, allowLossyConversion: allowLossyConversion) {
return data.withUnsafeBytes { (bytes: UnsafePointer<UInt8>) -> Int in
var pointer = bytes
var bytesRemaining = data.count
var totalBytesWritten = 0
while bytesRemaining > 0 {
let bytesWritten = self.write(pointer, maxLength: bytesRemaining)
if bytesWritten < 0 {
return -1
}
bytesRemaining -= bytesWritten
pointer += bytesWritten
totalBytesWritten += bytesWritten
}
return totalBytesWritten
}
}
return -1
}
}
// Prepare output file
let tsvURL = URL(fileURLWithPath: fcdFile.replacingOccurrences(of: ".xml", with: ".tsv"))
guard let tsvStream = OutputStream(url: tsvURL, append: true) else {
print("Error: Unable to open output file")
exit(EXIT_FAILURE)
}
tsvStream.open()
// Print header
_ = tsvStream.write("time\tid\txgeo\tygeo\n")
// Auxiliary variable to ensure we get time-sorted data
var lastTimestepTime: Double = -Double.greatestFiniteMagnitude
// Iterate through every timestep and vehicle, outputting TSV-formatted data
for xmlTimestep in fcdXML["fcd-export"]["timestep"] {
// 1. Get this timestep's time
guard let timestepElement = xmlTimestep.element,
let s_time = timestepElement.attribute(by: "time")?.text,
let timestepTime = Double(s_time)
else {
print("Error: Invalid timestep entry.")
exit(EXIT_FAILURE)
}
// 2. We assume the FCD data is provided to us sorted; if not, fail
if lastTimestepTime >= timestepTime {
print("Error: Floating car data not sorted in time.")
exit(EXIT_FAILURE)
} else { lastTimestepTime = timestepTime }
// 3. Iterate through the vehicles on this timestep
for vehicle in xmlTimestep["vehicle"] {
// Load the vehicle's ID and geographic position
guard let vehicleElement = vehicle.element,
let s_id = vehicleElement.attribute(by: "id")?.text,
let v_id = UInt(s_id),
let s_xgeo = vehicleElement.attribute(by: "x")?.text,
let v_xgeo = Double(s_xgeo),
let s_ygeo = vehicleElement.attribute(by: "y")?.text,
let v_ygeo = Double(s_ygeo)
//let s_speed = vehicleElement.attribute(by: "speed")?.text,
//let v_speed = Double(s_speed)
else {
print("Error: Unable to convert vehicle properties.")
print(vehicle.element as Any)
exit(EXIT_FAILURE)
}
// Write data to tsv file
_ = tsvStream.write("\(timestepTime)\t\(v_id)\t\(v_xgeo)\t\(v_ygeo)\n")
}
}
// Close stream
tsvStream.close()
| mit | 77357a7533713d4e5e6ae8abbaa09776 | 29.467626 | 123 | 0.695632 | 3.635193 | false | false | false | false |
jayesh15111988/JKWayfairPriceGame | JKWayfairPriceGame/GameAnswersStatisticsTableViewCell.swift | 1 | 1940 | //
// GameAnswersStatisticsTableViewCell.swift
// JKWayfairPriceGame
//
// Created by Jayesh Kawli Backup on 8/20/16.
// Copyright © 2016 Jayesh Kawli Backup. All rights reserved.
//
import UIKit
enum StatsLabelType: Int {
case Correct = 1
case Incorrect = 0
func labelColor() -> UIColor {
switch self {
case .Correct:
return Appearance.correctAnswerColor()
case .Incorrect:
return Appearance.incorrectAnswerColor()
}
}
}
class GameAnswersStatisticsTableViewCell: UITableViewCell {
let answersStatsLabel: UILabel
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
self.answersStatsLabel = UILabel()
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.answersStatsLabel.translatesAutoresizingMaskIntoConstraints = false
self.answersStatsLabel.numberOfLines = 0
self.answersStatsLabel.font = Appearance.defaultFont()
self.contentView.addSubview(self.answersStatsLabel)
let views = ["answersStatsLabel": answersStatsLabel]
self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-[answersStatsLabel]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
self.contentView.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-[answersStatsLabel]-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: views))
}
func setupWithAnswer(answer: QuizAnswer) {
answersStatsLabel.text = "\(answer.title)\n\nGiven Answer: \(answer.selectedOption)\n\nCorrect Answer: \(answer.correctOption)"
answersStatsLabel.textColor = StatsLabelType(rawValue: Int(answer.isCorrect))?.labelColor()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 390db0115b6083c52bad09058ed1513e | 37.019608 | 189 | 0.697267 | 5.226415 | false | false | false | false |
jtbandes/swift | test/SILGen/objc_dictionary_bridging.swift | 6 | 6734 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %build-silgen-test-overlays
// RUN: %target-swift-frontend(mock-sdk: -sdk %S/Inputs -I %t) -emit-silgen %s | %FileCheck %s
// REQUIRES: objc_interop
import Foundation
import gizmo
@objc class Foo : NSObject {
// Bridging dictionary parameters
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (NSDictionary, Foo) -> ()
func bridge_Dictionary_param(_ dict: Dictionary<Foo, Foo>) {
// CHECK: bb0([[NSDICT:%[0-9]+]] : $NSDictionary, [[SELF:%[0-9]+]] : $Foo):
// CHECK: [[NSDICT_COPY:%.*]] = copy_value [[NSDICT]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxq_GSo12NSDictionaryCSgFZ
// CHECK: [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT_COPY]] : $NSDictionary
// CHECK: [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type
// CHECK: [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]])
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}F
// CHECK: [[RESULT:%[0-9]+]] = apply [[SWIFT_FN]]([[DICT]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> ()
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]] : $()
}
// CHECK: } // end sil function '_T024objc_dictionary_bridging3FooC23bridge_Dictionary_param{{[_0-9a-zA-Z]*}}FTo'
// Bridging dictionary results
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}FTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary
func bridge_Dictionary_result() -> Dictionary<Foo, Foo> {
// CHECK: bb0([[SELF:%[0-9]+]] : $Foo):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SWIFT_FN:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}F : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo>
// CHECK: [[DICT:%[0-9]+]] = apply [[SWIFT_FN]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo>
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF
// CHECK: [[BORROWED_DICT:%.*]] = begin_borrow [[DICT]]
// CHECK: [[NSDICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[BORROWED_DICT]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: end_borrow [[BORROWED_DICT]] from [[DICT]]
// CHECK: destroy_value [[DICT]]
// CHECK: return [[NSDICT]] : $NSDictionary
}
// CHECK: } // end sil function '_T024objc_dictionary_bridging3FooC24bridge_Dictionary_result{{[_0-9a-zA-Z]*}}FTo'
var property: Dictionary<Foo, Foo> = [:]
// Property getter
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGfgTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary
// CHECK: bb0([[SELF:%[0-9]+]] : $Foo):
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[GETTER:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGfg : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo>
// CHECK: [[DICT:%[0-9]+]] = apply [[GETTER]]([[BORROWED_SELF_COPY]]) : $@convention(method) (@guaranteed Foo) -> @owned Dictionary<Foo, Foo>
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE19_bridgeToObjectiveCSo12NSDictionaryCyF
// CHECK: [[BORROWED_DICT:%.*]] = begin_borrow [[DICT]]
// CHECK: [[NSDICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[BORROWED_DICT]]) : $@convention(method) <τ_0_0, τ_0_1 where τ_0_0 : Hashable> (@guaranteed Dictionary<τ_0_0, τ_0_1>) -> @owned NSDictionary
// CHECK: end_borrow [[BORROWED_DICT]] from [[DICT]]
// CHECK: destroy_value [[DICT]]
// CHECK: return [[NSDICT]] : $NSDictionary
// CHECK: } // end sil function '_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGfgTo'
// Property setter
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGfsTo : $@convention(objc_method) (NSDictionary, Foo) -> ()
// CHECK: bb0([[NSDICT:%[0-9]+]] : $NSDictionary, [[SELF:%[0-9]+]] : $Foo):
// CHECK: [[NSDICT_COPY:%.*]] = copy_value [[NSDICT]]
// CHECK: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK: [[CONVERTER:%[0-9]+]] = function_ref @_T0s10DictionaryV10FoundationE36_unconditionallyBridgeFromObjectiveCAByxq_GSo12NSDictionaryCSgFZ
// CHECK: [[OPT_NSDICT:%[0-9]+]] = enum $Optional<NSDictionary>, #Optional.some!enumelt.1, [[NSDICT_COPY]] : $NSDictionary
// CHECK: [[DICT_META:%[0-9]+]] = metatype $@thin Dictionary<Foo, Foo>.Type
// CHECK: [[DICT:%[0-9]+]] = apply [[CONVERTER]]<Foo, Foo>([[OPT_NSDICT]], [[DICT_META]])
// CHECK: [[BORROWED_SELF_COPY:%.*]] = begin_borrow [[SELF_COPY]]
// CHECK: [[SETTER:%[0-9]+]] = function_ref @_T024objc_dictionary_bridging3FooC8propertys10DictionaryVyA2CGfs : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> ()
// CHECK: [[RESULT:%[0-9]+]] = apply [[SETTER]]([[DICT]], [[BORROWED_SELF_COPY]]) : $@convention(method) (@owned Dictionary<Foo, Foo>, @guaranteed Foo) -> ()
// CHECK: end_borrow [[BORROWED_SELF_COPY]] from [[SELF_COPY]]
// CHECK: destroy_value [[SELF_COPY]]
// CHECK: return [[RESULT]] : $()
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC19nonVerbatimProperty{{[_0-9a-zA-Z]*}}fgTo : $@convention(objc_method) (Foo) -> @autoreleased NSDictionary
// CHECK-LABEL: sil hidden [thunk] @_T024objc_dictionary_bridging3FooC19nonVerbatimProperty{{[_0-9a-zA-Z]*}}fsTo : $@convention(objc_method) (NSDictionary, Foo) -> ()
@objc var nonVerbatimProperty: Dictionary<String, Int> = [:]
}
func ==(x: Foo, y: Foo) -> Bool { }
| apache-2.0 | 07b354b2cad8ea75ed2d1483848efc8b | 71.301075 | 208 | 0.6395 | 3.375502 | false | false | false | false |
LiLe2015/DouYuLive | DouYuLive/DouYuLive/Classes/Home/Model/AnchorGroup.swift | 1 | 1283 | //
// AnchorGroup.swift
// DouYuLive
//
// Created by LiLe on 2016/11/15.
// Copyright © 2016年 LiLe. All rights reserved.
//
import UIKit
class AnchorGroup: NSObject {
/// 该组对应的房间信息
var room_list: [[String : NSObject]]? {
didSet {
guard let room_list = room_list else { return }
for dict in room_list {
anchors.append(AnchorModel(dict: dict))
}
}
}
/// 组显示的标题
var tag_name: String = ""
/// 组显示的图标
var icon_name: String = "home_header_normal"
/// 定义主播的模型对象数组
lazy var anchors: [AnchorModel] = [AnchorModel]()
// 构造函数
override init() {
}
init(dict: [String : NSObject]) {
super.init()
setValuesForKeysWithDictionary(dict)
}
override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
/*
override func setValue(value: AnyObject?, forKey key: String) {
if key == "room_list" {
if let dataArray = value as? [[String : NSObject]] {
for dict in dataArray {
anchors.append(AnchorModel(dict: dict))
}
}
}
}
*/
}
| mit | da0393a2ede99e5b9ce5d3adc3695cff | 22.230769 | 77 | 0.525662 | 4.238596 | false | false | false | false |
loudnate/Loop | Loop/Managers/StatusExtensionDataManager.swift | 1 | 5694 | //
// StatusExtensionDataManager.swift
// Loop
//
// Created by Bharat Mediratta on 11/25/16.
// Copyright © 2016 Nathan Racklyeft. All rights reserved.
//
import HealthKit
import UIKit
import LoopKit
final class StatusExtensionDataManager {
unowned let deviceManager: DeviceDataManager
init(deviceDataManager: DeviceDataManager) {
self.deviceManager = deviceDataManager
NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived(_:)), name: .LoopDataUpdated, object: deviceDataManager.loopManager)
NotificationCenter.default.addObserver(self, selector: #selector(notificationReceived(_:)), name: .PumpManagerChanged, object: nil)
// Wait until LoopDataManager has had a chance to initialize itself
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
self.update()
}
}
fileprivate var defaults: UserDefaults? {
return UserDefaults.appGroup
}
var context: StatusExtensionContext? {
return defaults?.statusExtensionContext
}
@objc private func notificationReceived(_ notification: Notification) {
update()
}
private func update() {
guard let unit = (deviceManager.loopManager.glucoseStore.preferredUnit ?? context?.predictedGlucose?.unit) else {
return
}
createContext(glucoseUnit: unit) { (context) in
if let context = context {
self.defaults?.statusExtensionContext = context
}
}
}
private func createContext(glucoseUnit: HKUnit, _ completionHandler: @escaping (_ context: StatusExtensionContext?) -> Void) {
let basalDeliveryState = deviceManager.pumpManager?.status.basalDeliveryState
deviceManager.loopManager.getLoopState { (manager, state) in
let dataManager = self.deviceManager
var context = StatusExtensionContext()
#if IOS_SIMULATOR
// If we're in the simulator, there's a higher likelihood that we don't have
// a fully configured app. Inject some baseline debug data to let us test the
// experience. This data will be overwritten by actual data below, if available.
context.batteryPercentage = 0.25
context.netBasal = NetBasalContext(
rate: 2.1,
percentage: 0.6,
start:
Date(timeIntervalSinceNow: -250),
end: Date(timeIntervalSinceNow: .minutes(30))
)
context.predictedGlucose = PredictedGlucoseContext(
values: (1...36).map { 89.123 + Double($0 * 5) }, // 3 hours of linear data
unit: HKUnit.milligramsPerDeciliter,
startDate: Date(),
interval: TimeInterval(minutes: 5))
let lastLoopCompleted = Date(timeIntervalSinceNow: -TimeInterval(minutes: 0))
#else
let lastLoopCompleted = manager.lastLoopCompleted
#endif
context.lastLoopCompleted = lastLoopCompleted
// Drop the first element in predictedGlucose because it is the currentGlucose
// and will have a different interval to the next element
if let predictedGlucose = state.predictedGlucose?.dropFirst(),
predictedGlucose.count > 1 {
let first = predictedGlucose[predictedGlucose.startIndex]
let second = predictedGlucose[predictedGlucose.startIndex.advanced(by: 1)]
context.predictedGlucose = PredictedGlucoseContext(
values: predictedGlucose.map { $0.quantity.doubleValue(for: glucoseUnit) },
unit: glucoseUnit,
startDate: first.startDate,
interval: second.startDate.timeIntervalSince(first.startDate))
}
if let basalDeliveryState = basalDeliveryState,
let basalSchedule = manager.basalRateScheduleApplyingOverrideHistory,
let netBasal = basalDeliveryState.getNetBasal(basalSchedule: basalSchedule, settings: manager.settings)
{
context.netBasal = NetBasalContext(rate: netBasal.rate, percentage: netBasal.percent, start: netBasal.start, end: netBasal.end)
}
context.batteryPercentage = dataManager.pumpManager?.status.pumpBatteryChargeRemaining
context.reservoirCapacity = dataManager.pumpManager?.pumpReservoirCapacity
if let sensorInfo = dataManager.sensorState {
context.sensor = SensorDisplayableContext(
isStateValid: sensorInfo.isStateValid,
stateDescription: sensorInfo.stateDescription,
trendType: sensorInfo.trendType,
isLocal: sensorInfo.isLocal
)
}
if let pumpManagerHUDProvider = dataManager.pumpManagerHUDProvider {
context.pumpManagerHUDViewsContext = PumpManagerHUDViewsContext(pumpManagerHUDViewsRawValue: PumpManagerHUDViewsRawValueFromHUDProvider(pumpManagerHUDProvider))
}
completionHandler(context)
}
}
}
extension StatusExtensionDataManager: CustomDebugStringConvertible {
var debugDescription: String {
return [
"## StatusExtensionDataManager",
"appGroupName: \(Bundle.main.appGroupSuiteName)",
"statusExtensionContext: \(String(reflecting: defaults?.statusExtensionContext))",
""
].joined(separator: "\n")
}
}
| apache-2.0 | 6fb18b9c9fb06f453c779ca744c6f6bf | 40.554745 | 176 | 0.631477 | 5.815117 | false | false | false | false |
pashka-kim/ourProject | My apps/saveHighScore/saveHighScore/ViewController.swift | 1 | 2001 | //
// ViewController.swift
// saveHighScore
//
// Created by Pavel on 23.02.17.
// Copyright © 2017 k.brklyn. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var scoreLabel: UILabel!
@IBOutlet weak var highscoreLabel: UILabel!
var Score = 0, Highscore = 0
override func viewDidLoad() {
super.viewDidLoad()
let HighscoreDefault = UserDefaults.standard
if HighscoreDefault.value(forKey: "Highscore") != nil
{
Highscore = HighscoreDefault.value(forKey: "Highscore") as! NSInteger
}
highscoreLabel.text = NSString(format: "Highscore: %i", Highscore) as String
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func resetButon(_ sender: Any)
{
Score = 0
scoreLabel.text = NSString(format: "Score: %i", Score) as String
}
@IBAction func countScoreButton(_ sender: Any)
{
Score += 1
scoreLabel.text = NSString(format: "Score: %i", Score) as String
if Score > Highscore
{
Highscore = Score
highscoreLabel.text = NSString(format: "Highscore: %i", Highscore) as String
let HighscoreDefault = UserDefaults.standard
HighscoreDefault.setValue(Highscore, forKey: "Highscore")
HighscoreDefault.synchronize()
}
}
@IBAction func fullResetButton(_ sender: Any) {
Score = 0
Highscore = 0
let HighscoreDefault = UserDefaults.standard
HighscoreDefault.setValue(Highscore, forKey: "Highscore")
HighscoreDefault.synchronize()
highscoreLabel.text = NSString(format: "Highscore: %i", Highscore) as String
scoreLabel.text = NSString(format: "Score: %i", Score) as String
}
}
| gpl-3.0 | 764a95db0a90d1d100dbb62f76ecff6d | 27.169014 | 88 | 0.6045 | 4.926108 | false | false | false | false |
aahmedae/blitz-news-ios | Blitz News/Controller/SourcesViewController.swift | 1 | 2633 | //
// SourcesViewController.swift
// Blitz News
//
// Created by Asad Ahmed on 5/16/17.
// VC reponsible for simply displaying the sources the user prefers and navigating to the news VC to show news for that source
//
import UIKit
class SourcesViewController: NewsSourceViewController
{
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var sourcesMessageLabel: UILabel!
// MARK:- Setup
override func viewWillAppear(_ animated: Bool)
{
loadSources()
}
override func viewDidLoad()
{
super.viewDidLoad()
allowUserSelections = false
view.backgroundColor = UISettings.VC_BACKGROUND_COLOR
}
// Loads the data for the sources
fileprivate func loadSources()
{
// load sources from core data storage
sources = CoreDataManager.sharedInstance.getNewsSources(userSelectedSources: true)
// set user message if no sources
sourcesMessageLabel.isHidden = (sources.count > 0)
// clear out categoryIDs for new batch of data since the user might have removed a category
categoryIDs.removeAll()
// set the category IDs for sources that the user has selected
for source in sources
{
if !categoryIDs.contains(source.categoryID!) {
categoryIDs.append(source.categoryID!)
}
}
categoryIDs.sort()
setupNewsSourceTableView(tableView: tableView)
}
// MARK:- Table View
// User taps on cell to navigate to see news for that source
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath)
{
tableView.deselectRow(at: indexPath, animated: false)
// navigate to news list view controller
let source = sourceForIndexPath(indexPath)
performSegue(withIdentifier: "ToNewsListVC", sender: source)
}
// MARK:- Events
@IBAction func addButtonTapped(_ sender: UIBarButtonItem)
{
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let addSourcesVC = storyboard.instantiateViewController(withIdentifier: "AddSourcesVC")
present(addSourcesVC, animated: true, completion: nil)
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?)
{
// set the source for the news list VC to show
if let vc = segue.destination as? NewsListViewController {
if let source = sender as? NewsSource {
vc.source = source
}
}
}
}
| mit | 60c5a8c2875f62fe5a06c23f76ac00fd | 28.920455 | 127 | 0.633878 | 5.073218 | false | false | false | false |
Look-ARound/LookARound2 | lookaround2/Models/LookAnchor.swift | 1 | 2103 | import ARKit
import CoreLocation
import Turf
public class LookAnchor: ARAnchor {
public var calloutString: String?
public convenience init(originLocation: CLLocation, location: CLLocation) {
let transform = matrix_identity_float4x4.transformMatrix(originLocation: originLocation, location: location)
self.init(transform: transform)
}
}
internal extension simd_float4x4 {
// Effectively copy the position of the start location, rotate it about
// the bearing of the end location and "push" it out the required distance
func transformMatrix(originLocation: CLLocation, location: CLLocation) -> simd_float4x4 {
// Determine the distance and bearing between the start and end locations
let distance = Float(location.distance(from: originLocation))
let scaledHeight = (distance / 100) * 1.5
let bearing = GLKMathDegreesToRadians(Float(originLocation.coordinate.direction(to: location.coordinate)))
// Effectively copy the position of the start location, rotate it about
// the bearing of the end location and instesad of "pushing" it out, lift it up in altitude
let position = vector_float4(0.0, scaledHeight, -30.0, 0.0)
let translationMatrix = matrix_identity_float4x4.translationMatrix(position)
let rotationMatrix = matrix_identity_float4x4.rotationAroundY(radians: bearing)
let transformMatrix = simd_mul(rotationMatrix, translationMatrix)
return simd_mul(self, transformMatrix)
}
}
internal extension matrix_float4x4 {
func rotationAroundY(radians: Float) -> matrix_float4x4 {
var m : matrix_float4x4 = self;
m.columns.0.x = cos(radians);
m.columns.0.z = -sin(radians);
m.columns.2.x = sin(radians);
m.columns.2.z = cos(radians);
return m.inverse;
}
func translationMatrix(_ translation : vector_float4) -> matrix_float4x4 {
var m : matrix_float4x4 = self
m.columns.3 = translation
return m
}
}
| apache-2.0 | b57e8fce49a9512e6c68db66ccff1f01 | 35.894737 | 116 | 0.671897 | 4.318275 | false | false | false | false |
mddios/SwiftQRCode | QRCode/Source/QRCode.swift | 3 | 10241 | //
// QRCode.swift
// QRCode
//
// Created by 刘凡 on 15/5/15.
// Copyright (c) 2015年 joyios. All rights reserved.
//
import UIKit
import AVFoundation
public class QRCode: NSObject, AVCaptureMetadataOutputObjectsDelegate {
/// corner line width
var lineWidth: CGFloat
/// corner stroke color
var strokeColor: UIColor
/// the max count for detection
var maxDetectedCount: Int
/// current count for detection
var currentDetectedCount: Int = 0
/// auto remove sub layers when detection completed
var autoRemoveSubLayers: Bool
/// completion call back
var completedCallBack: ((stringValue: String) -> ())?
/// the scan rect, default is the bounds of the scan view, can modify it if need
public var scanFrame: CGRect = CGRectZero
/// init function
///
/// - returns: the scanner object
public override init() {
self.lineWidth = 4
self.strokeColor = UIColor.greenColor()
self.maxDetectedCount = 20
self.autoRemoveSubLayers = false
super.init()
}
/// init function
///
/// - parameter autoRemoveSubLayers: remove sub layers auto after detected code image
/// - parameter lineWidth: line width, default is 4
/// - parameter strokeColor: stroke color, default is Green
/// - parameter maxDetectedCount: max detecte count, default is 20
///
/// - returns: the scanner object
public init(autoRemoveSubLayers: Bool, lineWidth: CGFloat = 4, strokeColor: UIColor = UIColor.greenColor(), maxDetectedCount: Int = 20) {
self.lineWidth = lineWidth
self.strokeColor = strokeColor
self.maxDetectedCount = maxDetectedCount
self.autoRemoveSubLayers = autoRemoveSubLayers
}
deinit {
if session.running {
session.stopRunning()
}
removeAllLayers()
}
/// Generate Qrcode Image
///
/// - parameter stringValue: string value to encoe
/// - parameter avatarImage: avatar image will display in the center of qrcode image
/// - parameter avatarScale: the scale for avatar image, default is 0.25
///
/// - returns: the generated image
class public func generateImage(stringValue: String, avatarImage: UIImage?, avatarScale: CGFloat = 0.25) -> UIImage? {
return generateImage(stringValue, avatarImage: avatarImage, avatarScale: avatarScale, color: CIColor(color: UIColor.blackColor())!, backColor: CIColor(color: UIColor.whiteColor())!)
}
/// Generate Qrcode Image
///
/// - parameter stringValue: string value to encoe
/// - parameter avatarImage: avatar image will display in the center of qrcode image
/// - parameter avatarScale: the scale for avatar image, default is 0.25
/// - parameter color: the CI color for forenground, default is black
/// - parameter backColor: th CI color for background, default is white
///
/// - returns: the generated image
class public func generateImage(stringValue: String, avatarImage: UIImage?, avatarScale: CGFloat = 0.25, color: CIColor, backColor: CIColor) -> UIImage? {
// generate qrcode image
let qrFilter = CIFilter(name: "CIQRCodeGenerator")
qrFilter.setDefaults()
qrFilter.setValue(stringValue.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false), forKey: "inputMessage")
let ciImage = qrFilter.outputImage
// scale qrcode image
let colorFilter = CIFilter(name: "CIFalseColor")
colorFilter.setDefaults()
colorFilter.setValue(ciImage, forKey: "inputImage")
colorFilter.setValue(color, forKey: "inputColor0")
colorFilter.setValue(backColor, forKey: "inputColor1")
let transform = CGAffineTransformMakeScale(5, 5)
let transformedImage = colorFilter.outputImage.imageByApplyingTransform(transform)
let image = UIImage(CIImage: transformedImage)
if avatarImage != nil && image != nil {
return insertAvatarImage(image!, avatarImage: avatarImage!, scale: avatarScale)
}
return image
}
class func insertAvatarImage(codeImage: UIImage, avatarImage: UIImage, scale: CGFloat) -> UIImage {
let rect = CGRectMake(0, 0, codeImage.size.width, codeImage.size.height)
UIGraphicsBeginImageContext(rect.size)
codeImage.drawInRect(rect)
let avatarSize = CGSizeMake(rect.size.width * scale, rect.size.height * scale)
let x = (rect.width - avatarSize.width) * 0.5
let y = (rect.height - avatarSize.height) * 0.5
avatarImage.drawInRect(CGRectMake(x, y, avatarSize.width, avatarSize.height))
let result = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return result
}
// MARK: - Video Scan
/// prepare scan
///
/// - parameter view: the scan view, the preview layer and the drawing layer will be insert into this view
/// - parameter completion: the completion call back
public func prepareScan(view: UIView, completion:(stringValue: String)->()) {
scanFrame = view.bounds
completedCallBack = completion
currentDetectedCount = 0
setupSession()
setupLayers(view)
}
/// start scan
public func startScan() {
if session.running {
println("the capture session is running")
return
}
session.startRunning()
}
/// stop scan
public func stopScan() {
if !session.running {
println("the capture session is running")
return
}
session.stopRunning()
}
func setupLayers(view: UIView) {
drawLayer.frame = view.bounds
view.layer.insertSublayer(drawLayer, atIndex: 0)
previewLayer.frame = view.bounds
view.layer.insertSublayer(previewLayer, atIndex: 0)
}
func setupSession() {
if session.running {
println("the capture session is running")
return
}
if !session.canAddInput(videoInput) {
println("can not add input device")
return
}
if !session.canAddOutput(dataOutput) {
println("can not add output device")
return
}
session.addInput(videoInput)
session.addOutput(dataOutput)
dataOutput.metadataObjectTypes = dataOutput.availableMetadataObjectTypes;
dataOutput.setMetadataObjectsDelegate(self, queue: dispatch_get_main_queue())
}
public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
clearDrawLayer()
for dataObject in metadataObjects {
if let codeObject = dataObject as? AVMetadataMachineReadableCodeObject {
let obj = previewLayer.transformedMetadataObjectForMetadataObject(codeObject) as! AVMetadataMachineReadableCodeObject
if CGRectContainsRect(scanFrame, obj.bounds) {
if currentDetectedCount++ > maxDetectedCount {
session.stopRunning()
completedCallBack!(stringValue: codeObject.stringValue)
if autoRemoveSubLayers {
removeAllLayers()
}
}
// transform codeObject
drawCodeCorners(previewLayer.transformedMetadataObjectForMetadataObject(codeObject) as! AVMetadataMachineReadableCodeObject)
}
}
}
}
public func removeAllLayers() {
previewLayer.removeFromSuperlayer()
drawLayer.removeFromSuperlayer()
}
func clearDrawLayer() {
if drawLayer.sublayers == nil {
return
}
for layer in drawLayer.sublayers {
layer.removeFromSuperlayer()
}
}
func drawCodeCorners(codeObject: AVMetadataMachineReadableCodeObject) {
if codeObject.corners.count == 0 {
return
}
let shapeLayer = CAShapeLayer()
shapeLayer.lineWidth = lineWidth
shapeLayer.strokeColor = strokeColor.CGColor
shapeLayer.fillColor = UIColor.clearColor().CGColor
shapeLayer.path = createPath(codeObject.corners).CGPath
drawLayer.addSublayer(shapeLayer)
}
func createPath(points: NSArray) -> UIBezierPath {
let path = UIBezierPath()
var point = CGPoint()
var index = 0
CGPointMakeWithDictionaryRepresentation(points[index++] as! CFDictionaryRef, &point)
path.moveToPoint(point)
while index < points.count {
CGPointMakeWithDictionaryRepresentation(points[index++] as! CFDictionaryRef, &point)
path.addLineToPoint(point)
}
path.closePath()
return path
}
/// previewLayer
lazy var previewLayer: AVCaptureVideoPreviewLayer = {
let layer = AVCaptureVideoPreviewLayer(session: self.session)
layer.videoGravity = AVLayerVideoGravityResizeAspectFill
return layer
}()
/// drawLayer
lazy var drawLayer: CALayer = {
return CALayer()
}()
/// session
lazy var session: AVCaptureSession = {
return AVCaptureSession()
}()
/// input
lazy var videoInput: AVCaptureDeviceInput? = {
if let device = AVCaptureDevice.defaultDeviceWithMediaType(AVMediaTypeVideo) {
return AVCaptureDeviceInput(device: device, error: nil)
}
return nil
}()
/// output
lazy var dataOutput: AVCaptureMetadataOutput = {
return AVCaptureMetadataOutput()
}()
} | mit | eaa388857261fd171d32d6a246ab885a | 33.234114 | 189 | 0.611724 | 5.733894 | false | false | false | false |
ifabijanovic/RxBattleNet | RxBattleNet/WoW/Model/Talents.swift | 1 | 2209 | //
// Talents.swift
// RxBattleNet
//
// Created by Ivan Fabijanović on 07/08/16.
// Copyright © 2016 Ivan Fabijanovic. All rights reserved.
//
import SwiftyJSON
public extension WoW {
public struct Talents: Model {
public struct CharacterSpec: Model {
public let backgroundImage: String
public let descriptionField: String
public let icon: String
public let name: String
public let order: Int
public let role: String
internal init(json: JSON) {
self.backgroundImage = json["backgroundImage"].stringValue
self.descriptionField = json["description"].stringValue
self.icon = json["icon"].stringValue
self.name = json["name"].stringValue
self.order = json["order"].intValue
self.role = json["role"].stringValue
}
}
public struct Talent: Model {
public let column: Int
public let spell: WoW.Spell
public let tier: Int
public let spec: WoW.Talents.CharacterSpec
internal init(json: JSON) {
self.column = json["column"].intValue
self.spell = WoW.Spell(json: json["spell"])
self.tier = json["tier"].intValue
self.spec = WoW.Talents.CharacterSpec(json: json["spec"])
}
}
// MARK: - Properties
public let characterClass: String
public let characterSpecs: [WoW.Talents.CharacterSpec]
public let talents: [[[WoW.Talents.Talent]]]
// MARK: - Init
internal init(json: JSON) {
self.characterClass = json["class"].stringValue
self.characterSpecs = json["specs"].map { WoW.Talents.CharacterSpec(json: $1) }
self.talents = json["talents"].map { (_, row) in
row.map { (_, column) in
column.map { (_, spec) in
WoW.Talents.Talent(json: spec)
}
}
}
}
}
}
| mit | 089ad0f1ef944eb1820d86d721e1b135 | 30.985507 | 91 | 0.513367 | 5.004535 | false | false | false | false |
serp1412/LazyTransitions | LazyTransitions/StaticViewGestureHandler.swift | 1 | 2179 | //
// StaticViewGestureHandler.swift
// LazyTransitions
//
// Created by Serghei Catraniuc on 12/6/16.
// Copyright © 2016 BeardWare. All rights reserved.
//
import Foundation
public class StaticViewGestureHandler: TransitionGestureHandlerType {
public var shouldFinish: Bool = false
public var didBegin: Bool = false
public var inProgressTransitionOrientation = TransitionOrientation.unknown
public weak var delegate: TransitionGestureHandlerDelegate?
public init() {}
public func didBegin(_ gesture: UIPanGestureRecognizer) {
inProgressTransitionOrientation = gesture.direction.orientation
didBegin = true
delegate?.beginInteractiveTransition(with: inProgressTransitionOrientation)
}
public func didChange(_ gesture: UIPanGestureRecognizer) {
let translation = gesture.translation(in: gesture.view)
let progress = calculateTransitionProgressWithTranslation(translation, on: gesture.view)
shouldFinish = progress > progressThreshold
delegate?.updateInteractiveTransitionWithProgress(progress)
}
public func calculateTransitionProgressWithTranslation(_ translation: CGPoint, on view: UIView?) -> CGFloat {
guard let view = view else { return 0 }
let progress = TransitionProgressCalculator
.progress(for: view,
withGestureTranslation: translation,
withTranslationOffset: .zero,
with: inProgressTransitionOrientation)
return progress
}
}
extension UIPanGestureRecognizerDirection {
public var orientation: TransitionOrientation {
switch self {
case .rightToLeft: return .rightToLeft
case .leftToRight: return .leftToRight
case .bottomToTop: return .bottomToTop
case .topToBottom: return .topToBottom
default: return .unknown
}
}
}
extension UIPanGestureRecognizerDirection {
public var isHorizontal: Bool {
switch self {
case .rightToLeft, .leftToRight:
return true
default:
return false
}
}
}
| bsd-2-clause | dfec8d82713c4124ee0ad7dabee1f6ef | 31.507463 | 113 | 0.676768 | 5.686684 | false | false | false | false |
mirchow/HungerFreeCity | ios/Hunger Free City/Models/PlaceMarker.swift | 1 | 546 | //
// PlaceMarker.swift
// Hunger Free City
//
// Created by Mirek Chowaniok on 6/26/15.
// Copyright (c) 2015 Jacksonville Community. All rights reserved.
//
import UIKit
import GoogleMaps
class PlaceMarker: GMSMarker {
let place: GooglePlace
init(place: GooglePlace) {
self.place = place
super.init()
position = place.coordinate
icon = UIImage(named: place.placeType+"_pin")
groundAnchor = CGPoint(x: 0.5, y: 1)
//appearAnimation = kGMSMarkerAnimationPop
}
}
| mit | 709b6857eeb58e8f7be4636a81bae0ac | 20.84 | 67 | 0.628205 | 3.791667 | false | false | false | false |
VBVMI/VerseByVerse-iOS | VBVMI/NSManagedObject+Extensions.swift | 1 | 4441 | //
// NSManagedObject+Extensions.swift
// VBVMI
//
// Created by Thomas Carey on 3/02/16.
// Copyright © 2016 Tom Carey. All rights reserved.
//
import Foundation
import CoreData
extension NSManagedObject {
class func VB_entityName() -> String {
return NSStringFromClass(self)
}
class func entityDescriptionInContext(_ context: NSManagedObjectContext) -> NSEntityDescription? {
return NSEntityDescription.entity(forEntityName: VB_entityName(), in: context)
}
class func findFirstOrCreate<T: NSManagedObject>(_ predicate: NSPredicate, context: NSManagedObjectContext) -> T? {
let fetchRequest = NSFetchRequest<T>(entityName: VB_entityName())
fetchRequest.predicate = predicate
fetchRequest.fetchLimit = 1
fetchRequest.entity = entityDescriptionInContext(context)
var results = [AnyObject]()
context.performAndWait({ () -> Void in
do {
results = try context.fetch(fetchRequest)
} catch let error {
logger.error("Error executing fetch: \(error)")
}
})
if let result = results.first {
return result as? T
}
guard let entityDesciption = entityDescriptionInContext(context) else { return nil }
var object: NSManagedObject?
context.performAndWait { () -> Void in
object = self.init(entity: entityDesciption, insertInto: context)
}
return object as? T
}
class func findFirstOrCreateWithDictionary(_ dict: [String: String], context: NSManagedObjectContext) -> NSManagedObject? {
return findFirstOrCreate(NSPredicate.predicateWithDictionary(dict), context: context)
}
class func findFirstWithDictionary(_ dict: [String: String], context: NSManagedObjectContext) -> NSManagedObject? {
let predicate = NSPredicate.predicateWithDictionary(dict)
return findFirstWithPredicate(predicate, context: context)
}
class func findFirst<T: NSManagedObject>(_ context: NSManagedObjectContext) -> T? {
let fetchRequest = NSFetchRequest<T>(entityName: VB_entityName())
fetchRequest.fetchLimit = 1
fetchRequest.entity = entityDescriptionInContext(context)
let result = try? context.fetch(fetchRequest)
return result?.first
}
class func findFirstWithPredicate<T: NSManagedObject>(_ predicate: NSPredicate, context: NSManagedObjectContext) -> T? {
let fetchRequest = NSFetchRequest<T>(entityName: VB_entityName())
fetchRequest.predicate = predicate
fetchRequest.fetchLimit = 1
fetchRequest.entity = entityDescriptionInContext(context)
let result = try? context.fetch(fetchRequest)
return result?.first
}
class func withIdentifier<T: NSManagedObject>(_ identifier: NSManagedObjectID, context: NSManagedObjectContext) throws -> T? {
return try context.existingObject(with: identifier) as? T
}
class func findAllWithDictionary(_ dict: [String: String], context: NSManagedObjectContext) -> [NSManagedObject] {
let predicate = NSPredicate.predicateWithDictionary(dict)
return findAllWithPredicate(predicate, context: context)
}
class func findAllWithPredicate<T: NSManagedObject>(_ predicate: NSPredicate, context: NSManagedObjectContext) -> [T] {
let fetchRequest = NSFetchRequest<T>(entityName: VB_entityName())
fetchRequest.predicate = predicate
fetchRequest.entity = entityDescriptionInContext(context)
let result = try? context.fetch(fetchRequest)
return result ?? []
}
class func findAll<T: NSManagedObject>(_ context: NSManagedObjectContext) -> [T] {
let fetchRequest = NSFetchRequest<T>(entityName: VB_entityName())
fetchRequest.entity = entityDescriptionInContext(context)
let result = try? context.fetch(fetchRequest)
return result ?? []
}
}
extension NSPredicate {
class func predicateWithDictionary(_ dict: [String: String]) -> NSPredicate {
var predicates = [NSPredicate]()
for (key, value) in dict {
predicates.append(NSPredicate(format: "%K == %@", key, value))
}
return NSCompoundPredicate(andPredicateWithSubpredicates: predicates)
}
}
| mit | 654df5af2e8d9d4a5046d8b7d9743794 | 37.275862 | 130 | 0.660135 | 5.529265 | false | false | false | false |
12207480/PureLayout | PureLayout/Example-iOS/Demos/iOSDemo6ViewController.swift | 1 | 2179 | //
// iOSDemo6ViewController.swift
// PureLayout Example-iOS
//
// Copyright (c) 2015 Tyler Fox
// https://github.com/smileyborg/PureLayout
//
import UIKit
import PureLayout
class iOSDemo6ViewController: UIViewController {
let blueView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .blueColor()
return view
}()
var didSetupConstraints = false
override func loadView() {
view = UIView()
view.backgroundColor = UIColor(white: 0.1, alpha: 1.0)
view.addSubview(blueView)
view.setNeedsUpdateConstraints() // bootstrap Auto Layout
}
override func updateViewConstraints() {
if (!didSetupConstraints) {
// Center the blueView in its superview, and match its width to its height
blueView.autoCenterInSuperview()
blueView.autoMatchDimension(.Width, toDimension: .Height, ofView: blueView)
// Make sure the blueView is always at least 20 pt from any edge
blueView.autoPinToTopLayoutGuideOfViewController(self, withInset: 20.0, relation: .GreaterThanOrEqual)
blueView.autoPinToBottomLayoutGuideOfViewController(self, withInset: 20.0, relation: .GreaterThanOrEqual)
blueView.autoPinEdgeToSuperviewEdge(.Left, withInset: 20.0, relation: .GreaterThanOrEqual)
blueView.autoPinEdgeToSuperviewEdge(.Right, withInset: 20.0, relation: .GreaterThanOrEqual)
// Add constraints that set the size of the blueView to a ridiculously large size, but set the priority of these constraints
// to a lower value than Required. This allows the Auto Layout solver to let these constraints be broken if one or both of
// them conflict with higher-priority constraint(s), such as the above 4 edge constraints.
UIView.autoSetPriority(UILayoutPriorityDefaultHigh) {
blueView.autoSetDimensionsToSize(CGSize(width: 10000.0, height: 10000.0))
}
didSetupConstraints = true
}
super.updateViewConstraints()
}
}
| mit | 220a0db24a7deed1cd64a2e3f3acc252 | 38.618182 | 136 | 0.658559 | 5.353808 | false | false | false | false |
findmybusnj/findmybusnj-swift | findmybusnj-widget/TodayViewController.swift | 1 | 6247 | //
// TodayViewController.swift
// Find My Bus NJ Today Widget
//
// Created by David Aghassi on 4/6/16.
// Copyright © 2016 David Aghassi. All rights reserved.
//
import UIKit
import NotificationCenter
// Dependencies
import SwiftyJSON
import findmybusnj_common
class TodayViewController: UIViewController {
// MARK: Properties
fileprivate var items: JSON = []
fileprivate var stop = "", route = ""
// MARK: Managers & Presenters
fileprivate let networkManager = ServerManager()
fileprivate let tableViewCellPresenter = WidgetTodayViewCellPresenter()
fileprivate let bannerPresenter = WidgetBannerPresenter()
fileprivate let sanatizer = JSONSanitizer()
// MARK: Outlets
@IBOutlet weak var stopLabel: UILabel!
@IBOutlet weak var routeLabel: UILabel!
@IBOutlet weak var etaTableView: UITableView!
@IBOutlet weak var nextArrivingLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Fade in without retaining self
view.alpha = 0
UIView.animate(withDuration: 0.4, animations: { [unowned self] in
self.view.alpha = 1
})
etaTableView.separatorColor = UIColor.clear
etaTableView.tableFooterView = UIView(frame: CGRect.zero)
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view from its nib.
loadFromAppGroup()
if #available(iOS 10.0, *) {
self.extensionContext?.widgetLargestAvailableDisplayMode = .expanded
} else {
// Fallback on earlier versions
nextArrivingLabel.textColor = UIColor.white
routeLabel.textColor = UIColor.white
stopLabel.textColor = UIColor.white
}
if !route.isEmpty {
networkManager.getJSONForStopFilteredByRoute(stop,
route: route,
completion: { [unowned self] (item, _) in
// If error we don't change anything.
if !item.isEmpty {
self.updateTable(item)
}
})
} else {
networkManager.getJSONForStop(stop, completion: { [unowned self] (item, _) in
// If error we don't change anything.
if !item.isEmpty {
self.updateTable(item)
}
})
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/**
Loads the most recent `stop` and `route` from the shared AppGroup
*/
fileprivate func loadFromAppGroup() {
if let appGroup = UserDefaults.init(suiteName: "group.aghassi.TodayExtensionSharingDefaults") {
guard let currentStop = appGroup.object(forKey: "currentStop") as? String else {
return
}
stop = currentStop
stopLabel.text = stop
if let selectedStop = appGroup.object(forKey: "filterRoute") as? String {
route = selectedStop
} else {
route = ""
}
routeLabel.text = route
}
}
/**
Used as a callback to update the `tableView` with new data, if any.
- parameter items: Items that will populate the `tableView`
*/
fileprivate func updateTable(_ items: JSON) {
updateBanner(items)
self.items = items
etaTableView.reloadData()
// Let the system handle the resize
guard #available(iOS 10.0, *) else {
// If we are on iOS 9, do it ourself
updateViewSize()
return
}
}
/**
Used as a callback to update the `nextArrivingLabel` with the first item in the json response.
- paramater items Items that were returned from the network call for the next buses
*/
fileprivate func updateBanner(_ items: JSON) {
if let jsonArray = items.array {
if let firstResponse = jsonArray.first {
bannerPresenter.assignTextForArrivalBanner(label: self.nextArrivingLabel, json: firstResponse)
}
}
}
/**
Updates the views `preferredContentSize` based on the height of the tableView
NOTE: This method is only called for iOS 9. iOS 10 uses `widgetActiveDisplayModeDidChange`
*/
fileprivate func updateViewSize() {
// Get the size and add a little so we don't cut off the button cell
// Set the new size to the size of the widget
let newHeight = etaTableView.contentSize.height + stopLabel.intrinsicContentSize.height + 100
let constantWidth = etaTableView.contentSize.width
let newPreferredContentSize = CGSize(width: constantWidth, height: newHeight)
self.preferredContentSize = newPreferredContentSize
}
@available(iOS 10.0, *)
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
if activeDisplayMode == NCWidgetDisplayMode.compact {
self.preferredContentSize = maxSize
} else {
self.preferredContentSize = CGSize(width: maxSize.width, height: 400)
}
}
}
// MARK: NCWidgetProviding
extension TodayViewController: NCWidgetProviding {
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
completionHandler(NCUpdateResult.newData)
}
}
// MARK: UITableViewDataSource
extension TodayViewController: UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if let array = items.array {
if array.count > 5 {
return 5
} else {
return array.count
}
} else {
return 0
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let identifier = "arrivalCell"
let cell = tableView.dequeueReusableCell(withIdentifier: identifier, for: indexPath) as! WidgetETATableViewCell
// cell.backgroundColor = UIColor.white.withAlphaComponent(0.25)
tableViewCellPresenter.formatCellForPresentation(cell, json: items[indexPath.row])
return cell
}
}
// MARK: UITableViewDelegate
extension TodayViewController: UITableViewDelegate {
}
| gpl-3.0 | c577305873762e2de50badfdf5732a0f | 30.23 | 116 | 0.683317 | 4.764302 | false | false | false | false |
TryFetch/PutioKit | Sources/Transfer.swift | 1 | 7908 | //
// Transfer.swift
// Fetch
//
// Created by Stephen Radford on 23/06/2016.
// Copyright © 2016 Cocoon Development Ltd. All rights reserved.
//
import Foundation
import Alamofire
/// The current status of a transfer
///
/// - downloading: The transfer is currently in progress
/// - inQueue: The transfer is queued and will be started shortly
/// - completed: The transfer has completed
/// - cancelled: The transfer was manually cancelled
public enum TransferStatus {
/// The transfer is currently in progress
case downloading
/// The transfer is queued and will be started shortly
case inQueue
/// The transfer has completed
case completed
/// The transfer was manually cancelled
case cancelled
}
/// Represents a transfer on Put.io
open class Transfer {
/// The number of bytes uploaded
open var uploaded = 0
/// The number of seconds remaining
open var estimatedTime = 0
/// Number of peers downloading from Put.io
open var peersGettingFromUs = 0
/// Should this file be extracted automatically or not?
open var extract = false
/// The current ration of downloaded to uploaded
open var currentRatio: Double = 0.0
/// The size of the file in bytes
open var size = 0
/// The upload of the transfer in bytes
open var upSpeed = 0
/// The ID of the transfer
open var id = 0
/// URL source of the file
open var source: String?
/// The ID of the subscription used to instigate the download
open var subscriptionID: Int?
/// The status message that's shown on Put.io
open var statusMessage: String?
/// The status of the transfer
open var status: TransferStatus = .downloading
/// The downspeed of the transfer in bytes
open var downSpeed = 0
/// The number of peers connected
open var peersConnected = 0
/// The number of bytes downloaded
open var downloaded = 0
/// The ID of the file that's being downloaded
open var fileID: Int?
/// The number of peers we're downloading from
open var peersSendingToUs = 0
/// The percentage donwloaded
open var percentComplete = 0
/// Custom message from the track (if there is one)
open var trackerMessage: String?
/// The name of the file that's being downloaded
open var name: String?
/// The date that the transfer was created
open var createdAt: String?
/// The error message, if there is one
open var errorMessage: String?
/// The folder that the file is being saved in
open var parentID = 0
/**
Create an empty transfer
- returns: A newly constructed transfer object
*/
init() { }
/**
Create a new transfer object from JSON
- parameter json: The JSON received from the server
- returns: A newly constructed transfer object
*/
internal convenience init(json: [String:Any]) {
self.init()
uploaded = (json["uploaded"] as? Int) ?? 0
estimatedTime = (json["estimated_time"] as? Int) ?? 0
peersGettingFromUs = (json["peers_getting_from_us"] as? Int) ?? 0
extract = (json["extract"] as? Bool) ?? false
currentRatio = (json["currentRatio"] as? Double) ?? 0.0
size = (json["size"] as? Int) ?? 0
upSpeed = (json["up_speed"] as? Int) ?? 0
id = (json["id"] as? Int) ?? 0
source = json["source"] as? String
subscriptionID = json["subscription_id"] as? Int
statusMessage = json["status_message"] as? String
status = {
switch json["status"] as! String {
case "COMPLETED":
return .completed
default:
return .downloading
}
}()
downSpeed = (json["down_speed"] as? Int) ?? 0
peersConnected = (json["peers_connected"] as? Int) ?? 0
downloaded = (json["downloaded"] as? Int) ?? 0
fileID = json["file_id"] as? Int
peersSendingToUs = (json["peers_sending_to_us"] as? Int) ?? 0
percentComplete = (json["percent_complete"] as? Int) ?? 0
trackerMessage = json["tracker_message"] as? String
name = json["name"] as? String
createdAt = json["created_at"] as? String
errorMessage = json["error_message"] as? String
parentID = (json["parent_id"] as? Int) ?? 0
}
}
// MARK: - Transfer class functions
extension Transfer {
/// Retry a failed transfer
///
/// - Parameter completionHandler: The response handler
public func retry(completionHandler: @escaping (Bool) -> Void) {
Putio.request(Router.retryTransfer(id)) { json, error in
guard error == nil else {
completionHandler(false)
return
}
completionHandler(true)
}
}
/// Cancel the current transfer
///
/// - Parameter completionHandler: The response handler
public func cancel(completionHandler: @escaping (Bool) -> Void) {
Putio.cancel(transfers: [self], completionHandler: completionHandler)
}
}
// MARK : - Main class functions
extension Putio {
/// Fetch transfers from the API
///
/// - Parameter completionHandler: The response handler
public class func getTransfers(completionHandler: @escaping ([Transfer], Error?) -> Void) {
Putio.request(Router.transfers) { response, error in
if let error = error {
completionHandler([], error)
return
}
guard let json = response as? [String:Any], let transfers = json["transfers"] as? [[String:Any]] else {
completionHandler([], PutioError.couldNotParseJSON)
return
}
completionHandler(transfers.flatMap(Transfer.init), error)
}
}
/// Add a new transfer from a URL string
///
/// - Parameters:
/// - url: The URL the transfer should be added from.
/// - parent: The parent directory the file should be added to. Defaults to the root directory.
/// - extract: Whether zip files should be extracted. Defaults to false.
/// - completionHandler: The response handler
public class func addTransfer(fromUrl url: String, parent: Int = 0, extract: Bool = false, completionHandler: @escaping (Transfer?, Error?) -> Void) {
Putio.request(Router.addTransfer(url, parent, extract)) { json, error in
if let error = error {
completionHandler(nil, error)
return
}
guard let json = json as? [String:Any] else {
completionHandler(nil, PutioError.couldNotParseJSON)
return
}
completionHandler(Transfer(json: json), error)
}
}
/// Clean up all completed transfers
///
/// - Parameter completionHandler: The response handler
public class func cleanTransfers(completionHandler: @escaping (Bool) -> Void) {
Putio.request(Router.cleanTransfers) { json, error in
guard error == nil else {
completionHandler(false)
return
}
completionHandler(true)
}
}
/// Cancel the selected transfers
///
/// - Parameters:
/// - transfers: The transfers to cancel
/// - completionHandler: The response handler
public class func cancel(transfers: [Transfer], completionHandler: @escaping (Bool) -> Void) {
let ids = transfers.map { $0.id }
Putio.request(Router.cancelTransfers(ids)) { json, error in
guard error == nil else {
completionHandler(false)
return
}
completionHandler(true)
}
}
}
| gpl-3.0 | 562d1993c84c14424cb5403086f58fd6 | 28.837736 | 154 | 0.596434 | 4.751803 | false | false | false | false |
TwoRingSoft/shared-utils | Sources/PippinAdapters/CoreLocation/CoreLocationAdapter.swift | 1 | 2854 | //
// CoreLocationAdapter.swift
// Pippin
//
// Created by Andrew McKnight on 8/15/18.
//
import CoreLocation
import Foundation
import Pippin
import Result
extension CLLocation: Location {
public var latitude: Double {
return self.coordinate.latitude
}
public var longitude: Double {
return self.coordinate.longitude
}
}
public class CoreLocationAdapter: NSObject, Locator {
public var environment: Environment?
private var authorizedLocationManager: CLLocationManager?
private var locatorDelegate: LocatorDelegate
private var authToken: AuthorizedCLLocationManager?
/// Initialize a new `CoreLocationAdapter` instance with a delegate and optionally preauthorized `CLLocationManager`. If one is not provided, then one will be authorized when necessary.
///
/// - Parameters:
/// - authorizedLocationManager: A preauthorized `CLLocationManager`. If one is not provided, then one will be authorized when necessary.
/// - locatorDelegate: A delegate to respond to callbacks.
public required init(authorizedLocationManager: CLLocationManager? = nil, locatorDelegate: LocatorDelegate) {
self.authorizedLocationManager = authorizedLocationManager
self.locatorDelegate = locatorDelegate
super.init()
authorizedLocationManager?.delegate = self
}
// MARK: Debuggable
public func debuggingControlPanel() -> UIView {
return UILabel.label(withText: "No current CoreLocationAdapter debugging controls")
}
public func startMonitoringLocation() {
if let authorizedLocationManager = authorizedLocationManager {
authorizedLocationManager.startUpdatingLocation()
} else {
authToken = AuthorizedCLLocationManager.authorizedLocationManager(scope: .whenInUse) { (authorizationResult) in
switch authorizationResult {
case .success(let authorizedLocationManager):
self.authorizedLocationManager = authorizedLocationManager
authorizedLocationManager.delegate = self
authorizedLocationManager.startUpdatingLocation()
case .failure(let error):
self.locatorDelegate.locator(locator: self, encounteredError: LocatorError.coreLocationError(error))
}
self.authToken = nil
}
}
}
public func stopMonitoringLocation() {
authorizedLocationManager?.stopUpdatingLocation()
}
}
extension CoreLocationAdapter: CLLocationManagerDelegate {
public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if let location = locations.first {
locatorDelegate.locator(locator: self, updatedToLocation: location)
}
}
}
| mit | 9b5548701c2a42e4842254a3f8a4a72e | 37.053333 | 189 | 0.695515 | 5.983229 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.