repo_name
stringlengths 6
91
| ref
stringlengths 12
59
| path
stringlengths 7
936
| license
stringclasses 15
values | copies
stringlengths 1
3
| content
stringlengths 61
714k
| hash
stringlengths 32
32
| line_mean
float64 4.88
60.8
| line_max
int64 12
421
| alpha_frac
float64 0.1
0.92
| autogenerated
bool 1
class | config_or_test
bool 2
classes | has_no_keywords
bool 2
classes | has_few_assignments
bool 1
class |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
vkedwardli/SignalR-Swift | refs/heads/feature/protobuf | SignalR-Swift/Custom/ProtoBufHubProxy.swift | mit | 1 | //
// ProtoBufHubProxy.swift
// SignalR-Swift
//
//
// Copyright © 2017 Jordan Camara. All rights reserved.
//
import Foundation
public class ProtoBufHubProxy: ProtoBufHubProxyProtocol {
public var state = [String: Any]()
private weak var connection: HubConnectionProtocol?
private var hubName: String?
private var subscriptions = [String: ProtoBufSubscription]()
// MARK: - Init
public init(connection: HubConnectionProtocol, hubName: String) {
print("🐣 \(String(describing: type(of:self)))")
self.connection = connection
self.hubName = hubName
}
// MARK: - Subscribe
public func on(eventName: String, handler: @escaping ProtoBufSubscription) -> ProtoBufSubscription? {
guard !eventName.isEmpty else {
NSException.raise(.invalidArgumentException, format: NSLocalizedString("Argument eventName is null", comment: "null event name exception"), arguments: getVaList(["nil"]))
return nil
}
return self.subscriptions[eventName] ?? self.subscriptions.updateValue(handler, forKey: eventName) ?? handler
}
public func invokeEvent(eventName: String, withArgs args: [String: Any]) {
if let subscription = self.subscriptions[eventName] {
subscription(args)
}
}
// MARK: - Publish
public func invoke(method: String, withArgs args: [String : Any]) {}
public func invoke(method: String, withArgs args: [String : Any], completionHandler: ((Any?, Error?) -> ())?) {}
deinit {
print("💀 \(String(describing: type(of:self)))")
}
}
| c13fb0f7647ce17b38368edfca07ee3a | 30.018868 | 182 | 0.643552 | false | false | false | false |
kingcos/Swift-X-Algorithms | refs/heads/master | Sort/06-MergeSort/06-MergeSort/main.swift | mit | 1 | //
// main.swift
// 06-MergeSort
//
// Created by 买明 on 11/03/2017.
// Copyright © 2017 买明. All rights reserved.
// Powered by https://maimieng.com from https://github.com/kingcos/Swift-X-Algorithms
import Foundation
func mergeSort<T: Comparable>(_ arr: Array<T>, _ isNotOrdered: (T, T) -> Bool) -> Array<T> {
// [0, mid) & [mid, arr.count)
func merge<T>(_ lArr: Array<T>, _ rArr: Array<T>, _ isNotOrdered: (T, T) -> Bool) -> Array<T> {
var arr = lArr + rArr
var l = 0, r = 0
for i in 0..<arr.count {
if l >= lArr.count {
arr[i] = rArr[r]
r += 1
} else if r >= rArr.count {
arr[i] = lArr[l]
l += 1
} else if isNotOrdered(lArr[l], rArr[r]) {
arr[i] = lArr[l]
l += 1
} else {
arr[i] = rArr[r]
r += 1
}
}
return arr
}
guard arr.count > 1 else { return arr }
let mid = arr.count / 2
let lArr = mergeSort(Array(arr[0..<mid]), isNotOrdered)
let rArr = mergeSort(Array(arr[mid..<arr.count]), isNotOrdered)
return merge(lArr, rArr, isNotOrdered)
}
TestHelper.checkSortAlgorithm(mergeSort)
TestHelper.checkSortAlgorithm(mergeSort, 10000)
| c4235f66218c857f11ab9d869dbcab71 | 27.234043 | 99 | 0.504145 | false | false | false | false |
noraesae/kawa | refs/heads/master | kawa/StatusBar.swift | mit | 1 | import AppKit
import Cocoa
class StatusBar {
static let shared: StatusBar = StatusBar()
let item = NSStatusBar.system.statusItem(withLength: NSStatusItem.variableLength)
init() {
let button = item.button!
let buttonImage = NSImage(named: "StatusItemIcon")
buttonImage?.isTemplate = true
button.target = self
button.action = #selector(StatusBar.action(_:))
button.image = buttonImage
button.appearsDisabled = false;
button.toolTip = "Click to open preferences"
}
@objc func action(_ sender: NSButton) {
MainWindowController.shared.showAndActivate(sender)
}
}
| 58de8daf0013f9d185fe5eed1d904ab6 | 23.48 | 83 | 0.714052 | false | false | false | false |
nifty-swift/Nifty | refs/heads/master | Sources/isequal.swift | apache-2.0 | 2 | /**************************************************************************************************
* isequal.swift
*
* This file provides functionality for comparing numbers, Vectors, Matrices, and Tensors for
* equality within given tolerances.
*
* Author: Philip Erickson
* Creation Date: 1 Jan 2017
*
* 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.
*
* Copyright 2017 Philip Erickson
**************************************************************************************************/
// The article "Comparing Floating Point Numbers, 2012 Edition", by Bruce Dawson was useful in this:
// https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/
extension Nifty.Options
{
public enum isequal
{
case absolute
case relative
}
}
/// Determine whether two numbers are equal, within the given tolerance.
///
/// The default method of comparison is to use absolute comparisons for small numbers, and relative
/// comparisons for large numbers. This default can be overridden by specifying in the function call
/// which comparison method to use.
///
/// - Parameters:
/// - a: first number to compare
/// - b: second number to compare
/// - within tolerance: tolerance to allow as equal
/// - comparison: optionally override default, specifying whether to compute absolute or relative
/// difference between numbers, which is then compared against the given tolerance
/// - Returns: true if values are equal according to the specified tolerance
public func isequal(_ a: Double, _ b: Double, within tolerance: Double = eps.single,
comparison: Nifty.Options.isequal? = nil) -> Bool
{
switch comparison
{
case .some(.absolute):
return abs(a-b) < tolerance
case .some(.relative):
let diff = abs(a-b)
return diff <= max(abs(a), abs(b)) * tolerance
case .none:
// TODO: revisit what should constitute a "small number"
// compare small numbers absolutely (relative comparsion against 0 doesn't make sense)
if abs(a) < 1 || abs(b) < 1
{
return abs(a-b) < tolerance
}
// larger numbers make more sense to compare relatively
else
{
let diff = abs(a-b)
return diff <= max(abs(a), abs(b)) * tolerance
}
}
}
public func isequal(_ a: Vector<Double>, _ b: Vector<Double>, within tolerance: Double = eps.single,
comparison: Nifty.Options.isequal? = nil) -> Bool
{
if a.count != b.count
{
return false
}
for i in 0..<a.count
{
if !isequal(a[i], b[i], within: tolerance, comparison: comparison)
{
return false
}
}
return true
}
public func isequal(_ a: Matrix<Double>, _ b: Matrix<Double>, within tolerance: Double = eps.single,
comparison: Nifty.Options.isequal? = nil) -> Bool
{
if a.size != b.size
{
return false
}
for i in 0..<a.count
{
if !isequal(a[i], b[i], within: tolerance, comparison: comparison)
{
return false
}
}
return true
}
public func isequal(_ a: Tensor<Double>, _ b: Tensor<Double>, within tolerance: Double = eps.single,
comparison: Nifty.Options.isequal? = nil) -> Bool
{
if a.size != b.size
{
return false
}
for i in 0..<a.count
{
if !isequal(a[i], b[i], within: tolerance, comparison: comparison)
{
return false
}
}
return true
} | 4cc71600b3380f25623a94dabae147c7 | 30.503817 | 101 | 0.594038 | false | false | false | false |
banxi1988/BXCodeScanner | refs/heads/master | Pod/Classes/BXCodeScanViewController.swift | mit | 1 | //
// BXCodeScanViewController.swift
//
// Created by Haizhen Lee on 15/11/14.
//
import UIKit
import AVFoundation
import PinAuto
// For Tool convient method
public extension UIViewController{
public func openCodeScanViewControllerWithDelegate(delegate:BXCodeScanViewControllerDelegate?){
let vc = BXCodeScanViewController()
vc.delegate = delegate
let nvc = UINavigationController(rootViewController: vc)
presentViewController(nvc, animated: true, completion: nil)
}
}
@objc
public protocol BXCodeScanViewControllerDelegate{
func codeScanViewController(viewController:BXCodeScanViewController,didRecognizeCode code:String)
optional func codeScanViewControllerDidCanceled(viewController:BXCodeScanViewController)
}
public class BXCodeScanViewController:UIViewController,AVCaptureMetadataOutputObjectsDelegate {
public init() {
super.init(nibName: nil, bundle: nil)
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
var restartButtonItem : UIBarButtonItem?
public let scanFeedbackView = BXScanFeedbackView()
public lazy var scanTipLabel: UILabel = {
let label = UILabel(frame: CGRectZero)
label.text = BXStrings.scan_tip
label.textColor = .whiteColor()
label.font = UIFont.boldSystemFontOfSize(18)
return label
}()
// MARK: Customize Property
public var scanRectSize = CGSize(width: 208, height: 208)
public var scanCodeTypes = [
AVMetadataObjectTypeQRCode,
AVMetadataObjectTypeAztecCode,
AVMetadataObjectTypeDataMatrixCode,
]
public var tipsOnTop = true
public var tipsMargin :CGFloat = 40
public weak var delegate:BXCodeScanViewControllerDelegate?
public override func loadView() {
super.loadView()
for childView in [previewView,scanFeedbackView, scanTipLabel]{
self.view.addSubview(childView)
childView.translatesAutoresizingMaskIntoConstraints = false
}
// Setup
installConstraints()
}
func installConstraints(){
scanTipLabel.pa_centerX.install()
previewView.pac_edge()
scanFeedbackView.pac_center()
scanFeedbackView.pac_size(scanRectSize)
if tipsOnTop{
scanTipLabel.pa_above(scanFeedbackView, offset: 40).install()
}else{
scanTipLabel.pa_below(scanFeedbackView, offset: 40).install()
}
}
public override func updateViewConstraints() {
super.updateViewConstraints()
NSLog("\(#function)")
}
// MARK: Scan Support Variable
let previewView = BXPreviewView()
let sessionQueue = dispatch_queue_create("session_queue", DISPATCH_QUEUE_SERIAL)
var videoDeviceInput:AVCaptureDeviceInput?
var session = AVCaptureSession()
var sessionRunning = false
var setupResult = BXCodeSetupResult.Success
override public func viewDidLoad() {
super.viewDidLoad()
// prepare
loadQRCodeCompletedSound()
// setup session
previewView.session = session
setupResult = .Success
previewView.previewLayer?.videoGravity = AVLayerVideoGravityResizeAspectFill
// UI
let cancelButton = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: #selector(BXCodeScanViewController.cancel(_:)))
navigationItem.rightBarButtonItem = cancelButton
checkAuthorization()
setupSession()
}
@IBAction func cancel(sender:AnyObject){
closeSelf()
}
func setupSession(){
session_async{
if self.setupResult != .Success{
return
}
guard let videoDevice = self.deviceWithMediaType(AVMediaTypeVideo, preferringPosition: AVCaptureDevicePosition.Back) else {
self.setupResult = .NoDevice
return
}
let videoDeviceInput = try? AVCaptureDeviceInput(device: videoDevice)
if videoDeviceInput == nil {
NSLog("Could not create video device input ")
return
}
NSLog("session preset \(self.session.sessionPreset)")
self.session.beginConfiguration()
if self.session.canAddInput(videoDeviceInput) {
self.session.addInput(videoDeviceInput)
self.videoDeviceInput = videoDeviceInput
runInUiThread{
let statusBarOrientation = UIApplication.sharedApplication().statusBarOrientation
var initialVideoOrientation = AVCaptureVideoOrientation.Portrait
if statusBarOrientation != .Unknown{
initialVideoOrientation = AVCaptureVideoOrientation(rawValue: statusBarOrientation.rawValue)!
}
self.previewView.previewLayer?.connection.videoOrientation = initialVideoOrientation
}
}else{
NSLog("Could not add video deviceinput to the session")
self.setupResult = BXCodeSetupResult.SessionconfigurationFailed
}
NSLog("session preset \(self.session.sessionPreset)")
let metadataOutput = AVCaptureMetadataOutput()
if self.session.canAddOutput(metadataOutput){
let queue = dispatch_queue_create("myScanOutputQueue", DISPATCH_QUEUE_SERIAL)
metadataOutput.setMetadataObjectsDelegate(self, queue: queue)
self.session.addOutput(metadataOutput)
let types: [String] = metadataOutput.availableMetadataObjectTypes as? [String] ?? []
let availableTypes = self.scanCodeTypes.filter{types.contains($0)}
if availableTypes.count > 0{
metadataOutput.metadataObjectTypes = availableTypes
}else{
NSLog("QRCode metadataObjectType is not available ,available types \(types)")
self.setupResult = .SessionconfigurationFailed
}
let bounds = self.view.bounds
let x = (bounds.width - self.scanRectSize.width) * 0.5 / bounds.width
let y = (bounds.height - self.scanRectSize.height) * 0.5 / bounds.height
let w = self.scanRectSize.width / bounds.width
let h = self.scanRectSize.height / bounds.height
let interestRect = CGRect(x: x, y: y, width: w, height: h)
NSLog("rectOfInterest \(interestRect)")
// metadataOutput.rectOfInterest = interestRect
}else{
NSLog("Could not add metadata output to the session")
self.setupResult = BXCodeSetupResult.SessionconfigurationFailed
}
self.session.commitConfiguration()
}
}
func checkAuthorization(){
let status = AVCaptureDevice.authorizationStatusForMediaType(AVMediaTypeVideo)
switch status{
case .Authorized:
if setupResult != .Success{
setupSession()
}
break
case .NotDetermined:
promptAuthorize()
default:
setupResult = .NotAuthorized // Deny or Restricted
}
}
func promptAuthorize(){
dispatch_suspend(sessionQueue)
AVCaptureDevice.requestAccessForMediaType(AVMediaTypeVideo){
granted in
if !granted{
self.setupResult = BXCodeSetupResult.NotAuthorized
}
dispatch_resume(self.sessionQueue)
}
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
checkAuthorization() // authorization can be change we we are not in front
dispatch_async(self.sessionQueue){
switch self.setupResult{
case .Success:
self.session.startRunning()
self.sessionRunning = self.session.running
case .NotAuthorized:
runInUiThread{
self.promptNotAuthorized()
}
case .NoDevice:
runInUiThread{
self.showTip(BXStrings.error_no_device)
}
case .SessionconfigurationFailed:
runInUiThread{
self.showTip(BXStrings.error_session_failed)
}
}
}
}
public override func viewDidAppear(animated: Bool) {
super.viewDidDisappear(animated)
if self.setupResult == .Success && self.sessionRunning{
startScanningUI()
}
}
public override func viewWillDisappear(animated: Bool) {
session_async{
if self.setupResult == .Success{
self.session.stopRunning()
}
}
stopScanningUI()
super.viewDidDisappear(animated)
}
override public func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
stopScanning()
}
public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
return .All
}
public override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
let deviceOrientation = UIDevice.currentDevice().orientation
if deviceOrientation.isPortrait || deviceOrientation.isLandscape{
if let orientation = AVCaptureVideoOrientation(rawValue: deviceOrientation.rawValue){
previewView.previewLayer?.connection.videoOrientation = orientation
}
}
}
func stopScanning(){
session.stopRunning()
sessionRunning = false
}
struct BXCoderKey{
static let sessionRunning = "sessionRunning"
}
func session_async(block:dispatch_block_t){
dispatch_async(self.sessionQueue, block)
}
func startScanningUI(){
scanFeedbackView.hidden = false
scanFeedbackView.animateScanLine()
self.view.sendSubviewToBack(previewView)
}
func stopScanningUI(){
scanFeedbackView.hidden = true
scanFeedbackView.stopScanLineAnimation()
}
// MARK: Capture Manager
func deviceWithMediaType(mediaType:String,preferringPosition:AVCaptureDevicePosition) -> AVCaptureDevice?{
let devices = AVCaptureDevice.devicesWithMediaType(mediaType)
for obj in devices{
if let device = obj as? AVCaptureDevice{
if device.position == preferringPosition{
return device
}
}
}
return devices.first as? AVCaptureDevice
}
// MARK : AVCaptureMetadataOutputObjectsDelegate
var isRecognized = false
public func captureOutput(captureOutput: AVCaptureOutput!, didOutputMetadataObjects metadataObjects: [AnyObject]!, fromConnection connection: AVCaptureConnection!) {
if let metadataObject = metadataObjects.first as? AVMetadataMachineReadableCodeObject
where self.scanCodeTypes.contains(metadataObject.type){
NSLog("scan result type:\(metadataObject.type) content:\(metadataObject.stringValue)")
self.stopScanning()
// 如果不在这里马上停止,那么此结果,因为扫描成功之后,还会有多次回调.
if isRecognized{
// 同时这里没有设置为false,是因为后面也不根据此变量来设置其他值
return // 停止得慢可能重复识别
}
isRecognized = true
runInUiThread{
self.stopScanningUI()
self.onCodeRecognized(metadataObject.stringValue)
self.isRecognized = false
}
}else{
NSLog("scan failed")
}
}
func onCodeRecognized(codeString:String){
audioPlayer?.play()
self.delegate?.codeScanViewController(self, didRecognizeCode: codeString)
closeSelf()
}
func closeSelf(){
let poped = self.navigationController?.popViewControllerAnimated(true)
if poped == nil{
dismissViewControllerAnimated(true, completion: nil)
}
}
// MARK: Recognized Sound Effects
var audioPlayer:AVAudioPlayer?
func loadQRCodeCompletedSound(){
let assetBundle = NSBundle.mainBundle()
guard let soundURL = assetBundle.URLForResource("qrcode_completed", withExtension: "mp3") else{
return
}
audioPlayer = try? AVAudioPlayer(contentsOfURL: soundURL)
if audioPlayer == nil{
NSLog("unable to read qrcode_completed file")
}else{
audioPlayer?.prepareToPlay()
}
}
// MARK: State Restoration
public override func encodeRestorableStateWithCoder(coder: NSCoder) {
super.encodeRestorableStateWithCoder(coder)
coder.encodeBool(sessionRunning, forKey: BXCoderKey.sessionRunning)
}
public override func decodeRestorableStateWithCoder(coder: NSCoder) {
super.decodeRestorableStateWithCoder(coder)
}
} | f2160fd6f834066fa4893f48a8156eea | 33.060453 | 169 | 0.617484 | false | false | false | false |
cocoascientist/Passengr | refs/heads/master | Passengr/DetailViewController.swift | mit | 1 | //
// DetailViewController.swift
// Passengr
//
// Created by Andrew Shepard on 11/25/15.
// Copyright © 2015 Andrew Shepard. All rights reserved.
//
import UIKit
private let reuseIdentifier = String(describing: PassDetailCell.self)
final class DetailViewController: UICollectionViewController {
var dataSource: PassDataSource?
var indexPath = IndexPath(row: 0, section: 0)
private var passes: [Pass] {
guard let dataSource = dataSource else {
fatalError("data source is missing")
}
return dataSource.visiblePasses
}
// MARK: - Lifecycle
override func awakeFromNib() {
super.awakeFromNib()
self.collectionView?.collectionViewLayout = DetailViewLayout()
self.collectionView?.isPagingEnabled = true
}
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.backgroundColor = AppStyle.Color.lightBlue
let nib = UINib(nibName: String(describing: PassDetailCell.self), bundle: nil)
self.collectionView!.register(nib, forCellWithReuseIdentifier: reuseIdentifier)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.collectionView?.scrollToItem(at: self.indexPath, at: .centeredHorizontally, animated: true)
self.setTitleText(for: self.indexPath)
}
override func encodeRestorableState(with coder: NSCoder) {
coder.encode(self.dataSource, forKey: "dataSource")
coder.encode(self.indexPath, forKey: "indexPath")
super.encodeRestorableState(with: coder)
}
override func decodeRestorableState(with coder: NSCoder) {
guard let dataSource = coder.decodeObject(forKey: "dataSource") as? PassDataSource else { return }
guard let indexPath = coder.decodeObject(forKey: "indexPath") as? IndexPath else { return }
self.dataSource = dataSource
self.indexPath = indexPath
super.decodeRestorableState(with: coder)
}
// MARK: - UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.passes.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
configure(cell: cell, for: indexPath)
return cell
}
// MARK: - UIScrollView
override func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
guard let indexPath = self.collectionView?.indexPathsForVisibleItems.first else { return }
self.indexPath = indexPath
self.setTitleText(for: indexPath)
}
// MARK: - Private
private func setTitleText(for indexPath: IndexPath) -> Void {
let pass = passes[indexPath.row]
self.title = pass.name
}
private func configure(cell: UICollectionViewCell, for indexPath: IndexPath) {
guard let cell = cell as? PassDetailCell else { return }
let pass = passes[indexPath.row]
cell.titleLabel.text = pass.name
cell.conditionsLabel.text = pass.conditions
cell.eastboundLabel.text = pass.eastbound
cell.westboundLabel.text = pass.westbound
cell.lastUpdatedLabel.text = self.dateFormatter.string(from: pass.lastModified)
cell.statusView.backgroundColor = pass.color
}
private lazy var dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.dateFormat = "EEEE MMMM d, yyyy h:mm a"
return formatter
}()
}
extension DetailViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return DetailViewLayout.detailLayoutItemSize(for: UIScreen.main.bounds)
}
}
| 6f55cad654eff4cc53c9d63a0c90d836 | 33.064 | 160 | 0.676844 | false | false | false | false |
iAugux/Zoom-Contacts | refs/heads/master | Phonetic/BlurActionSheet/BlurActionSheet.swift | mit | 1 | //
// BlurActionSheet.swift
// BlurActionSheetDemo
//
// Created by nathan on 15/4/23.
// Copyright (c) 2015年 nathan. All rights reserved.
//
import UIKit
import SnapKit
class BlurActionSheet: UIView, UITableViewDataSource {
private let actionSheetCellHeight: CGFloat = 44.0
private let actionSheetCancelHeight: CGFloat = 58.0
private var showSet: NSMutableSet = NSMutableSet()
var titles: [String]?
private var containerView: UIView?
var handler: ((index: Int) -> Void)?
private var tableView: UITableView!
private var blurBackgroundView: BlurBackgroundView!
override init(frame: CGRect) {
super.init(frame: frame)
blurBackgroundView = BlurBackgroundView()
addSubview(blurBackgroundView)
blurBackgroundView.snp_makeConstraints { (make) in
make.edges.equalTo(UIEdgeInsetsZero)
}
tableView = UITableView()
tableView.delegate = self
tableView.dataSource = self
tableView.backgroundView = nil
tableView.scrollEnabled = false
tableView.backgroundColor = UIColor.clearColor()
tableView.separatorStyle = .None
tableView.tableFooterView = UIView()
blurBackgroundView.addSubview(tableView)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
class func showWithTitles(titles: [String], handler: ((index: Int) -> Void)) -> BlurActionSheet {
return showWithTitles(titles, view: nil, handler: handler)
}
class func showWithTitles(titles: [String], view: UIView?, handler: ((index: Int) -> Void)) -> BlurActionSheet {
let actionSheet = BlurActionSheet(frame: UIScreen.mainScreen().bounds)
actionSheet.titles = titles
actionSheet.containerView = view
actionSheet.handler = handler
actionSheet.show()
return actionSheet
}
private func show() {
let maxHeight = actionSheetCellHeight * CGFloat(titles!.count - 1) + actionSheetCancelHeight
tableView.snp_makeConstraints { (make) in
make.left.bottom.right.equalTo(blurBackgroundView)
make.height.equalTo(maxHeight)
}
if (containerView != nil) {
containerView!.addSubview(self)
} else {
UIApplication.topMostViewController?.view.addSubview(self)
}
guard self.superview != nil else { return }
self.snp_makeConstraints(closure: { (make) in
make.edges.equalTo(UIEdgeInsetsZero)
})
blurBackgroundView.alpha = 0
UIView.animateWithDuration(1.0, animations: { () -> Void in
self.blurBackgroundView.alpha = 1
})
}
private func hide() {
var index = 0
for visibleCell in tableView.visibleCells {
if let cell = visibleCell as? BlurActionSheetCell {
index = index + 1
let height = tableView.frame.size.height
cell.underLineView?.alpha = 0.5
cell.textLabel?.alpha = 0.5
UIView.animateWithDuration(0.45, delay: 0.2, options: .CurveEaseOut, animations: { () -> Void in
cell.layer.transform = CATransform3DTranslate(cell.layer.transform, 0, height * 2, 0)
}, completion: { (Bool) -> Void in
self.removeFromSuperview()
})
}
}
UIView.animateWithDuration(0.6, animations: { () -> Void in
self.blurBackgroundView.alpha = 0.0
})
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
hide()
if let handler = handler {
if let titles = titles {
handler(index: titles.count - 1)
}
}
}
// MARK: - tableView dataSource and delegate
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if (titles != nil) {
return titles!.count
} else {
return 0
}
}
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if let titles = titles {
return indexPath.row == titles.count - 1 ? actionSheetCancelHeight : actionSheetCellHeight
}
return actionSheetCellHeight
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "actionSheetCell"
var cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier) as? BlurActionSheetCell
if (cell == nil) {
cell = BlurActionSheetCell(style: .Default, reuseIdentifier: cellIdentifier)
}
if (indexPath.row == 0) {
cell?.underLineView.hidden = true
}
cell?.textLabel?.text = titles![indexPath.row]
cell?.textLabel?.textAlignment = .Center
cell?.textLabel?.textColor = UIColor.whiteColor()
return cell!
}
}
extension BlurActionSheet: UITableViewDelegate {
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
hide()
if let handler = handler {
handler(index: indexPath.row)
}
}
func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
if (!showSet.containsObject(indexPath)) {
showSet.addObject(indexPath)
let delayTime: NSTimeInterval! = 0.3 + sqrt(Double(indexPath.row)) * 0.09
cell.layer.transform = CATransform3DTranslate(cell.layer.transform, 0, 400, 0)
cell.alpha = 0.5
UIView.animateWithDuration(0.5, delay: delayTime, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.0, options: UIViewAnimationOptions.CurveEaseInOut, animations: { () -> Void in
cell.layer.transform = CATransform3DIdentity
cell.alpha = 1
}, completion: nil)
}
}
}
| 8143adcc9b7fb5e964ca4bbd9edea715 | 32.753927 | 194 | 0.597022 | false | false | false | false |
jovito-royeca/ManaKit | refs/heads/master | Example/ManaKit/Set/SetViewController.swift | mit | 1 | //
// SetViewController.swift
// ManaKit
//
// Created by Jovito Royeca on 15/04/2017.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import UIKit
import ManaKit
import MBProgressHUD
import PromiseKit
class SetViewController: BaseViewController {
// MARK: - Overrides
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
searchController.searchResultsUpdater = self
searchController.searchBar.delegate = self
searchController.searchBar.placeholder = "Filter"
searchController.dimsBackgroundDuringPresentation = false
definesPresentationContext = true
if #available(iOS 11.0, *) {
navigationItem.searchController = searchController
navigationItem.hidesSearchBarWhenScrolling = false
} else {
tableView.tableHeaderView = searchController.searchBar
}
tableView.keyboardDismissMode = .onDrag
tableView.register(ManaKit.sharedInstance.nibFromBundle("CardTableViewCell"),
forCellReuseIdentifier: CardTableViewCell.reuseIdentifier)
fetchData()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if #available(iOS 11.0, *) {
navigationItem.hidesSearchBarWhenScrolling = true
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showCard" {
guard let dest = segue.destination as? CardViewController,
let card = sender as? MGCard,
let id = card.id else {
return
}
let viewModel = CardViewModel(withId: id)
dest.viewModel = viewModel
}
}
}
// MARK: - UITableViewDataSource
extension SetViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.numberOfRows(inSection: section)
}
func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.numberOfSections()
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard let cell = tableView.dequeueReusableCell(withIdentifier: CardTableViewCell.reuseIdentifier,
for: indexPath) as? CardTableViewCell else {
fatalError("Unexpected indexPath: \(indexPath)")
}
cell.selectionStyle = .none
cell.card = viewModel.object(forRowAt: indexPath) as? MGCard
cell.updateDataDisplay()
return cell
}
func sectionIndexTitles(for tableView: UITableView) -> [String]? {
return viewModel.sectionIndexTitles()
}
func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
return viewModel.sectionForSectionIndexTitle(title: title, at: index)
}
func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return viewModel.titleForHeaderInSection(section: section)
}
}
// MARK: - UITableViewDelegate
extension SetViewController : UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let card = viewModel.object(forRowAt: indexPath)
performSegue(withIdentifier: "showCard", sender: card)
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return CardTableViewCell.cellHeight
}
}
// MARK: - UISearchResultsUpdating
extension SetViewController : UISearchResultsUpdating {
func updateSearchResults(for searchController: UISearchController) {
guard let text = searchController.searchBar.text else {
return
}
viewModel.queryString = text
fetchData()
}
}
// MARK: - UISearchBarDelegate
extension SetViewController : UISearchBarDelegate {
func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
viewModel.searchCancelled = false
}
func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
viewModel.searchCancelled = true
}
func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
if viewModel.searchCancelled {
searchBar.text = viewModel.queryString
} else {
viewModel.queryString = searchBar.text ?? ""
}
}
}
| bdf95a74db32031aabfaa6a3639f4689 | 32.442029 | 111 | 0.656338 | false | false | false | false |
peterk9/card-2.io-iOS-SDK-master | refs/heads/master | SampleApp-Swift/SampleApp-Swift/PickUpViewController.swift | mit | 1 | //
// PickUpViewController.swift
// RBCInstaBank
//
// Created by Kevin Peters on 2015-08-14.
// Copyright © 2015 Punskyy, Roman. All rights reserved.
//
import UIKit
import CoreLocation
import MapKit
class PickUpViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var mapView: MKMapView!
@IBOutlet weak var deliveryTime: UILabel!
@IBOutlet weak var lightTimeProgressView: LightProgressView!
@IBOutlet weak var timeProgressView: DateProgressView!
@IBOutlet weak var label1: UILabel!
@IBOutlet weak var label2: UILabel!
@IBOutlet weak var label3: UILabel!
@IBOutlet weak var labelline: UILabel!
@IBOutlet weak var ETA: UILabel!
var timer = NSTimer()
var seconds = 0
@IBOutlet weak var confirmLocationBtn: UIButton!
@IBOutlet weak var signDeliverybtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
lightTimeProgressView.hidden = true
timeProgressView.hidden = true
ETA.hidden = true
signDeliverybtn.hidden = true
let date: NSDate = NSDate()
let dateFormatter: NSDateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
let tempDate: String = dateFormatter.stringFromDate(date)
self.deliveryTime.text = tempDate
timeProgressView.animateProgressView(1)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location = locations.last as CLLocation!
let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
self.mapView.setRegion(region, animated: true)
}
@IBAction func confirmPressed(sender: AnyObject) {
label1.hidden = true
label2.hidden = true
label3.hidden = true
labelline.hidden = true
deliveryTime.hidden = true
lightTimeProgressView.hidden = false
timeProgressView.hidden = false
confirmLocationBtn.hidden = true
ETA.hidden = false
seconds = 5
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("subtractTime"), userInfo: nil, repeats: true)
timeProgressView.animateProgressView(1)
}
func subtractTime() {
//self.ETA.text = "ETA: \(seconds) Min"
if seconds == 5 {
let notification = UILocalNotification()
notification.alertBody = "Your delivery is 10 minutes away!"
notification.soundName = "Default";
notification.fireDate = NSDate(timeIntervalSinceNow: 5)
UIApplication.sharedApplication().scheduleLocalNotification(notification)
let notification2 = UILocalNotification()
notification2.alertBody = "Your delivery has arrived"
notification2.soundName = "Default";
notification2.fireDate = NSDate(timeIntervalSinceNow: 10)
UIApplication.sharedApplication().scheduleLocalNotification(notification2)
}
if seconds == 0 {
timer.invalidate()
self.signDeliverybtn.hidden = false
}
seconds--
}
/*
// 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.
}
*/
}
| b991f5947af73415dbcf69f0953bf428 | 32.203252 | 139 | 0.655975 | false | false | false | false |
flodolo/firefox-ios | refs/heads/main | Shared/Extensions/UIBarButtonItemExtensions.swift | mpl-2.0 | 2 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import UIKit
// https://medium.com/@BeauNouvelle/adding-a-closure-to-uibarbuttonitem-24dfc217fe72
extension UIBarButtonItem {
private class UIBarButtonItemClosureWrapper: NSObject {
let closure: (UIBarButtonItem) -> Void
init(_ closure: @escaping (UIBarButtonItem) -> Void) {
self.closure = closure
}
}
private struct AssociatedKeys {
static var targetClosure = "targetClosure"
}
private var targetClosure: ((UIBarButtonItem) -> Void)? {
get {
guard let closureWrapper = objc_getAssociatedObject(self, &AssociatedKeys.targetClosure) as? UIBarButtonItemClosureWrapper else { return nil }
return closureWrapper.closure
}
set(newValue) {
guard let newValue = newValue else { return }
objc_setAssociatedObject(self, &AssociatedKeys.targetClosure, UIBarButtonItemClosureWrapper(newValue), objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
public convenience init(title: String?, style: UIBarButtonItem.Style, closure: @escaping (UIBarButtonItem) -> Void) {
self.init(title: title, style: style, target: nil, action: #selector(UIBarButtonItem.closureAction))
self.target = self
targetClosure = closure
}
public convenience init(barButtonSystemItem systemItem: UIBarButtonItem.SystemItem, closure: @escaping (UIBarButtonItem) -> Void) {
self.init(barButtonSystemItem: systemItem, target: nil, action: #selector(UIBarButtonItem.closureAction))
self.target = self
targetClosure = closure
}
@objc func closureAction() {
targetClosure?(self)
}
}
| ccfdb2e01f994d2182127051d337407f | 39.913043 | 172 | 0.68916 | false | false | false | false |
YuanZhu-apple/ResearchKit | refs/heads/master | samples/ORKCatalog/ORKCatalog/Tasks/TaskListRow.swift | bsd-3-clause | 4 | /*
Copyright (c) 2015, Apple Inc. All rights reserved.
Copyright (c) 2015-2016, Ricardo Sánchez-Sáez.
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 ResearchKit
import AudioToolbox
/**
Wraps a SystemSoundID.
A class is used in order to provide appropriate cleanup when the sound is
no longer needed.
*/
class SystemSound {
var soundID: SystemSoundID = 0
init?(soundURL: NSURL) {
if AudioServicesCreateSystemSoundID(soundURL as CFURLRef, &soundID) != noErr {
return nil
}
}
deinit {
AudioServicesDisposeSystemSoundID(soundID)
}
}
/**
An enum that corresponds to a row displayed in a `TaskListViewController`.
Each of the tasks is composed of one or more steps giving examples of the
types of functionality supported by the ResearchKit framework.
*/
enum TaskListRow: Int, CustomStringConvertible {
case Form = 0
case Survey
case BooleanQuestion
case DateQuestion
case DateTimeQuestion
case HeightQuestion
case ImageChoiceQuestion
case LocationQuestion
case NumericQuestion
case ScaleQuestion
case TextQuestion
case TextChoiceQuestion
case TimeIntervalQuestion
case TimeOfDayQuestion
case ValuePickerChoiceQuestion
case ValidatedTextQuestion
case ImageCapture
case Wait
case EligibilityTask
case Consent
case AccountCreation
case Login
case Passcode
case Audio
case Fitness
case HolePegTest
case PSAT
case ReactionTime
case ShortWalk
case SpatialSpanMemory
case TimedWalk
case ToneAudiometry
case TowerOfHanoi
case TwoFingerTappingInterval
case WalkBackAndForth
class TaskListRowSection {
var title: String
var rows: [TaskListRow]
init(title: String, rows: [TaskListRow]) {
self.title = title
self.rows = rows
}
}
/// Returns an array of all the task list row enum cases.
static var sections: [ TaskListRowSection ] {
return [
TaskListRowSection(title: "Surveys", rows:
[
.Form,
.Survey,
]),
TaskListRowSection(title: "Survey Questions", rows:
[
.BooleanQuestion,
.DateQuestion,
.DateTimeQuestion,
.HeightQuestion,
.ImageChoiceQuestion,
.LocationQuestion,
.NumericQuestion,
.ScaleQuestion,
.TextQuestion,
.TextChoiceQuestion,
.TimeIntervalQuestion,
.TimeOfDayQuestion,
.ValuePickerChoiceQuestion,
.ValidatedTextQuestion,
.ImageCapture,
.Wait,
]),
TaskListRowSection(title: "Onboarding", rows:
[
.EligibilityTask,
.Consent,
.AccountCreation,
.Login,
.Passcode,
]),
TaskListRowSection(title: "Active Tasks", rows:
[
.Audio,
.Fitness,
.HolePegTest,
.PSAT,
.ReactionTime,
.ShortWalk,
.SpatialSpanMemory,
.TimedWalk,
.ToneAudiometry,
.TowerOfHanoi,
.TwoFingerTappingInterval,
.WalkBackAndForth,
]),
]}
// MARK: CustomStringConvertible
var description: String {
switch self {
case .Form:
return NSLocalizedString("Form Survey Example", comment: "")
case .Survey:
return NSLocalizedString("Simple Survey Example", comment: "")
case .BooleanQuestion:
return NSLocalizedString("Boolean Question", comment: "")
case .DateQuestion:
return NSLocalizedString("Date Question", comment: "")
case .DateTimeQuestion:
return NSLocalizedString("Date and Time Question", comment: "")
case .HeightQuestion:
return NSLocalizedString("Height Question", comment: "")
case .ImageChoiceQuestion:
return NSLocalizedString("Image Choice Question", comment: "")
case .LocationQuestion:
return NSLocalizedString("Location Question", comment: "")
case .NumericQuestion:
return NSLocalizedString("Numeric Question", comment: "")
case .ScaleQuestion:
return NSLocalizedString("Scale Question", comment: "")
case .TextQuestion:
return NSLocalizedString("Text Question", comment: "")
case .TextChoiceQuestion:
return NSLocalizedString("Text Choice Question", comment: "")
case .TimeIntervalQuestion:
return NSLocalizedString("Time Interval Question", comment: "")
case .TimeOfDayQuestion:
return NSLocalizedString("Time of Day Question", comment: "")
case .ValuePickerChoiceQuestion:
return NSLocalizedString("Value Picker Choice Question", comment: "")
case .ValidatedTextQuestion:
return NSLocalizedString("Validated Text Question", comment: "")
case .ImageCapture:
return NSLocalizedString("Image Capture Step", comment: "")
case .Wait:
return NSLocalizedString("Wait Step", comment: "")
case .EligibilityTask:
return NSLocalizedString("Eligibility Task Example", comment: "")
case .Consent:
return NSLocalizedString("Consent-Obtaining Example", comment: "")
case .AccountCreation:
return NSLocalizedString("Account Creation", comment: "")
case .Login:
return NSLocalizedString("Login", comment: "")
case .Passcode:
return NSLocalizedString("Passcode Creation", comment: "")
case .Audio:
return NSLocalizedString("Audio", comment: "")
case .Fitness:
return NSLocalizedString("Fitness Check", comment: "")
case .HolePegTest:
return NSLocalizedString("Hole Peg Test", comment: "")
case .PSAT:
return NSLocalizedString("PSAT", comment: "")
case .ReactionTime:
return NSLocalizedString("Reaction Time", comment: "")
case .ShortWalk:
return NSLocalizedString("Short Walk", comment: "")
case .SpatialSpanMemory:
return NSLocalizedString("Spatial Span Memory", comment: "")
case .TimedWalk:
return NSLocalizedString("Timed Walk", comment: "")
case .ToneAudiometry:
return NSLocalizedString("Tone Audiometry", comment: "")
case .TowerOfHanoi:
return NSLocalizedString("Tower of Hanoi", comment: "")
case .TwoFingerTappingInterval:
return NSLocalizedString("Two Finger Tapping Interval", comment: "")
case .WalkBackAndForth:
return NSLocalizedString("Walk Back and Forth", comment: "")
}
}
// MARK: Types
/**
Every step and task in the ResearchKit framework has to have an identifier.
Within a task, the step identifiers should be unique.
Here we use an enum to ensure that the identifiers are kept unique. Since
the enum has a raw underlying type of a `String`, the compiler can determine
the uniqueness of the case values at compile time.
In a real application, the identifiers for your tasks and steps might
come from a database, or in a smaller application, might have some
human-readable meaning.
*/
private enum Identifier {
// Task with a form, where multiple items appear on one page.
case FormTask
case FormStep
case FormItem01
case FormItem02
case FormItem03
// Survey task specific identifiers.
case SurveyTask
case IntroStep
case QuestionStep
case SummaryStep
// Task with a Boolean question.
case BooleanQuestionTask
case BooleanQuestionStep
// Task with an example of date entry.
case DateQuestionTask
case DateQuestionStep
// Task with an example of date and time entry.
case DateTimeQuestionTask
case DateTimeQuestionStep
// Task with an example of height entry.
case HeightQuestionTask
case HeightQuestionStep1
case HeightQuestionStep2
case HeightQuestionStep3
// Task with an image choice question.
case ImageChoiceQuestionTask
case ImageChoiceQuestionStep
// Task with a location entry.
case LocationQuestionTask
case LocationQuestionStep
// Task with examples of numeric questions.
case NumericQuestionTask
case NumericQuestionStep
case NumericNoUnitQuestionStep
// Task with examples of questions with sliding scales.
case ScaleQuestionTask
case DiscreteScaleQuestionStep
case ContinuousScaleQuestionStep
case DiscreteVerticalScaleQuestionStep
case ContinuousVerticalScaleQuestionStep
case TextScaleQuestionStep
case TextVerticalScaleQuestionStep
// Task with an example of free text entry.
case TextQuestionTask
case TextQuestionStep
// Task with an example of a multiple choice question.
case TextChoiceQuestionTask
case TextChoiceQuestionStep
// Task with an example of time of day entry.
case TimeOfDayQuestionTask
case TimeOfDayQuestionStep
// Task with an example of time interval entry.
case TimeIntervalQuestionTask
case TimeIntervalQuestionStep
// Task with a value picker.
case ValuePickerChoiceQuestionTask
case ValuePickerChoiceQuestionStep
// Task with an example of validated text entry.
case ValidatedTextQuestionTask
case ValidatedTextQuestionStepEmail
case ValidatedTextQuestionStepDomain
// Image capture task specific identifiers.
case ImageCaptureTask
case ImageCaptureStep
// Task with an example of waiting.
case WaitTask
case WaitStepDeterminate
case WaitStepIndeterminate
// Eligibility task specific indentifiers.
case EligibilityTask
case EligibilityIntroStep
case EligibilityFormStep
case EligibilityFormItem01
case EligibilityFormItem02
case EligibilityFormItem03
case EligibilityIneligibleStep
case EligibilityEligibleStep
// Consent task specific identifiers.
case ConsentTask
case VisualConsentStep
case ConsentSharingStep
case ConsentReviewStep
case ConsentDocumentParticipantSignature
case ConsentDocumentInvestigatorSignature
// Account creation task specific identifiers.
case AccountCreationTask
case RegistrationStep
case WaitStep
case VerificationStep
// Login task specific identifiers.
case LoginTask
case LoginStep
case LoginWaitStep
// Passcode task specific identifiers.
case PasscodeTask
case PasscodeStep
// Active tasks.
case AudioTask
case FitnessTask
case HolePegTestTask
case PSATTask
case ReactionTime
case ShortWalkTask
case SpatialSpanMemoryTask
case TimedWalkTask
case ToneAudiometryTask
case TowerOfHanoi
case TwoFingerTappingIntervalTask
case WalkBackAndForthTask
}
// MARK: Properties
/// Returns a new `ORKTask` that the `TaskListRow` enumeration represents.
var representedTask: ORKTask {
switch self {
case .Form:
return formTask
case .Survey:
return surveyTask
case .BooleanQuestion:
return booleanQuestionTask
case .DateQuestion:
return dateQuestionTask
case .DateTimeQuestion:
return dateTimeQuestionTask
case .HeightQuestion:
return heightQuestionTask
case .ImageChoiceQuestion:
return imageChoiceQuestionTask
case .LocationQuestion:
return locationQuestionTask
case .NumericQuestion:
return numericQuestionTask
case .ScaleQuestion:
return scaleQuestionTask
case .TextQuestion:
return textQuestionTask
case .TextChoiceQuestion:
return textChoiceQuestionTask
case .TimeIntervalQuestion:
return timeIntervalQuestionTask
case .TimeOfDayQuestion:
return timeOfDayQuestionTask
case .ValuePickerChoiceQuestion:
return valuePickerChoiceQuestionTask
case .ValidatedTextQuestion:
return validatedTextQuestionTask
case .ImageCapture:
return imageCaptureTask
case .Wait:
return waitTask
case .EligibilityTask:
return eligibilityTask
case .Consent:
return consentTask
case .AccountCreation:
return accountCreationTask
case .Login:
return loginTask
case .Passcode:
return passcodeTask
case .Audio:
return audioTask
case .Fitness:
return fitnessTask
case .HolePegTest:
return holePegTestTask
case .PSAT:
return PSATTask
case .ReactionTime:
return reactionTimeTask
case .ShortWalk:
return shortWalkTask
case .SpatialSpanMemory:
return spatialSpanMemoryTask
case .TimedWalk:
return timedWalkTask
case .ToneAudiometry:
return toneAudiometryTask
case .TowerOfHanoi:
return towerOfHanoiTask
case .TwoFingerTappingInterval:
return twoFingerTappingIntervalTask
case .WalkBackAndForth:
return walkBackAndForthTask
}
}
// MARK: Task Creation Convenience
/**
This task demonstrates a form step, in which multiple items are presented
in a single scrollable form. This might be used for entering multi-value
data, like taking a blood pressure reading with separate systolic and
diastolic values.
*/
private var formTask: ORKTask {
let step = ORKFormStep(identifier: String(Identifier.FormStep), title: exampleQuestionText, text: exampleDetailText)
// A first field, for entering an integer.
let formItem01Text = NSLocalizedString("Field01", comment: "")
let formItem01 = ORKFormItem(identifier: String(Identifier.FormItem01), text: formItem01Text, answerFormat: ORKAnswerFormat.integerAnswerFormatWithUnit(nil))
formItem01.placeholder = NSLocalizedString("Your placeholder here", comment: "")
// A second field, for entering a time interval.
let formItem02Text = NSLocalizedString("Field02", comment: "")
let formItem02 = ORKFormItem(identifier: String(Identifier.FormItem02), text: formItem02Text, answerFormat: ORKTimeIntervalAnswerFormat())
formItem02.placeholder = NSLocalizedString("Your placeholder here", comment: "")
step.formItems = [
formItem01,
formItem02
]
return ORKOrderedTask(identifier: String(Identifier.FormTask), steps: [step])
}
/**
A task demonstrating how the ResearchKit framework can be used to present a simple
survey with an introduction, a question, and a conclusion.
*/
private var surveyTask: ORKTask {
// Create the intro step.
let instructionStep = ORKInstructionStep(identifier: String(Identifier.IntroStep))
instructionStep.title = NSLocalizedString("Sample Survey", comment: "")
instructionStep.text = exampleDescription
// Add a question step.
let questionStepAnswerFormat = ORKBooleanAnswerFormat()
let questionStepTitle = NSLocalizedString("Would you like to subscribe to our newsletter?", comment: "")
let questionStep = ORKQuestionStep(identifier: String(Identifier.QuestionStep), title: questionStepTitle, answer: questionStepAnswerFormat)
// Add a summary step.
let summaryStep = ORKInstructionStep(identifier: String(Identifier.SummaryStep))
summaryStep.title = NSLocalizedString("Thanks", comment: "")
summaryStep.text = NSLocalizedString("Thank you for participating in this sample survey.", comment: "")
return ORKOrderedTask(identifier: String(Identifier.SurveyTask), steps: [
instructionStep,
questionStep,
summaryStep
])
}
/// This task presents just a single "Yes" / "No" question.
private var booleanQuestionTask: ORKTask {
let answerFormat = ORKBooleanAnswerFormat()
// We attach an answer format to a question step to specify what controls the user sees.
let questionStep = ORKQuestionStep(identifier: String(Identifier.BooleanQuestionStep), title: exampleQuestionText, answer: answerFormat)
// The detail text is shown in a small font below the title.
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.BooleanQuestionTask), steps: [questionStep])
}
/// This task demonstrates a question which asks for a date.
private var dateQuestionTask: ORKTask {
/*
The date answer format can also support minimum and maximum limits,
a specific default value, and overriding the calendar to use.
*/
let answerFormat = ORKAnswerFormat.dateAnswerFormat()
let step = ORKQuestionStep(identifier: String(Identifier.DateQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.DateQuestionTask), steps: [step])
}
/// This task demonstrates a question asking for a date and time of an event.
private var dateTimeQuestionTask: ORKTask {
/*
This uses the default calendar. Use a more detailed constructor to
set minimum / maximum limits.
*/
let answerFormat = ORKAnswerFormat.dateTimeAnswerFormat()
let step = ORKQuestionStep(identifier: String(Identifier.DateTimeQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.DateTimeQuestionTask), steps: [step])
}
/// This task demonstrates a question asking for the user height.
private var heightQuestionTask: ORKTask {
let answerFormat1 = ORKAnswerFormat.heightAnswerFormat()
let step1 = ORKQuestionStep(identifier: String(Identifier.HeightQuestionStep1), title: "Height (local system)", answer: answerFormat1)
step1.text = exampleDetailText
let answerFormat2 = ORKAnswerFormat.heightAnswerFormatWithMeasurementSystem(ORKMeasurementSystem.Metric)
let step2 = ORKQuestionStep(identifier: String(Identifier.HeightQuestionStep2), title: "Height (metric system)", answer: answerFormat2)
step2.text = exampleDetailText
let answerFormat3 = ORKAnswerFormat.heightAnswerFormatWithMeasurementSystem(ORKMeasurementSystem.USC)
let step3 = ORKQuestionStep(identifier: String(Identifier.HeightQuestionStep3), title: "Height (USC system)", answer: answerFormat3)
step2.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.HeightQuestionTask), steps: [step1, step2, step3])
}
/**
This task demonstrates a survey question involving picking from a series of
image choices. A more realistic applciation of this type of question might be to
use a range of icons for faces ranging from happy to sad.
*/
private var imageChoiceQuestionTask: ORKTask {
let roundShapeImage = UIImage(named: "round_shape")!
let roundShapeText = NSLocalizedString("Round Shape", comment: "")
let squareShapeImage = UIImage(named: "square_shape")!
let squareShapeText = NSLocalizedString("Square Shape", comment: "")
let imageChoces = [
ORKImageChoice(normalImage: roundShapeImage, selectedImage: nil, text: roundShapeText, value: roundShapeText),
ORKImageChoice(normalImage: squareShapeImage, selectedImage: nil, text: squareShapeText, value: squareShapeText)
]
let answerFormat = ORKAnswerFormat.choiceAnswerFormatWithImageChoices(imageChoces)
let questionStep = ORKQuestionStep(identifier: String(Identifier.ImageChoiceQuestionStep), title: exampleQuestionText, answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.ImageChoiceQuestionTask), steps: [questionStep])
}
/// This task presents just a single location question.
private var locationQuestionTask: ORKTask {
let answerFormat = ORKLocationAnswerFormat()
// We attach an answer format to a question step to specify what controls the user sees.
let questionStep = ORKQuestionStep(identifier: String(Identifier.LocationQuestionStep), title: exampleQuestionText, answer: answerFormat)
// The detail text is shown in a small font below the title.
questionStep.text = exampleDetailText
questionStep.placeholder = NSLocalizedString("Address", comment: "");
return ORKOrderedTask(identifier: String(Identifier.LocationQuestionTask), steps: [questionStep])
}
/**
This task demonstrates use of numeric questions with and without units.
Note that the unit is just a string, prompting the user to enter the value
in the expected unit. The unit string propagates into the result object.
*/
private var numericQuestionTask: ORKTask {
// This answer format will display a unit in-line with the numeric entry field.
let localizedQuestionStep1AnswerFormatUnit = NSLocalizedString("Your unit", comment: "")
let questionStep1AnswerFormat = ORKAnswerFormat.decimalAnswerFormatWithUnit(localizedQuestionStep1AnswerFormatUnit)
let questionStep1 = ORKQuestionStep(identifier: String(Identifier.NumericQuestionStep), title: exampleQuestionText, answer: questionStep1AnswerFormat)
questionStep1.text = exampleDetailText
questionStep1.placeholder = NSLocalizedString("Your placeholder.", comment: "")
// This answer format is similar to the previous one, but this time without displaying a unit.
let questionStep2 = ORKQuestionStep(identifier: String(Identifier.NumericNoUnitQuestionStep), title: exampleQuestionText, answer: ORKAnswerFormat.decimalAnswerFormatWithUnit(nil))
questionStep2.text = exampleDetailText
questionStep2.placeholder = NSLocalizedString("Placeholder without unit.", comment: "")
return ORKOrderedTask(identifier: String(Identifier.NumericQuestionTask), steps: [
questionStep1,
questionStep2
])
}
/// This task presents two options for questions displaying a scale control.
private var scaleQuestionTask: ORKTask {
// The first step is a scale control with 10 discrete ticks.
let step1AnswerFormat = ORKAnswerFormat.scaleAnswerFormatWithMaximumValue(10, minimumValue: 1, defaultValue: NSIntegerMax, step: 1, vertical: false, maximumValueDescription: exampleHighValueText, minimumValueDescription: exampleLowValueText)
let questionStep1 = ORKQuestionStep(identifier: String(Identifier.DiscreteScaleQuestionStep), title: exampleQuestionText, answer: step1AnswerFormat)
questionStep1.text = exampleDetailText
// The second step is a scale control that allows continuous movement with a percent formatter.
let step2AnswerFormat = ORKAnswerFormat.continuousScaleAnswerFormatWithMaximumValue(1.0, minimumValue: 0.0, defaultValue: 99.0, maximumFractionDigits: 0, vertical: false, maximumValueDescription: nil, minimumValueDescription: nil)
step2AnswerFormat.numberStyle = .Percent
let questionStep2 = ORKQuestionStep(identifier: String(Identifier.ContinuousScaleQuestionStep), title: exampleQuestionText, answer: step2AnswerFormat)
questionStep2.text = exampleDetailText
// The third step is a vertical scale control with 10 discrete ticks.
let step3AnswerFormat = ORKAnswerFormat.scaleAnswerFormatWithMaximumValue(10, minimumValue: 1, defaultValue: NSIntegerMax, step: 1, vertical: true, maximumValueDescription: nil, minimumValueDescription: nil)
let questionStep3 = ORKQuestionStep(identifier: String(Identifier.DiscreteVerticalScaleQuestionStep), title: exampleQuestionText, answer: step3AnswerFormat)
questionStep3.text = exampleDetailText
// The fourth step is a vertical scale control that allows continuous movement.
let step4AnswerFormat = ORKAnswerFormat.continuousScaleAnswerFormatWithMaximumValue(5.0, minimumValue: 1.0, defaultValue: 99.0, maximumFractionDigits: 2, vertical: true, maximumValueDescription: exampleHighValueText, minimumValueDescription: exampleLowValueText)
let questionStep4 = ORKQuestionStep(identifier: String(Identifier.ContinuousVerticalScaleQuestionStep), title: exampleQuestionText, answer: step4AnswerFormat)
questionStep4.text = exampleDetailText
// The fifth step is a scale control that allows text choices.
let textChoices : [ORKTextChoice] = [ORKTextChoice(text: "Poor", value: 1), ORKTextChoice(text: "Fair", value: 2), ORKTextChoice(text: "Good", value: 3), ORKTextChoice(text: "Above Average", value: 10), ORKTextChoice(text: "Excellent", value: 5)]
let step5AnswerFormat = ORKAnswerFormat.textScaleAnswerFormatWithTextChoices(textChoices, defaultIndex: NSIntegerMax, vertical: false)
let questionStep5 = ORKQuestionStep(identifier: String(Identifier.TextScaleQuestionStep), title: exampleQuestionText, answer: step5AnswerFormat)
questionStep5.text = exampleDetailText
// The sixth step is a vertical scale control that allows text choices.
let step6AnswerFormat = ORKAnswerFormat.textScaleAnswerFormatWithTextChoices(textChoices, defaultIndex: NSIntegerMax, vertical: true)
let questionStep6 = ORKQuestionStep(identifier: String(Identifier.TextVerticalScaleQuestionStep), title: exampleQuestionText, answer: step6AnswerFormat)
questionStep6.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.ScaleQuestionTask), steps: [
questionStep1,
questionStep2,
questionStep3,
questionStep4,
questionStep5,
questionStep6
])
}
/**
This task demonstrates asking for text entry. Both single and multi-line
text entry are supported, with appropriate parameters to the text answer
format.
*/
private var textQuestionTask: ORKTask {
let answerFormat = ORKAnswerFormat.textAnswerFormat()
let step = ORKQuestionStep(identifier: String(Identifier.TextQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.TextQuestionTask), steps: [step])
}
/**
This task demonstrates a survey question for picking from a list of text
choices. In this case, the text choices are presented in a table view
(compare with the `valuePickerQuestionTask`).
*/
private var textChoiceQuestionTask: ORKTask {
let textChoiceOneText = NSLocalizedString("Choice 1", comment: "")
let textChoiceTwoText = NSLocalizedString("Choice 2", comment: "")
let textChoiceThreeText = NSLocalizedString("Choice 3", comment: "")
// The text to display can be separate from the value coded for each choice:
let textChoices = [
ORKTextChoice(text: textChoiceOneText, value: "choice_1"),
ORKTextChoice(text: textChoiceTwoText, value: "choice_2"),
ORKTextChoice(text: textChoiceThreeText, value: "choice_3")
]
let answerFormat = ORKAnswerFormat.choiceAnswerFormatWithStyle(.SingleChoice, textChoices: textChoices)
let questionStep = ORKQuestionStep(identifier: String(Identifier.TextChoiceQuestionStep), title: exampleQuestionText, answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.TextChoiceQuestionTask), steps: [questionStep])
}
/**
This task demonstrates requesting a time interval. For example, this might
be a suitable answer format for a question like "How long is your morning
commute?"
*/
private var timeIntervalQuestionTask: ORKTask {
/*
The time interval answer format is constrained to entering a time
less than 24 hours and in steps of minutes. For times that don't fit
these restrictions, use another mode of data entry.
*/
let answerFormat = ORKAnswerFormat.timeIntervalAnswerFormat()
let step = ORKQuestionStep(identifier: String(Identifier.TimeIntervalQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.TimeIntervalQuestionTask), steps: [step])
}
/// This task demonstrates a question asking for a time of day.
private var timeOfDayQuestionTask: ORKTask {
/*
Because we don't specify a default, the picker will default to the
time the step is presented. For questions like "What time do you have
breakfast?", it would make sense to set the default on the answer
format.
*/
let answerFormat = ORKAnswerFormat.timeOfDayAnswerFormat()
let questionStep = ORKQuestionStep(identifier: String(Identifier.TimeOfDayQuestionStep), title: exampleQuestionText, answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.TimeOfDayQuestionTask), steps: [questionStep])
}
/**
This task demonstrates a survey question using a value picker wheel.
Compare with the `textChoiceQuestionTask` and `imageChoiceQuestionTask`
which can serve a similar purpose.
*/
private var valuePickerChoiceQuestionTask: ORKTask {
let textChoiceOneText = NSLocalizedString("Choice 1", comment: "")
let textChoiceTwoText = NSLocalizedString("Choice 2", comment: "")
let textChoiceThreeText = NSLocalizedString("Choice 3", comment: "")
// The text to display can be separate from the value coded for each choice:
let textChoices = [
ORKTextChoice(text: textChoiceOneText, value: "choice_1"),
ORKTextChoice(text: textChoiceTwoText, value: "choice_2"),
ORKTextChoice(text: textChoiceThreeText, value: "choice_3")
]
let answerFormat = ORKAnswerFormat.valuePickerAnswerFormatWithTextChoices(textChoices)
let questionStep = ORKQuestionStep(identifier: String(Identifier.ValuePickerChoiceQuestionStep), title: exampleQuestionText,
answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.ValuePickerChoiceQuestionTask), steps: [questionStep])
}
/**
This task demonstrates asking for text entry. Both single and multi-line
text entry are supported, with appropriate parameters to the text answer
format.
*/
private var validatedTextQuestionTask: ORKTask {
let answerFormatEmail = ORKAnswerFormat.emailAnswerFormat()
let stepEmail = ORKQuestionStep(identifier: String(Identifier.ValidatedTextQuestionStepEmail), title: NSLocalizedString("Email", comment: ""), answer: answerFormatEmail)
stepEmail.text = exampleDetailText
let domainRegex = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"
let answerFormatDomain = ORKAnswerFormat.textAnswerFormatWithValidationRegex(domainRegex, invalidMessage:"Invalid URL: %@")
answerFormatDomain.multipleLines = false
answerFormatDomain.keyboardType = UIKeyboardType.URL
answerFormatDomain.autocapitalizationType = UITextAutocapitalizationType.None
answerFormatDomain.autocorrectionType = UITextAutocorrectionType.No
answerFormatDomain.spellCheckingType = UITextSpellCheckingType.No
let stepDomain = ORKQuestionStep(identifier: String(Identifier.ValidatedTextQuestionStepDomain), title: NSLocalizedString("URL", comment: ""), answer: answerFormatDomain)
stepDomain.text = exampleDetailText
return ORKOrderedTask(identifier: String(Identifier.ValidatedTextQuestionTask), steps: [stepEmail, stepDomain])
}
/// This task presents the image capture step in an ordered task.
private var imageCaptureTask: ORKTask {
// Create the intro step.
let instructionStep = ORKInstructionStep(identifier: String(Identifier.IntroStep))
instructionStep.title = NSLocalizedString("Sample Survey", comment: "")
instructionStep.text = exampleDescription
let handSolidImage = UIImage(named: "hand_solid")!
instructionStep.image = handSolidImage.imageWithRenderingMode(.AlwaysTemplate)
let imageCaptureStep = ORKImageCaptureStep(identifier: String(Identifier.ImageCaptureStep))
imageCaptureStep.optional = false
imageCaptureStep.accessibilityInstructions = NSLocalizedString("Your instructions for capturing the image", comment: "")
imageCaptureStep.accessibilityHint = NSLocalizedString("Captures the image visible in the preview", comment: "")
imageCaptureStep.templateImage = UIImage(named: "hand_outline_big")!
imageCaptureStep.templateImageInsets = UIEdgeInsets(top: 0.05, left: 0.05, bottom: 0.05, right: 0.05)
return ORKOrderedTask(identifier: String(Identifier.ImageCaptureTask), steps: [
instructionStep,
imageCaptureStep
])
}
/// This task presents a wait task.
private var waitTask: ORKTask {
let waitStepIndeterminate = ORKWaitStep(identifier: String(Identifier.WaitStepIndeterminate))
waitStepIndeterminate.title = exampleQuestionText
waitStepIndeterminate.text = exampleDescription
waitStepIndeterminate.indicatorType = ORKProgressIndicatorType.Indeterminate
let waitStepDeterminate = ORKWaitStep(identifier: String(Identifier.WaitStepDeterminate))
waitStepDeterminate.title = exampleQuestionText
waitStepDeterminate.text = exampleDescription
waitStepDeterminate.indicatorType = ORKProgressIndicatorType.ProgressBar
return ORKOrderedTask(identifier: String(Identifier.WaitTask), steps: [waitStepIndeterminate, waitStepDeterminate])
}
/**
A task demonstrating how the ResearchKit framework can be used to determine
eligibility using a navigable ordered task.
*/
private var eligibilityTask: ORKTask {
// Intro step
let introStep = ORKInstructionStep(identifier: String(Identifier.EligibilityIntroStep))
introStep.title = NSLocalizedString("Eligibility Task Example", comment: "")
// Form step
let formStep = ORKFormStep(identifier: String(Identifier.EligibilityFormStep))
formStep.title = NSLocalizedString("Eligibility", comment: "")
formStep.text = exampleQuestionText
formStep.optional = false
// Form items
let textChoices : [ORKTextChoice] = [ORKTextChoice(text: "Yes", value: "Yes"), ORKTextChoice(text: "No", value: "No"), ORKTextChoice(text: "N/A", value: "N/A")]
let answerFormat = ORKTextChoiceAnswerFormat(style: ORKChoiceAnswerStyle.SingleChoice, textChoices: textChoices)
let formItem01 = ORKFormItem(identifier: String(Identifier.EligibilityFormItem01), text: exampleQuestionText, answerFormat: answerFormat)
formItem01.optional = false
let formItem02 = ORKFormItem(identifier: String(Identifier.EligibilityFormItem02), text: exampleQuestionText, answerFormat: answerFormat)
formItem02.optional = false
let formItem03 = ORKFormItem(identifier: String(Identifier.EligibilityFormItem03), text: exampleQuestionText, answerFormat: answerFormat)
formItem03.optional = false
formStep.formItems = [
formItem01,
formItem02,
formItem03
]
// Ineligible step
let ineligibleStep = ORKInstructionStep(identifier: String(Identifier.EligibilityIneligibleStep))
ineligibleStep.title = NSLocalizedString("You are ineligible to join the study", comment: "")
// Eligible step
let eligibleStep = ORKCompletionStep(identifier: String(Identifier.EligibilityEligibleStep))
eligibleStep.title = NSLocalizedString("You are eligible to join the study", comment: "")
// Create the task
let eligibilityTask = ORKNavigableOrderedTask(identifier: String(Identifier.EligibilityTask), steps: [
introStep,
formStep,
ineligibleStep,
eligibleStep
])
// Build navigation rules.
var resultSelector = ORKResultSelector(stepIdentifier: String(Identifier.EligibilityFormStep), resultIdentifier: String(Identifier.EligibilityFormItem01))
let predicateFormItem01 = ORKResultPredicate.predicateForChoiceQuestionResultWithResultSelector(resultSelector, expectedAnswerValue: "Yes")
resultSelector = ORKResultSelector(stepIdentifier: String(Identifier.EligibilityFormStep), resultIdentifier: String(Identifier.EligibilityFormItem02))
let predicateFormItem02 = ORKResultPredicate.predicateForChoiceQuestionResultWithResultSelector(resultSelector, expectedAnswerValue: "Yes")
resultSelector = ORKResultSelector(stepIdentifier: String(Identifier.EligibilityFormStep), resultIdentifier: String(Identifier.EligibilityFormItem03))
let predicateFormItem03 = ORKResultPredicate.predicateForChoiceQuestionResultWithResultSelector(resultSelector, expectedAnswerValue: "No")
let predicateEligible = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateFormItem01, predicateFormItem02, predicateFormItem03])
let predicateRule = ORKPredicateStepNavigationRule(resultPredicatesAndDestinationStepIdentifiers: [ (predicateEligible, String(Identifier.EligibilityEligibleStep)) ])
eligibilityTask.setNavigationRule(predicateRule, forTriggerStepIdentifier:String(Identifier.EligibilityFormStep))
// Add end direct rules to skip unneeded steps
let directRule = ORKDirectStepNavigationRule(destinationStepIdentifier: ORKNullStepIdentifier)
eligibilityTask.setNavigationRule(directRule, forTriggerStepIdentifier:String(Identifier.EligibilityIneligibleStep))
return eligibilityTask
}
/// A task demonstrating how the ResearchKit framework can be used to obtain informed consent.
private var consentTask: ORKTask {
/*
Informed consent starts by presenting an animated sequence conveying
the main points of your consent document.
*/
let visualConsentStep = ORKVisualConsentStep(identifier: String(Identifier.VisualConsentStep), document: consentDocument)
let investigatorShortDescription = NSLocalizedString("Institution", comment: "")
let investigatorLongDescription = NSLocalizedString("Institution and its partners", comment: "")
let localizedLearnMoreHTMLContent = NSLocalizedString("Your sharing learn more content here.", comment: "")
/*
If you want to share the data you collect with other researchers for
use in other studies beyond this one, it is best practice to get
explicit permission from the participant. Use the consent sharing step
for this.
*/
let sharingConsentStep = ORKConsentSharingStep(identifier: String(Identifier.ConsentSharingStep), investigatorShortDescription: investigatorShortDescription, investigatorLongDescription: investigatorLongDescription, localizedLearnMoreHTMLContent: localizedLearnMoreHTMLContent)
/*
After the visual presentation, the consent review step displays
your consent document and can obtain a signature from the participant.
The first signature in the document is the participant's signature.
This effectively tells the consent review step which signatory is
reviewing the document.
*/
let signature = consentDocument.signatures!.first
let reviewConsentStep = ORKConsentReviewStep(identifier: String(Identifier.ConsentReviewStep), signature: signature, inDocument: consentDocument)
// In a real application, you would supply your own localized text.
reviewConsentStep.text = loremIpsumText
reviewConsentStep.reasonForConsent = loremIpsumText
return ORKOrderedTask(identifier: String(Identifier.ConsentTask), steps: [
visualConsentStep,
sharingConsentStep,
reviewConsentStep
])
}
/// This task presents the Account Creation process.
private var accountCreationTask: ORKTask {
/*
A registration step provides a form step that is populated with email and password fields.
If you wish to include any of the additional fields, then you can specify it through the `options` parameter.
*/
let registrationTitle = NSLocalizedString("Registration", comment: "")
let passcodeValidationRegex = "^(?=.*\\d).{4,8}$"
let passcodeInvalidMessage = NSLocalizedString("A valid password must be 4 and 8 digits long and include at least one numeric character.", comment: "")
let registrationOptions: ORKRegistrationStepOption = [.IncludeGivenName, .IncludeFamilyName, .IncludeGender, .IncludeDOB]
let registrationStep = ORKRegistrationStep(identifier: String(Identifier.RegistrationStep), title: registrationTitle, text: exampleDetailText, passcodeValidationRegex: passcodeValidationRegex, passcodeInvalidMessage: passcodeInvalidMessage, options: registrationOptions)
/*
A wait step allows you to upload the data from the user registration onto your server before presenting the verification step.
*/
let waitTitle = NSLocalizedString("Creating account", comment: "")
let waitText = NSLocalizedString("Please wait while we upload your data", comment: "")
let waitStep = ORKWaitStep(identifier: String(Identifier.WaitStep))
waitStep.title = waitTitle
waitStep.text = waitText
/*
A verification step view controller subclass is required in order to use the verification step.
The subclass provides the view controller button and UI behavior by overriding the following methods.
*/
class VerificationViewController : ORKVerificationStepViewController {
override func resendEmailButtonTapped() {
let alertTitle = NSLocalizedString("Resend Verification Email", comment: "")
let alertMessage = NSLocalizedString("Button tapped", comment: "")
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
let verificationStep = ORKVerificationStep(identifier: String(Identifier.VerificationStep), text: exampleDetailText, verificationViewControllerClass: VerificationViewController.self)
return ORKOrderedTask(identifier: String(Identifier.AccountCreationTask), steps: [
registrationStep,
waitStep,
verificationStep
])
}
/// This tasks presents the login step.
private var loginTask: ORKTask {
/*
A login step view controller subclass is required in order to use the login step.
The subclass provides the behavior for the login step forgot password button.
*/
class LoginViewController : ORKLoginStepViewController {
override func forgotPasswordButtonTapped() {
let alertTitle = NSLocalizedString("Forgot password?", comment: "")
let alertMessage = NSLocalizedString("Button tapped", comment: "")
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
self.presentViewController(alert, animated: true, completion: nil)
}
}
/*
A login step provides a form step that is populated with email and password fields,
and a button for `Forgot password?`.
*/
let loginTitle = NSLocalizedString("Login", comment: "")
let loginStep = ORKLoginStep(identifier: String(Identifier.LoginStep), title: loginTitle, text: exampleDetailText, loginViewControllerClass: LoginViewController.self)
/*
A wait step allows you to validate the data from the user login against your server before proceeding.
*/
let waitTitle = NSLocalizedString("Logging in", comment: "")
let waitText = NSLocalizedString("Please wait while we validate your credentials", comment: "")
let waitStep = ORKWaitStep(identifier: String(Identifier.LoginWaitStep))
waitStep.title = waitTitle
waitStep.text = waitText
return ORKOrderedTask(identifier: String(Identifier.LoginTask), steps: [loginStep, waitStep])
}
/// This task demonstrates the Passcode creation process.
private var passcodeTask: ORKTask {
/*
If you want to protect the app using a passcode. It is reccomended to
ask user to create passcode as part of the consent process and use the
authentication and editing view controllers to interact with the passcode.
The passcode is stored in the keychain.
*/
let passcodeConsentStep = ORKPasscodeStep(identifier: String(Identifier.PasscodeStep))
return ORKOrderedTask(identifier: String(Identifier.PasscodeStep), steps: [passcodeConsentStep])
}
/// This task presents the Audio pre-defined active task.
private var audioTask: ORKTask {
return ORKOrderedTask.audioTaskWithIdentifier(String(Identifier.AudioTask), intendedUseDescription: exampleDescription, speechInstruction: exampleSpeechInstruction, shortSpeechInstruction: exampleSpeechInstruction, duration: 20, recordingSettings: nil, checkAudioLevel: true, options: [])
}
/**
This task presents the Fitness pre-defined active task. For this example,
short walking and rest durations of 20 seconds each are used, whereas more
realistic durations might be several minutes each.
*/
private var fitnessTask: ORKTask {
return ORKOrderedTask.fitnessCheckTaskWithIdentifier(String(Identifier.FitnessTask), intendedUseDescription: exampleDescription, walkDuration: 20, restDuration: 20, options: [])
}
/// This task presents the Hole Peg Test pre-defined active task.
private var holePegTestTask: ORKTask {
return ORKNavigableOrderedTask.holePegTestTaskWithIdentifier(String(Identifier.HolePegTestTask), intendedUseDescription: exampleDescription, dominantHand: .Right, numberOfPegs: 9, threshold: 0.2, rotated: false, timeLimit: 300, options: [])
}
/// This task presents the PSAT pre-defined active task.
private var PSATTask: ORKTask {
return ORKOrderedTask.PSATTaskWithIdentifier(String(Identifier.PSATTask), intendedUseDescription: exampleDescription, presentationMode: ORKPSATPresentationMode.Auditory.union(.Visual), interStimulusInterval: 3.0, stimulusDuration: 1.0, seriesLength: 60, options: [])
}
/// This task presents the Reaction Time pre-defined active task.
private var reactionTimeTask: ORKTask {
/// An example of a custom sound.
let successSoundURL = NSBundle.mainBundle().URLForResource("tap", withExtension: "aif")!
let successSound = SystemSound(soundURL: successSoundURL)!
return ORKOrderedTask.reactionTimeTaskWithIdentifier(String(Identifier.ReactionTime), intendedUseDescription: exampleDescription, maximumStimulusInterval: 10, minimumStimulusInterval: 4, thresholdAcceleration: 0.5, numberOfAttempts: 3, timeout: 3, successSound: successSound.soundID, timeoutSound: 0, failureSound: UInt32(kSystemSoundID_Vibrate), options: [])
}
/// This task presents the Gait and Balance pre-defined active task.
private var shortWalkTask: ORKTask {
return ORKOrderedTask.shortWalkTaskWithIdentifier(String(Identifier.ShortWalkTask), intendedUseDescription: exampleDescription, numberOfStepsPerLeg: 20, restDuration: 20, options: [])
}
/// This task presents the Spatial Span Memory pre-defined active task.
private var spatialSpanMemoryTask: ORKTask {
return ORKOrderedTask.spatialSpanMemoryTaskWithIdentifier(String(Identifier.SpatialSpanMemoryTask), intendedUseDescription: exampleDescription, initialSpan: 3, minimumSpan: 2, maximumSpan: 15, playSpeed: 1.0, maximumTests: 5, maximumConsecutiveFailures: 3, customTargetImage: nil, customTargetPluralName: nil, requireReversal: false, options: [])
}
/// This task presents the Timed Walk pre-defined active task.
private var timedWalkTask: ORKTask {
return ORKOrderedTask.timedWalkTaskWithIdentifier(String(Identifier.TimedWalkTask), intendedUseDescription: exampleDescription, distanceInMeters: 100.0, timeLimit: 180.0, includeAssistiveDeviceForm: true, options: [])
}
/// This task presents the Tone Audiometry pre-defined active task.
private var toneAudiometryTask: ORKTask {
return ORKOrderedTask.toneAudiometryTaskWithIdentifier(String(Identifier.ToneAudiometryTask), intendedUseDescription: exampleDescription, speechInstruction: nil, shortSpeechInstruction: nil, toneDuration: 20, options: [])
}
private var towerOfHanoiTask: ORKTask {
return ORKOrderedTask.towerOfHanoiTaskWithIdentifier(String(Identifier.TowerOfHanoi), intendedUseDescription: exampleDescription, numberOfDisks: 5, options: [])
}
/// This task presents the Two Finger Tapping pre-defined active task.
private var twoFingerTappingIntervalTask: ORKTask {
return ORKOrderedTask.twoFingerTappingIntervalTaskWithIdentifier(String(Identifier.TwoFingerTappingIntervalTask), intendedUseDescription: exampleDescription, duration: 10, handOptions: [.Both], options: [])
}
/// This task presents a walk back-and-forth task
private var walkBackAndForthTask: ORKTask {
return ORKOrderedTask.walkBackAndForthTaskWithIdentifier(String(Identifier.WalkBackAndForthTask), intendedUseDescription: exampleDescription, walkDuration: 30, restDuration: 30, options: [])
}
// MARK: Consent Document Creation Convenience
/**
A consent document provides the content for the visual consent and consent
review steps. This helper sets up a consent document with some dummy
content. You should populate your consent document to suit your study.
*/
private var consentDocument: ORKConsentDocument {
let consentDocument = ORKConsentDocument()
/*
This is the title of the document, displayed both for review and in
the generated PDF.
*/
consentDocument.title = NSLocalizedString("Example Consent", comment: "")
// This is the title of the signature page in the generated document.
consentDocument.signaturePageTitle = NSLocalizedString("Consent", comment: "")
/*
This is the line shown on the signature page of the generated document,
just above the signatures.
*/
consentDocument.signaturePageContent = NSLocalizedString("I agree to participate in this research study.", comment: "")
/*
Add the participant signature, which will be filled in during the
consent review process. This signature initially does not have a
signature image or a participant name; these are collected during
the consent review step.
*/
let participantSignatureTitle = NSLocalizedString("Participant", comment: "")
let participantSignature = ORKConsentSignature(forPersonWithTitle: participantSignatureTitle, dateFormatString: nil, identifier: String(Identifier.ConsentDocumentParticipantSignature))
consentDocument.addSignature(participantSignature)
/*
Add the investigator signature. This is pre-populated with the
investigator's signature image and name, and the date of their
signature. If you need to specify the date as now, you could generate
a date string with code here.
This signature is only used for the generated PDF.
*/
let signatureImage = UIImage(named: "signature")!
let investigatorSignatureTitle = NSLocalizedString("Investigator", comment: "")
let investigatorSignatureGivenName = NSLocalizedString("Jonny", comment: "")
let investigatorSignatureFamilyName = NSLocalizedString("Appleseed", comment: "")
let investigatorSignatureDateString = "3/10/15"
let investigatorSignature = ORKConsentSignature(forPersonWithTitle: investigatorSignatureTitle, dateFormatString: nil, identifier: String(Identifier.ConsentDocumentInvestigatorSignature), givenName: investigatorSignatureGivenName, familyName: investigatorSignatureFamilyName, signatureImage: signatureImage, dateString: investigatorSignatureDateString)
consentDocument.addSignature(investigatorSignature)
/*
This is the HTML content for the "Learn More" page for each consent
section. In a real consent, this would be your content, and you would
have different content for each section.
If your content is just text, you can use the `content` property
instead of the `htmlContent` property of `ORKConsentSection`.
*/
let htmlContentString = "<ul><li>Lorem</li><li>ipsum</li><li>dolor</li></ul><p>\(loremIpsumLongText)</p><p>\(loremIpsumMediumText)</p>"
/*
These are all the consent section types that have pre-defined animations
and images. We use them in this specific order, so we see the available
animated transitions.
*/
let consentSectionTypes: [ORKConsentSectionType] = [
.Overview,
.DataGathering,
.Privacy,
.DataUse,
.TimeCommitment,
.StudySurvey,
.StudyTasks,
.Withdrawing
]
/*
For each consent section type in `consentSectionTypes`, create an
`ORKConsentSection` that represents it.
In a real app, you would set specific content for each section.
*/
var consentSections: [ORKConsentSection] = consentSectionTypes.map { contentSectionType in
let consentSection = ORKConsentSection(type: contentSectionType)
consentSection.summary = loremIpsumShortText
if contentSectionType == .Overview {
consentSection.htmlContent = htmlContentString
}
else {
consentSection.content = loremIpsumLongText
}
return consentSection
}
/*
This is an example of a section that is only in the review document
or only in the generated PDF, and is not displayed in `ORKVisualConsentStep`.
*/
let consentSection = ORKConsentSection(type: .OnlyInDocument)
consentSection.summary = NSLocalizedString(".OnlyInDocument Scene Summary", comment: "")
consentSection.title = NSLocalizedString(".OnlyInDocument Scene", comment: "")
consentSection.content = loremIpsumLongText
consentSections += [consentSection]
// Set the sections on the document after they've been created.
consentDocument.sections = consentSections
return consentDocument
}
// MARK: `ORKTask` Reused Text Convenience
private var exampleDescription: String {
return NSLocalizedString("Your description goes here.", comment: "")
}
private var exampleSpeechInstruction: String {
return NSLocalizedString("Your more specific voice instruction goes here. For example, say 'Aaaah'.", comment: "")
}
private var exampleQuestionText: String {
return NSLocalizedString("Your question goes here.", comment: "")
}
private var exampleHighValueText: String {
return NSLocalizedString("High Value", comment: "")
}
private var exampleLowValueText: String {
return NSLocalizedString("Low Value", comment: "")
}
private var exampleDetailText: String {
return NSLocalizedString("Additional text can go here.", comment: "")
}
private var exampleEmailText: String {
return NSLocalizedString("[email protected]", comment: "")
}
private var loremIpsumText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
}
private var loremIpsumShortText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
}
private var loremIpsumMediumText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam adhuc, meo fortasse vitio, quid ego quaeram non perspicis. Plane idem, inquit, et maxima quidem, qua fieri nulla maior potest. Quonam, inquit, modo?"
}
private var loremIpsumLongText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam adhuc, meo fortasse vitio, quid ego quaeram non perspicis. Plane idem, inquit, et maxima quidem, qua fieri nulla maior potest. Quonam, inquit, modo? An potest, inquit ille, quicquam esse suavius quam nihil dolere? Cave putes quicquam esse verius. Quonam, inquit, modo?"
}
}
| 8ad83b6e4390a5f0408f374e6f61f162 | 44.082615 | 367 | 0.674225 | false | false | false | false |
SusanDoggie/Doggie | refs/heads/main | Sources/DoggieMath/Accelerate/Radix2CooleyTukey/Radix2CooleyTukey.swift | mit | 1 | //
// Radix2CooleyTukey.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. 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.
//
@inlinable
@inline(__always)
public func Radix2CooleyTukey<T: BinaryFloatingPoint>(_ log2n: Int, _ input: UnsafePointer<T>, _ in_stride: Int, _ in_count: Int, _ out_real: UnsafeMutablePointer<T>, _ out_imag: UnsafeMutablePointer<T>, _ out_stride: Int) where T: ElementaryFunctions {
let length = 1 << log2n
if _slowPath(in_count == 0) {
var out_real = out_real
var out_imag = out_imag
for _ in 0..<length {
out_real.pointee = 0
out_imag.pointee = 0
out_real += out_stride
out_imag += out_stride
}
return
}
switch log2n {
case 0:
out_real.pointee = in_count == 0 ? 0 : input.pointee
out_imag.pointee = 0
case 1:
cooleytukey_forward_2(input, in_stride, in_count, out_real, out_imag, out_stride)
case 2:
cooleytukey_forward_4(input, in_stride, in_count, out_real, out_imag, out_stride)
case 3:
cooleytukey_forward_8(input, in_stride, in_count, out_real, out_imag, out_stride)
case 4:
cooleytukey_forward_16(input, in_stride, in_count, out_real, out_imag, out_stride)
default:
let half = length >> 1
let fourth = length >> 2
let _in_count = in_count >> 1
cooleytukey_forward(log2n - 1, input, input + in_stride, in_stride << 1, (_in_count + in_count & 1, _in_count), out_real, out_imag, out_stride)
let _out_stride = half * out_stride
var op_r = out_real
var op_i = out_imag
var oph_r = out_real + _out_stride
var oph_i = out_imag + _out_stride
var oph2_r = oph_r
var oph2_i = oph_i
var opb_r = out_real + length * out_stride
var opb_i = out_imag + length * out_stride
let tr = op_r.pointee
let ti = op_i.pointee
op_r.pointee = tr + ti
op_i.pointee = 0
oph_r.pointee = tr - ti
oph_i.pointee = 0
let opf_r = op_r + fourth * out_stride
let opf_i = op_i + fourth * out_stride
let optf_r = oph_r + fourth * out_stride
let optf_i = oph_i + fourth * out_stride
optf_r.pointee = opf_r.pointee
optf_i.pointee = opf_i.pointee
opf_i.pointee = -opf_i.pointee
let angle = -T.pi / T(half)
let _cos = T.cos(angle)
let _sin = T.sin(angle)
var _cos1 = _cos
var _sin1 = _sin
for _ in 1..<fourth {
op_r += out_stride
op_i += out_stride
oph_r -= out_stride
oph_i -= out_stride
oph2_r += out_stride
oph2_i += out_stride
opb_r -= out_stride
opb_i -= out_stride
let or = op_r.pointee
let oi = op_i.pointee
let ohr = oph_r.pointee
let ohi = oph_i.pointee
let evenreal = or + ohr
let evenim = oi - ohi
let oddreal = oi + ohi
let oddim = ohr - or
let _r = oddreal * _cos1 - oddim * _sin1
let _i = oddreal * _sin1 + oddim * _cos1
let _r1 = 0.5 * (evenreal + _r)
let _i1 = 0.5 * (_i + evenim)
let _r2 = 0.5 * (evenreal - _r)
let _i2 = 0.5 * (_i - evenim)
op_r.pointee = _r1
op_i.pointee = _i1
oph_r.pointee = _r2
oph_i.pointee = _i2
oph2_r.pointee = _r2
oph2_i.pointee = -_i2
opb_r.pointee = _r1
opb_i.pointee = -_i1
let _c1 = _cos * _cos1 - _sin * _sin1
let _s1 = _cos * _sin1 + _sin * _cos1
_cos1 = _c1
_sin1 = _s1
}
}
}
@inlinable
@inline(__always)
public func Radix2CooleyTukey<T: BinaryFloatingPoint>(_ log2n: Int, _ in_real: UnsafePointer<T>, _ in_imag: UnsafePointer<T>, _ in_stride: Int, _ in_count: Int, _ out_real: UnsafeMutablePointer<T>, _ out_imag: UnsafeMutablePointer<T>, _ out_stride: Int) where T: ElementaryFunctions {
cooleytukey_forward(log2n, in_real, in_imag, in_stride, (in_count, in_count), out_real, out_imag, out_stride)
}
@inlinable
@inline(__always)
func cooleytukey_forward_reorderd<T: BinaryFloatingPoint>(_ log2n: Int, _ real: UnsafeMutablePointer<T>, _ imag: UnsafeMutablePointer<T>, _ stride: Int) where T: ElementaryFunctions {
let count = 1 << log2n
do {
var _r = real
var _i = imag
let m_stride = stride << 4
for _ in Swift.stride(from: 0, to: count, by: 16) {
cooleytukey_forward_reorderd_16(_r, _i, stride)
_r += m_stride
_i += m_stride
}
}
for s in 4..<log2n {
let m = 2 << s
let n = 1 << s
let angle = -T.pi / T(n)
let _cos = T.cos(angle)
let _sin = T.sin(angle)
let m_stride = m * stride
let n_stride = n * stride
var r1 = real
var i1 = imag
for _ in Swift.stride(from: 0, to: count, by: m) {
var _cos1 = 1 as T
var _sin1 = 0 as T
var _r1 = r1
var _i1 = i1
var _r2 = r1 + n_stride
var _i2 = i1 + n_stride
for _ in 0..<n {
let ur = _r1.pointee
let ui = _i1.pointee
let vr = _r2.pointee
let vi = _i2.pointee
let vrc = vr * _cos1
let vic = vi * _cos1
let vrs = vr * _sin1
let vis = vi * _sin1
let _c = _cos * _cos1 - _sin * _sin1
let _s = _cos * _sin1 + _sin * _cos1
_cos1 = _c
_sin1 = _s
_r1.pointee = ur + vrc - vis
_i1.pointee = ui + vrs + vic
_r2.pointee = ur - vrc + vis
_i2.pointee = ui - vrs - vic
_r1 += stride
_i1 += stride
_r2 += stride
_i2 += stride
}
r1 += m_stride
i1 += m_stride
}
}
}
@inlinable
@inline(__always)
func cooleytukey_forward<T: BinaryFloatingPoint>(_ log2n: Int, _ in_real: UnsafePointer<T>, _ in_imag: UnsafePointer<T>, _ in_stride: Int, _ in_count: (Int, Int), _ out_real: UnsafeMutablePointer<T>, _ out_imag: UnsafeMutablePointer<T>, _ out_stride: Int) where T: ElementaryFunctions {
let count = 1 << log2n
if _slowPath(in_count.0 == 0 && in_count.1 == 0) {
var out_real = out_real
var out_imag = out_imag
for _ in 0..<count {
out_real.pointee = 0
out_imag.pointee = 0
out_real += out_stride
out_imag += out_stride
}
return
}
switch log2n {
case 0:
out_real.pointee = in_count.0 == 0 ? 0 : in_real.pointee
out_imag.pointee = in_count.1 == 0 ? 0 : in_imag.pointee
case 1:
cooleytukey_forward_2(in_real, in_imag, in_stride, in_count, out_real, out_imag, out_stride)
case 2:
cooleytukey_forward_4(in_real, in_imag, in_stride, in_count, out_real, out_imag, out_stride)
case 3:
cooleytukey_forward_8(in_real, in_imag, in_stride, in_count, out_real, out_imag, out_stride)
case 4:
cooleytukey_forward_16(in_real, in_imag, in_stride, in_count, out_real, out_imag, out_stride)
default:
let offset = Int.bitWidth - log2n
do {
var in_real = in_real
var in_imag = in_imag
for i in 0..<count {
let _i = Int(UInt(i).reverse >> offset)
out_real[_i * out_stride] = i < in_count.0 ? in_real.pointee : 0
out_imag[_i * out_stride] = i < in_count.1 ? in_imag.pointee : 0
in_real += in_stride
in_imag += in_stride
}
}
cooleytukey_forward_reorderd(log2n, out_real, out_imag, out_stride)
}
}
@inlinable
@inline(__always)
public func Radix2CooleyTukey<T: BinaryFloatingPoint>(_ log2n: Int, _ real: UnsafeMutablePointer<T>, _ imag: UnsafeMutablePointer<T>, _ stride: Int) where T: ElementaryFunctions {
let count = 1 << log2n
switch log2n {
case 0: break
case 1:
cooleytukey_forward_2(real, imag, stride, (count, count), real, imag, stride)
case 2:
cooleytukey_forward_4(real, imag, stride, (count, count), real, imag, stride)
case 3:
cooleytukey_forward_8(real, imag, stride, (count, count), real, imag, stride)
case 4:
cooleytukey_forward_16(real, imag, stride, (count, count), real, imag, stride)
default:
do {
let offset = Int.bitWidth - log2n
var _real = real
var _imag = imag
for i in 1..<count - 1 {
let _i = Int(UInt(i).reverse >> offset)
_real += stride
_imag += stride
if i < _i {
swap(&_real.pointee, &real[_i * stride])
swap(&_imag.pointee, &imag[_i * stride])
}
}
}
cooleytukey_forward_reorderd(log2n, real, imag, stride)
}
}
| 4adc461478ab1f90ed8c17d26e4854a7 | 33.142857 | 286 | 0.514551 | false | false | false | false |
vector-im/vector-ios | refs/heads/master | Riot/Modules/Room/TimelineCells/SizableCell/SizableBaseRoomCell.swift | apache-2.0 | 1 | /*
Copyright 2020 New Vector Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
import UIKit
import MatrixSDK
@objc protocol SizableBaseRoomCellType: BaseRoomCellProtocol {
static func sizingViewHeightHashValue(from bubbleCellData: MXKRoomBubbleCellData) -> Int
}
/// `SizableBaseRoomCell` allows a cell using Auto Layout that inherits from this class to automatically return the height of the cell and cache the result.
@objcMembers
class SizableBaseRoomCell: BaseRoomCell, SizableBaseRoomCellType {
// MARK: - Constants
private static let sizingViewHeightStore = SizingViewHeightStore()
private static var sizingViews: [String: SizableBaseRoomCell] = [:]
private static let sizingReactionsView = RoomReactionsView()
private static let reactionsViewSizer = RoomReactionsViewSizer()
private static let reactionsViewModelBuilder = RoomReactionsViewModelBuilder()
private static let urlPreviewViewSizer = URLPreviewViewSizer()
private class var sizingView: SizableBaseRoomCell {
let sizingView: SizableBaseRoomCell
let reuseIdentifier: String = self.defaultReuseIdentifier()
if let cachedSizingView = self.sizingViews[reuseIdentifier] {
sizingView = cachedSizingView
} else {
sizingView = self.createSizingView()
self.sizingViews[reuseIdentifier] = sizingView
}
return sizingView
}
// MARK: - Overrides
override class func height(for cellData: MXKCellData!, withMaximumWidth maxWidth: CGFloat) -> CGFloat {
guard let cellData = cellData else {
return 0
}
guard let roomBubbleCellData = cellData as? MXKRoomBubbleCellData else {
return 0
}
return self.height(for: roomBubbleCellData, fitting: maxWidth)
}
// MARK - SizableBaseRoomCellType
// Each sublcass should override this method, to indicate a unique identifier for a view height.
// This means that the value should change if there is some data that modify the cell height.
class func sizingViewHeightHashValue(from bubbleCellData: MXKRoomBubbleCellData) -> Int {
// TODO: Improve default hash value computation:
// - Implement RoomBubbleCellData hash
// - Handle reactions
return bubbleCellData.hashValue
}
// MARK: - Private
class func createSizingView() -> SizableBaseRoomCell {
return self.init(style: .default, reuseIdentifier: self.defaultReuseIdentifier())
}
private class func height(for roomBubbleCellData: MXKRoomBubbleCellData, fitting width: CGFloat) -> CGFloat {
// FIXME: Size cache is disabled for the moment waiting for a better default `sizingViewHeightHashValue` implementation.
// let height: CGFloat
//
// let sizingViewHeight = self.findOrCreateSizingViewHeight(from: roomBubbleCellData)
//
// if let cachedHeight = sizingViewHeight.heights[width] {
// height = cachedHeight
// } else {
// height = self.contentViewHeight(for: roomBubbleCellData, fitting: width)
// sizingViewHeight.heights[width] = height
// }
//
// return height
return self.contentViewHeight(for: roomBubbleCellData, fitting: width)
}
private static func findOrCreateSizingViewHeight(from bubbleData: MXKRoomBubbleCellData) -> SizingViewHeight {
let bubbleDataHashValue = self.sizingViewHeightHashValue(from: bubbleData)
return self.sizingViewHeightStore.findOrCreateSizingViewHeight(from: bubbleDataHashValue)
}
private static func contentViewHeight(for cellData: MXKCellData, fitting width: CGFloat) -> CGFloat {
let sizingView = self.sizingView
sizingView.didEndDisplay()
sizingView.render(cellData)
sizingView.setNeedsLayout()
sizingView.layoutIfNeeded()
let fittingSize = CGSize(width: width, height: UIView.layoutFittingCompressedSize.height)
var height = sizingView.systemLayoutSizeFitting(fittingSize).height
// Add read receipt height if needed
if let roomBubbleCellData = cellData as? RoomBubbleCellData, let readReceipts = roomBubbleCellData.readReceipts, readReceipts.count > 0, sizingView is RoomCellReadReceiptsDisplayable {
height+=PlainRoomCellLayoutConstants.readReceiptsViewHeight
}
// Add reactions view height if needed
if sizingView is RoomCellReactionsDisplayable,
let roomBubbleCellData = cellData as? RoomBubbleCellData,
let reactionsViewModel = self.reactionsViewModelBuilder.buildForFirstVisibleComponent(of: roomBubbleCellData) {
let reactionWidth = sizingView.roomCellContentView?.reactionsContentView.frame.width ?? roomBubbleCellData.maxTextViewWidth
let reactionsHeight = self.reactionsViewSizer.height(for: reactionsViewModel, fittingWidth: reactionWidth)
height+=reactionsHeight
}
// Add thread summary view height if needed
if sizingView is RoomCellThreadSummaryDisplayable,
let roomBubbleCellData = cellData as? RoomBubbleCellData,
roomBubbleCellData.hasThreadRoot {
let bottomMargin = sizingView.roomCellContentView?.threadSummaryContentViewBottomConstraint.constant ?? 0
height += PlainRoomCellLayoutConstants.threadSummaryViewHeight
height += bottomMargin
}
// Add URL preview view height if needed
if sizingView is RoomCellURLPreviewDisplayable,
let roomBubbleCellData = cellData as? RoomBubbleCellData, let firstBubbleComponent =
roomBubbleCellData.getFirstBubbleComponentWithDisplay(), firstBubbleComponent.showURLPreview, let urlPreviewData = firstBubbleComponent.urlPreviewData as? URLPreviewData {
let urlPreviewMaxWidth = sizingView.roomCellContentView?.urlPreviewContentView.frame.width ?? roomBubbleCellData.maxTextViewWidth
let urlPreviewHeight = self.urlPreviewViewSizer.height(for: urlPreviewData, fittingWidth: urlPreviewMaxWidth)
height+=urlPreviewHeight
}
// Add read marker view height if needed
// Note: We cannot check if readMarkerView property is set here. Extra non needed height can be added
if sizingView is RoomCellReadMarkerDisplayable,
let roomBubbleCellData = cellData as? RoomBubbleCellData, let firstBubbleComponent =
roomBubbleCellData.getFirstBubbleComponentWithDisplay(),
let eventId = firstBubbleComponent.event.eventId, let room = roomBubbleCellData.mxSession.room(withRoomId: roomBubbleCellData.roomId), let readMarkerEventId = room.accountData.readMarkerEventId, eventId == readMarkerEventId {
height+=PlainRoomCellLayoutConstants.readMarkerViewHeight
}
return height
}
}
| 49a10e1315685c83754b966d2f164dad | 43.573099 | 236 | 0.701916 | false | false | false | false |
xiaoxionglaoshi/DNSwiftProject | refs/heads/master | DNSwiftProject/DNSwiftProject/Classes/Vendor/DNLaunchImage/DNLaunchImageView.swift | apache-2.0 | 1 | //
// DNLaunchImageView.swift
// DNSwiftProject
//
// Created by mainone on 16/12/16.
// Copyright © 2016年 wjn. All rights reserved.
//
import UIKit
import Kingfisher
let LaunchImagePath: String = "launchImagePath"
class DNLaunchImageView: UIView {
fileprivate var imageViewDefault: UIImageView!
fileprivate var bgImageView: DNLaunchImageAction!
fileprivate var timeButton: UIButton!
fileprivate var isImageDownLoad: Bool?
fileprivate var timer: Timer?
fileprivate var timeNum: Int!
var imageClickAction: () -> () = {
Void in
}
var adsViewCompletion: (DNLaunchImageView) -> Void = {
(launchImageView: DNLaunchImageView) in
}
init(imageUrl: String, clickImageAction: @escaping () -> ()) {
super.init(frame: UIScreen.main.bounds)
isImageDownLoad = false
imageClickAction = clickImageAction
imageViewDefault = UIImageView(frame: UIScreen.main.bounds)
imageViewDefault.contentMode = UIViewContentMode.scaleToFill
imageViewDefault.image = DNLaunchImage.getSystemLaunchImage()
addSubview(imageViewDefault)
bgImageView = DNLaunchImageAction.init(frame: UIScreen.main.bounds)
bgImageView.alpha = 0.0
bgImageView.contentMode = UIViewContentMode.scaleToFill
bgImageView.addTarget(target: self, action: #selector(imageClick(sender:)))
addSubview(bgImageView)
timeButton = UIButton.init(frame: CGRect.init(x: UIScreen.main.bounds.size.width - 13 - 52, y: 20, width: 52, height: 25))
timeButton.layer.cornerRadius = 25 / 2.0
timeButton.clipsToBounds = true
timeButton.titleLabel?.font = UIFont.systemFont(ofSize: 12)
timeButton.backgroundColor = UIColor.init(red: 0, green: 0, blue: 0, alpha: 0.3)
timeButton.setTitleColor(UIColor.white, for: UIControlState.normal)
timeButton.addTarget(self, action: #selector(loadAds(sender:)), for: UIControlEvents.touchUpInside)
bgImageView.addSubview(timeButton)
// 缓存图片
let imageCacheMgr = ImageCache.init(name: LaunchImagePath, path: nil)
let cacheResult = imageCacheMgr.isImageCached(forKey: imageUrl)
if cacheResult.cached {
timeButton.isHidden = false
bgImageView.kf.setImage(with: ImageResource(downloadURL: URL(string: imageUrl)!), placeholder: DNLaunchImage.getSystemLaunchImage(), options: [.transition(ImageTransition.fade(1))], progressBlock: nil, completionHandler: nil)
isImageDownLoad = true
}else{
timeButton.isHidden = true
bgImageView.image = DNLaunchImage.getSystemLaunchImage()
KingfisherManager.shared.retrieveImage(with: ImageResource.init(downloadURL: URL.init(string: imageUrl)!, cacheKey: LaunchImagePath), options: [.targetCache(ImageCache.init(name: LaunchImagePath))], progressBlock: nil, completionHandler: nil)
isImageDownLoad = false
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func removeAdsView() {
if (timer?.isValid)! {
timer?.invalidate()
}
timer = nil
UIView.animate(withDuration: 0.5, delay: 0.0, options: .curveEaseOut, animations: { [weak self] in
self?.bgImageView.alpha = 0.0
self?.bgImageView.frame = CGRect.init(x: UIScreen.main.bounds.size.width / 20, y: -(UIScreen.main.bounds.size.height / 20), width: 1.1 * (UIScreen.main.bounds.size.width), height: 1.1 * (UIScreen.main.bounds.size.height))
self?.alpha = 0.0
}) { (finish : Bool) in
self.removeFromSuperview()
self.adsViewCompletion(self)
}
}
// MARK: public method
public class func startAdsWith(imageUrl: String, clickImageAction: @escaping () -> ()) -> Any {
return DNLaunchImageView.init(imageUrl: imageUrl, clickImageAction: clickImageAction)
}
func startAnimationTime(time: Int, completionBlock: @escaping (DNLaunchImageView) -> Void) {
timeNum = time
adsViewCompletion = completionBlock
UIApplication.shared.keyWindow?.addSubview(self)
UIApplication.shared.keyWindow?.bringSubview(toFront: self)
UIView.animate(withDuration: 0.5) { [weak self] in
self?.bgImageView.alpha = 1
}
timeButton.setTitle("跳过\(timeNum!)", for: UIControlState.normal)
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction(timer:)), userInfo: nil, repeats: true)
}
public class func downLoadAdsImage(imageUrl: String) {
let imageCacheMgr = ImageCache.init(name: LaunchImagePath, path: nil)
let cacheResult = imageCacheMgr.isImageCached(forKey: imageUrl)
if cacheResult.cached {
} else {
KingfisherManager.shared.retrieveImage(with: ImageResource.init(downloadURL: URL.init(string: imageUrl)!, cacheKey: imageUrl), options: [.targetCache(ImageCache.init(name: LaunchImagePath))], progressBlock: nil, completionHandler: nil)
}
}
// MARK: -- action
func imageClick(sender: UIView) {
if isImageDownLoad! {
self.imageClickAction()
self.removeFromSuperview()
}
}
func loadAds(sender: Any) {
removeAdsView()
}
func timerAction(timer: Timer) {
if timeNum == 0 {
removeAdsView()
return
}
timeNum = timeNum - 1
if isImageDownLoad! {
timeButton.setTitle("跳过\(timeNum!)", for: UIControlState.normal)
}
}
}
| 502a467cb82cc02c00e4189cb39496c5 | 39.744681 | 254 | 0.651175 | false | false | false | false |
KoCMoHaBTa/MHAppKit | refs/heads/master | MHAppKit/ViewControllers/NavigationController.swift | mit | 1 | //
// NavigationController.swift
// MHAppKit
//
// Created by Milen Halachev on 2/13/15.
// Copyright (c) 2015 Milen Halachev. All rights reserved.
//
#if canImport(UIKit) && !os(watchOS)
import UIKit
open class NavigationController: UINavigationController {
open var popAnimator: UIViewControllerAnimatedTransitioning? {
didSet {
self.popInteractiveGestureRecognizer?.isEnabled = self.popAnimator != nil
}
}
open var pushAnimator: UIViewControllerAnimatedTransitioning?
open private(set) var popInteractionController: UIPercentDrivenInteractiveTransition?
open private(set) lazy var popInteractiveGestureRecognizer: UIGestureRecognizer? = { [unowned self] in
#if os(tvOS)
return nil
#else
let popInteractiveGestureRecognizer = UIScreenEdgePanGestureRecognizer()
popInteractiveGestureRecognizer.edges = .left
popInteractiveGestureRecognizer.addTarget(self, action: #selector(NavigationController.handleInteractivePopGestureRecognizer(_:)))
popInteractiveGestureRecognizer.delegate = self
self.view.addGestureRecognizer(popInteractiveGestureRecognizer)
return popInteractiveGestureRecognizer
#endif
}()
/*
http://stackoverflow.com/questions/32707698/custom-unwind-segue-for-ios-8-and-ios-9
override func segueForUnwindingToViewController(toViewController: UIViewController, fromViewController: UIViewController, identifier: String?) -> UIStoryboardSegue? {
if toViewController.providesCustomUnwindSegueToViewController(toViewController, fromViewController: fromViewController, identifier: identifier) {
return toViewController.segueForUnwindingToViewController(toViewController, fromViewController: fromViewController, identifier: identifier)
}
return super.segueForUnwindingToViewController(toViewController, fromViewController: fromViewController, identifier: identifier)
}
*/
public override init(navigationBarClass: AnyClass?, toolbarClass: AnyClass?) {
super.init(navigationBarClass: navigationBarClass, toolbarClass: toolbarClass)
self.setup()
}
public override init(rootViewController: UIViewController) {
super.init(rootViewController: rootViewController)
self.setup()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.setup()
}
open func setup() {
self.delegate = self
}
@objc open func handleInteractivePopGestureRecognizer(_ recongnizer: UIGestureRecognizer) {
if self.popAnimator == nil {
return
}
var progress = recongnizer.location(in: recongnizer.view).x / recongnizer.view!.bounds.size.width * 1
progress = min(1, max(0, progress))
switch recongnizer.state {
case .began:
self.popInteractionController = UIPercentDrivenInteractiveTransition()
self.popViewController(animated: true)
case .changed:
self.popInteractionController?.update(progress)
case .ended, .cancelled, .failed:
if progress > 0.5 {
self.popInteractionController?.finish()
}
else {
self.popInteractionController?.cancel()
}
self.popInteractionController = nil
default:
print("")
}
}
}
//MARK: - BaseNavigationController: UINavigationControllerDelegate
extension NavigationController: UINavigationControllerDelegate {
open func navigationController(_ navigationController: UINavigationController, willShow viewController: UIViewController, animated: Bool) {
if let viewController = viewController as? UINavigationControllerPreferencesProvider {
if viewController.providesNavigationControllerPreferences() {
let prefersNavigationBarHidden = viewController.prefersNavigationBarHidden()
navigationController.setNavigationBarHidden(prefersNavigationBarHidden, animated: animated)
}
}
#if !os(tvOS)
let toolbarItemsCount = viewController.toolbarItems?.count ?? 0
navigationController.setToolbarHidden(toolbarItemsCount < 1, animated: true)
#endif
}
open func navigationController(_ navigationController: UINavigationController, animationControllerFor operation: UINavigationController.Operation, from fromVC: UIViewController, to toVC: UIViewController) -> UIViewControllerAnimatedTransitioning? {
let animator = { [unowned self] (operation: UINavigationController.Operation) -> UIViewControllerAnimatedTransitioning? in
switch operation {
case .pop:
return self.popAnimator
case .push:
return self.pushAnimator
default:
return nil
}
}(operation)
?? fromVC.preferedNavigationAnimator(for: operation, toController: toVC)
?? toVC.preferedNavigationAnimator(for: operation, fromController: fromVC)
return animator
}
open func navigationController(_ navigationController: UINavigationController, interactionControllerFor animationController: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? {
if animationController === self.popAnimator {
return self.popInteractionController
}
return nil
}
open override func responds(to aSelector: Selector) -> Bool {
let respond = super.responds(to: aSelector)
if aSelector == #selector(UINavigationControllerDelegate.navigationController(_:animationControllerFor:from:to:)) && respond && self.popAnimator == nil {
return false
}
return respond
}
}
//MARK: - BaseNavigationController: UIGestureRecognizerDelegate
extension NavigationController: UIGestureRecognizerDelegate {
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return false
}
open func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldBeRequiredToFailBy otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
extension UIViewController {
//used when presentor defines the transition to the presented controller
public func preferedNavigationAnimator(for operation: UINavigationController.Operation, toController controller: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return nil
}
//used when presented controller defines its own transition
public func preferedNavigationAnimator(for operation: UINavigationController.Operation, fromController controller: UIViewController) -> UIViewControllerAnimatedTransitioning? {
return nil
}
/*
http://stackoverflow.com/questions/32707698/custom-unwind-segue-for-ios-8-and-ios-9
func providesCustomUnwindSegueToViewController(toViewController: UIViewController, fromViewController: UIViewController, identifier: String?) -> Bool {
return false
}
*/
}
public protocol UINavigationControllerPreferencesProvider {
func providesNavigationControllerPreferences() -> Bool
func prefersNavigationBarHidden() -> Bool
// func prefersToolBarHidden() -> Bool
}
#endif
| ed644f08a48e8530dd9aa3a16180e686 | 33.577869 | 252 | 0.647268 | false | false | false | false |
Allow2CEO/browser-ios | refs/heads/development | Storage/CompletionOps.swift | mpl-2.0 | 8 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import Shared
import XCGLogger
private let log = Logger.syncLogger
public protocol PerhapsNoOp {
var isNoOp: Bool { get }
}
open class LocalOverrideCompletionOp: PerhapsNoOp {
open var processedLocalChanges: Set<GUID> = Set() // These can be deleted when we're run. Mark mirror as non-overridden, too.
open var mirrorItemsToDelete: Set<GUID> = Set() // These were locally or remotely deleted.
open var mirrorItemsToInsert: [GUID: BookmarkMirrorItem] = [:] // These were locally or remotely added.
open var mirrorItemsToUpdate: [GUID: BookmarkMirrorItem] = [:] // These were already in the mirror, but changed.
open var mirrorStructures: [GUID: [GUID]] = [:] // New or changed structure.
open var mirrorValuesToCopyFromBuffer: Set<GUID> = Set() // No need to synthesize BookmarkMirrorItem instances in memory.
open var mirrorValuesToCopyFromLocal: Set<GUID> = Set()
open var modifiedTimes: [Timestamp: [GUID]] = [:] // Only for copy.
open var isNoOp: Bool {
return processedLocalChanges.isEmpty &&
mirrorValuesToCopyFromBuffer.isEmpty &&
mirrorValuesToCopyFromLocal.isEmpty &&
mirrorItemsToDelete.isEmpty &&
mirrorItemsToInsert.isEmpty &&
mirrorItemsToUpdate.isEmpty &&
mirrorStructures.isEmpty
}
open func setModifiedTime(_ time: Timestamp, guids: [GUID]) {
var forCopy: [GUID] = self.modifiedTimes[time] ?? []
for guid in guids {
// This saves us doing an UPDATE on these items.
if var item = self.mirrorItemsToInsert[guid] {
item.serverModified = time
} else if var item = self.mirrorItemsToUpdate[guid] {
item.serverModified = time
} else {
forCopy.append(guid)
}
}
if !forCopy.isEmpty {
modifiedTimes[time] = forCopy
}
}
public init() {
}
}
open class BufferCompletionOp: PerhapsNoOp {
open var processedBufferChanges: Set<GUID> = Set() // These can be deleted when we're run.
open var isNoOp: Bool {
return self.processedBufferChanges.isEmpty
}
public init() {
}
}
| 738fad5cb8b083cffaf38a23c7663805 | 36.220588 | 144 | 0.624654 | false | false | false | false |
kylehickinson/FastImage | refs/heads/master | FastImage/Size Decoders/Exif.swift | mit | 1 | //
// Exif.swift
// FastImage
//
// Created by Kyle Hickinson on 2019-03-23.
// Copyright © 2019 Kyle Hickinson. All rights reserved.
//
import Foundation
/// Obtains the image width, height and orientation from an EXIF data structure
///
/// Can also be used for EXIF JPEG's, but will only find orientation data (among other Exif tags we dont care about)
///
/// http://www.fileformat.info/format/tiff/egff.htm
final class Exif {
private(set) var orientation: UIImage.Orientation?
private(set) var width: UInt16?
private(set) var height: UInt16?
init?(data: Data) throws {
// Little endian defined as "II", big endian defined as "MM"
let isLittleEndian = try String(bytes: data.readBytes(0..<2), encoding: .ascii) == "II"
let swap32 = isLittleEndian ? CFSwapInt32LittleToHost : CFSwapInt32BigToHost
let swap16 = isLittleEndian ? CFSwapInt16LittleToHost : CFSwapInt16BigToHost
var offset = Int(swap32(try data.read(4..<8)))
let numberOfTags = swap16(try data.read(from: offset, length: 2))
offset += 2
for _ in 0..<numberOfTags {
let tagIdentifier = swap16(try data.read(from: offset, length: 2))
let value = swap16(try data.read(from: offset + 8, length: 2))
switch tagIdentifier {
case 0x0100: // ImageWidth
width = value
case 0x0101:
height = value
case 0x0112:
orientation = UIImage.Orientation(rawValue: Int(value))
default:
break
}
if let _ = width, let _ = height, let _ = orientation {
return
}
// Each tag is 12 bytes long
offset += 12
}
if width == nil, height == nil, orientation == nil {
// Found nothing
return nil
}
}
}
| d049ce3e82ef4d5532e068b059777143 | 30.472727 | 116 | 0.642981 | false | false | false | false |
julienbodet/wikipedia-ios | refs/heads/develop | Wikipedia/Code/NewsViewController.swift | mit | 1 | import WMF
@objc(WMFNewsViewController)
class NewsViewController: ColumnarCollectionViewController {
fileprivate static let cellReuseIdentifier = "NewsCollectionViewCell"
fileprivate static let headerReuseIdentifier = "NewsCollectionViewHeader"
let stories: [WMFFeedNewsStory]
let dataStore: MWKDataStore
@objc required init(stories: [WMFFeedNewsStory], dataStore: MWKDataStore, theme: Theme) {
self.stories = stories
self.dataStore = dataStore
super.init()
self.theme = theme
title = CommonStrings.inTheNewsTitle
navigationItem.backBarButtonItem = UIBarButtonItem(title: CommonStrings.backTitle, style: .plain, target:nil, action:nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) not supported")
}
override func viewDidLoad() {
super.viewDidLoad()
layoutManager.register(NewsCollectionViewCell.self, forCellWithReuseIdentifier: NewsViewController.cellReuseIdentifier, addPlaceholder: true)
layoutManager.register(UINib(nibName: NewsViewController.headerReuseIdentifier, bundle: nil), forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: NewsViewController.headerReuseIdentifier, addPlaceholder: false)
collectionView.allowsSelection = false
}
override func metrics(with size: CGSize, readableWidth: CGFloat, layoutMargins: UIEdgeInsets) -> ColumnarCollectionViewLayoutMetrics {
return ColumnarCollectionViewLayoutMetrics.tableViewMetrics(with: size, readableWidth: readableWidth, layoutMargins: layoutMargins, interSectionSpacing: 22, interItemSpacing: 0)
}
// MARK: - ColumnarCollectionViewLayoutDelegate
override func collectionView(_ collectionView: UICollectionView, estimatedHeightForHeaderInSection section: Int, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate {
return ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: headerTitle(for: section) == nil ? 0 : 57)
}
override func collectionView(_ collectionView: UICollectionView, estimatedHeightForItemAt indexPath: IndexPath, forColumnWidth columnWidth: CGFloat) -> ColumnarCollectionViewLayoutHeightEstimate {
var estimate = ColumnarCollectionViewLayoutHeightEstimate(precalculated: false, height: 350)
guard let placeholderCell = layoutManager.placeholder(forCellWithReuseIdentifier: NewsViewController.cellReuseIdentifier) as? NewsCollectionViewCell else {
return estimate
}
let story = stories[indexPath.section]
placeholderCell.layoutMargins = layout.itemLayoutMargins
placeholderCell.configure(with: story, dataStore: dataStore, theme: theme, layoutOnly: true)
estimate.height = placeholderCell.sizeThatFits(CGSize(width: columnWidth, height: UIViewNoIntrinsicMetric), apply: false).height
estimate.precalculated = true
return estimate
}
override func apply(theme: Theme) {
super.apply(theme: theme)
guard viewIfLoaded != nil else {
return
}
view.backgroundColor = theme.colors.paperBackground
collectionView.backgroundColor = theme.colors.paperBackground
}
}
// MARK: - UICollectionViewDataSource
extension NewsViewController {
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return stories.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: NewsViewController.cellReuseIdentifier, for: indexPath)
guard let newsCell = cell as? NewsCollectionViewCell else {
return cell
}
cell.layoutMargins = layout.itemLayoutMargins
let story = stories[indexPath.section]
newsCell.configure(with: story, dataStore: dataStore, theme: theme, layoutOnly: false)
return newsCell
}
func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
switch kind {
case UICollectionElementKindSectionHeader:
let view = collectionView.dequeueReusableSupplementaryView(ofKind: kind, withReuseIdentifier: NewsViewController.headerReuseIdentifier, for: indexPath)
guard let header = view as? NewsCollectionViewHeader else {
return view
}
header.label.text = headerTitle(for: indexPath.section)
header.apply(theme: theme)
return header
default:
assert(false, "ensure you've registered cells and added cases to this switch statement to handle all header/footer types")
return UICollectionReusableView()
}
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let cell = cell as? NewsCollectionViewCell else {
return
}
cell.selectionDelegate = self
}
func collectionView(_ collectionView: UICollectionView, didEndDisplaying cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
guard let cell = cell as? NewsCollectionViewCell else {
return
}
cell.selectionDelegate = nil
}
static let headerDateFormatter: DateFormatter = {
let headerDateFormatter = DateFormatter()
headerDateFormatter.locale = Locale.autoupdatingCurrent
headerDateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
headerDateFormatter.setLocalizedDateFormatFromTemplate("EEEEMMMMd") // Year is invalid on news content dates, we can only show month and day
return headerDateFormatter
}()
func headerTitle(for section: Int) -> String? {
let story = stories[section]
guard let date = story.midnightUTCMonthAndDay else {
return nil
}
return NewsViewController.headerDateFormatter.string(from: date)
}
}
// MARK: - SideScrollingCollectionViewCellDelegate
extension NewsViewController: SideScrollingCollectionViewCellDelegate {
func sideScrollingCollectionViewCell(_ sideScrollingCollectionViewCell: SideScrollingCollectionViewCell, didSelectArticleWithURL articleURL: URL) {
wmf_pushArticle(with: articleURL, dataStore: dataStore, theme: self.theme, animated: true)
}
}
// MARK: - UIViewControllerPreviewingDelegate
extension NewsViewController {
override func previewingContext(_ previewingContext: UIViewControllerPreviewing, viewControllerForLocation location: CGPoint) -> UIViewController? {
guard let indexPath = collectionView.indexPathForItem(at: location),
let cell = collectionView.cellForItem(at: indexPath) as? NewsCollectionViewCell else {
return nil
}
let pointInCellCoordinates = collectionView.convert(location, to: cell)
let index = cell.subItemIndex(at: pointInCellCoordinates)
guard index != NSNotFound, let view = cell.viewForSubItem(at: index) else {
return nil
}
let story = stories[indexPath.section]
guard let previews = story.articlePreviews, index < previews.count else {
return nil
}
previewingContext.sourceRect = view.convert(view.bounds, to: collectionView)
let article = previews[index]
let articleVC = WMFArticleViewController(articleURL: article.articleURL, dataStore: dataStore, theme: theme)
articleVC.wmf_addPeekableChildViewController(for: article.articleURL, dataStore: dataStore, theme: theme)
articleVC.articlePreviewingActionsDelegate = self
return articleVC
}
override func previewingContext(_ previewingContext: UIViewControllerPreviewing, commit viewControllerToCommit: UIViewController) {
viewControllerToCommit.wmf_removePeekableChildViewControllers()
wmf_push(viewControllerToCommit, animated: true)
}
}
// MARK: - EventLoggingEventValuesProviding
extension NewsViewController: EventLoggingEventValuesProviding {
var eventLoggingCategory: EventLoggingCategory {
return .feed
}
var eventLoggingLabel: EventLoggingLabel? {
return .news
}
}
| 026c2c1edbf02c6d5b5ab4b115873029 | 46.61326 | 253 | 0.72453 | false | false | false | false |
a178960320/MyDouyu | refs/heads/master | Douyu/Douyu/Classes/Home/Controller/HomeViewController.swift | mit | 1 | //
// HomeViewController.swift
// Douyu
//
// Created by 住梦iOS on 2017/2/24.
// Copyright © 2017年 qiongjiwuxian. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController,PageTitleViewDelegate,PageContentViewDelegate{
lazy var pageTitleView:PageTitleView = {
let titleView = PageTitleView(frame: CGRect.init(x: 0, y: 64, width: SCREEN_WIDTH, height: 40), titles: ["推荐","娱乐","游戏","趣玩"])
titleView.delegate = self
return titleView
}()
lazy var pageContentView:PageContentView = {
var childVC = [UIViewController]()
childVC.append(RecommendViewController())
//循环添加子视图控制器
for i in 0..<3{
let vc = UIViewController()
vc.view.backgroundColor = UIColor.init(r: 50*CGFloat(i), g: 100, b: 150)
childVC.append(vc)
}
let pageCV = PageContentView(frame: CGRect.init(x: 0, y: 64+40, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - 64 - 40 - 49), childVC: childVC, parentViewController: self)
pageCV.delegate = self
return pageCV
}()
override func viewDidLoad() {
super.viewDidLoad()
//设置UI界面
setupUI()
}
}
//MARK: - 设置ui界面
extension HomeViewController{
func setupUI(){
automaticallyAdjustsScrollViewInsets = false
setNavigationUI()
self.view.addSubview(pageTitleView)
self.view.addSubview(pageContentView)
}
func setNavigationUI(){
//设置导航条背景颜色
self.navigationController?.navigationBar.barTintColor = UIColor.orange
//设置左侧的item
let size = CGSize(width: 40, height: 40)
self.navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "homeLogoIcon")
//设置右侧items
let hisstoryItem = UIBarButtonItem(imageName: "viewHistoryIcon", highImageName: "viewHistoryIconHL", size: size)
let searchItem = UIBarButtonItem(imageName: "searchBtnIcon", highImageName: "searchBtnIconHL", size: size)
let qrcodeItem = UIBarButtonItem(imageName: "scanIcon", highImageName: "scanIconHL", size: size)
self.navigationItem.rightBarButtonItems = [hisstoryItem,searchItem,qrcodeItem]
}
}
// MARK: - 实现pagetitleview的代理
extension HomeViewController{
func pageTitleView(titleView: PageTitleView, selectIndex index: Int) {
pageContentView.setCurrentInde(index: index)
}
func pageContentView(pageContentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) {
print(progress,sourceIndex,targetIndex)
pageTitleView.setIndexWithProgress(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
| 6e68f99dd678b4fa49da7621dbbc11f7 | 30.076923 | 177 | 0.641796 | false | false | false | false |
elslooo/hoverboard | refs/heads/master | HoverboardKit/HoverboardKit/Grid.swift | mit | 1 | /*
* Copyright (c) 2017 Tim van Elsloo
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
import Foundation
public struct Grid {
// swiftlint:disable identifier_name
public var x: CGFloat = 0.0
public var y: CGFloat = 0.0
// swiftlint:enable identifier_name
public var xnum: CGFloat = 1.0
public var ynum: CGFloat = 1.0
public var width: CGFloat = 1.0
public var height: CGFloat = 1.0
public mutating func normalize() {
self.width = min(3.0, self.width)
self.height = min(3.0, self.height)
self.x = min(self.width - 1.0, self.x)
self.y = min(self.height - 1.0, self.y)
self.x = max(0, self.x)
self.y = max(0, self.y)
self.xnum = min(self.xnum, self.width)
self.ynum = min(self.ynum, self.height)
self.x = min(self.x, self.width - self.xnum)
self.y = min(self.y, self.height - self.ynum)
}
}
| 2fb3edc1cae7448ac8d372d38a6d86bf | 40.583333 | 80 | 0.672345 | false | false | false | false |
noehou/TWB | refs/heads/master | TWB/TWB/Classes/Compose/ComposeTextView.swift | mit | 1 | //
// ComposeTextView.swift
// TWB
//
// Created by Tommaso on 2017/5/23.
// Copyright © 2017年 Tommaso. All rights reserved.
//
import UIKit
import SnapKit
class ComposeTextView: UITextView {
//MARK:- 懒加载属性
lazy var placeHolderLabel :UILabel = UILabel()
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupUI()
}
}
// //MARK:- 设置UI界面
extension ComposeTextView {
func setupUI(){
//1、添加子控件
addSubview(placeHolderLabel)
//2、设置frame
placeHolderLabel.snp_makeConstraints { (make) in
make.top.equalTo(8)
make.left.equalTo(10)
}
//3、设置placeholderlabel属性
placeHolderLabel.textColor = UIColor.lightGray
placeHolderLabel.font = font
//4、设置placeholderlabel的文字
placeHolderLabel.text = "分享新鲜事..."
//5、设置内容的内边距
textContainerInset = UIEdgeInsets(top: 0, left: 10, bottom: 0, right: 10)
}
}
| 3ac7becde92bc1d72231ab38923ba97d | 21.795455 | 81 | 0.598205 | false | false | false | false |
Marquis103/instagram-clone | refs/heads/master | ParseStarterProject/ViewController.swift | mit | 1 | /**
* Copyright (c) 2015-present, Parse, LLC.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import UIKit
import Parse
class ViewController: UIViewController {
var signUpActive = true
@IBOutlet var password: UITextField!
@IBOutlet var username: UITextField!
@IBOutlet var btnSignUp: UIButton!
@IBOutlet var btnLogin: UIButton!
@IBOutlet var lblRegistered: UILabel!
var activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView()
@available(iOS 8.0, *)
@IBAction func btnSignUp(sender: AnyObject) {
if username.text == "" || password.text == "" {
displayAlert("SignUp Error", message: "Username or password missing")
} else {
showActivitySpinner()
var errorMessage = "Please try again"
if signUpActive == true {
let user = PFUser()
user.username = username.text
user.password = password.text
user.signUpInBackgroundWithBlock({ (success, error) -> Void in
self.hideActivitySpinner()
if error == nil {
//signup successful
} else {
if let errorString = error!.userInfo["error"] as? String {
errorMessage = errorString
self.displayAlert("Registration Error", message: errorMessage)
}
}
})
} else {
PFUser.logInWithUsernameInBackground(username.text!, password: password.text!, block: { (user, error) -> Void in
self.hideActivitySpinner()
if user != nil {
} else {
if let errorString = error!.userInfo["error"] as? String {
errorMessage = errorString
}
self.displayAlert("Login Failed", message: errorMessage)
}
})
}
}
}
@IBAction func btnLogin(sender: AnyObject) {
if signUpActive == true {
btnSignUp.setTitle("Log In", forState: UIControlState.Normal)
lblRegistered.text = "Not Registered"
btnLogin.setTitle("Sign Up", forState: UIControlState.Normal)
signUpActive = false
} else {
btnSignUp.setTitle("Sign Up", forState: UIControlState.Normal)
lblRegistered.text = "Already Registered?"
btnLogin.setTitle("Log In", forState: UIControlState.Normal)
signUpActive = true
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
//MARK: Activity Spinner Code
//show activity spinner
func showActivitySpinner() {
//add a spiny
activityIndicator = UIActivityIndicatorView(frame: CGRectMake(0,0,50,50))
activityIndicator.center = self.view.center
activityIndicator.hidesWhenStopped = true
activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray
self.view.addSubview(activityIndicator)
activityIndicator.startAnimating()
UIApplication.sharedApplication().beginIgnoringInteractionEvents()
}
func hideActivitySpinner() {
activityIndicator.stopAnimating()
UIApplication.sharedApplication().endIgnoringInteractionEvents()
}
@available(iOS 8.0, *)
func displayAlert(title: String, message: String) {
let alert = UIAlertController(title: title, message: message, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: { (action) -> Void in
self.dismissViewControllerAnimated(true, completion: nil)
}))
self.presentViewController(alert, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 7806f3bbf50e2bd0539fdceeddec1b9d | 37.440678 | 128 | 0.580688 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS | refs/heads/master | SmartReceipts/Modules/Graphs/GraphsViewController.swift | agpl-3.0 | 2 | //
// GraphsViewController.swift
// SmartReceipts
//
// Created Bogdan Evsenev on 04.04.2020.
// Copyright © 2020 Will Baumann. All rights reserved.
//
import UIKit
import RxSwift
import Charts
class GraphsViewController: UIViewController, Storyboardable {
var viewModel: GraphsViewModelProtocol!
private let bag = DisposeBag()
@IBOutlet private var barChartView: BarChart!
@IBOutlet private var lineChartView: LineChart!
@IBOutlet private var pieChartView: PieChart!
@IBOutlet private var periodButton: UIButton!
@IBOutlet private var modelButton: UIButton!
@IBOutlet private var closeButton: UIBarButtonItem!
@IBOutlet private var shareButton: UIBarButtonItem!
@IBOutlet private var graphsTitle: UILabel!
var activeChart: ChartProtocol?
private var graphsInfoViewController: GraphsInfoViewController?
private lazy var valueFormatter: IValueFormatter = {
return DefaultValueFormatter(formatter: numberFormatter)
}()
private lazy var numberFormatter: NumberFormatter = {
let locale = Locale.current as NSLocale
let symbol = locale.displayName(forKey: .currencySymbol, value: viewModel.trip.defaultCurrency.code) ?? ""
let numberFormatter = NumberFormatter()
numberFormatter.numberStyle = .decimal
numberFormatter.maximumFractionDigits = 2
numberFormatter.minimumFractionDigits = 2
numberFormatter.negativeSuffix = " \(symbol)"
numberFormatter.positiveSuffix = numberFormatter.negativeSuffix
return numberFormatter
}()
override func viewDidLoad() {
super.viewDidLoad()
pieChartView.valueFormatter = valueFormatter
barChartView.valueFormatter = valueFormatter
lineChartView.valueFormatter = valueFormatter
setupChartData()
viewModel.moduleDidLoad()
title = LocalizedString("report_info_graphs")
periodButton.layer.cornerRadius = periodButton.bounds.height/2
modelButton.layer.cornerRadius = modelButton.bounds.height/2
graphsTitle.text = viewModel.trip.name
bind()
AnalyticsManager.sharedManager.record(event: Event.Graphs.GraphsShown)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
configureInfoViewIfNeeded()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
}
private func bind() {
viewModel.period.map { $0.title }
.bind(to: periodButton.rx.titleBinder())
.disposed(by: bag)
periodButton.rx.tap.map { .period }
.bind(to: viewModel.routeObserver)
.disposed(by: bag)
modelButton.rx.tap.map { .model }
.bind(to: viewModel.routeObserver)
.disposed(by: bag)
closeButton.rx.tap.map { .close }
.bind(to: viewModel.routeObserver)
.disposed(by: bag)
shareButton.rx.tap
.subscribe(onNext: { [weak self] in
self?.shareGraph()
}).disposed(by: bag)
}
private func configureInfoViewIfNeeded() {
guard let activeChart = activeChart, graphsInfoViewController == nil else { return }
let infoHeight = view.bounds.height - (activeChart.bounds.height + activeChart.frame.origin.y)
graphsInfoViewController = GraphsInfoViewController.create(maxHeight: infoHeight)
addPullUpController(graphsInfoViewController!, initialStickyPointOffset: infoHeight, animated: false, completion: nil)
setupChartData()
}
private func shareGraph() {
AnalyticsManager.sharedManager.record(event: Event.Graphs.GraphsShare)
guard let activeChart = activeChart else { return }
let color = activeChart.backgroundColor
activeChart.backgroundColor = .white
let snapshot = activeChart.makeSnapshot()
activeChart.backgroundColor = color
guard let image = snapshot else { return }
let shareVC = UIActivityViewController(activityItems: [image], applicationActivities: nil)
present(shareVC, animated: true, completion: nil)
}
private func setupChartData() {
viewModel.dataSet
.subscribe(onNext: { [weak self] dataSet in
self?.modelButton.set(title: dataSet.title)
self?.activateChart(dataSet: dataSet)
}).disposed(by: bag)
}
private func activateChart(dataSet: ChartDataSetProtocol) {
lineChartView.isHidden = true
barChartView.isHidden = true
pieChartView.isHidden = true
switch dataSet.chartType {
case .barChart:
barChartView.isHidden = false
activeChart = barChartView
case .lineChart:
lineChartView.isHidden = false
activeChart = lineChartView
case .pieChart:
pieChartView.isHidden = false
activeChart = pieChartView
}
guard let activeChart = activeChart else { return }
activeChart.buildChart(dataSet: dataSet)
let items = dataSet.entries.enumerated().map { index, entry -> GraphsInfoDataSource.Item in
let title = dataSet.xLabels[index]
let color = activeChart.color(at: index) ?? .violetMain
let total = numberFormatter.string(from: NSNumber(value: entry.y)) ?? "NaN"
return .init(title: title, total: total, color: color)
}
graphsInfoViewController?.dataSource = GraphsInfoDataSource(items: items)
}
}
extension GraphsAssembly.PeriodSelection {
var title: String {
switch self {
case .daily: return LocalizedString("graphs.period.day")
case .weekly: return LocalizedString("graphs.period.week")
case .monthly: return LocalizedString("graphs.period.month")
case .report: return LocalizedString("report")
}
}
}
| 6ede6b7aeda6e157663d727c3c0a9866 | 35.136905 | 126 | 0.652117 | false | false | false | false |
romansorochak/ParallaxHeader | refs/heads/master | Exmple/ItemDetailedHeaderDataSourse.swift | mit | 1 | //
// ItemDetailedHeaderDataSourse.swift
// ParallaxHeader
//
// Created by Roman Sorochak on 6/27/17.
// Copyright © 2017 MagicLab. All rights reserved.
//
import UIKit
import Reusable
typealias ItemDetailedHeaderClickHandler = (_ item: IndexPath, _ image: UIImage, _ cell: ItemDetailedCell)->Void
class ImageHeaderDataSourse: ImagesDataSourse {
private (set) var selectedImageIndex = 0
private (set) var scrollToItem: IndexPath?
private (set) var clickHandler: ItemDetailedHeaderClickHandler?
var selectedImage: UIImage? {
if let cell = collectionView?.cellForItem(
at: IndexPath(item: selectedImageIndex, section: 0)
) as? ItemDetailedCell {
return cell.image
}
return nil
}
//MARK: setup
func setup(
collectionView: UICollectionView,
images: [UIImage]?,
handler: ((_ item: IndexPath)->Void)? = nil,
clickHandler: ItemDetailedHeaderClickHandler? = nil
) {
self.clickHandler = clickHandler
super.setup(collectionView: collectionView, images: images, handler: handler)
}
override func selectCell(forIndexPath indexPath: IndexPath) {
scrollToItem = indexPath
collectionView?.scrollToItem(
at: indexPath,
at: .right,
animated: true
)
}
override func checkOnRightToLeftMode() {
if UIApplication.isRTL {
let indexPath = IndexPath(row: 0, section: 0)
// collectionView?.scrollToItem(at: indexPath, at: .right, animated: false)
// selectCell(forIndexPath: indexPath)
collectionView?.scrollToItem(
at: indexPath,
at: .right,
animated: false
)
}
}
// MARK: CollectionView protocols
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
let height = collectionView.frame.height
let width = collectionView.frame.width
return CGSize(width: width, height: height)
}
override func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
return 0
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueCell(for: indexPath) as ItemDetailedCell
cell.isSelected = true
cell.image = images?[indexPath.row]
return cell
}
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard let cell = collectionView.cellForItem(at: indexPath) as? ItemDetailedCell else {
return
}
clickHandler?(indexPath, cell.image ?? UIImage(), cell)
}
//MARK: scroll view delegate
func scrollViewDidScroll(_ scrollView: UIScrollView) {
let page: Int = {
let pageLtR = Int(scrollView.contentOffset.x / scrollView.frame.width)
if UIApplication.isRTL,
let photosCount = images?.count {
return photosCount - 1 - pageLtR
}
return pageLtR
}()
guard page != selectedImageIndex else { return }
let indexPath = IndexPath(item: page, section: 0)
//check wether need to call handler
if let toItem = scrollToItem,
indexPath == toItem {
handler?(indexPath)
selectedImageIndex = page
scrollToItem = nil
return
}
if scrollToItem == nil {
handler?(indexPath)
selectedImageIndex = page
}
}
}
| 62025f80e283aad9bacca44d7b67482d | 29.559701 | 179 | 0.596581 | false | false | false | false |
mgadda/zig | refs/heads/master | Sources/MessagePackEncoder/MessagePackKeyedEncodingContainer.swift | mit | 1 | //
// MessagePackKeyedEncodingContainer.swift
// zigPackageDescription
//
// Created by Matt Gadda on 9/27/17.
//
import Foundation
import MessagePack
internal class MessagePackKeyedEncodingContainer<K : CodingKey> : KeyedEncodingContainerProtocol {
typealias Key = K
private let encoder: _MessagePackEncoder
private var container: MutableDictionaryReference<BoxedValue, BoxedValue> = [:]
private(set) public var codingPath: [CodingKey]
internal init(referencing encoder: _MessagePackEncoder, codingPath: [CodingKey], wrapping container: MutableDictionaryReference<BoxedValue, BoxedValue>) {
self.encoder = encoder
self.codingPath = codingPath
self.container = container
}
func encodeNil(forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = BoxedValue.`nil` }
func encode(_ value: Bool, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode(_ value: Int, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode(_ value: Int8, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode(_ value: Int16, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode(_ value: Int32, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode(_ value: Int64, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode(_ value: UInt, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode(_ value: UInt8, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode(_ value: UInt16, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode(_ value: UInt32, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode(_ value: UInt64, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode(_ value: Float, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode(_ value: Double, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode(_ value: String, forKey key: MessagePackKeyedEncodingContainer.Key) throws { container[.string(key.stringValue)] = encoder.box(value) }
func encode<T>(_ value: T, forKey key: MessagePackKeyedEncodingContainer.Key) throws where T : Encodable {
encoder.codingPath.append(key)
defer { encoder.codingPath.removeLast() }
self.container[.string(key.stringValue)] = try encoder.box(value)
}
func nestedContainer<NestedKey>(keyedBy keyType: NestedKey.Type, forKey key: MessagePackKeyedEncodingContainer.Key) -> KeyedEncodingContainer<NestedKey> where NestedKey : CodingKey {
let dictRef = MutableDictionaryReference<BoxedValue, BoxedValue>()
let boxedDict: BoxedValue = .map(dictRef)
self.container[.string(key.stringValue)] = boxedDict
self.codingPath.append(key)
defer { self.codingPath.removeLast() }
let container = MessagePackKeyedEncodingContainer<NestedKey>(referencing: encoder, codingPath: codingPath, wrapping: dictRef)
return KeyedEncodingContainer(container)
}
func nestedUnkeyedContainer(forKey key: MessagePackKeyedEncodingContainer.Key) -> UnkeyedEncodingContainer {
let arrayRef = MutableArrayReference<BoxedValue>()
let boxedArray: BoxedValue = .array(arrayRef)
self.container[.string(key.stringValue)] = boxedArray
self.codingPath.append(key)
defer { self.codingPath.removeLast() }
return MessagePackUnkeyedEncodingContainer(referencing: encoder, codingPath: codingPath, wrapping: arrayRef)
}
func superEncoder() -> Encoder {
return MessagePackReferencingEncoder(referencing: self.encoder, at: MessagePackKey.superKey, wrapping: self.container)
}
func superEncoder(forKey key: MessagePackKeyedEncodingContainer.Key) -> Encoder {
return MessagePackReferencingEncoder(referencing: self.encoder, at: key, wrapping: self.container)
}
}
| dd095458914b3b7e028ec9599905b3ff | 60.746667 | 184 | 0.771971 | false | false | false | false |
PGSSoft/ParallaxView | refs/heads/master | Sources/Views/ParallaxView.swift | mit | 1 | //
// ParallaxCollectionViewCell.swift
//
// Created by Łukasz Śliwiński on 20/04/16.
// Copyright © 2016 Łukasz Śliwiński. All rights reserved.
//
import UIKit
/// An object that provides default implementation of the parallax effect for the `UIView`.
/// If you will override `init` method it is important to provide default setup for the unfocused state of the view
/// e.g. `parallaxViewActions.setupUnfocusedState?(self)`
open class ParallaxView: UIView, ParallaxableView {
// MARK: Properties
open var parallaxEffectOptions = ParallaxEffectOptions()
open var parallaxViewActions = ParallaxViewActions<ParallaxView>()
// MARK: Initialization
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
parallaxViewActions.setupUnfocusedState?(self)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
parallaxViewActions.setupUnfocusedState?(self)
}
/// Override this method in your `ParallaxView` subclass if you would like to provide custom
/// setup for the `parallaxEffectOptions` and/or `parallaxViewActions`
open func setupParallax() {}
internal func commonInit() {
if parallaxEffectOptions.glowContainerView == nil {
let view = UIView(frame: bounds)
addSubview(view)
parallaxEffectOptions.glowContainerView = view
}
setupParallax()
}
// MARK: UIView
open override var canBecomeFocused : Bool {
return true
}
open override func layoutSubviews() {
super.layoutSubviews()
guard let glowEffectContainerView = parallaxEffectOptions.glowContainerView,
let glowImageView = getGlowImageView()
else { return }
parallaxEffectOptions.glowPosition.layout(glowEffectContainerView, glowImageView)
}
// MARK: UIResponder
// Generally, all responders which do custom touch handling should override all four of these methods.
// If you want to customize animations for press events do not forget to call super.
open override func pressesBegan(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
parallaxViewActions.animatePressIn?(self, presses, event)
super.pressesBegan(presses, with: event)
}
open override func pressesCancelled(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
parallaxViewActions.animatePressOut?(self, presses, event)
super.pressesCancelled(presses, with: event)
}
open override func pressesEnded(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
parallaxViewActions.animatePressOut?(self, presses, event)
super.pressesEnded(presses, with: event)
}
open override func pressesChanged(_ presses: Set<UIPress>, with event: UIPressesEvent?) {
super.pressesChanged(presses, with: event)
}
// MARK: UIFocusEnvironment
open override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
super.didUpdateFocus(in: context, with: coordinator)
if self == context.nextFocusedView {
// Add parallax effect to focused cell
parallaxViewActions.becomeFocused?(self, context, coordinator)
} else if self == context.previouslyFocusedView {
// Remove parallax effect
parallaxViewActions.resignFocus?(self, context, coordinator)
}
}
}
| e58423f1d278691f5763aa4261c97f00 | 32.132075 | 120 | 0.692768 | false | false | false | false |
Miridescen/M_365key | refs/heads/master | 365KEY_swift/365KEY_swift/MainController/Class/Produce/controller/productDetailModel/SKProductDetailTeamModel.swift | apache-2.0 | 1 | //
// SKProductDetailTeamModel.swift
// 365KEY_swift
//
// Created by 牟松 on 2016/11/17.
// Copyright © 2016年 DoNews. All rights reserved.
//
import UIKit
class SKProductDetailTeamModel: NSObject {
var id: Int64 = 0
var info: String?
var inputtime: Date?
var job: String?
var name: String?
var pro_id: Int64 = 0
var role_id: Int64 = 0
var thumbnail: String? {
didSet{
guard let thumb = thumbnail else {
return
}
showThumbnail = thumb.hasPrefix("http") ? thumb : "http://www.365key.com" + thumb
}
}
var showThumbnail: String?
var weight: Int64 = 0
override var description: String{
return yy_modelDescription()
}
}
| 0b2962da385a4686c0cf52a606b4ba43 | 18.625 | 93 | 0.563057 | false | false | false | false |
omarojo/MyC4FW | refs/heads/master | Demos/DemoApp/Pods/C4/C4/Core/Rect.swift | mit | 2 | // Copyright © 2014 C4
//
// 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 CoreGraphics
/// A structure that contains the location and dimensions of a rectangle.
public struct Rect: Equatable, CustomStringConvertible {
/// The origin (top-left) of the rect.
public var origin: Point
/// The size (width / height) of the rect.
public var size: Size
/// The width of the rect.
public var width: Double {
get {
return size.width
} set {
size.width = newValue
}
}
/// The height of the rect.
public var height: Double {
get {
return size.height
} set {
size.height = newValue
}
}
/// Initializes a new Rect with the origin {0,0} and the size {0,0}
/// ````
/// let r = Rect()
/// ````
public init() {
self.init(0, 0, 0, 0)
}
/// Initializes a new Rect with the origin {x,y} and the size {w,h}
/// ````
/// let r = Rect(0.0,0.0,10.0,10.0)
/// ````
public init(_ x: Double, _ y: Double, _ w: Double, _ h: Double) {
origin = Point(x, y)
size = Size(w, h)
}
/// Initializes a new Rect with the origin {x,y} and the size {w,h}, converting values from Int to Double
/// ````
/// let r = Rect(0,0,10,10)
/// ````
public init(_ x: Int, _ y: Int, _ w: Int, _ h: Int) {
origin = Point(x, y)
size = Size(w, h)
}
/// Initializes a new Rect with the origin {o.x,o.y} and the size {s.w,s.h}
/// ````
/// let p = Point()
/// let s = Size()
/// let r = Rect(p,s)
/// ````
public init(_ o: Point, _ s: Size) {
origin = o
size = s
}
/// Initializes a Rect from a CGRect
public init(_ rect: CGRect) {
origin = Point(rect.origin)
size = Size(rect.size)
}
/// Initializes a rectangle that contains all of the specified coordinates in an array.
/// ````
/// let pts = [Point(), Point(0,5), Point(10,10), Point(9,8)]
/// let r = Rect(pts) //-> {{0.0, 0.0}, {10.0, 10.0}}
/// ````
/// - parameter points: An array of Point coordinates
public init(_ points: [Point]) {
let count = points.count
assert(count >= 2, "To create a Polygon you need to specify an array of at least 2 points")
var cgPoints = [CGPoint]()
for i in 0..<count {
cgPoints.append(CGPoint(points[i]))
}
let r = CGRectMakeFromPoints(cgPoints)
let f = Rect(r)
self.init(f.origin, f.size)
}
/// Initializes a rectangle that contains the specified coordinates in a tuple.
/// ````
/// let pts = (Point(), Point(0,5))
/// let r = Rect(pts)
/// ````
/// - parameter points: An tuple of Point coordinates
public init(_ points: (Point, Point)) {
let r = CGRectMakeFromPoints([CGPoint(points.0), CGPoint(points.1)])
let f = Rect(r)
self.init(f.origin, f.size)
}
// MARK: - Comparing
/// Returns whether two rectangles intersect.
/// ````
/// let r1 = Rect(0,0,10,10)
/// let r2 = Rect(5,5,10,10)
/// let r3 = Rect(10,10,10,10)
/// r1.intersects(r2) //-> true
/// r1.intersects(r3) //-> false
/// ````
/// - parameter rect: The rectangle to examine.
/// - returns: true if the two specified rectangles intersect; otherwise, false.
public func intersects(_ rect: Rect) -> Bool {
return CGRect(self).intersects(CGRect(rect))
}
// MARK: - Center & Max
/// The center point of the receiver.
/// ````
/// let r = Rect(0,0,10,10)
/// r.center //-> {5,5}
/// ````
public var center: Point {
get {
return Point(origin.x + size.width/2, origin.y + size.height/2)
}
set {
origin.x = newValue.x - size.width/2
origin.y = newValue.y - size.height/2
}
}
/// The bottom-right point of the receiver.
/// ````
/// let r = Rect(5,5,10,10)
/// r.max //-> {15,15}
/// ````
public var max: Point {
return Point(origin.x + size.width, origin.y + size.height)
}
/// Checks to see if the receiver has zero size and position
/// ````
/// let r = Point()
/// r.isZero() //-> true
/// ````
/// - returns: true if origin = {0,0} and size = {0,0}
public func isZero() -> Bool {
return origin.isZero() && size.isZero()
}
// MARK: - Membership
/// Returns whether a rectangle contains a specified point.
/// ````
/// let r1 = Rect(0,0,10,10)
/// let r2 = Rect(5,5,10,10)
/// let p = Rect(2,2,2,2)
/// r1.contains(p) //-> true
/// r2.contains(p) //-> false
/// ````
/// - parameter point: The point to examine.
/// - returns: true if the rectangle is not null or empty and the point is located within the rectangle; otherwise, false.
public func contains(_ point: Point) -> Bool {
return CGRect(self).contains(CGPoint(point))
}
/// Returns whether the first rectangle contains the second rectangle.
/// ````
/// let r1 = Rect(0,0,10,10)
/// let r2 = Rect(5,5,10,10)
/// let r3 = Rect(2,2,2,2)
/// r1.contains(r2) //-> false
/// r1.contains(r3) //-> true
/// ````
/// - parameter rect: The rectangle to examine for containment.
/// - returns: `true` if the rectangle is contained in this rectangle; otherwise, `false`.
public func contains(_ rect: Rect) -> Bool {
return CGRect(self).contains(CGRect(rect))
}
/// A string representation of the rect.
/// - returns: A string formatted to look like {{x,y},{w,h}}
public var description: String {
return "{\(origin),\(size)}"
}
}
// MARK: - Comparing
/// Checks to see if two Rects share identical origin and size
///
/// ````
/// let r1 = Rect(0,0,10,10)
/// let r2 = Rect(0,0,10,10.5)
/// println(r1 == r2) //-> false
/// ````
/// - parameter lhs: The first rectangle to compare
/// - parameter rhs: The second rectangle to compare
/// - returns: A bool, `true` if the rects are identical, otherwise `false`.
public func == (lhs: Rect, rhs: Rect) -> Bool {
return lhs.origin == rhs.origin && lhs.size == rhs.size
}
// MARK: - Manipulating
/// Returns the intersection of two rectangles.
///
/// ````
/// let r1 = Rect(0,0,10,10)
/// let r2 = Rect(5,5,10,10)
/// intersection(r1,r2) //-> {5,5,5,5}
/// ````
///
/// - parameter rect1: The first source rectangle.
/// - parameter rect2: The second source rectangle.
///
/// - returns: A rectangle that represents the intersection of the two specified rectangles.
public func intersection(_ rect1: Rect, rect2: Rect) -> Rect {
return Rect(CGRect(rect1).intersection(CGRect(rect2)))
}
/// Returns the smallest rectangle that contains the two source rectangles.
///
/// ````
/// let r1 = Rect(0,0,10,10)
/// let r2 = Rect(5,5,10,10)
/// intersection(r1,r2) //-> {0,0,15,15}
/// ````
///
/// - parameter rect1: The first source rectangle.
/// - parameter rect2: The second source rectangle.
/// - returns: The smallest rectangle that completely contains both of the source rectangles.
public func union(_ rect1: Rect, rect2: Rect) -> Rect {
return Rect(CGRect(rect1).union(CGRect(rect2)))
}
/// Returns the smallest rectangle that results from converting the source rectangle values to integers.
///
/// ````
/// let r = Rect(0.1, 0.9, 9.1, 9.9)
/// integral(r) //-> {0, 0, 10, 10}
/// ````
///
/// - parameter r: The source rectangle.
/// - returns: A rectangle with the smallest integer values for its origin and size that contains the source rectangle.
public func integral(_ r: Rect) -> Rect {
return Rect(CGRect(r).integral)
}
/// Returns a rectangle with a positive width and height.
///
/// ````
/// let r = Rect(0, 0, -10, -10)
/// standardize(r) //-> {-10, -10, 10, 10}
/// ````
///
/// - parameter r: The source rectangle.
/// - returns: A rectangle that represents the source rectangle, but with positive width and height values.
public func standardize(_ r: Rect) -> Rect {
return Rect(CGRect(r).standardized)
}
/// Returns a rectangle that is smaller or larger than the source rectangle, with the same center point.
///
/// ````
/// let r = Rect(0,0,10,10)
/// inset(r, 1, 1) //-> {1,1,8,8}
/// ````
///
/// - parameter r: The source Rect structure.
/// - parameter dx: The x-coordinate value to use for adjusting the source rectangle.
/// - parameter dy: The y-coordinate value to use for adjusting the source rectangle.
/// - returns: A rectangle.
public func inset(_ r: Rect, dx: Double, dy: Double) -> Rect {
return Rect(CGRect(r).insetBy(dx: CGFloat(dx), dy: CGFloat(dy)))
}
// MARK: - Casting to CGRect
public extension CGRect {
/// Initializes a CGRect from a Rect
public init(_ rect: Rect) {
origin = CGPoint(rect.origin)
size = CGSize(rect.size)
}
}
| 4b6392f3386dcc5af822d68d74812e51 | 31.321429 | 126 | 0.592165 | false | false | false | false |
nodes-ios/NStack | refs/heads/master | NStackSDK/NStackSDKTests/Translations/TranslationsRepositoryMock.swift | mit | 1 | //
// TranslationsRepositoryMock.swift
// NStackSDK
//
// Created by Dominik Hádl on 05/12/2016.
// Copyright © 2016 Nodes ApS. All rights reserved.
//
import Foundation
import Alamofire
@testable import NStackSDK
class TranslationsRepositoryMock: TranslationsRepository {
var translationsResponse: TranslationsResponse?
var availableLanguages: [Language]?
var currentLanguage: Language?
var preferredLanguages = ["en"]
var customBundles: [Bundle]?
func fetchTranslations(acceptLanguage: String, completion: @escaping ((DataResponse<TranslationsResponse>) -> Void)) {
let error = NSError(domain: "", code: 0, userInfo: nil)
let result: Result = translationsResponse != nil ? .success(translationsResponse!) : .failure(error)
let response = DataResponse(request: nil, response: nil, data: nil, result: result)
completion(response)
}
func fetchAvailableLanguages(completion: @escaping ((DataResponse<[Language]>) -> Void)) {
let error = NSError(domain: "", code: 0, userInfo: nil)
let result: Result = availableLanguages != nil ? .success(availableLanguages!) : .failure(error)
let response = DataResponse(request: nil, response: nil, data: nil, result: result)
completion(response)
}
func fetchCurrentLanguage(acceptLanguage: String, completion: @escaping ((DataResponse<Language>) -> Void)) {
let error = NSError(domain: "", code: 0, userInfo: nil)
let result: Result = currentLanguage != nil ? .success(currentLanguage!) : .failure(error)
let response = DataResponse(request: nil, response: nil, data: nil, result: result)
completion(response)
}
func fetchPreferredLanguages() -> [String] {
return preferredLanguages
}
func fetchBundles() -> [Bundle] {
return customBundles ?? Bundle.allBundles
}
func fetchCurrentPhoneLanguage() -> String? {
return preferredLanguages.first
}
}
| 594fa59f65928e7def85989aedca8491 | 36.509434 | 122 | 0.682596 | false | false | false | false |
flodolo/firefox-ios | refs/heads/main | Client/Frontend/Browser/MailProviders.swift | mpl-2.0 | 2 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import Shared
// mailto headers: subject, body, cc, bcc
protocol MailProvider {
var beginningScheme: String {get set}
var supportedHeaders: [String] {get set}
func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL?
}
private func constructEmailURLString(_ beginningURLString: String, metadata: MailToMetadata, supportedHeaders: [String], bodyHName: String = "body", toHName: String = "to") -> String {
var lowercasedHeaders = [String: String]()
metadata.headers.forEach { (hname, hvalue) in
lowercasedHeaders[hname.lowercased()] = hvalue
}
var toParam: String
if let toHValue = lowercasedHeaders["to"] {
let value = metadata.to.isEmpty ? toHValue : [metadata.to, toHValue].joined(separator: "%2C%20")
lowercasedHeaders.removeValue(forKey: "to")
toParam = "\(toHName)=\(value)"
} else {
toParam = "\(toHName)=\(metadata.to)"
}
var queryParams: [String] = []
lowercasedHeaders.forEach({ (hname, hvalue) in
if supportedHeaders.contains(hname) {
queryParams.append("\(hname)=\(hvalue)")
} else if hname == "body" {
queryParams.append("\(bodyHName)=\(hvalue)")
}
})
let stringParams = queryParams.joined(separator: "&")
let finalURLString = beginningURLString + (stringParams.isEmpty ? toParam : [toParam, stringParams].joined(separator: "&"))
return finalURLString
}
class ReaddleSparkIntegration: MailProvider {
var beginningScheme = "readdle-spark://compose?"
var supportedHeaders = [
"subject",
"recipient",
"textbody",
"html",
"cc",
"bcc"
]
func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? {
return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders, bodyHName: "textbody", toHName: "recipient").asURL
}
}
class AirmailIntegration: MailProvider {
var beginningScheme = "airmail://compose?"
var supportedHeaders = [
"subject",
"from",
"to",
"cc",
"bcc",
"plainBody",
"htmlBody"
]
func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? {
return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders, bodyHName: "htmlBody").asURL
}
}
class MyMailIntegration: MailProvider {
var beginningScheme = "mymail-mailto://?"
var supportedHeaders = [
"to",
"subject",
"body",
"cc",
"bcc"
]
func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? {
return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL
}
}
class MailRuIntegration: MyMailIntegration {
override init() {
super.init()
self.beginningScheme = "mailru-mailto://?"
}
}
class MSOutlookIntegration: MailProvider {
var beginningScheme = "ms-outlook://emails/new?"
var supportedHeaders = [
"to",
"cc",
"bcc",
"subject",
"body"
]
func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? {
return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL
}
}
class YMailIntegration: MailProvider {
var beginningScheme = "ymail://mail/any/compose?"
var supportedHeaders = [
"to",
"cc",
"subject",
"body"
]
func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? {
return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL
}
}
class GoogleGmailIntegration: MailProvider {
var beginningScheme = "googlegmail:///co?"
var supportedHeaders = [
"to",
"cc",
"bcc",
"subject",
"body"
]
func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? {
return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL
}
}
class FastmailIntegration: MailProvider {
var beginningScheme = "fastmail://mail/compose?"
var supportedHeaders = [
"to",
"cc",
"bcc",
"subject",
"body"
]
func newEmailURLFromMetadata(_ metadata: MailToMetadata) -> URL? {
return constructEmailURLString(beginningScheme, metadata: metadata, supportedHeaders: supportedHeaders).asURL
}
}
| 2934b4714b03bc6669db258275344925 | 29.403846 | 184 | 0.646848 | false | false | false | false |
rockgarden/swift_language | refs/heads/swift3 | Playground/Swift Language Guide.playground/Pages/Enumerations.xcplaygroundpage/Contents.swift | mit | 1 | //: [Previous](@previous)
import UIKit
//: # Enum
/*:
An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.
*/
//: # Enumeration Syntax
enum SomeEnumeration {
// enumeration definition goes here
}
enum CompassPoint {
case north
case south
case east
case west
}
do {
/// 使用
let someEnum = CompassPoint.west
("This is the enum: \(someEnum)")
(someEnum == .west) ? ("Equal") : ("Not Equal")
switch(someEnum){
case .north:
CompassPoint.north
case .south:
CompassPoint.south
case .east:
CompassPoint.east
case .west:
CompassPoint.west
}
}
/*
- NOTE:
Unlike C and Objective-C, Swift enumeration cases are not assigned a default integer value when they are created. In the CompassPoint example above, north, south, east and west do not implicitly equal 0, 1, 2 and 3. Instead, the different enumeration cases are fully-fledged values in their own right, with an explicitly-defined type of CompassPoint.
*/
//: Multiple cases can appear on a single line, separated by commas:
enum Planet {
case mercury, venus, earth, mars, jupiter, saturn, uranus, neptune
}
do {
var directionToHead = CompassPoint.west
directionToHead = .east
}
//: # Matching Enumeration Values with a Switch Statement
do {
var directionToHead = CompassPoint.west
directionToHead = .south
switch directionToHead {
case .north:
print("Lots of planets have a north")
case .south:
print("Watch out for penguins")
case .east:
print("Where the sun rises")
case .west:
print("Where the skies are blue")
}
}
do {
/// When it is not appropriate to provide a case for every enumeration case, you can provide a default case to cover any cases that are not addressed explicitly
let somePlanet = Planet.earth
switch somePlanet {
case .earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
}
do {
do {
enum Shape {
case rectangle
case ellipse
case diamond
func addShape (to p: CGMutablePath, in r : CGRect) -> () {
switch self {
case .rectangle:
p.addRect(r)
case .ellipse:
p.addEllipse(in:r)
case .diamond:
p.move(to: CGPoint(x:r.minX, y:r.midY))
p.addLine(to: CGPoint(x: r.midX, y: r.minY))
p.addLine(to: CGPoint(x: r.maxX, y: r.midY))
p.addLine(to: CGPoint(x: r.midX, y: r.maxY))
p.closeSubpath()
}
}
}
}
}
//: # Associated Values 关联值
/*:
显式定义枚举成员
- Defines an enum with members with explicit types.
*/
enum Barcode {
case upc(Int, Int, Int, Int)
case qrCode(String)
}
//: mean “Define an enumeration type called Barcode, which can take either a value of upc with an associated value of type (Int, Int, Int, Int), or a value of qrCode with an associated value of type String.”
do {
/// New barcodes can then be created using either type
var productBarcode = Barcode.upc(8, 85909, 51226, 3)
/// assigned a different type of barcode
productBarcode = .qrCode("ABCDEFGHIJKLMNOP")
switch productBarcode {
case .upc(let numberSystem, let manufacturer, let product, let check):
print("UPC: \(numberSystem), \(manufacturer), \(product), \(check).")
case .qrCode(let productCode):
print("QR code: \(productCode).")
}
}
do {
enum planet {
case earth(weight: Double, name: String)
case mars(density: Double, name: String, weight: Double)
case venus(Double, String)
case saturn
case neptune
}
var p1 = planet.earth(weight: 1.0, name: "地球")
var p3 = planet.mars(density: 3.95, name: "火星", weight: 0.1)
var p2: planet = .venus(3.95, "水星")
switch(p3){
case planet.earth(var weight, var name):
("earth \(weight)")
case let planet.mars(density:d, name:n, weight:w):
("\(n)\(w)\(d)")
default:
break
}
enum Error2 {
case Number(Int)
case Message(String)
case Fatal(n:Int, s:String)
}
do {
let fatalMaker = Error2.Fatal
let err = fatalMaker(n:-1000, s:"Unbelievably bad error")
_ = err
}
}
//: # Raw Values 原始值
/*:
在这种情况下,枚举与原始值的定义必须是独一无二的
In this case, the enum is defined with raw values.
They must be unique.
*/
enum ASCIIControlCharacter: Character {
case tab = "\t"
case lineFeed = "\n"
case carriageReturn = "\r"
}
do {
let asciiCode = ASCIIControlCharacter.lineFeed
("Code is \(asciiCode.rawValue)")
/// In this case, since it's not guaranteed to find an enum for the specified rawValue, the initializer returns an optional
if let lineFeed = ASCIIControlCharacter(rawValue: "\r") {
//Do something
lineFeed
}
}
/*
- NOTE:
Raw values are not the same as associated values. Raw values are set to prepopulated values when you first define the enumeration in your code, like the three ASCII codes above. The raw value for a particular enumeration case is always the same. Associated values are set when you create a new constant or variable based on one of the enumeration’s cases, and can be different each time you do so.
原始值与关联值不同。 当您首次在代码中定义枚举时,原始值将设置为预填充值,如上面的三个ASCII代码。 特定枚举大小的原始值总是相同的。 当您基于枚举的一种情况创建新的常量或变量时,相关值将被设置,并且每次这样做都可能不同。
*/
do {
/// 赋值
enum season: Character{
case spring="春"
case summer="夏"
case fall="秋"
case winter="冬"
}
var mySeason = season(rawValue: "秋")
if mySeason != nil {
switch(mySeason!) {
case .spring:
season.spring
case .summer:
season.summer
case .fall, .winter:
season.fall
}
}
}
/*:
## Implicitly Assigned Raw Values 隐式赋值原始值
赋值推断
*/
do {
/// with integer raw values to represent each planet’s order from the sun:
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
/// with string raw values to represent each direction’s name:
enum CompassPoint: String {
case north, south, east, west
}
/// 获取原始值
let earthsOrder = Planet.earth.rawValue
let sunsetDirection = CompassPoint.west.rawValue
}
//: ## Initializing from a Raw Value
do {
enum Planet: Int {
case mercury = 1, venus, earth, mars, jupiter, saturn, uranus, neptune
}
let possiblePlanet = Planet(rawValue: 7)
/// possiblePlanet is of type Planet? and equals Planet.uranus
/// eturned by the raw value initializer will be nil:
let positionToFind = 11
if let somePlanet = Planet(rawValue: positionToFind) {
switch somePlanet {
case .earth:
print("Mostly harmless")
default:
print("Not a safe place for humans")
}
} else {
print("There isn't a planet at position \(positionToFind)")
}
}
/*
- NOTE:
The raw value initializer is a failable initializer, because not every raw value will return an enumeration case.
*/
//: # Recursive Enumerations
enum ArithmeticExpression {
case number(Int)
indirect case addition(ArithmeticExpression, ArithmeticExpression)
indirect case multiplication(ArithmeticExpression, ArithmeticExpression)
}
do {
/// can also write indirect before the beginning of the enumeration, to enable indirection for all of the enumeration’s cases that need it.
indirect enum ArithmeticExpression {
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
}
do {
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
func evaluate(_ expression: ArithmeticExpression) -> Int {
switch expression {
case let .number(value):
return value
case let .addition(left, right):
return evaluate(left) + evaluate(right)
case let .multiplication(left, right):
return evaluate(left) * evaluate(right)
}
}
print(evaluate(product))
}
//: # Example
//: ## Initializers
import MediaPlayer
do {
enum Filter : String {
case albums = "Albums"
case playlists = "Playlists"
case podcasts = "Podcasts"
case books = "Audiobooks"
static var cases : [Filter] = [albums, playlists, podcasts, books]
init!(_ ix: Int) {
if !(0...3).contains(ix) {
return nil
}
self = Filter.cases[ix]
}
init!(_ rawValue: String) {
self.init(rawValue: rawValue)
}
var description : String { return self.rawValue }
var s : String {
get { return "howdy" }
set {}
}
mutating func advance() {
var ix = Filter.cases.index(of:self)!
ix = (ix + 1) % 4
self = Filter.cases[ix]
}
var query : MPMediaQuery {
switch self {
case .albums:
return .albums()
case .playlists:
return .playlists()
case .podcasts:
return .podcasts()
case .books:
return .audiobooks()
}
}
}
let type1 = Filter.albums
/// init Filter 若 rawValue 存在 则 fatal error: unexpectedly found nil while unwrapping an Optional value
let type2 = Filter(rawValue: "Playlists")!
let type3 = Filter(2) // .Podcasts
let type4 = Filter(5) // nil
let type5 = Filter("Playlists")
type5?.description
// type5.s = "test" // compile error
var type6 = type5
type6?.s = "test" //no set, so still type5
(type6?.s)
var type7 = Filter.books
type7.advance() // Filter.Albums, 返回0 = Albums
(type7)
}
do {
var s : String? = "howdy"
switch s {
case .some(let theString):
(theString)
case .none:
("it's nil")
}
}
//: [Next](@next)
| c367e21f73c9433e0e26246c390ed420 | 28.765714 | 398 | 0.610098 | false | false | false | false |
VBVMI/VerseByVerse-iOS | refs/heads/master | Pods/STRegex/Source/Options.swift | mit | 3 | import Foundation
/// `Options` defines alternate behaviours of regular expressions when matching.
public struct Options: OptionSet {
/// Ignores the case of letters when matching.
///
/// Example:
///
/// let a = Regex("a", options: .ignoreCase)
/// a.allMatches(in: "aA").map { $0.matchedString } // ["a", "A"]
public static let ignoreCase = Options(rawValue: 1)
/// Ignore any metacharacters in the pattern, treating every character as
/// a literal.
///
/// Example:
///
/// let parens = Regex("()", options: .ignoreMetacharacters)
/// parens.matches("()") // true
public static let ignoreMetacharacters = Options(rawValue: 1 << 1)
/// By default, "^" matches the beginning of the string and "$" matches the
/// end of the string, ignoring any newlines. With this option, "^" will
/// the beginning of each line, and "$" will match the end of each line.
///
/// let foo = Regex("^foo", options: .anchorsMatchLines)
/// foo.allMatches(in: "foo\nbar\nfoo\n").count // 2
public static let anchorsMatchLines = Options(rawValue: 1 << 2)
/// Usually, "." matches all characters except newlines (\n). Using this
/// this options will allow "." to match newLines
///
/// let newLines = Regex("test.test", options: .dotMatchesLineSeparators)
/// newLines.allMatches(in: "test\ntest").count // 1
public static let dotMatchesLineSeparators = Options(rawValue: 1 << 3)
// MARK: OptionSetType
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
}
internal extension Options {
/// Transform an instance of `Regex.Options` into the equivalent `NSRegularExpression.Options`.
///
/// - returns: The equivalent `NSRegularExpression.Options`.
func toNSRegularExpressionOptions() -> NSRegularExpression.Options {
var options = NSRegularExpression.Options()
if contains(.ignoreCase) { options.insert(.caseInsensitive) }
if contains(.ignoreMetacharacters) { options.insert(.ignoreMetacharacters) }
if contains(.anchorsMatchLines) { options.insert(.anchorsMatchLines) }
if contains(.dotMatchesLineSeparators) { options.insert(.dotMatchesLineSeparators) }
return options
}
}
// MARK: Deprecations / Removals
extension Options {
@available(*, unavailable, renamed: "ignoreCase")
public static var IgnoreCase: Options {
fatalError()
}
@available(*, unavailable, renamed: "ignoreMetacharacters")
public static var IgnoreMetacharacters: Options {
fatalError()
}
@available(*, unavailable, renamed: "anchorsMatchLines")
public static var AnchorsMatchLines: Options {
fatalError()
}
@available(*, unavailable, renamed: "dotMatchesLineSeparators")
public static var DotMatchesLineSeparators: Options {
fatalError()
}
}
| e800462b02d97eb156ef5177e1ea795c | 30.977273 | 97 | 0.685856 | false | false | false | false |
PhillipEnglish/TIY-Assignments | refs/heads/master | VenueMenu/VenueMenu/SearchViewController.swift | cc0-1.0 | 1 | //
// SearchViewController.swift
// VenueMenu
//
// Created by Phillip English on 11/29/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import CoreData
protocol FoursquareAPIResultsProtocol
{
func didReceiveFoursquareAPIResults(results: NSDictionary)
}
class SearchViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, FoursquareAPIResultsProtocol
{
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet var tableView: UITableView!
var delegate: VenueSearchDelegate
var venues = [NSManagedObject]()
var apiDelegate: APIController!
override func viewDidLoad()
{
super.viewDidLoad()
title = "Search"
tableView.delegate = self
tableView.dataSource = self
searchBar.delegate = self
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
}
// MARK: - Search Bar
func searchBarSearchButtonClicked(searchBar: UISearchBar)
{
let term = searchBar.text
UIApplication.sharedApplication().networkActivityIndicatorVisible = true
searchQueryToAPIController(term!)
}
// MARK: - Foursquare API
func searchQueryToAPIController(searchTerm: String)
{
self.apiDelegate = APIController(foursquareDelegate: self)
apiDelegate.searchFoursquareFor(searchTerm)
}
func didReceiveFoursquareAPIResults(results: NSDictionary) {
var venuesArray = [NSManagedObject]()
venuesArray = Venue.searchResultsJSON(results)
self.venues = venuesArray
tableView.reloadData()
}
// MARK: - Table view data source
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return venues.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
UIApplication.sharedApplication().networkActivityIndicatorVisible = false
let cell = tableView.dequeueReusableCellWithIdentifier("SearchCell", forIndexPath: indexPath)
let aVenue = venues[indexPath.row]
cell.textLabel!.text = aVenue.valueForKey("name") as? String
cell.detailTextLabel?.text = aVenue.valueForKey("address") as? String
return cell
}
func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath)
{
let venue = venues[indexPath.row]
delegate.venueWasselected(venue)
self.dismissViewControllerAnimated(true, completion: nil)
}
/*
// 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.
}
*/
}
| 7551f33104088608a01ccdecae2b007a | 28.364486 | 139 | 0.685551 | false | false | false | false |
Shopify/mobile-buy-sdk-ios | refs/heads/main | Buy/Generated/Storefront/PaymentSettings.swift | mit | 1 | //
// PaymentSettings.swift
// Buy
//
// Created by Shopify.
// Copyright (c) 2017 Shopify Inc. 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
extension Storefront {
/// Settings related to payments.
open class PaymentSettingsQuery: GraphQL.AbstractQuery, GraphQLQuery {
public typealias Response = PaymentSettings
/// List of the card brands which the shop accepts.
@discardableResult
open func acceptedCardBrands(alias: String? = nil) -> PaymentSettingsQuery {
addField(field: "acceptedCardBrands", aliasSuffix: alias)
return self
}
/// The url pointing to the endpoint to vault credit cards.
@discardableResult
open func cardVaultUrl(alias: String? = nil) -> PaymentSettingsQuery {
addField(field: "cardVaultUrl", aliasSuffix: alias)
return self
}
/// The country where the shop is located.
@discardableResult
open func countryCode(alias: String? = nil) -> PaymentSettingsQuery {
addField(field: "countryCode", aliasSuffix: alias)
return self
}
/// The three-letter code for the shop's primary currency.
@discardableResult
open func currencyCode(alias: String? = nil) -> PaymentSettingsQuery {
addField(field: "currencyCode", aliasSuffix: alias)
return self
}
/// A list of enabled currencies (ISO 4217 format) that the shop accepts.
/// Merchants can enable currencies from their Shopify Payments settings in the
/// Shopify admin.
@discardableResult
open func enabledPresentmentCurrencies(alias: String? = nil) -> PaymentSettingsQuery {
addField(field: "enabledPresentmentCurrencies", aliasSuffix: alias)
return self
}
/// The shop’s Shopify Payments account id.
@discardableResult
open func shopifyPaymentsAccountId(alias: String? = nil) -> PaymentSettingsQuery {
addField(field: "shopifyPaymentsAccountId", aliasSuffix: alias)
return self
}
/// List of the digital wallets which the shop supports.
@discardableResult
open func supportedDigitalWallets(alias: String? = nil) -> PaymentSettingsQuery {
addField(field: "supportedDigitalWallets", aliasSuffix: alias)
return self
}
}
/// Settings related to payments.
open class PaymentSettings: GraphQL.AbstractResponse, GraphQLObject {
public typealias Query = PaymentSettingsQuery
internal override func deserializeValue(fieldName: String, value: Any) throws -> Any? {
let fieldValue = value
switch fieldName {
case "acceptedCardBrands":
guard let value = value as? [String] else {
throw SchemaViolationError(type: PaymentSettings.self, field: fieldName, value: fieldValue)
}
return value.map { return CardBrand(rawValue: $0) ?? .unknownValue }
case "cardVaultUrl":
guard let value = value as? String else {
throw SchemaViolationError(type: PaymentSettings.self, field: fieldName, value: fieldValue)
}
return URL(string: value)!
case "countryCode":
guard let value = value as? String else {
throw SchemaViolationError(type: PaymentSettings.self, field: fieldName, value: fieldValue)
}
return CountryCode(rawValue: value) ?? .unknownValue
case "currencyCode":
guard let value = value as? String else {
throw SchemaViolationError(type: PaymentSettings.self, field: fieldName, value: fieldValue)
}
return CurrencyCode(rawValue: value) ?? .unknownValue
case "enabledPresentmentCurrencies":
guard let value = value as? [String] else {
throw SchemaViolationError(type: PaymentSettings.self, field: fieldName, value: fieldValue)
}
return value.map { return CurrencyCode(rawValue: $0) ?? .unknownValue }
case "shopifyPaymentsAccountId":
if value is NSNull { return nil }
guard let value = value as? String else {
throw SchemaViolationError(type: PaymentSettings.self, field: fieldName, value: fieldValue)
}
return value
case "supportedDigitalWallets":
guard let value = value as? [String] else {
throw SchemaViolationError(type: PaymentSettings.self, field: fieldName, value: fieldValue)
}
return value.map { return DigitalWallet(rawValue: $0) ?? .unknownValue }
default:
throw SchemaViolationError(type: PaymentSettings.self, field: fieldName, value: fieldValue)
}
}
/// List of the card brands which the shop accepts.
open var acceptedCardBrands: [Storefront.CardBrand] {
return internalGetAcceptedCardBrands()
}
func internalGetAcceptedCardBrands(alias: String? = nil) -> [Storefront.CardBrand] {
return field(field: "acceptedCardBrands", aliasSuffix: alias) as! [Storefront.CardBrand]
}
/// The url pointing to the endpoint to vault credit cards.
open var cardVaultUrl: URL {
return internalGetCardVaultUrl()
}
func internalGetCardVaultUrl(alias: String? = nil) -> URL {
return field(field: "cardVaultUrl", aliasSuffix: alias) as! URL
}
/// The country where the shop is located.
open var countryCode: Storefront.CountryCode {
return internalGetCountryCode()
}
func internalGetCountryCode(alias: String? = nil) -> Storefront.CountryCode {
return field(field: "countryCode", aliasSuffix: alias) as! Storefront.CountryCode
}
/// The three-letter code for the shop's primary currency.
open var currencyCode: Storefront.CurrencyCode {
return internalGetCurrencyCode()
}
func internalGetCurrencyCode(alias: String? = nil) -> Storefront.CurrencyCode {
return field(field: "currencyCode", aliasSuffix: alias) as! Storefront.CurrencyCode
}
/// A list of enabled currencies (ISO 4217 format) that the shop accepts.
/// Merchants can enable currencies from their Shopify Payments settings in the
/// Shopify admin.
open var enabledPresentmentCurrencies: [Storefront.CurrencyCode] {
return internalGetEnabledPresentmentCurrencies()
}
func internalGetEnabledPresentmentCurrencies(alias: String? = nil) -> [Storefront.CurrencyCode] {
return field(field: "enabledPresentmentCurrencies", aliasSuffix: alias) as! [Storefront.CurrencyCode]
}
/// The shop’s Shopify Payments account id.
open var shopifyPaymentsAccountId: String? {
return internalGetShopifyPaymentsAccountId()
}
func internalGetShopifyPaymentsAccountId(alias: String? = nil) -> String? {
return field(field: "shopifyPaymentsAccountId", aliasSuffix: alias) as! String?
}
/// List of the digital wallets which the shop supports.
open var supportedDigitalWallets: [Storefront.DigitalWallet] {
return internalGetSupportedDigitalWallets()
}
func internalGetSupportedDigitalWallets(alias: String? = nil) -> [Storefront.DigitalWallet] {
return field(field: "supportedDigitalWallets", aliasSuffix: alias) as! [Storefront.DigitalWallet]
}
internal override func childResponseObjectMap() -> [GraphQL.AbstractResponse] {
return []
}
}
}
| 7779af563a0a3f37b006f41b0976402b | 36.5 | 104 | 0.735111 | false | false | false | false |
sabyapradhan/IBM-Ready-App-for-Banking | refs/heads/master | HatchReadyApp/apps/Hatch/iphone/native/Hatch/Extensions/DoubleExtension.swift | epl-1.0 | 1 | /*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import Foundation
extension Double{
var toCGFloat:CGFloat {return CGFloat(self)}
func roundToDecimalDigits(decimals:Int) -> Double
{
let a : Double = self
var format : NSNumberFormatter = NSNumberFormatter()
format.numberStyle = NSNumberFormatterStyle.DecimalStyle
format.roundingMode = NSNumberFormatterRoundingMode.RoundHalfUp
format.maximumFractionDigits = 2
var string: NSString = format.stringFromNumber(NSNumber(double: a))!
return string.doubleValue
}
} | 4edf04837732bfb8b4de45318d36e2f9 | 28.318182 | 76 | 0.703416 | false | false | false | false |
realm/SwiftLint | refs/heads/main | Source/SwiftLintFramework/Rules/Idiomatic/LegacyHashingRule.swift | mit | 1 | import SwiftSyntax
struct LegacyHashingRule: SwiftSyntaxRule, ConfigurationProviderRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static let description = RuleDescription(
identifier: "legacy_hashing",
name: "Legacy Hashing",
description: "Prefer using the `hash(into:)` function instead of overriding `hashValue`",
kind: .idiomatic,
nonTriggeringExamples: [
Example("""
struct Foo: Hashable {
let bar: Int = 10
func hash(into hasher: inout Hasher) {
hasher.combine(bar)
}
}
"""),
Example("""
class Foo: Hashable {
let bar: Int = 10
func hash(into hasher: inout Hasher) {
hasher.combine(bar)
}
}
"""),
Example("""
var hashValue: Int { return 1 }
class Foo: Hashable { \n }
"""),
Example("""
class Foo: Hashable {
let bar: String = "Foo"
public var hashValue: String {
return bar
}
}
"""),
Example("""
class Foo: Hashable {
let bar: String = "Foo"
public var hashValue: String {
get { return bar }
set { bar = newValue }
}
}
""")
],
triggeringExamples: [
Example("""
struct Foo: Hashable {
let bar: Int = 10
public ↓var hashValue: Int {
return bar
}
}
"""),
Example("""
class Foo: Hashable {
let bar: Int = 10
public ↓var hashValue: Int {
return bar
}
}
""")
]
)
func makeVisitor(file: SwiftLintFile) -> ViolationsSyntaxVisitor {
Visitor(viewMode: .sourceAccurate)
}
}
extension LegacyHashingRule {
private final class Visitor: ViolationsSyntaxVisitor {
override func visitPost(_ node: VariableDeclSyntax) {
guard
node.parent?.is(MemberDeclListItemSyntax.self) == true,
node.letOrVarKeyword.tokenKind == .varKeyword,
let binding = node.bindings.onlyElement,
let identifier = binding.pattern.as(IdentifierPatternSyntax.self),
identifier.identifier.text == "hashValue",
let returnType = binding.typeAnnotation?.type.as(SimpleTypeIdentifierSyntax.self),
returnType.name.text == "Int"
else {
return
}
violations.append(node.letOrVarKeyword.positionAfterSkippingLeadingTrivia)
}
}
}
| f1abc0ab703e0789ff2494710720c386 | 27.980198 | 98 | 0.476939 | false | false | false | false |
barteljan/RocketChatAdapter | refs/heads/master | Example/Pods/SwiftDDP/SwiftDDP/Meteor.swift | mit | 2 | // Copyright (c) 2016 Peter Siegesmund <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
import UIKit
/*
enum Error: String {
case BadRequest = "400" // The server cannot or will not process the request due to something that is perceived to be a client error
case Unauthorized = "401" // Similar to 403 Forbidden, but specifically for use when authentication is required and has failed or has not yet been provided.
case NotFound = "404" // ex. Method not found, Subscription not found
case Forbidden = "403" // Not authorized to access resource, also issued when you've been logged out by the server
case RequestConflict = "409" // ex. MongoError: E11000 duplicate key error
case PayloadTooLarge = "413" // The request is larger than the server is willing or able to process.
case InternalServerError = "500"
}
*/
public protocol MeteorCollectionType {
func documentWasAdded(collection:String, id:String, fields:NSDictionary?)
func documentWasChanged(collection:String, id:String, fields:NSDictionary?, cleared:[String]?)
func documentWasRemoved(collection:String, id:String)
}
/**
Meteor is a class to simplify communicating with and consuming MeteorJS server services
*/
public class Meteor {
/**
client is a singleton instance of DDPClient
*/
public static let client = Meteor.Client() // Client is a singleton object
internal static var collections = [String:MeteorCollectionType]()
/**
returns a Meteor collection, if it exists
*/
public static func collection(name:String) -> MeteorCollectionType? {
return collections[name]
}
/**
Sends a subscription request to the server.
- parameter name: The name of the subscription.
*/
public static func subscribe(name:String) -> String { return client.sub(name, params:nil) }
/**
Sends a subscription request to the server.
- parameter name: The name of the subscription.
- parameter params: An object containing method arguments, if any.
*/
public static func subscribe(name:String, params:[AnyObject]) -> String { return client.sub(name, params:params) }
/**
Sends a subscription request to the server. If a callback is passed, the callback asynchronously
runs when the client receives a 'ready' message indicating that the initial subset of documents contained
in the subscription has been sent by the server.
- parameter name: The name of the subscription.
- parameter params: An object containing method arguments, if any.
- parameter callback: The closure to be executed when the server sends a 'ready' message.
*/
public static func subscribe(name:String, params:[AnyObject]?, callback: DDPCallback?) -> String { return client.sub(name, params:params, callback:callback) }
/**
Sends a subscription request to the server. If a callback is passed, the callback asynchronously
runs when the client receives a 'ready' message indicating that the initial subset of documents contained
in the subscription has been sent by the server.
- parameter name: The name of the subscription.
- parameter callback: The closure to be executed when the server sends a 'ready' message.
*/
public static func subscribe(name:String, callback: DDPCallback?) -> String { return client.sub(name, params: nil, callback: callback) }
/**
Sends an unsubscribe request to the server.
*/
public static func unsubscribe(name:String) -> String? { return client.unsub(name) }
/**
Sends an unsubscribe request to the server. If a callback is passed, the callback asynchronously
runs when the unsubscribe transaction is complete.
*/
public static func unsubscribe(name:String, callback:DDPCallback?) -> String? { return client.unsub(name, callback: callback) }
/**
Calls a method on the server. If a callback is passed, the callback is asynchronously
executed when the method has completed. The callback takes two arguments: result and error. It
the method call is successful, result contains the return value of the method, if any. If the method fails,
error contains information about the error.
- parameter name: The name of the method
- parameter params: An array containing method arguments, if any
- parameter callback: The closure to be executed when the method has been executed
*/
public static func call(name:String, params:[AnyObject]?, callback:DDPMethodCallback?) -> String? {
return client.method(name, params: params, callback: callback)
}
/**
Call a single function to establish a DDP connection, and login with email and password
- parameter url: The url of a Meteor server
- parameter email: A string email address associated with a Meteor account
- parameter password: A string password
*/
public static func connect(url:String, email:String, password:String) {
client.connect(url) { session in
client.loginWithPassword(email, password: password) { result, error in
guard let _ = error else {
if let _ = result as? NSDictionary {
// client.userDidLogin(credentials)
}
return
}
}
}
}
/**
Connect to a Meteor server and resume a prior session, if the user was logged in
- parameter url: The url of a Meteor server
*/
public static func connect(url:String) {
client.resume(url, callback: nil)
}
/**
Connect to a Meteor server and resume a prior session, if the user was logged in
- parameter url: The url of a Meteor server
- parameter callback: An optional closure to be executed after the connection is established
*/
public static func connect(url:String, callback:DDPCallback?) {
client.resume(url, callback: callback)
}
/**
Creates a user account on the server with an email and password
- parameter email: An email string
- parameter password: A password string
- parameter callback: A closure with result and error parameters describing the outcome of the operation
*/
public static func signupWithEmail(email: String, password: String, callback: DDPMethodCallback?) {
client.signupWithEmail(email, password: password, callback: callback)
}
/**
Logs a user into the server using an email and password
- parameter email: An email string
- parameter password: A password string
- parameter callback: A closure with result and error parameters describing the outcome of the operation
*/
public static func loginWithPassword(email:String, password:String, callback:DDPMethodCallback?) {
client.loginWithPassword(email, password: password, callback: callback)
}
/**
Logs a user into the server using an email and password
- parameter email: An email string
- parameter password: A password string
*/
public static func loginWithPassword(email:String, password:String) {
client.loginWithPassword(email, password: password, callback: nil)
}
internal static func loginWithService<T: UIViewController>(service: String, clientId: String, viewController: T) {
// Resume rather than
if Meteor.client.loginWithToken(nil) == false {
var url:String!
switch service {
case "twitter":
url = MeteorOAuthServices.twitter()
case "facebook":
url = MeteorOAuthServices.facebook(clientId)
case "github":
url = MeteorOAuthServices.github(clientId)
case "google":
url = MeteorOAuthServices.google(clientId)
default:
url = nil
}
let oauthDialog = MeteorOAuthDialogViewController()
oauthDialog.serviceName = service.capitalizedString
oauthDialog.url = NSURL(string: url)
viewController.presentViewController(oauthDialog, animated: true, completion: nil)
} else {
log.debug("Already have valid server login credentials. Logging in with preexisting login token")
}
}
/**
Logs a user into the server using Twitter
- parameter viewController: A view controller from which to launch the OAuth modal dialog
*/
public static func loginWithTwitter<T: UIViewController>(viewController: T) {
Meteor.loginWithService("twitter", clientId: "", viewController: viewController)
}
/**
Logs a user into the server using Facebook
- parameter viewController: A view controller from which to launch the OAuth modal dialog
- parameter clientId: The apps client id, provided by the service (Facebook, Google, etc.)
*/
public static func loginWithFacebook<T: UIViewController>(clientId: String, viewController: T) {
Meteor.loginWithService("facebook", clientId: clientId, viewController: viewController)
}
/**
Logs a user into the server using Github
- parameter viewController: A view controller from which to launch the OAuth modal dialog
- parameter clientId: The apps client id, provided by the service (Facebook, Google, etc.)
*/
public static func loginWithGithub<T: UIViewController>(clientId: String, viewController: T) {
Meteor.loginWithService("github", clientId: clientId, viewController: viewController)
}
/**
Logs a user into the server using Google
- parameter viewController: A view controller from which to launch the OAuth modal dialog
- parameter clientId: The apps client id, provided by the service (Facebook, Google, etc.)
*/
public static func loginWithGoogle<T: UIViewController>(clientId: String, viewController: T) {
Meteor.loginWithService("google", clientId: clientId, viewController: viewController)
}
/**
Logs a user out of the server and executes a callback when the logout process has completed
- parameter callback: An optional closure to be executed after the client has logged out
*/
public static func logout(callback:DDPMethodCallback?) {
client.logout(callback)
}
/**
Logs a user out of the server
*/
public static func logout() {
client.logout()
}
/**
Meteor.Client is a subclass of DDPClient that facilitates interaction with the MeteorCollection class
*/
public class Client: DDPClient {
typealias SubscriptionCallback = () -> ()
let notifications = NSNotificationCenter.defaultCenter()
public convenience init(url:String, email:String, password:String) {
self.init()
}
/**
Calls the documentWasAdded method in the MeteorCollection subclass instance associated with the document
collection
- parameter collection: the string name of the collection to which the document belongs
- parameter id: the string unique id that identifies the document on the server
- parameter fields: an optional NSDictionary with the documents properties
*/
public override func documentWasAdded(collection:String, id:String, fields:NSDictionary?) {
if let meteorCollection = Meteor.collections[collection] {
meteorCollection.documentWasAdded(collection, id: id, fields: fields)
}
}
/**
Calls the documentWasChanged method in the MeteorCollection subclass instance associated with the document
collection
- parameter collection: the string name of the collection to which the document belongs
- parameter id: the string unique id that identifies the document on the server
- parameter fields: an optional NSDictionary with the documents properties
- parameter cleared: an optional array of string property names to delete
*/
public override func documentWasChanged(collection:String, id:String, fields:NSDictionary?, cleared:[String]?) {
if let meteorCollection = Meteor.collections[collection] {
meteorCollection.documentWasChanged(collection, id: id, fields: fields, cleared: cleared)
}
}
/**
Calls the documentWasRemoved method in the MeteorCollection subclass instance associated with the document
collection
- parameter collection: the string name of the collection to which the document belongs
- parameter id: the string unique id that identifies the document on the server
*/
public override func documentWasRemoved(collection:String, id:String) {
if let meteorCollection = Meteor.collections[collection] {
meteorCollection.documentWasRemoved(collection, id: id)
}
}
}
}
| 2ab8aff9c17d623fa33217cde0a152fa | 39.138587 | 170 | 0.656421 | false | false | false | false |
yeziahehe/Gank | refs/heads/master | Pods/Kingfisher/Sources/Image/ImageFormat.swift | gpl-3.0 | 1 | //
// ImageFormat.swift
// Kingfisher
//
// Created by onevcat on 2018/09/28.
//
// Copyright (c) 2019 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.
import Foundation
/// Represents image format.
///
/// - unknown: The format cannot be recognized or not supported yet.
/// - PNG: PNG image format.
/// - JPEG: JPEG image format.
/// - GIF: GIF image format.
public enum ImageFormat {
/// The format cannot be recognized or not supported yet.
case unknown
/// PNG image format.
case PNG
/// JPEG image format.
case JPEG
/// GIF image format.
case GIF
struct HeaderData {
static var PNG: [UInt8] = [0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]
static var JPEG_SOI: [UInt8] = [0xFF, 0xD8]
static var JPEG_IF: [UInt8] = [0xFF]
static var GIF: [UInt8] = [0x47, 0x49, 0x46]
}
}
extension Data: KingfisherCompatible {}
// MARK: - Misc Helpers
extension KingfisherWrapper where Base == Data {
/// Gets the image format corresponding to the data.
public var imageFormat: ImageFormat {
var buffer = [UInt8](repeating: 0, count: 8)
(base as NSData).getBytes(&buffer, length: 8)
if buffer == ImageFormat.HeaderData.PNG {
return .PNG
} else if buffer[0] == ImageFormat.HeaderData.JPEG_SOI[0] &&
buffer[1] == ImageFormat.HeaderData.JPEG_SOI[1] &&
buffer[2] == ImageFormat.HeaderData.JPEG_IF[0]
{
return .JPEG
} else if buffer[0] == ImageFormat.HeaderData.GIF[0] &&
buffer[1] == ImageFormat.HeaderData.GIF[1] &&
buffer[2] == ImageFormat.HeaderData.GIF[2]
{
return .GIF
}
return .unknown
}
}
| 7b163d8d09b17efcf2657002e44820ed | 35.089744 | 82 | 0.657904 | false | false | false | false |
IngmarStein/swift | refs/heads/master | validation-test/compiler_crashers_fixed/01640-swift-typebase-getcanonicaltype.swift | apache-2.0 | 11 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -parse
protocol A : A {
typealias A {
func b: C {
func b) -> String {
}
}
extension Array {
}
class A {
}
private class B == B<c) {
}
let f == .B {
var b = {
}
}
}
}
extension A =
| 7e6d75684ab9966350bc0efae7c77b1f | 19.925926 | 78 | 0.683186 | false | false | false | false |
OneBusAway/onebusaway-iphone | refs/heads/develop | Carthage/Checkouts/swift-protobuf/Sources/protoc-gen-swift/GeneratorOptions.swift | apache-2.0 | 3 | // Sources/protoc-gen-swift/GeneratorOptions.swift - Wrapper for generator options
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
import SwiftProtobufPluginLibrary
class GeneratorOptions {
enum OutputNaming : String {
case FullPath
case PathToUnderscores
case DropPath
}
enum Visibility : String {
case Internal
case Public
}
let outputNaming: OutputNaming
let protoToModuleMappings: ProtoFileToModuleMappings
let visibility: Visibility
/// A string snippet to insert for the visibility
let visibilitySourceSnippet: String
init(parameter: String?) throws {
var outputNaming: OutputNaming = .FullPath
var moduleMapPath: String?
var visibility: Visibility = .Internal
var swiftProtobufModuleName: String? = nil
for pair in parseParameter(string:parameter) {
switch pair.key {
case "FileNaming":
if let naming = OutputNaming(rawValue: pair.value) {
outputNaming = naming
} else {
throw GenerationError.invalidParameterValue(name: pair.key,
value: pair.value)
}
case "ProtoPathModuleMappings":
if !pair.value.isEmpty {
moduleMapPath = pair.value
}
case "Visibility":
if let value = Visibility(rawValue: pair.value) {
visibility = value
} else {
throw GenerationError.invalidParameterValue(name: pair.key,
value: pair.value)
}
case "SwiftProtobufModuleName":
// This option is not documented in PLUGIN.md, because it's a feature
// that would ordinarily not be required for a given adopter.
if isValidSwiftIdentifier(pair.value) {
swiftProtobufModuleName = pair.value
} else {
throw GenerationError.invalidParameterValue(name: pair.key,
value: pair.value)
}
default:
throw GenerationError.unknownParameter(name: pair.key)
}
}
if let moduleMapPath = moduleMapPath {
do {
self.protoToModuleMappings = try ProtoFileToModuleMappings(path: moduleMapPath, swiftProtobufModuleName: swiftProtobufModuleName)
} catch let e {
throw GenerationError.wrappedError(
message: "Parameter 'ProtoPathModuleMappings=\(moduleMapPath)'",
error: e)
}
} else {
self.protoToModuleMappings = ProtoFileToModuleMappings(swiftProtobufModuleName: swiftProtobufModuleName)
}
self.outputNaming = outputNaming
self.visibility = visibility
switch visibility {
case .Internal:
visibilitySourceSnippet = ""
case .Public:
visibilitySourceSnippet = "public "
}
}
}
| 6118410e92424408ab989f5bd8104fdd | 31.431579 | 137 | 0.629017 | false | false | false | false |
huangboju/Moots | refs/heads/master | Examples/SwiftUI/Mac/RedditOS-master/RedditOs/Features/Comments/CommentRow.swift | mit | 1 | //
// CommentRow.swift
// RedditOs
//
// Created by Thomas Ricouard on 26/07/2020.
//
import SwiftUI
import Backend
struct CommentRow: View {
@StateObject private var viewModel: CommentViewModel
@State private var showUserPopover = false
init(comment: Comment) {
_viewModel = StateObject(wrappedValue: CommentViewModel(comment: comment))
}
var body: some View {
HStack(alignment: .top) {
CommentVoteView(viewModel: viewModel).padding(.top, 4)
VStack(alignment: .leading, spacing: 8) {
HStack(spacing: 0) {
HStack(spacing: 6) {
if let richText = viewModel.comment.authorFlairRichtext, !richText.isEmpty {
FlairView(richText: richText,
textColorHex: viewModel.comment.authorFlairTextColor,
backgroundColorHex: viewModel.comment.authorFlairBackgroundColor,
display: .small)
}
if let author = viewModel.comment.author {
Button(action: {
showUserPopover = true
}, label: {
HStack(spacing: 4) {
if viewModel.comment.isSubmitter == true {
Image(systemName: "music.mic")
.foregroundColor(.redditBlue)
} else {
Image(systemName: "person")
}
Text(author)
.font(.callout)
.fontWeight(.bold)
}
})
.buttonStyle(BorderlessButtonStyle())
.popover(isPresented: $showUserPopover, content: {
UserPopoverView(username: author)
})
} else {
Text("Deleted user")
.font(.footnote)
}
}
if let score = viewModel.comment.score {
Text(" · \(score.toRoundedSuffixAsString()) points · ")
.foregroundColor(.gray)
.font(.caption)
}
if let date = viewModel.comment.createdUtc {
Text(date, style: .relative)
.foregroundColor(.gray)
.font(.caption)
}
if let awards = viewModel.comment.allAwardings, !awards.isEmpty {
AwardsView(awards: awards).padding(.leading, 8)
}
}
if let body = viewModel.comment.body {
Text(body)
.font(.body)
.fixedSize(horizontal: false, vertical: true)
} else {
Text("Deleted comment")
.font(.footnote)
.foregroundColor(.gray)
}
CommentActionsView(viewModel: viewModel)
.foregroundColor(.gray)
Divider()
}.padding(.vertical, 4)
}
}
}
struct CommentRow_Previews: PreviewProvider {
static var previews: some View {
List {
CommentRow(comment: static_comment)
CommentRow(comment: static_comment)
CommentRow(comment: static_comment)
CommentRow(comment: static_comment)
}
}
}
| 10d0ce257ba83dd45097ead9a269c647 | 39.75 | 103 | 0.4182 | false | false | false | false |
WhisperSystems/Signal-iOS | refs/heads/master | Signal/src/ViewControllers/ConversationView/Cells/ThreadDetailsCell.swift | gpl-3.0 | 1 | //
// Copyright (c) 2019 Open Whisper Systems. All rights reserved.
//
import Foundation
@objc(OWSThreadDetailsCell)
public class ThreadDetailsCell: ConversationViewCell {
// MARK: -
@objc
public static let cellReuseIdentifier = "ThreadDetailsCell"
@available(*, unavailable, message:"use other constructor instead.")
@objc
public required init(coder aDecoder: NSCoder) {
notImplemented()
}
// MARK: Dependencies
var contactsManager: OWSContactsManager {
return Environment.shared.contactsManager
}
// MARK:
private let avatarContainer = UIView()
private var avatarView: ConversationAvatarImageView?
private let avatarDiameter: CGFloat = 112
private let titleLabel = UILabel()
private let detailsLabel = UILabel()
private let mutualGroupsContainer = UIView()
private let mutualGroupsLabel = UILabel()
let stackViewMargins = UIEdgeInsets(top: 8, leading: 16, bottom: 28, trailing: 16)
let stackViewSpacing: CGFloat = 3
let avatarBottomInset: CGFloat = 7
let mutualGroupsLabelTopInset: CGFloat = 11
override init(frame: CGRect) {
super.init(frame: frame)
self.layoutMargins = .zero
self.contentView.layoutMargins = .zero
avatarContainer.layoutMargins = UIEdgeInsets(top: 0, leading: 0, bottom: avatarBottomInset, trailing: 0)
titleLabel.font = UIFont.ows_dynamicTypeTitle1.ows_bold()
titleLabel.textColor = Theme.primaryColor
titleLabel.numberOfLines = 0
titleLabel.lineBreakMode = .byWordWrapping
titleLabel.textAlignment = .center
titleLabel.setContentHuggingHigh()
titleLabel.setCompressionResistanceHigh()
detailsLabel.font = .ows_dynamicTypeSubheadline
detailsLabel.textColor = Theme.secondaryColor
detailsLabel.numberOfLines = 0
detailsLabel.lineBreakMode = .byWordWrapping
detailsLabel.textAlignment = .center
detailsLabel.setContentHuggingHigh()
detailsLabel.setCompressionResistanceHigh()
mutualGroupsContainer.addSubview(mutualGroupsLabel)
mutualGroupsContainer.layoutMargins = UIEdgeInsets(top: mutualGroupsLabelTopInset, leading: 0, bottom: 0, trailing: 0)
mutualGroupsLabel.autoPinEdgesToSuperviewMargins()
mutualGroupsLabel.font = .ows_dynamicTypeSubheadline
mutualGroupsLabel.textColor = Theme.secondaryColor
mutualGroupsLabel.numberOfLines = 0
mutualGroupsLabel.lineBreakMode = .byWordWrapping
mutualGroupsLabel.textAlignment = .center
mutualGroupsLabel.setContentHuggingHigh()
mutualGroupsLabel.setCompressionResistanceHigh()
let detailsStack = UIStackView(arrangedSubviews: [
avatarContainer,
titleLabel,
detailsLabel,
mutualGroupsContainer
])
detailsStack.spacing = stackViewSpacing
detailsStack.axis = .vertical
detailsStack.isLayoutMarginsRelativeArrangement = true
detailsStack.layoutMargins = stackViewMargins
contentView.addSubview(detailsStack)
detailsStack.autoPinEdgesToSuperviewMargins()
}
@objc
public override func loadForDisplay() {
configureAvatarView()
configureTitleLabel()
configureDetailsLabel()
configureMutualGroupsLabel()
}
private func configureAvatarView() {
defer {
avatarContainer.isHidden = avatarView?.image == nil
}
guard let viewItem = self.viewItem else {
return owsFailDebug("Missing viewItem")
}
guard avatarView == nil else {
self.avatarView?.updateImage()
return
}
self.avatarView = ConversationAvatarImageView(
thread: viewItem.thread,
diameter: UInt(avatarDiameter),
contactsManager: Environment.shared.contactsManager
)
avatarContainer.addSubview(avatarView!)
avatarView?.autoSetDimension(.height, toSize: avatarDiameter)
avatarView?.autoHCenterInSuperview()
avatarView?.autoPinHeightToSuperviewMargins()
}
private func configureTitleLabel() {
var title: String?
defer {
titleLabel.text = title
titleLabel.isHidden = title == nil
}
guard let viewItem = self.viewItem else {
return owsFailDebug("Missing viewItem")
}
switch viewItem.thread {
case let groupThread as TSGroupThread:
title = groupThread.groupNameOrDefault
case let contactThread as TSContactThread:
title = Environment.shared.contactsManager.displayName(for: contactThread.contactAddress)
default:
return owsFailDebug("interaction incorrect thread type")
}
}
private func configureDetailsLabel() {
var details: String?
defer {
detailsLabel.text = details
detailsLabel.isHidden = details == nil
}
guard let viewItem = self.viewItem else {
return owsFailDebug("Missing viewItem")
}
guard let threadDetails = viewItem.interaction as? ThreadDetailsInteraction else {
return owsFailDebug("Missing threadDetails")
}
switch viewItem.thread {
case let groupThread as TSGroupThread:
let formatString = NSLocalizedString("THREAD_DETAILS_GROUP_MEMBER_COUNT_FORMAT",
comment: "The number of members in a group. Embeds {{member count}}")
details = String(format: formatString, groupThread.groupModel.groupMembers.count)
case let contactThread as TSContactThread:
let threadName = self.contactsManager.displayName(for: contactThread.contactAddress)
if let phoneNumber = contactThread.contactAddress.phoneNumber, phoneNumber != threadName {
let formattedNumber = PhoneNumber.bestEffortFormatPartialUserSpecifiedText(toLookLikeAPhoneNumber: phoneNumber)
if threadName != formattedNumber {
details = formattedNumber
}
}
if let username = viewItem.senderUsername {
if let formattedUsername = CommonFormats.formatUsername(username), threadName != formattedUsername {
if let existingDetails = details {
details = existingDetails + "\n" + formattedUsername
} else {
details = formattedUsername
}
}
}
default:
return owsFailDebug("interaction incorrect thread type")
}
}
private func configureMutualGroupsLabel() {
var attributedString: NSAttributedString?
defer {
mutualGroupsLabel.attributedText = attributedString
mutualGroupsContainer.isHidden = attributedString == nil
}
guard let viewItem = self.viewItem else {
return owsFailDebug("Missing viewItem")
}
let mutualGroupNames = viewItem.mutualGroupNames ?? []
let formatString: String
var groupsToInsert = mutualGroupNames
switch mutualGroupNames.count {
case 0:
return
case 1:
formatString = NSLocalizedString(
"THREAD_DETAILS_ONE_MUTUAL_GROUP",
comment: "A string indicating a mutual group the user shares with this contact. Embeds {{mutual group name}}"
)
case 2:
formatString = NSLocalizedString(
"THREAD_DETAILS_TWO_MUTUAL_GROUP",
comment: "A string indicating two mutual groups the user shares with this contact. Embeds {{mutual group name}}"
)
case 3:
formatString = NSLocalizedString(
"THREAD_DETAILS_THREE_MUTUAL_GROUP",
comment: "A string indicating three mutual groups the user shares with this contact. Embeds {{mutual group name}}"
)
default:
formatString = NSLocalizedString(
"THREAD_DETAILS_MORE_MUTUAL_GROUP",
comment: "A string indicating two mutual groups the user shares with this contact and that there are more unlisted. Embeds {{mutual group name}}"
)
groupsToInsert = Array(groupsToInsert[0...1])
}
var formatStringCount = formatString.components(separatedBy: "%@").count
if formatString.count > 1 { formatStringCount -= 1 }
guard formatStringCount == groupsToInsert.count else {
return owsFailDebug("Incorrect number of format characters in string")
}
let mutableAttributedString = NSMutableAttributedString(string: formatString)
// We don't use `String(format:)` so that we can make sure each group name is bold.
for groupName in groupsToInsert {
let nextInsertionPoint = (mutableAttributedString.string as NSString).range(of: "%@")
guard nextInsertionPoint.location != NSNotFound else {
return owsFailDebug("Unexpectedly tried to insert too many group names")
}
let boldGroupName = NSAttributedString(string: groupName, attributes: [.font: UIFont.ows_dynamicTypeSubheadline.ows_semiBold()])
mutableAttributedString.replaceCharacters(in: nextInsertionPoint, with: boldGroupName)
}
// We also need to insert the count if we're more than 3
if mutualGroupNames.count > 3 {
let nextInsertionPoint = (mutableAttributedString.string as NSString).range(of: "%lu")
guard nextInsertionPoint.location != NSNotFound else {
return owsFailDebug("Unexpectedly failed to insert more count")
}
mutableAttributedString.replaceCharacters(in: nextInsertionPoint, with: "\(mutualGroupNames.count - 2)")
} else if mutableAttributedString.string.range(of: "%lu") != nil {
return owsFailDebug("unexpected format string remaining in string")
}
attributedString = mutableAttributedString
}
@objc
public override func cellSize() -> CGSize {
guard let conversationStyle = self.conversationStyle else {
owsFailDebug("Missing conversationStyle")
return .zero
}
loadForDisplay()
let viewWidth = conversationStyle.viewWidth
var height: CGFloat = stackViewMargins.top + stackViewMargins.bottom
func measureHeight(label: UILabel) -> CGFloat {
return label.sizeThatFits(CGSize(
width: viewWidth - stackViewMargins.left - stackViewMargins.right,
height: .greatestFiniteMagnitude
)).height
}
if !avatarContainer.isHidden {
height += avatarDiameter + avatarBottomInset + stackViewSpacing
}
if !titleLabel.isHidden {
height += measureHeight(label: titleLabel) + stackViewSpacing
}
if !detailsLabel.isHidden {
height += measureHeight(label: detailsLabel) + stackViewSpacing
}
if !mutualGroupsContainer.isHidden {
height += measureHeight(label: mutualGroupsLabel) + mutualGroupsLabelTopInset + stackViewSpacing
}
return CGSizeCeil(CGSize(width: viewWidth, height: height))
}
public override func prepareForReuse() {
super.prepareForReuse()
avatarView?.removeFromSuperview()
avatarView = nil
}
}
| 31e410bc1bf010a054245dd6b711c257 | 35.762658 | 161 | 0.645175 | false | false | false | false |
EBGToo/SBVariables | refs/heads/master | Sources/Variable.swift | mit | 1 | //
// Variable.swift
// SBVariables
//
// Created by Ed Gamble on 10/22/15.
// Copyright © 2015 Edward B. Gamble Jr. All rights reserved.
//
// See the LICENSE file at the project root for license information.
// See the CONTRIBUTORS file at the project root for a list of contributors.
//
import SBUnits
public struct VariableDelegate<Value> {
public var canAssign = { (variable: Variable<Value>, value:Value) -> Bool in return true }
public var didAssign = { (variable: Variable<Value>, value:Value) -> Void in return }
public var didNotAssign = { (variable: Variable<Value>, value:Value) -> Void in return }
public init (
canAssign : ((_ variable: Variable<Value>, _ value:Value) -> Bool)?,
didAssign : ((_ variable: Variable<Value>, _ value:Value) -> Void)? = nil,
didNotAssign : ((_ variable: Variable<Value>, _ value:Value) -> Void)? = nil)
{
self.canAssign = canAssign ?? self.canAssign
self.didAssign = didAssign ?? self.didAssign
self.didNotAssign = didNotAssign ?? self.didNotAssign
}
public init () {}
}
///
/// A Variable is a Nameable, MonitoredObject that holds a time-series of values in a Domain. The
/// variable's value is updated when assigned; if the assigned value is not in the domain then ...;
/// if the variable's delegate returns `false` for `canAssign:variable:value` then ... If a
/// `History<Value>` is associated with the variable then upon assignemet, the history is extended.
///
public class Variable<Value> : MonitoredObject<Value>, Nameable {
/// The variable name
public let name : String
/// The variable domain
public let domain : Domain<Value>
/// The variable value
public internal(set) var value : Value
/// The variable time of last assignment
public internal(set) var time : Quantity<Time>
/// The variable delegate
public var delegate : VariableDelegate<Value>
/// The optional variable history
public internal(set) var history : History<Value>?
/// Initialize an instance. This is `Optional` because the provided `value` must be in `domain`
/// for the initialization to succeeed.
///
/// - parameter name:
/// - parameter time:
/// - parameter value:
/// - parameter domain:
/// - parameter history:
/// - parameter delegate
///
public init? (name: String, time:Quantity<Time>, value: Value, domain: Domain<Value>,
history : History<Value>? = nil,
delegate : VariableDelegate<Value> = VariableDelegate<Value>()) {
// Initialize everything - even though we've not checked domain.contains(value) yet
self.name = name
self.value = value
self.time = time;
self.domain = domain
self.delegate = delegate
self.history = history
// Required after everything initialized and before anything more.
super.init()
// Ensure `domain` contains `value`
guard domain.contains(value) else { return nil }
// Formalize the assignment
assign(value, time: time)
}
///
/// Assign `value`.
///
/// - parameter value:
/// - parameter time:
///
public func assign (_ value: Value, time:Quantity<Time>) {
guard domain.contains(value) && delegate.canAssign(self, value) else {
delegate.didNotAssign(self, value)
return
}
self.value = value
history?.extend (time, value: value)
updateMonitorsFor(value)
delegate.didAssign(self, value)
}
}
///
/// A QuantityVariable is a Variable with value of type Quantity<D> where D is an Dimension (such
/// as Length, Time or Mass).
///
public class QuantityVariable<D:SBUnits.Dimension> : Variable<Quantity<D>> {
public override init? (name: String, time:Quantity<Time>, value: Quantity<D>, domain: Domain<Quantity<D>>,
history : History<Quantity<D>>? = nil,
delegate : VariableDelegate<Quantity<D>> = VariableDelegate<Quantity<D>>()) {
super.init(name: name, time: time, value: value, domain: domain, history: history, delegate: delegate)
}
}
| a391789d60b75450805537ce0ac37b98 | 31.959016 | 108 | 0.665257 | false | false | false | false |
motoom/ios-apps | refs/heads/master | Pour3/Pour/Solver.swift | mit | 1 |
// editor-identation-style: banner
import Foundation
// Specifies how many vessels a configuration contains, and their capacity.
struct CapacitiesConfig {
var capacity: [Int] = []
}
// Idem, but their contents.
struct ContentsConfig: Hashable {
var content: [Int] = []
// http://stackoverflow.com/questions/31438210/how-to-implement-the-hashable-protocol-in-swift-for-an-int-array-a-custom-strin
var hashValue: Int {
var v = 0
for nr in content {
v <<= 4
v |= nr
}
return v
}
}
// Required for Hashable protocol.
func ==(left: ContentsConfig, right: ContentsConfig) -> Bool {
return left.content == right.content
}
// Specifies a pouring from a vessel into another.
struct Pouring {
var from: Int
var to: Int
}
// Given a specific configuration of vessels and a pouring, can the pouring be done?
func canPour(_ capacities: CapacitiesConfig, _ contents: ContentsConfig, _ pouring: Pouring) -> Bool
{
if pouring.from == pouring.to { // Can't pour a vessel into itself.
return false
}
if contents.content[pouring.from] == 0 { // Can't pour from an empty vessel.
return false;
}
if contents.content[pouring.to] >= capacities.capacity[pouring.to] { // Can't pour to a full vessel.
return false;
}
return true;
}
// Given a specific configuration of vessels and a pouring, what quantity of fluid can be transferred?
func pourableQuantity(_ capacities: CapacitiesConfig, _ contents: ContentsConfig, _ pouring: Pouring) -> Int
{
let room = capacities.capacity[pouring.to] - contents.content[pouring.to]
var quantity = contents.content[pouring.from]
if quantity > room {
quantity = room
}
return quantity
}
// Return a new contents configuration resulting from a pouring. Assumes the pouring is valid.
func performPouring(_ capacities: CapacitiesConfig, _ contents: ContentsConfig, _ pouring: Pouring) -> ContentsConfig
{
var result = ContentsConfig(content: contents.content)
let q = pourableQuantity(capacities, result, pouring)
result.content[pouring.from] -= q
result.content[pouring.to] += q
return result
}
func solve(_ capacities: CapacitiesConfig, _ contents: ContentsConfig, _ target: Int) -> [Pouring]?
{
var configs: [ContentsConfig] = [] // All reached configurations, including the given one.
var pourings: [(Int, Pouring)] = [] // Array of tuples of (source configuration index, pouring).
var processed = Set<ContentsConfig>() // Earlier processed configurations, to prevent duplicates.
configs.append(contents)
pourings.append((0, Pouring(from: 0, to: 0)))
// Generate configs until
// - target volume reached (return an array of pourings for quickest solution)
// - no more new configs found (in this case, return nil, denoting 'no solution found')
var extending = true
while extending {
extending = false // Assume we're done.
// Extend the configs array with new configs, if possible.
var index = configs.count - 1
while index >= 0 {
// The configuration to process.
let current = configs[index]
// Target present anywhere?
for c in current.content {
if c == target { // Solved!
// Traceback the necessary pourings
var solvesteps = [Pouring]()
while index != 0 {
let (fromindex, pouring) = pourings[index]
solvesteps.append(pouring)
index = fromindex
}
return solvesteps.reversed()
}
}
if processed.contains(current) {
index -= 1
continue
}
// Try all possible pourings.
for to in 0 ..< capacities.capacity.count {
for from in 0 ..< capacities.capacity.count {
let pouring = Pouring(from: from, to: to)
if !canPour(capacities, current, pouring) {
continue
}
let result = performPouring(capacities, current, pouring)
if processed.contains(result) {
continue // This configuration has been reached before, and already processed.
}
configs.append(result)
pourings.append((index, pouring))
extending = true // Apparently we're not done extending.
}
}
// Done with this one
processed.insert(current)
// Next one
index -= 1
}
}
return nil
}
func solvetest()
{
let capacities = CapacitiesConfig(capacity: [12, 7, 4])
let contents = ContentsConfig(content: [6, 4, 0])
let newcontents = performPouring(capacities, contents, Pouring(from: 0, to: 1))
assert(newcontents == ContentsConfig(content: [3, 7, 0]))
let target = 8
let res = solve(capacities, contents, target)
if let pourings = res {
print("Pourings:", pourings)
}
else {
print("No solution")
}
}
| f3e8cf4bf1c422d17408726c6b7ef05d | 32.329193 | 130 | 0.585911 | false | true | false | false |
cemolcay/MIDISequencer | refs/heads/master | Source/MIDISequencerTrack.swift | mit | 1 | //
// MIDISequencerTrack.swift
// MIDISequencer
//
// Created by Cem Olcay on 12/09/2017.
//
//
import Foundation
/// Checks equatibility of two optional `MIDISequencerTrack`s.
///
/// - Parameters:
/// - lhs: Left hand side of the equation.
/// - rhs: Right hand side of the equation.
/// - Returns: Bool value of equation.
public func ==(lhs: MIDISequencerTrack?, rhs: MIDISequencerTrack?) -> Bool {
switch (lhs, rhs) {
case (.some(let left), .some(let right)):
return left.id == right.id
default:
return false
}
}
/// Checks equatibility of two `MIDISequencerTrack`s.
///
/// - Parameters:
/// - lhs: Left hand side of the equation.
/// - rhs: Right hand side of the equation.
/// - Returns: Bool value of equation.
public func ==(lhs: MIDISequencerTrack, rhs: MIDISequencerTrack) -> Bool {
return lhs.id == rhs.id
}
/// A track that has `MIDISequencerStep`s in `MIDISequencer`.
public class MIDISequencerTrack: Equatable, Codable {
/// Unique identifier of track.
public let id: String
/// Name of track.
public var name: String
/// MIDI Channel of track to send notes to.
public var midiChannels: [Int]
/// Steps in track.
public var steps: [MIDISequencerStep]
/// Mute or unmute track.
public var isMute: Bool = false
/// Make other tracks mute if they are not on solo mode.
public var isSolo: Bool = false
/// Duration of the track in form of beats.
public var duration: Double {
return steps.map({ $0.position + $0.duration }).sorted().last ?? 0
}
/// Initilizes the track with name and optional channel and steps properties. You can always change its steps and channel after created it.
///
/// - Parameters:
/// - name: Name of track.
/// - midiChannel: Channel of track to send notes to. Defaults 0.
/// - steps: Steps in track. Defaults empty.
public init(name: String, midiChannels: [Int] = [0], steps: [MIDISequencerStep] = [], isMute: Bool = false) {
self.id = UUID().uuidString
self.name = name
self.midiChannels = midiChannels
self.steps = steps
self.isMute = isMute
}
}
| fa96748d25e3deaba1cfc2ad93d997d2 | 29.434783 | 141 | 0.666667 | false | false | false | false |
Somnibyte/MLKit | refs/heads/master | Example/Pods/Upsurge/Source/ND/Span.swift | mit | 1 | // Copyright © 2015 Venture Media Labs.
//
// 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.
/// Span is a collection of Ranges to specify a multi-dimensional slice of a Tensor.
public struct Span: ExpressibleByArrayLiteral, Sequence {
public typealias Element = CountableClosedRange<Int>
var ranges: [Element]
var startIndex: [Int] {
return ranges.map { $0.lowerBound }
}
var endIndex: [Int] {
return ranges.map { $0.upperBound + 1 }
}
var count: Int {
return dimensions.reduce(1, *)
}
var rank: Int {
return ranges.count
}
var dimensions: [Int] {
return ranges.map { $0.count }
}
init(ranges: [Element]) {
self.ranges = ranges
}
public init(arrayLiteral elements: Element...) {
self.init(ranges: elements)
}
init(base: Span, intervals: [IntervalType]) {
assert(base.contains(intervals))
var ranges = [Element]()
for i in 0..<intervals.count {
let start = intervals[i].start ?? base[i].lowerBound
let end = intervals[i].end ?? base[i].upperBound + 1
assert(base[i].lowerBound <= start && end <= base[i].upperBound + 1)
ranges.append(start ... end - 1)
}
self.init(ranges: ranges)
}
init(dimensions: [Int], intervals: [IntervalType]) {
var ranges = [Element]()
for i in 0..<intervals.count {
let start = intervals[i].start ?? 0
let end = intervals[i].end ?? dimensions[i]
assert(0 <= start && end <= dimensions[i])
ranges.append(start ... end - 1)
}
self.init(ranges: ranges)
}
init(zeroTo dimensions: [Int]) {
let start = [Int](repeating: 0, count: dimensions.count)
self.init(start: start, end: dimensions)
}
init(start: [Int], end: [Int]) {
ranges = zip(start, end).map { $0...$1 - 1 }
}
init(start: [Int], length: [Int]) {
let end = zip(start, length).map { $0 + $1 }
self.init(start: start, end: end)
}
public func makeIterator() -> SpanGenerator {
return SpanGenerator(span: self)
}
subscript(index: Int) -> Element {
return self.ranges[index]
}
subscript(range: ClosedRange<Int>) -> ArraySlice<Element> {
return self.ranges[range]
}
subscript(range: Range<Int>) -> ArraySlice<Element> {
return self.ranges[range]
}
func contains(_ other: Span) -> Bool {
for i in 0..<dimensions.count {
if other[i].startIndex < self[i].startIndex || self[i].endIndex < other[i].endIndex {
return false
}
}
return true
}
func contains(_ intervals: [IntervalType]) -> Bool {
assert(dimensions.count == intervals.count)
for i in 0..<dimensions.count {
let start = intervals[i].start ?? self[i].lowerBound
let end = intervals[i].end ?? self[i].upperBound + 1
if start < self[i].lowerBound || self[i].upperBound + 1 < end {
return false
}
}
return true
}
}
open class SpanGenerator: IteratorProtocol {
fileprivate var span: Span
fileprivate var presentIndex: [Int]
fileprivate var kill = false
init(span: Span) {
self.span = span
self.presentIndex = span.startIndex.map { $0 }
}
open func next() -> [Int]? {
return incrementIndex(presentIndex.count - 1)
}
func incrementIndex(_ position: Int) -> [Int]? {
if position < 0 || span.count <= position || kill {
return nil
} else if presentIndex[position] < span[position].upperBound {
let result = presentIndex
presentIndex[position] += 1
return result
} else {
guard let result = incrementIndex(position - 1) else {
kill = true
return presentIndex
}
presentIndex[position] = span[position].lowerBound
return result
}
}
}
// MARK: - Dimensional Congruency
infix operator ≅ : ComparisonPrecedence
public func ≅(lhs: Span, rhs: Span) -> Bool {
if lhs.dimensions == rhs.dimensions {
return true
}
let (max, min) = lhs.dimensions.count > rhs.dimensions.count ? (lhs, rhs) : (rhs, lhs)
let diff = max.dimensions.count - min.dimensions.count
return max.dimensions[0..<diff].reduce(1, *) == 1 && Array(max.dimensions[diff..<max.dimensions.count]) == min.dimensions
}
| 7bb4221d35cdbea411e126feb1403d38 | 31.346821 | 125 | 0.604539 | false | false | false | false |
yoonthinker/SSRouter | refs/heads/master | Demo/SSRouter/Router/SSRouterUtility.swift | mit | 2 | //
// SSRouterUtility.swift
// Sunshine
//
// Created by yst on 2017/5/17.
// Copyright © 2017年 jryghq. All rights reserved.
//
import UIKit
class SSRouterFetch: NSObject {
//mode of jump to the new the page
enum SSRouterPageMode {
case push, modal
}
//mode of action
//you can expand the type of action flexible
enum SSRouterActionMode: Int {
case net
}
//the type of routing operation
enum SSRouterOperation {
case page(SSRouterPageMode), action(SSRouterActionMode), unknow
}
//result of fetched from pattern
struct FetchResult {
//operation from pattern url's host
var operation: SSRouterOperation = .unknow
//parameters from pattern url's query|gragment
var params: [String: Any]?
}
//parsing the pattern
static func fetch(_ pattern: SSRouterPattern,_ params: [String: Any]? = nil) -> FetchResult {
var parameters = [String: Any]()
if params != nil { parameters += params! }
var operation: SSRouterOperation = .unknow
if let host = pattern.pHost {
switch host {
case SSRouter.pagePush:
operation = .page(.push)
break
case SSRouter.pageModal:
operation = .page(.modal)
break
case SSRouter.actionNet:
operation = .action(.net)
default:
operation = .unknow
break
}
}
if let query = pattern.pQuery {
parameters += fetchParams(query)
}
if let fragment = pattern.pFragment {
parameters += fetchParams(fragment)
}
let result = FetchResult(operation: operation, params: parameters)
return result
}
//fetch query parameters
//name=testname&age=testage -> {"name":"testname","age":"testage"}
//name=testname&age=testage&address= -> {"name":"testname","age":"testage","address":""}
static func fetchParams(_ string: String) -> [String: String] {
var params = [String: String]()
let items = string.components(separatedBy: "&")
for item in items {
let itemArray = item.components(separatedBy: "=")
if itemArray.count == 2 {
let (key, value) = (itemArray[0], itemArray[1])
params[key] = value.removingPercentEncoding
}else if itemArray.count == 1{
let key = itemArray[0]
params[key] = ""
}
}
return params
}
}
extension UIWindow {
static func rootViewController() -> UIViewController? {
let window = UIApplication.shared.keyWindow
let rootViewController = window?.rootViewController
return rootViewController
}
static func topViewController() -> UIViewController? {
return UIWindow.top(of: UIWindow.rootViewController())
}
//Returns the top most view controller from given view controller's stack.
static func top(of viewController: UIViewController? ) -> UIViewController? {
//UITabBarController
if let tabBarViewController = viewController as? UITabBarController, let selectedViewController = tabBarViewController.selectedViewController {
return self.top(of: selectedViewController)
}
//UINavigationController
if let navigationCotroller = viewController as? UINavigationController, let visibleController = navigationCotroller.visibleViewController {
return self.top(of: visibleController)
}
//presentedViewController
if let presentViewController = viewController?.presentedViewController {
return self.top(of: presentViewController)
}
//child viewController
for subView in viewController?.view?.subviews ?? [] {
if let childViewController = subView.next as? UIViewController {
return self.top(of: childViewController)
}
}
return viewController
}
}
public func += <keyType, valueType>(lhs: inout Dictionary<keyType, valueType>, rhs: Dictionary<keyType, valueType>) {
for (key, value) in rhs {
lhs[key] = value
}
}
| 437175b2f4e7f628d0951027e010093a | 29.319728 | 151 | 0.582679 | false | true | false | false |
per-dalsgaard/20-apps-in-20-weeks | refs/heads/master | App 21 - MagicalGrid/MagicalGrid/ViewController.swift | mit | 1 | //
// ViewController.swift
// MagicalGrid
//
// Created by Per Kristensen on 03/06/2017.
// Copyright © 2017 Per Dalsgaard. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
let numberOfViewPerRow = 15
let numberOfColums = 30
private var cells = [NSValue: UIView]()
override func viewDidLoad() {
super.viewDidLoad()
let width = view.frame.width / CGFloat(numberOfViewPerRow)
for y in 0...numberOfColums {
for x in 0...numberOfViewPerRow {
let cellView = UIView()
cellView.backgroundColor = randomColor()
cellView.layer.borderWidth = 0.5
cellView.layer.borderColor = UIColor.black.cgColor
cellView.frame = CGRect(x: CGFloat(x) * width, y: CGFloat(y) * width, width: width, height: width)
view.addSubview(cellView)
let point = getReferenceTypePoint(x, y)
cells[point] = cellView
}
}
view.addGestureRecognizer(UIPanGestureRecognizer(target: self, action: #selector(handlePan)))
}
var selectedCell: UIView?
func handlePan(gesture: UIPanGestureRecognizer) {
let location = gesture.location(in: view)
let width = view.frame.width / CGFloat(numberOfViewPerRow)
let x = Int(location.x / width)
let y = Int(location.y / width)
let point = getReferenceTypePoint(x, y)
guard let cellView = cells[point] else { return }
if selectedCell != cellView {
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
self.selectedCell?.layer.transform = CATransform3DIdentity
}, completion: nil)
}
selectedCell = cellView
view.bringSubview(toFront: cellView)
UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 1, options: .curveEaseOut, animations: {
cellView.layer.transform = CATransform3DMakeScale(3, 3, 3)
}, completion: nil)
if gesture.state == .ended {
UIView.animate(withDuration: 0.5, delay: 0.2, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.5, options: .curveEaseOut, animations: {
cellView.layer.transform = CATransform3DIdentity
}, completion: nil)
}
}
private func getReferenceTypePoint(_ x: Int, _ y: Int) -> NSValue {
return NSValue(cgPoint: CGPoint(x: x,y: y))
}
private func randomColor() -> UIColor {
let red = CGFloat(drand48())
let green = CGFloat(drand48())
let blue = CGFloat(drand48())
return UIColor(red: red, green: green, blue: blue, alpha: 1)
}
}
| aec91c876d065dba43a2218a9bc1e2f8 | 32.555556 | 152 | 0.57947 | false | false | false | false |
dreamsxin/swift | refs/heads/master | validation-test/compiler_crashers_2_fixed/0022-rdar21625478.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend %s -emit-silgen
import StdlibUnittest
public struct MyRange<Bound : ForwardIndex> {
var startIndex: Bound
var endIndex: Bound
}
public protocol ForwardIndex : Equatable {
associatedtype Distance : SignedNumber
func successor() -> Self
}
public protocol MySequence {
associatedtype Iterator : IteratorProtocol
associatedtype SubSequence = Void
func makeIterator() -> Iterator
var underestimatedCount: Int { get }
func map<T>(
@noescape _ transform: (Iterator.Element) -> T
) -> [T]
func filter(
@noescape _ includeElement: (Iterator.Element) -> Bool
) -> [Iterator.Element]
func _customContainsEquatableElement(
_ element: Iterator.Element
) -> Bool?
func _preprocessingPass<R>(
@noescape _ preprocess: (Self) -> R
) -> R?
func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Iterator.Element>
func _copyContents(
initializing ptr: UnsafeMutablePointer<Iterator.Element>
) -> UnsafeMutablePointer<Iterator.Element>
}
extension MySequence {
var underestimatedCount: Int {
return 0
}
public func map<T>(
@noescape _ transform: (Iterator.Element) -> T
) -> [T] {
return []
}
public func filter(
@noescape _ includeElement: (Iterator.Element) -> Bool
) -> [Iterator.Element] {
return []
}
public func _customContainsEquatableElement(
_ element: Iterator.Element
) -> Bool? {
return nil
}
public func _preprocessingPass<R>(
@noescape _ preprocess: (Self) -> R
) -> R? {
return nil
}
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Iterator.Element> {
fatalError()
}
public func _copyContents(
initializing ptr: UnsafeMutablePointer<Iterator.Element>
) -> UnsafeMutablePointer<Iterator.Element> {
fatalError()
}
}
public protocol MyIndexable : MySequence {
associatedtype Index : ForwardIndex
var startIndex: Index { get }
var endIndex: Index { get }
associatedtype _Element
subscript(_: Index) -> _Element { get }
}
public protocol MyCollection : MyIndexable {
associatedtype Iterator : IteratorProtocol = IndexingIterator<Self>
associatedtype SubSequence : MySequence
subscript(_: Index) -> Iterator.Element { get }
subscript(_: MyRange<Index>) -> SubSequence { get }
var first: Iterator.Element? { get }
var isEmpty: Bool { get }
var count: Index.Distance { get }
func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index??
}
extension MyCollection {
public var isEmpty: Bool {
return startIndex == endIndex
}
public func _preprocessingPass<R>(
@noescape _ preprocess: (Self) -> R
) -> R? {
return preprocess(self)
}
public var count: Index.Distance { return 0 }
public func _customIndexOfEquatableElement(_ element: Iterator.Element) -> Index?? {
return nil
}
}
public struct IndexingIterator<I : MyIndexable> : IteratorProtocol {
public func next() -> I._Element? {
return nil
}
}
protocol Resettable : AnyObject {
func reset()
}
internal var _allResettables: [Resettable] = []
public class TypeIndexed<Value> : Resettable {
public init(_ value: Value) {
self.defaultValue = value
_allResettables.append(self)
}
public subscript(t: Any.Type) -> Value {
get {
return byType[ObjectIdentifier(t)] ?? defaultValue
}
set {
byType[ObjectIdentifier(t)] = newValue
}
}
public func reset() { byType = [:] }
internal var byType: [ObjectIdentifier:Value] = [:]
internal var defaultValue: Value
}
//===--- LoggingWrappers.swift --------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
public protocol Wrapper {
associatedtype Base
init(_: Base)
var base: Base {get set}
}
public protocol LoggingType : Wrapper {
associatedtype Log : AnyObject
}
extension LoggingType {
public var log: Log.Type {
return Log.self
}
public var selfType: Any.Type {
return self.dynamicType
}
}
public class IteratorLog {
public static func dispatchTester<G : IteratorProtocol>(
_ g: G
) -> LoggingIterator<LoggingIterator<G>> {
return LoggingIterator(LoggingIterator(g))
}
public static var next = TypeIndexed(0)
}
public struct LoggingIterator<Base: IteratorProtocol>
: IteratorProtocol, LoggingType {
public typealias Log = IteratorLog
public init(_ base: Base) {
self.base = base
}
public mutating func next() -> Base.Element? {
Log.next[selfType] += 1
return base.next()
}
public var base: Base
}
public class SequenceLog {
public static func dispatchTester<S: MySequence>(
_ s: S
) -> LoggingSequence<LoggingSequence<S>> {
return LoggingSequence(LoggingSequence(s))
}
public static var iterator = TypeIndexed(0)
public static var underestimatedCount = TypeIndexed(0)
public static var map = TypeIndexed(0)
public static var filter = TypeIndexed(0)
public static var _customContainsEquatableElement = TypeIndexed(0)
public static var _preprocessingPass = TypeIndexed(0)
public static var _copyToNativeArrayBuffer = TypeIndexed(0)
public static var _copyContents = TypeIndexed(0)
}
public protocol LoggingSequenceType : MySequence, LoggingType {
associatedtype Base : MySequence
associatedtype Log : AnyObject = SequenceLog
associatedtype Iterator : IteratorProtocol = LoggingIterator<Base.Iterator>
}
extension LoggingSequenceType {
public var underestimatedCount: Int {
SequenceLog.underestimatedCount[selfType] += 1
return base.underestimatedCount
}
}
extension LoggingSequenceType
where Log == SequenceLog, Iterator == LoggingIterator<Base.Iterator> {
public func makeIterator() -> LoggingIterator<Base.Iterator> {
Log.iterator[selfType] += 1
return LoggingIterator(base.makeIterator())
}
public func map<T>(
@noescape _ transform: (Base.Iterator.Element) -> T
) -> [T] {
Log.map[selfType] += 1
return base.map(transform)
}
public func filter(
@noescape _ includeElement: (Base.Iterator.Element) -> Bool
) -> [Base.Iterator.Element] {
Log.filter[selfType] += 1
return base.filter(includeElement)
}
public func _customContainsEquatableElement(
_ element: Base.Iterator.Element
) -> Bool? {
Log._customContainsEquatableElement[selfType] += 1
return base._customContainsEquatableElement(element)
}
/// If `self` is multi-pass (i.e., a `Collection`), invoke
/// `preprocess` on `self` and return its result. Otherwise, return
/// `nil`.
public func _preprocessingPass<R>(
@noescape _ preprocess: (Self) -> R
) -> R? {
Log._preprocessingPass[selfType] += 1
return base._preprocessingPass { _ in preprocess(self) }
}
/// Create a native array buffer containing the elements of `self`,
/// in the same order.
public func _copyToNativeArrayBuffer()
-> _ContiguousArrayBuffer<Base.Iterator.Element> {
Log._copyToNativeArrayBuffer[selfType] += 1
return base._copyToNativeArrayBuffer()
}
/// Copy a Sequence into an array.
public func _copyContents(
initializing ptr: UnsafeMutablePointer<Base.Iterator.Element>
) -> UnsafeMutablePointer<Base.Iterator.Element> {
Log._copyContents[selfType] += 1
return base._copyContents(initializing: ptr)
}
}
public struct LoggingSequence<
Base_: MySequence
> : LoggingSequenceType, MySequence {
public typealias Log = SequenceLog
public typealias Base = Base_
public init(_ base: Base_) {
self.base = base
}
public var base: Base_
}
public class CollectionLog : SequenceLog {
public class func dispatchTester<C: MyCollection>(
_ c: C
) -> LoggingCollection<LoggingCollection<C>> {
return LoggingCollection(LoggingCollection(c))
}
static var startIndex = TypeIndexed(0)
static var endIndex = TypeIndexed(0)
static var subscriptIndex = TypeIndexed(0)
static var subscriptRange = TypeIndexed(0)
static var isEmpty = TypeIndexed(0)
static var count = TypeIndexed(0)
static var _customIndexOfEquatableElement = TypeIndexed(0)
static var first = TypeIndexed(0)
}
public protocol LoggingCollectionType : LoggingSequenceType, MyCollection {
associatedtype Base : MyCollection
associatedtype Index : ForwardIndex = Base.Index
}
extension LoggingCollectionType
where Index == Base.Index {
public var startIndex: Base.Index {
CollectionLog.startIndex[selfType] += 1
return base.startIndex
}
public var endIndex: Base.Index {
CollectionLog.endIndex[selfType] += 1
return base.endIndex
}
public subscript(position: Base.Index) -> Base.Iterator.Element {
CollectionLog.subscriptIndex[selfType] += 1
return base[position]
}
public subscript(_prext_bounds: MyRange<Base.Index>) -> Base.SubSequence {
CollectionLog.subscriptRange[selfType] += 1
return base[_prext_bounds]
}
public var isEmpty: Bool {
CollectionLog.isEmpty[selfType] += 1
return base.isEmpty
}
public var count: Base.Index.Distance {
CollectionLog.count[selfType] += 1
return base.count
}
public func _customIndexOfEquatableElement(_ element: Base.Iterator.Element) -> Base.Index?? {
CollectionLog._customIndexOfEquatableElement[selfType] += 1
return base._customIndexOfEquatableElement(element)
}
public var first: Base.Iterator.Element? {
CollectionLog.first[selfType] += 1
return base.first
}
}
public struct LoggingCollection<Base_ : MyCollection> : LoggingCollectionType {
public typealias Iterator = LoggingIterator<Base.Iterator>
public typealias Log = CollectionLog
public typealias Base = Base_
public typealias SubSequence = Base.SubSequence
public func makeIterator() -> Iterator {
return Iterator(base.makeIterator())
}
public init(_ base: Base_) {
self.base = base
}
public var base: Base_
}
public func expectCustomizable<
T : Wrapper where
T : LoggingType,
T.Base : Wrapper, T.Base : LoggingType,
T.Log == T.Base.Log
>(_: T, _ counters: TypeIndexed<Int>,
stackTrace: SourceLocStack? = nil,
file: String = #file, line: UInt = #line,
collectMoreInfo: (()->String)? = nil
) {
expectNotEqual(
0, counters[T.self], collectMoreInfo?() ?? "",
stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line)
expectEqual(
counters[T.self], counters[T.Base.self], collectMoreInfo?() ?? "",
stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line)
}
public func expectNotCustomizable<
T : Wrapper where
T : LoggingType,
T.Base : Wrapper, T.Base : LoggingType,
T.Log == T.Base.Log
>(_: T, _ counters: TypeIndexed<Int>,
stackTrace: SourceLocStack? = nil,
file: String = #file, line: UInt = #line,
collectMoreInfo: (()->String)? = nil
) {
expectNotEqual(
0, counters[T.self], collectMoreInfo?() ?? "",
stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line)
expectEqual(
0, counters[T.Base.self], collectMoreInfo?() ?? "",
stackTrace: stackTrace ?? SourceLocStack(), file: file, line: line)
}
| 81e6e8026712675887597016c2678f00 | 25.761124 | 96 | 0.690032 | false | false | false | false |
CodaFi/swift | refs/heads/main | test/Constraints/if_expr.swift | apache-2.0 | 20 | // RUN: %target-typecheck-verify-swift
func useInt(_ x: Int) {}
func useDouble(_ x: Double) {}
class B {
init() {}
}
class D1 : B {
override init() { super.init() }
}
class D2 : B {
override init() { super.init() }
}
func useB(_ x: B) {}
func useD1(_ x: D1) {}
func useD2(_ x: D2) {}
var a = true ? 1 : 0 // should infer Int
var b : Double = true ? 1 : 0 // should infer Double
var c = true ? 1 : 0.0 // should infer Double
var d = true ? 1.0 : 0 // should infer Double
useInt(a)
useDouble(b)
useDouble(c)
useDouble(d)
var z = true ? a : b // expected-error{{result values in '? :' expression have mismatching types 'Int' and 'Double'}}
var _ = a ? b : b // expected-error{{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
var e = true ? B() : B() // should infer B
var f = true ? B() : D1() // should infer B
var g = true ? D1() : B() // should infer B
var h = true ? D1() : D1() // should infer D1
var i = true ? D1() : D2() // should infer B
useB(e)
useD1(e) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}}
useB(f)
useD1(f) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}}
useB(g)
useD1(g) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}}
useB(h)
useD1(h)
useB(i)
useD1(i) // expected-error{{cannot convert value of type 'B' to expected argument type 'D1'}}
useD2(i) // expected-error{{cannot convert value of type 'B' to expected argument type 'D2'}}
var x = true ? 1 : 0
var y = 22 ? 1 : 0 // expected-error{{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
_ = x ? x : x // expected-error {{type 'Int' cannot be used as a boolean; test for '!= 0' instead}}
_ = true ? x : 1.2 // expected-error {{result values in '? :' expression have mismatching types 'Int' and 'Double'}}
_ = (x: true) ? true : false // expected-error {{cannot convert value of type '(x: Bool)' to expected condition type 'Bool'}}
_ = (x: 1) ? true : false // expected-error {{cannot convert value of type '(x: Int)' to expected condition type 'Bool'}}
let ib: Bool! = false
let eb: Bool? = .some(false)
let conditional = ib ? "Broken" : "Heart" // should infer Bool!
let conditional = eb ? "Broken" : "Heart" // expected-error {{value of optional type 'Bool?' must be unwrapped}}
// expected-note@-1{{coalesce using '??' to provide a default when the optional value contains 'nil'}}
// expected-note@-2{{force-unwrap using '!' to abort execution if the optional value contains 'nil'}}
// <rdar://problem/39586166> - crash when IfExpr has UnresolvedType in condition
struct Delegate {
var shellTasks: [ShellTask]
}
extension Array {
subscript(safe safe: Int) -> Element? {
get { }
set { }
}
}
struct ShellTask {
var commandLine: [String]
}
let delegate = Delegate(shellTasks: [])
_ = delegate.shellTasks[safe: 0]?.commandLine.compactMap({ $0.asString.hasPrefix("") ? $0 : nil }).count ?? 0
// expected-error@-1 {{value of type 'String' has no member 'asString'}}
| 721418d89b18e0a9a7b3d3ae692af5cf | 33.758621 | 125 | 0.644511 | false | false | false | false |
avito-tech/Marshroute | refs/heads/master | Marshroute/Sources/Transitions/TransitionAnimationsLaunching/AnimationsLaunching/AnimationLaunchingContextBoxes/PresentationAnimationLaunchingContextBox.swift | mit | 1 | import UIKit
/// Описание параметров запуска анимаций прямого перехода
public enum PresentationAnimationLaunchingContextBox {
case modal(launchingContext: ModalPresentationAnimationLaunchingContext)
case modalNavigation(launchingContext: ModalNavigationPresentationAnimationLaunchingContext)
case modalEndpointNavigation(launchingContext: ModalEndpointNavigationPresentationAnimationLaunchingContext)
case modalMasterDetail(launchingContext: ModalMasterDetailPresentationAnimationLaunchingContext)
case push(launchingContext: PushAnimationLaunchingContext)
case popover(launchingContext: PopoverPresentationAnimationLaunchingContext)
case popoverNavigation(launchingContext: PopoverNavigationPresentationAnimationLaunchingContext)
public var transitionsAnimatorBox: TransitionsAnimatorBox
{
switch self {
case .modal(let launchingContext):
return .modal(animator: launchingContext.animator)
case .modalNavigation(let launchingContext):
return .modalNavigation(animator: launchingContext.animator)
case .modalEndpointNavigation(let launchingContext):
return .modalEndpointNavigation(animator: launchingContext.animator)
case .modalMasterDetail(let launchingContext):
return .modalMasterDetail(animator: launchingContext.animator)
case .push(let launchingContext):
return .navigation(animator: launchingContext.animator)
case .popover(let launchingContext):
return .popover(animator: launchingContext.animator)
case .popoverNavigation(let launchingContext):
return .popoverNavigation(animator: launchingContext.animator)
}
}
public mutating func appendSourceViewController(_ sourceViewController: UIViewController)
{
switch self {
case .modal(var launchingContext):
launchingContext.sourceViewController = sourceViewController
self = .modal(launchingContext: launchingContext)
case .modalNavigation(var launchingContext):
launchingContext.sourceViewController = sourceViewController
self = .modalNavigation(launchingContext: launchingContext)
case .modalEndpointNavigation(var launchingContext):
launchingContext.sourceViewController = sourceViewController
self = .modalEndpointNavigation(launchingContext: launchingContext)
case .modalMasterDetail(var launchingContext):
launchingContext.sourceViewController = sourceViewController
self = .modalMasterDetail(launchingContext: launchingContext)
case .push(var launchingContext):
launchingContext.sourceViewController = sourceViewController
self = .push(launchingContext: launchingContext)
case .popover(var launchingContext):
launchingContext.sourceViewController = sourceViewController
self = .popover(launchingContext: launchingContext)
case .popoverNavigation(var launchingContext):
launchingContext.sourceViewController = sourceViewController
self = .popoverNavigation(launchingContext: launchingContext)
}
}
public var isDescribingScreenThatWasAlreadyDismissedWithoutInvokingMarshroute: Bool
{
switch self {
case .modal(let launchingContext):
return launchingContext.isDescribingScreenThatWasAlreadyDismissedWithoutInvokingMarshroute
case .modalNavigation(let launchingContext):
return launchingContext.isDescribingScreenThatWasAlreadyDismissedWithoutInvokingMarshroute
case .modalEndpointNavigation(let launchingContext):
return launchingContext.isDescribingScreenThatWasAlreadyDismissedWithoutInvokingMarshroute
case .modalMasterDetail(let launchingContext):
return launchingContext.isDescribingScreenThatWasAlreadyDismissedWithoutInvokingMarshroute
case .push(let launchingContext):
return launchingContext.isDescribingScreenThatWasAlreadyDismissedWithoutInvokingMarshroute
case .popover(let launchingContext):
return launchingContext.isDescribingScreenThatWasAlreadyDismissedWithoutInvokingMarshroute
case .popoverNavigation(let launchingContext):
return launchingContext.isDescribingScreenThatWasAlreadyDismissedWithoutInvokingMarshroute
}
}
}
| 325318bfb4e63ba1dcb6a32be5ccaa17 | 47.123711 | 112 | 0.721722 | false | false | false | false |
kinddevelopment/nursing-ios | refs/heads/master | NursingCommon/CKMeal.swift | apache-2.0 | 1 | //
// CKMeal.swift
// Nursing
//
// Created by Markus Svensson on 2017-03-09.
// Copyright © 2017 Markus Svensson. All rights reserved.
//
import CloudKit
import EVReflection
/**
Represents a meal/breatfeeding session with CloudKit. As CloudKit cannot
handle all data types whis intermediate class is needed between CloudKit and
the `Meal` class.
*/
class CKMeal: CKDataObject {
var duration: Int = 0
var start: Date = Date.init()
var type: Int = MealType.leftBreast.rawValue
init(meal: Meal) {
super.init()
self.duration = meal.duration
self.start = meal.start.date
self.type = meal.type.rawValue
}
required public init() {
super.init()
duration = 0
start = Date.init()
type = MealType.leftBreast.rawValue
}
}
| 975726553b61988b95f4d30b6536005c | 21.184211 | 77 | 0.628707 | false | false | false | false |
itsaboutcode/WordPress-iOS | refs/heads/develop | WordPress/Classes/Utility/BackgroundTasks/BackgroundTasksCoordinator.swift | gpl-2.0 | 1 | import BackgroundTasks
protocol BackgroundTask {
static var identifier: String { get }
// MARK: - Scheduling
/// Returns a schedule request for this task, so it can be scheduled by the coordinator.
///
func nextRunDate() -> Date?
/// This method allows the task to perform extra processing before scheduling the BG Task.
///
func willSchedule(completion: @escaping (Result<Void, Error>) -> Void)
// MARK: - Execution
func expirationHandler()
/// Runs the background task.
///
/// - Parameters:
/// - osTask: the `BGTask` associated with this `BackgroundTask`.
/// - event: called for important events in the background tasks execution.
///
func run(onError: @escaping (Error) -> Void, completion: @escaping (_ cancelled: Bool) -> Void)
}
/// Events during the execution of background tasks.
///
enum BackgroundTaskEvent {
case start(identifier: String)
case error(identifier: String, error: Error)
case expirationHandlerCalled(identifier: String)
case taskCompleted(identifier: String, cancelled: Bool)
case rescheduled(identifier: String)
}
/// An event handler for background task events.
///
protocol BackgroundTaskEventHandler {
func handle(_ event: BackgroundTaskEvent)
}
/// The task coordinator. This is the entry point for registering and scheduling background tasks.
///
class BackgroundTasksCoordinator {
enum SchedulingError: Error {
case schedulingFailed(tasksAndErrors: [String: Error])
case schedulingFailed(task: String, error: Error)
}
/// Event handler. Useful for logging or tracking purposes.
///
private let eventHandler: BackgroundTaskEventHandler
/// The task scheduler. It's a weak reference because the scheduler retains the coordinator through the
///
private let scheduler: BGTaskScheduler
/// The tasks that were registered through this coordinator on initialization.
///
private let registeredTasks: [BackgroundTask]
/// Default initializer. Immediately registers the task handlers with the scheduler.
///
/// - Parameters:
/// - scheduler: The scheduler to use.
/// - tasks: The tasks that this coordinator will manage.
///
init(
scheduler: BGTaskScheduler = BGTaskScheduler.shared,
tasks: [BackgroundTask],
eventHandler: BackgroundTaskEventHandler) {
self.eventHandler = eventHandler
self.scheduler = scheduler
self.registeredTasks = tasks
for task in tasks {
scheduler.register(forTaskWithIdentifier: type(of: task).identifier, using: nil) { osTask in
guard Feature.enabled(.weeklyRoundup) else {
osTask.setTaskCompleted(success: false)
eventHandler.handle(.taskCompleted(identifier: type(of: task).identifier, cancelled: true))
return
}
eventHandler.handle(.start(identifier: type(of: task).identifier))
osTask.expirationHandler = {
eventHandler.handle(.expirationHandlerCalled(identifier: type(of: task).identifier))
task.expirationHandler()
}
task.run(onError: { error in
eventHandler.handle(.error(identifier: type(of: task).identifier, error: error))
}) { cancelled in
eventHandler.handle(.taskCompleted(identifier: type(of: task).identifier, cancelled: cancelled))
self.schedule(task) { result in
switch result {
case .success:
eventHandler.handle(.rescheduled(identifier: type(of: task).identifier))
case .failure(let error):
eventHandler.handle(.error(identifier: type(of: task).identifier, error: error))
}
osTask.setTaskCompleted(success: !cancelled)
}
}
}
}
}
/// Schedules the registered tasks. The reason this step is separated from the registration of the tasks, is that we need
/// to make sure the task registration completes before the App finishes launching, while scheduling can be taken care
/// of separately.
///
/// Ref: https://developer.apple.com/documentation/backgroundtasks/bgtaskscheduler
///
func scheduleTasks(completion: (Result<Void, Error>) -> Void) {
var tasksAndErrors = [String: Error]()
scheduler.cancelAllTaskRequests()
for task in registeredTasks {
schedule(task) { result in
if case .failure(let error) = result {
tasksAndErrors[type(of: task).identifier] = error
}
}
}
if tasksAndErrors.isEmpty {
completion(.success(()))
} else {
completion(.failure(SchedulingError.schedulingFailed(tasksAndErrors: tasksAndErrors)))
}
}
func schedule(_ task: BackgroundTask, completion: @escaping (Result<Void, Error>) -> Void) {
guard let nextDate = task.nextRunDate() else {
return
}
let request = BGAppRefreshTaskRequest(identifier: type(of: task).identifier)
request.earliestBeginDate = nextDate
task.willSchedule(completion: completion)
do {
try self.scheduler.submit(request)
} catch {
completion(.failure(SchedulingError.schedulingFailed(task: type(of: task).identifier, error: error)))
}
}
}
| 4ff4b835a1621e706f6d1545a1cfc2f4 | 35.050955 | 126 | 0.620318 | false | false | false | false |
choofie/MusicTinder | refs/heads/master | MusicTinder/Classes/Application/Modules/ArtistDetail/ArtistDetailWireframe.swift | mit | 1 | //
// ArtistDetailWireframe.swift
// MusicTinder
//
// Created by Mate Lorincz on 12/11/16.
// Copyright © 2016 MateLorincz. All rights reserved.
//
import UIKit
protocol ArtistDetailRouter : class {
}
typealias ArtistDetailCompletion = (() -> ())?
class ArtistDetailWireframe {
weak var router : MainRouter?
fileprivate let artistDetailViewController = ArtistDetailViewController()
fileprivate var presenter: ArtistDetailPresenter?
fileprivate let completion: ArtistDetailCompletion
init(completion: ArtistDetailCompletion) {
self.completion = completion
presenter = ArtistDetailPresenter(view: artistDetailViewController, router: self)
artistDetailViewController.eventHandler = presenter
}
}
extension ArtistDetailWireframe : Wireframe {
func viewController() -> UIViewController {
return artistDetailViewController
}
}
extension ArtistDetailWireframe : PayloadHandler {
func handlePayload(_ payload: Any?) {
if let artist = payload as? Artist {
presenter?.artist = artist
}
}
}
extension ArtistDetailWireframe : ArtistDetailRouter {
}
| 08b9aa06278f627e455b0dee87dd7ca3 | 23.142857 | 89 | 0.703297 | false | false | false | false |
tal/trailcutter | refs/heads/master | Trailcutter/RouteSet.swift | mit | 1 | //
// RouteSet.swift
// Trailcutter
//
// Created by Tal Atlas on 11/27/15.
// Copyright © 2015 Range. All rights reserved.
//
import Foundation
public typealias RouteableMatchingFunc = Routeable.Type -> RouterMatch? -> RouterMatch?
private let defaultMatchers = [matchPathRouteable, matchHostRouteable, matchSchemeRouteable, matchWasMatched]
public struct RouteSet {
private let routes: [Routeable.Type]
private let matchers: [RouteableMatchingFunc]
public init(routes: [Routeable.Type], matchers: [RouteableMatchingFunc] = defaultMatchers) {
self.routes = routes
self.matchers = matchers
}
public init(routes: [Routeable.Type], additionalMatchers: [RouteableMatchingFunc]) {
let matchers = additionalMatchers + defaultMatchers
self.init(routes: routes, matchers: matchers)
}
private func matchRoute(Route: Routeable.Type, match: RouterMatch?) -> RouterMatch? {
let curriedFuncs = matchers.map { $0(Route) }
return curriedFuncs.reduce(match) { $1($0) }
}
public func match(url: NSURL) -> Routeable? {
var routeInstance:Routeable? = nil
for Route in routes {
let match = RouterMatch(url: url)
if let successfulMatch = matchRoute(Route, match: match) {
routeInstance = Route.init(routerMatch: successfulMatch)
break
}
}
return routeInstance
}
}
| 5a46b6904fea81c3d27cf64d28c0fa56 | 28.764706 | 109 | 0.631752 | false | false | false | false |
vectorform/Yarp | refs/heads/master | Source/Yarp.swift | bsd-3-clause | 1 | // Copyright (c) 2016 Vectorform LLC
// http://www.vectorform.com/
// http://github.com/vectorform/Yarp
//
// Yarp
// Yarp.swift
//
import Foundation
import SystemConfiguration
// Callback function that receives change events of network connectivity
private func reachabilityCallback(_ reachability: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) {
// This function is called on a background thread so we'll need to move to the main thread.
DispatchQueue.main.async {
// Our instance of Yarp is passed through the info parameter. If it doesn't exist there's nothing we can do.
guard let info = info else {
return
}
// Extract the yarp instance from the info paramater and set the flags so they can be checked during the handler block
let yarp = Unmanaged<Yarp>.fromOpaque(info).takeUnretainedValue()
yarp.reachabilityFlags = flags
yarp.notifyListenerOfChange()
}
}
open class Yarp {
// Notifications are sent out on reachability changes with this name.
public static let StatusChangedNotification = NSNotification.Name("com.vectorform.yarp.statusChangedNotification")
//if nil, means there has been no change in the status of your reachability
public var isReachable : Bool? {
if let flags = reachabilityFlags {
return flags.contains(.reachable)
}
return nil
}
// In addition to notifications, closures can be used to observe changes.
public typealias Handler = (Yarp) -> ()
// Yarp will hold a dictionary of Handlers indexed by a token's key(string).
fileprivate var handlers = [String : Handler]()
fileprivate var reachability: SCNetworkReachability
fileprivate var reachabilitySerialQueue: DispatchQueue?
fileprivate let isUsingIPAddress: Bool
//gets set once the reachability status changes for a given yarp object
public var reachabilityFlags: SCNetworkReachabilityFlags?
// Default init simply tests if there's an internet connection at all NOTE: does NOT shoot off an event upon starting
public init?() {
self.isUsingIPAddress = true
// Reachability treats 0.0.0.0 as a special token to monitor general routing status for IPv4 and IPv6 (information gathered from Apple's reachability)
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(to: &zeroAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return nil
}
self.reachability = reachability
}
//initialize with a custom hostname NOTE: DOES shoot off an event upon starting if you use a name (www.google.com), but does not if given the IP address ("http://216.58.195.238")
public init?(hostName: String) {
self.isUsingIPAddress = false
guard let reachability = SCNetworkReachabilityCreateWithName(nil, hostName) else {
return nil
}
self.reachability = reachability
}
//initialize with a custom reachability address (ie. "216.58.195.238" or similar)
public init?(hostAddress: String) {
self.isUsingIPAddress = true
var remoteAddress = sockaddr_in()
var remoteIPv6Address = sockaddr_in6()
if hostAddress.withCString({ cstring in inet_pton(AF_INET6, cstring, &remoteIPv6Address) }) == 1 {
// IPv6
remoteIPv6Address.sin6_len = UInt8(MemoryLayout.size(ofValue: remoteIPv6Address))
remoteIPv6Address.sin6_family = sa_family_t(AF_INET6)
guard let reachability = withUnsafePointer(to: &remoteIPv6Address, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return nil
}
self.reachability = reachability
} else if hostAddress.withCString({ cstring in inet_pton(AF_INET, cstring, &remoteAddress.sin_addr) }) == 1 {
// IPv4
remoteAddress.sin_len = UInt8(MemoryLayout.size(ofValue: remoteAddress))
remoteAddress.sin_family = sa_family_t(AF_INET)
guard let reachability = withUnsafePointer(to: &remoteAddress, {
$0.withMemoryRebound(to: sockaddr.self, capacity: 1) {
SCNetworkReachabilityCreateWithAddress(nil, $0)
}
}) else {
return nil
}
self.reachability = reachability
} else {
return nil
}
}
fileprivate func notifyListenerOfChange(){
// Send out a notification
NotificationCenter.default.post(name: Yarp.StatusChangedNotification, object: self)
// Call any handlers.
for (_, handler) in self.handlers {
handler(self)
}
}
// must call this in order to start listening for default reachability changes. Can be called multiple times
public func start() {
objc_sync_enter(self)
defer {
objc_sync_exit(self)
}
// If we already have the queue setup to process reachability events then we are done
if self.reachabilitySerialQueue != nil {
return
}
let dispatchQueue = DispatchQueue(label: "com.vectorform.yarp.reachabilitySerialQueue", attributes: [])
if !SCNetworkReachabilitySetDispatchQueue(self.reachability, dispatchQueue) {
debugPrint( "Yarp: Unable to get default reachability route" )
return
}
var context = SCNetworkReachabilityContext( version: 0, info: nil, retain: nil, release: nil, copyDescription: nil )
context.info = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque())
if !SCNetworkReachabilitySetCallback(self.reachability, reachabilityCallback, &context) {
debugPrint( "Yarp: Unable to setup reachability callback." )
return
}
self.reachabilitySerialQueue = dispatchQueue
if self.isUsingIPAddress {
var flags = SCNetworkReachabilityFlags()
SCNetworkReachabilityGetFlags(self.reachability, &flags)
self.reachabilityFlags = flags
self.notifyListenerOfChange()
}
}
// Stops the current listening of Reachability Changes and optionally clears the handlers.
public func stop(clearHandlers: Bool = false) {
objc_sync_enter(self)
defer {
objc_sync_exit(self)
}
if !SCNetworkReachabilitySetDispatchQueue(self.reachability, nil) {
debugPrint( "Yarp: Unable to set default reachability route" )
}
if !SCNetworkReachabilitySetCallback(self.reachability, nil, nil) {
debugPrint( "Yarp: Unable to setup nil reachability callback." )
}
if clearHandlers {
self.handlers.removeAll()
}
}
// Adds a listener
@discardableResult public func addHandler(_ key: String?, handler: @escaping Handler) -> String {
var token: String
if let userKey = key {
token = userKey
} else {
token = NSUUID().uuidString
}
self.handlers[token] = handler
return token
}
// Remove a Specific Handler based on your key or the one generated for you in addHandler
public func removeHandler(_ key: String) {
self.handlers.removeValue(forKey: key)
}
// Removes all handlers, but does not stop the listening events
public func removeAllHandlers() {
self.handlers.removeAll()
}
}
| 576b6e793cb7a65eee689fc61ad9e55d | 35.484581 | 182 | 0.618087 | false | false | false | false |
coach-plus/ios | refs/heads/master | Pods/NotificationBannerSwift/NotificationBanner/Classes/NotificationBanner.swift | mit | 1 | /*
The MIT License (MIT)
Copyright (c) 2017-2018 Dalton Hinterscher
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR
ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH
THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import UIKit
import SnapKit
import MarqueeLabel
@objcMembers
open class NotificationBanner: BaseNotificationBanner {
/// The bottom most label of the notification if a subtitle is provided
public private(set) var subtitleLabel: MarqueeLabel?
/// The view that is presented on the left side of the notification
private var leftView: UIView?
/// The view that is presented on the right side of the notification
private var rightView: UIView?
/// Font used for the title label
private var titleFont: UIFont = UIFont.systemFont(ofSize: 17.5, weight: UIFont.Weight.bold)
/// Font used for the subtitle label
private var subtitleFont: UIFont = UIFont.systemFont(ofSize: 15.0)
public init(title: String? = nil,
subtitle: String? = nil,
leftView: UIView? = nil,
rightView: UIView? = nil,
style: BannerStyle = .info,
colors: BannerColorsProtocol? = nil) {
super.init(style: style, colors: colors)
if let leftView = leftView {
contentView.addSubview(leftView)
let size = (leftView.frame.height > 0) ? min(44, leftView.frame.height) : 44
leftView.snp.makeConstraints({ (make) in
make.centerY.equalToSuperview().offset(heightAdjustment / 4)
make.left.equalToSuperview().offset(10)
make.size.equalTo(size)
})
}
if let rightView = rightView {
contentView.addSubview(rightView)
let size = (rightView.frame.height > 0) ? min(44, rightView.frame.height) : 44
rightView.snp.makeConstraints({ (make) in
make.centerY.equalToSuperview().offset(heightAdjustment / 4)
make.left.equalToSuperview().offset(10)
make.size.equalTo(size)
})
}
let labelsView = UIView()
contentView.addSubview(labelsView)
if let title = title {
titleLabel = MarqueeLabel()
(titleLabel as! MarqueeLabel).type = .left
titleLabel!.font = titleFont
titleLabel!.textColor = .white
titleLabel!.text = title
labelsView.addSubview(titleLabel!)
titleLabel!.snp.makeConstraints { (make) in
make.top.equalToSuperview()
make.left.equalToSuperview()
make.right.equalToSuperview()
if let _ = subtitle {
titleLabel!.numberOfLines = 1
} else {
titleLabel!.numberOfLines = 2
}
}
}
if let subtitle = subtitle {
subtitleLabel = MarqueeLabel()
subtitleLabel!.type = .left
subtitleLabel!.font = subtitleFont
subtitleLabel!.numberOfLines = 1
subtitleLabel!.textColor = .white
subtitleLabel!.text = subtitle
labelsView.addSubview(subtitleLabel!)
subtitleLabel!.snp.makeConstraints { (make) in
if title != nil {
make.top.equalTo(titleLabel!.snp.bottom).offset(2.5)
make.left.equalTo(titleLabel!)
make.right.equalTo(titleLabel!)
}
else {
make.top.equalToSuperview()
make.left.equalToSuperview()
make.right.equalToSuperview()
}
}
}
labelsView.snp.makeConstraints { (make) in
make.centerY.equalToSuperview().offset(heightAdjustment / 4)
if let leftView = leftView {
make.left.equalTo(leftView.snp.right).offset(padding)
} else {
make.left.equalToSuperview().offset(padding)
}
if let rightView = rightView {
make.right.equalTo(rightView.snp.left).offset(-padding)
} else {
make.right.equalToSuperview().offset(-padding)
}
if let subtitleLabel = subtitleLabel {
make.bottom.equalTo(subtitleLabel)
} else {
make.bottom.equalTo(titleLabel!)
}
}
updateMarqueeLabelsDurations()
}
public convenience init(attributedTitle: NSAttributedString,
attributedSubtitle: NSAttributedString? = nil,
leftView: UIView? = nil,
rightView: UIView? = nil,
style: BannerStyle = .info,
colors: BannerColorsProtocol? = nil) {
let subtitle: String? = (attributedSubtitle != nil) ? "" : nil
self.init(title: "", subtitle: subtitle, leftView: leftView, rightView: rightView, style: style, colors: colors)
titleLabel!.attributedText = attributedTitle
subtitleLabel?.attributedText = attributedSubtitle
}
public init(customView: UIView) {
super.init(style: .customView)
self.customView = customView
contentView.addSubview(customView)
customView.snp.makeConstraints { (make) in
make.edges.equalTo(contentView)
}
spacerView.backgroundColor = customView.backgroundColor
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
internal override func updateMarqueeLabelsDurations() {
super.updateMarqueeLabelsDurations()
subtitleLabel?.speed = .duration(CGFloat(duration <= 3 ? 0.5 : duration - 3))
}
}
public extension NotificationBanner {
func applyStyling(cornerRadius: CGFloat? = nil,
titleFont: UIFont? = nil,
titleColor: UIColor? = nil,
titleTextAlign: NSTextAlignment? = nil,
subtitleFont: UIFont? = nil,
subtitleColor: UIColor? = nil,
subtitleTextAlign: NSTextAlignment? = nil) {
if let cornerRadius = cornerRadius {
contentView.layer.cornerRadius = cornerRadius
}
if let titleFont = titleFont {
titleLabel!.font = titleFont
}
if let titleColor = titleColor {
titleLabel!.textColor = titleColor
}
if let titleTextAlign = titleTextAlign {
titleLabel!.textAlignment = titleTextAlign
}
if let subtitleFont = subtitleFont {
subtitleLabel!.font = subtitleFont
}
if let subtitleColor = subtitleColor {
subtitleLabel!.textColor = subtitleColor
}
if let subtitleTextAlign = subtitleTextAlign {
subtitleLabel!.textAlignment = subtitleTextAlign
}
if titleFont != nil || subtitleFont != nil {
updateBannerHeight()
}
}
}
| 38ed245121bbeb753105dd053f7f6eee | 36.075556 | 147 | 0.575282 | false | false | false | false |
Jnosh/swift | refs/heads/master | test/SILGen/copy_lvalue_peepholes.swift | apache-2.0 | 5 | // RUN: %target-swift-frontend -parse-stdlib -parse-as-library -emit-silgen %s | %FileCheck %s
precedencegroup AssignmentPrecedence { assignment: true }
typealias Int = Builtin.Int64
var zero = getInt()
func getInt() -> Int { return zero }
// CHECK-LABEL: sil hidden @_T021copy_lvalue_peepholes014init_var_from_B0{{[_0-9a-zA-Z]*}}F
// CHECK: [[X:%.*]] = alloc_box ${ var Builtin.Int64 }
// CHECK: [[PBX:%.*]] = project_box [[X]]
// CHECK: [[Y:%.*]] = alloc_box ${ var Builtin.Int64 }
// CHECK: [[PBY:%.*]] = project_box [[Y]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBX]]
// CHECK: copy_addr [[READ]] to [initialization] [[PBY]] : $*Builtin.Int64
func init_var_from_lvalue(x: Int) {
var x = x
var y = x
}
// -- Peephole doesn't apply to computed lvalues
var computed: Int {
get {
return zero
}
set {}
}
// CHECK-LABEL: sil hidden @_T021copy_lvalue_peepholes023init_var_from_computed_B0{{[_0-9a-zA-Z]*}}F
// CHECK: [[GETTER:%.*]] = function_ref @_T021copy_lvalue_peepholes8computedBi64_fg
// CHECK: [[GOTTEN:%.*]] = apply [[GETTER]]()
// CHECK: store [[GOTTEN]] to [trivial] {{%.*}}
func init_var_from_computed_lvalue() {
var y = computed
}
// CHECK-LABEL: sil hidden @_T021copy_lvalue_peepholes021assign_computed_from_B0{{[_0-9a-zA-Z]*}}F
// CHECK: [[Y:%.*]] = alloc_box
// CHECK: [[PBY:%.*]] = project_box [[Y]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBY]]
// CHECK: [[Y_VAL:%.*]] = load [trivial] [[READ]]
// CHECK: [[SETTER:%.*]] = function_ref @_T021copy_lvalue_peepholes8computedBi64_fs
// CHECK: apply [[SETTER]]([[Y_VAL]])
func assign_computed_from_lvalue(y: Int) {
var y = y
computed = y
}
// CHECK-LABEL: sil hidden @_T021copy_lvalue_peepholes24assign_var_from_computed{{[_0-9a-zA-Z]*}}F
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] %0
// CHECK: assign {{%.*}} to [[WRITE]]
func assign_var_from_computed(x: inout Int) {
x = computed
}
| ca76bd99e65630f3ae093d0175d1f18b | 33.946429 | 100 | 0.612672 | false | false | false | false |
AndreyPanov/AwesomeButton | refs/heads/master | AwesomeButton/AwesomeButton.swift | mit | 3 | //
// AwesomeButton.swift
//
// Created by Andrey Panov on 26.12.15.
// Copyright © 2015 Andrey Panov. 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 UIKit
public enum ImagePosition {
case left, right
}
private struct ButtonStyle {
struct StateAlpha {
static let normal = CGFloat(1.0)
static let highlighted = CGFloat(0.7)
static let disabled = CGFloat(0.5)
}
struct AttributedStringStyles {
static let Spacing: CGFloat = 1.2
}
static let cornerRadius: CGFloat = 5.0
static let borderWidth: CGFloat = 3.0
static let borderColor: UIColor = UIColor.lightGray
static let iconYOffset: CGFloat = 0.0
}
@IBDesignable
open class AwesomeButton: UIButton {
//MARK: Designable
@IBInspectable open var iconNormal: UIImage? {
didSet { iconConfiguration(iconNormal, iconState: UIControlState()) }
}
@IBInspectable open var iconHighlighted: UIImage? {
didSet { iconConfiguration(iconHighlighted, iconState: .highlighted) }
}
@IBInspectable open var iconSelected: UIImage? {
didSet { iconConfiguration(iconSelected, iconState: .selected) }
}
@IBInspectable open var cornerRadius: CGFloat = ButtonStyle.cornerRadius {
didSet {
layer.cornerRadius = cornerRadius
layer.masksToBounds = cornerRadius > 0
}
}
@IBInspectable open var borderWidth: CGFloat = ButtonStyle.borderWidth {
didSet { layer.borderWidth = borderWidth }
}
@IBInspectable open var borderColor: UIColor = ButtonStyle.borderColor {
didSet { layer.borderColor = borderColor.cgColor }
}
@IBInspectable open var iconYOffset: CGFloat = ButtonStyle.iconYOffset {
didSet { setNewYOffset() }
}
//MARK: Public
open var iconPosition: ImagePosition = .right {
didSet {
switchIconAndTextPosition()
}
}
open override var isHighlighted: Bool {
didSet {
if isHighlighted {
backgroundColor = backgroundColor?.withAlphaComponent(ButtonStyle.StateAlpha.highlighted)
} else {
backgroundColor = backgroundColor?.withAlphaComponent(ButtonStyle.StateAlpha.normal)
}
}
}
open override var isSelected: Bool {
didSet {
if isSelected {
backgroundColor = backgroundColor?.withAlphaComponent(ButtonStyle.StateAlpha.highlighted)
} else {
backgroundColor = backgroundColor?.withAlphaComponent(ButtonStyle.StateAlpha.normal)
}
}
}
open override var isEnabled: Bool {
didSet {
if isEnabled {
backgroundColor = backgroundColor?.withAlphaComponent(ButtonStyle.StateAlpha.normal)
} else {
backgroundColor = backgroundColor?.withAlphaComponent(ButtonStyle.StateAlpha.disabled)
}
}
}
open var textSpacing: CGFloat = ButtonStyle.AttributedStringStyles.Spacing
// store design
fileprivate var iconAttachments: [UInt : NSAttributedString] = [:]
fileprivate var attributedStrings: [UInt : NSAttributedString] = [:]
open override func awakeFromNib() {
super.awakeFromNib()
contentVerticalAlignment = .center
}
open func buttonWithIcon(_ icon: UIImage, highlightedImage: UIImage? = nil, selectedImage: UIImage? = nil, iconPosition: ImagePosition = .left, title: String = "") {
setTitle(title, for: UIControlState())
self.iconPosition = iconPosition
iconNormal = icon
iconHighlighted = highlightedImage
iconSelected = selectedImage
}
}
private extension AwesomeButton {
func iconConfiguration(_ icon: UIImage?, iconState: UIControlState) {
guard let iconUnwrapped = icon else { return }
iconAttachments[iconState.rawValue] = getAttachmentStringWithImage(iconUnwrapped, iconState: iconState)
attributedStrings[iconState.rawValue] = getAttributedStringForState(iconState)
configurateAttributedStringWithState(iconState)
}
func switchIconAndTextPosition() {
guard ((attributedStrings.isEmpty == false) || (iconAttachments.isEmpty == false)) else { return }
[UIControlState.highlighted, UIControlState.selected].forEach({ stateButton in
configurateAttributedStringWithState(stateButton)
})
}
func configurateAttributedStringWithState(_ state: UIControlState) {
let finalString = NSMutableAttributedString(string: "")
if let attachmentString = iconAttachments[state.rawValue],
let attributedString = attributedStrings[state.rawValue] {
if iconPosition == .left {
finalString.append(attachmentString)
finalString.append(attributedString)
print("Left set for state \(state)")
}
else if iconPosition == .right {
finalString.append(attributedString)
finalString.append(attachmentString)
print("Right set for state \(state)")
}
setAttributedTitle(finalString, for: state)
}
}
func getAttributedStringForState(_ buttonState: UIControlState) -> NSAttributedString {
// order of if--else statement is important here
if let titleUnwrapped = title(for: buttonState), let fontUnwrapped = titleLabel?.font, let textColor = titleColor(for: buttonState) {
return NSAttributedString(string: titleUnwrapped, attributes: [NSFontAttributeName : fontUnwrapped, NSForegroundColorAttributeName : textColor, NSKernAttributeName : ButtonStyle.AttributedStringStyles.Spacing])
}
else if let attributedTitleUnwrapped = attributedTitle(for: buttonState) {
return NSAttributedString(string: attributedTitleUnwrapped.string, attributes: attributedTitleUnwrapped.fontAttributes())
}
else {
return NSAttributedString(string: "")
}
}
func getImageForState(_ state: UIControlState) -> UIImage? {
switch (state) {
case UIControlState():
return iconNormal
case UIControlState.highlighted:
return iconHighlighted
case UIControlState.selected:
return iconSelected
default:
return nil
}
}
func calculateOffsetYForState(_ state: UIControlState) -> CGFloat {
guard let imageHeight = getImageForState(state)?.size.height else { return 0.0 }
let attr = getAttributedStringForState(state)
let imageOffsetY: CGFloat
if imageHeight > attr.fontSize() {
imageOffsetY = attr.fontOffset() - imageHeight / 2 + attr.mid()
} else {
imageOffsetY = 0
}
return imageOffsetY + iconYOffset
}
func getAttachmentStringWithImage(_ icon: UIImage, iconState: UIControlState) -> NSAttributedString {
let attachment = NSTextAttachment()
attachment.image = icon
attachment.bounds = CGRect(x: 0, y: calculateOffsetYForState(iconState), width: icon.size.width, height: icon.size.height).integral
return NSAttributedString(attachment: attachment)
}
func setNewYOffset() {
[UIControlState.highlighted, UIControlState.selected].forEach({ stateButton in
if let image = getImageForState(stateButton) {
iconConfiguration(image, iconState: stateButton)
}
})
}
}
private extension NSAttributedString {
func fontAttributes() -> [String : AnyObject] {
let limitRange = NSMakeRange(0, self.length)
if let font = self.attribute(NSFontAttributeName, at: 0, longestEffectiveRange: nil, in: limitRange) {
return [NSFontAttributeName : font as AnyObject, NSKernAttributeName : ButtonStyle.AttributedStringStyles.Spacing as AnyObject]
}
return [:]
}
func fontSize() -> CGFloat {
if let fontSize = (self.fontAttributes()[NSFontAttributeName])?.pointSize { return fontSize }
return 0.0
}
func fontOffset() -> CGFloat {
if let offset = (self.fontAttributes()[NSFontAttributeName])?.descender { return offset }
return 0.0
}
func mid() -> CGFloat {
if let font = (self.fontAttributes()[NSFontAttributeName]) { return font.descender + font.capHeight }
return 0.0
}
}
| c2ae94478869bed213eb8a2b705d563e | 36.210526 | 222 | 0.640837 | false | false | false | false |
iOSWizards/AwesomeMedia | refs/heads/master | Example/Pods/AwesomeCore/AwesomeCore/Classes/BusinessObjects/AcademyBO.swift | mit | 1 | //
// AcademyBO.swift
// AwesomeCore
//
// Created by Antonio da Silva on 30/08/2017.
//
import Foundation
public struct AcademyBO {
static var academyNS = AcademyNS.shared
private init() {}
/// Fetch Academies to a given user authenticated.
///
/// **Note: This block operation is sent back to the Main thread once its execution is done.**
///
/// - forcingUpdate: a flag used to force updating the local cache ( false by default )
/// - Parameter response: an Array of ACAcademies or in case of error
///an empty Array of ACAcademies and the proper error object with.
public static func fetchAcademies(forcingUpdate: Bool = false, response: @escaping ([ACAcademy], ErrorData?) -> Void) {
academyNS.fetchAcademies() { (academies, error) in
DispatchQueue.main.async {
response(academies, error)
}
}
}
public static func fetchMembershipAcademies(forcingUpdate: Bool = false, response: @escaping ([MembershipAcademy], ErrorData?) -> Void) {
academyNS.fetchMembershipAcademies() { (academies, error) in
DispatchQueue.main.async {
response(academies, error)
}
}
}
public static func fetchAcademy(usingAcademyId: Int, forcingUpdate: Bool = false, response: @escaping (ACAcademy?, ErrorData?) -> Void) {
academyNS.fetchAcademy(usingAcademy: usingAcademyId) { (academy, error) in
DispatchQueue.main.async {
response(academy, error)
}
}
}
public static func fetchAcademiesAsCollections(
itemsPerPage: Int,
params: AwesomeCoreNetworkServiceParams = .standard,
response: @escaping ([ACAcademy],
Int?,
ErrorData?,
AwesomeResponseType) -> Void) {
academyNS.fetchAcademiesTypedAs(.collection, itemsPerPage: itemsPerPage, params: params) { (academiesAsCollections, total, error, responseType) in
DispatchQueue.main.async {
response(academiesAsCollections, total, error, responseType)
}
}
}
public static func fetchAcademiesAsSubscriptions(
itemsPerPage: Int, forcingUpdate: Bool = false, response: @escaping ([ACAcademy], Int?, ErrorData?, AwesomeResponseType) -> Void) {
academyNS.fetchAcademiesTypedAs(.subscription, itemsPerPage: itemsPerPage) { (academiesAsSubscriptions, total, error, responseType) in
DispatchQueue.main.async {
response(academiesAsSubscriptions, total, error, responseType)
}
}
}
}
| 265b223de5ccf2c25408bf35703d0e12 | 36.828571 | 154 | 0.637462 | false | false | false | false |
openhab/openhab.ios | refs/heads/sse-monitor-and-tracker-changes | openHAB/UIAlertView+Block.swift | epl-1.0 | 1 | // Copyright (c) 2010-2022 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
import ObjectiveC
import UIKit
private var kNSCBAlertWrapper = 0
class NSCBAlertWrapper: NSObject {
var completionBlock: ((_ alertView: UIAlertView?, _ buttonIndex: Int) -> Void)?
// MARK: - UIAlertViewDelegate
// Called when a button is clicked. The view will be automatically dismissed after this call returns
func alertView(_ alertView: UIAlertView, clickedButtonAt buttonIndex: Int) {
if completionBlock != nil {
completionBlock?(alertView, buttonIndex)
}
}
// Called when we cancel a view (eg. the user clicks the Home button). This is not called when the user clicks the cancel button.
// If not defined in the delegate, we simulate a click in the cancel button
func alertViewCancel(_ alertView: UIAlertView) {
// Just simulate a cancel button click
if completionBlock != nil {
completionBlock?(alertView, alertView.cancelButtonIndex)
}
}
}
extension UIAlertView {
@objc
func show(withCompletion completion: @escaping (_ alertView: UIAlertView?, _ buttonIndex: Int) -> Void) {
let alertWrapper = NSCBAlertWrapper()
alertWrapper.completionBlock = completion
delegate = alertWrapper as AnyObject
// Set the wrapper as an associated object
objc_setAssociatedObject(self, &kNSCBAlertWrapper, alertWrapper, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC)
// Show the alert as normal
show()
}
// MARK: - Class Public
}
| b9f00c1ba33e21ffba6925667a2ed799 | 33.888889 | 133 | 0.697452 | false | false | false | false |
1amageek/Bleu | refs/heads/master | Sample/PostViewController.swift | mit | 1 | //
// PostViewController.swift
// Bleu
//
// Created by 1amageek on 2017/03/14.
// Copyright © 2017年 Stamp inc. All rights reserved.
//
import UIKit
class PostViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Bleu.removeAllReceivers()
Bleu.addReceiver(Receiver(communication: PostUserID(), post: { [weak self] (manager, request) in
let data: Data = request.value!
let text: String = String(data: data, encoding: .utf8)!
self?.peripheralTextField.text = text
manager.respond(to: request, withResult: .success)
}))
Bleu.startAdvertising()
}
deinit {
print("deinit post ViewController")
Bleu.stopAdvertising()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBOutlet weak var centralTextField: UITextField!
@IBOutlet weak var peripheralTextField: UITextField!
@IBAction func post(_ sender: Any) {
guard let text: String = self.centralTextField.text else {
return
}
let data: Data = text.data(using: .utf8)!
let request: Request = Request(communication: PostUserID()) { (peripheral, characteristic, error) in
if let error = error {
debugPrint(error)
return
}
print("success")
}
request.value = data
Bleu.send([request]) { completedRequests, error in
print("timeout")
}
}
}
| 7e40adb87731be53130e4f3de974cf12 | 27.016949 | 108 | 0.588022 | false | false | false | false |
Tsiems/mobile-sensing-apps | refs/heads/master | 06-Daily/code/Daily/IBAnimatable/ActivityIndicatorAnimationBallRotate.swift | gpl-3.0 | 5 | //
// Created by Tom Baranes on 23/08/16.
// Copyright (c) 2016 IBAnimatable. All rights reserved.
//
import UIKit
public class ActivityIndicatorAnimationBallRotate: ActivityIndicatorAnimating {
// MARK: Properties
fileprivate let duration: CFTimeInterval = 1
fileprivate let timingFunction = CAMediaTimingFunction(controlPoints: 0.7, -0.13, 0.22, 0.86)
// MARK: ActivityIndicatorAnimating
public func configureAnimation(in layer: CALayer, size: CGSize, color: UIColor) {
let circleSize: CGFloat = size.width / 5
let animation = self.animation
// Draw circles
let leftCircle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color)
let rightCircle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color)
let centerCircle = ActivityIndicatorShape.circle.makeLayer(size: CGSize(width: circleSize, height: circleSize), color: color)
leftCircle.opacity = 0.8
leftCircle.frame = CGRect(x: 0, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize)
rightCircle.opacity = 0.8
rightCircle.frame = CGRect(x: size.width - circleSize, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize)
centerCircle.frame = CGRect(x: (size.width - circleSize) / 2, y: (size.height - circleSize) / 2, width: circleSize, height: circleSize)
let circle = CALayer()
let frame = CGRect(x: (layer.bounds.size.width - size.width) / 2, y: (layer.bounds.size.height - size.height) / 2, width: size.width, height: size.height)
circle.frame = frame
circle.addSublayer(leftCircle)
circle.addSublayer(rightCircle)
circle.addSublayer(centerCircle)
circle.add(animation, forKey: "animation")
layer.addSublayer(circle)
}
}
// MARK: - Setup
private extension ActivityIndicatorAnimationBallRotate {
var animation: CAAnimationGroup {
let animation = CAAnimationGroup()
animation.animations = [scaleAnimation, rotateAnimation]
animation.duration = duration
animation.repeatCount = .infinity
animation.isRemovedOnCompletion = false
return animation
}
var scaleAnimation: CAKeyframeAnimation {
let scaleAnimation = CAKeyframeAnimation(keyPath: "transform.scale")
scaleAnimation.keyTimes = [0, 0.5, 1]
scaleAnimation.timingFunctions = [timingFunction, timingFunction]
scaleAnimation.values = [1, 0.6, 1]
scaleAnimation.duration = duration
return scaleAnimation
}
var rotateAnimation: CAKeyframeAnimation {
let rotateAnimation = CAKeyframeAnimation(keyPath:"transform.rotation.z")
rotateAnimation.keyTimes = [0, 0.5, 1]
rotateAnimation.timingFunctions = [timingFunction, timingFunction]
rotateAnimation.values = [0, CGFloat.pi, 2 * CGFloat.pi]
rotateAnimation.duration = duration
return rotateAnimation
}
}
| b18c0553117a0afad4a24b6d9caddb6a | 37.546667 | 158 | 0.73504 | false | false | false | false |
marcbaldwin/AutoLayoutBuilder | refs/heads/master | AutoLayoutBuilderTests/DimensionTests.swift | mit | 1 | import UIKit
import XCTest
@testable import AutoLayoutBuilder
class DimensionTests: ALBTestCase {
// MARK: Relative to view
func testDeclareWidthOfViewEqualToWidthOfAnotherView() {
let constraints = view1[.Width] == view2[.Width]
XCTAssertEqual([NSLayoutConstraint(view1, .Width, .Equal, view2, .Width, 1, 0)], constraints)
}
func testDeclareWidthOfViewEqualToHeightOfView() {
let constraints = view1[.Width] == view1[.Height]
XCTAssertEqual([NSLayoutConstraint(view1, .Width, .Equal, view1, .Height, 1, 0)], constraints)
}
func testDeclareHeightOfMultipleViewsEqualToHeightOfAnotherView() {
let constraints = Group(view1,view2)[.Height] == view3[.Height]
XCTAssertEqual([
NSLayoutConstraint(view1, .Height, .Equal, view3, .Height, 1, 0),
NSLayoutConstraint(view2, .Height, .Equal, view3, .Height, 1, 0)], constraints)
}
func testDeclareWidthOfViewGreaterThanOrEqualToWidthOfAnotherView() {
let constraints = view1[.Width] >= view2[.Width]
XCTAssertEqual([NSLayoutConstraint(view1, .Width, .GreaterThanOrEqual, view2, .Width, 1, 0)], constraints)
}
func testDeclareWidthOfViewLessThanOrEqualToWidthOfAnotherView() {
let constraints = view1[.Width] <= view2[.Width]
XCTAssertEqual([NSLayoutConstraint(view1, .Width, .LessThanOrEqual, view2, .Width, 1, 0)], constraints)
}
// MARK: Relative to view with constant
func testDeclareWidthOfViewEqualToWidthOfAnotherViewPlusConstant() {
let constraints = view1[.Width] == view2[.Width] + 10
XCTAssertEqual([NSLayoutConstraint(view1, .Width, .Equal, view2, .Width, 1, 10)], constraints)
}
func testDeclareWidthOfViewEqualToWidthOfAnotherViewMinusConstant() {
let constraints = view1[.Width] == view2[.Width] - 10
XCTAssertEqual([NSLayoutConstraint(view1, .Width, .Equal, view2, .Width, 1, -10)], constraints)
}
// MARK: Relative to view with multiplier
func testDeclareWidthOfViewEqualToWidthOfAnotherViewMultipliedByConstant() {
let constraints = view1[.Width] == view2[.Width] * 2
XCTAssertEqual([NSLayoutConstraint(view1, .Width, .Equal, view2, .Width, 2, 0)], constraints)
}
func testDeclareWidthOfViewEqualToWidthOfAnotherViewDividedByConstant() {
let constraints = view1[.Width] == view2[.Width] / 2
XCTAssertEqual([NSLayoutConstraint(view1, .Width, .Equal, view2, .Width, 0.5, 0)], constraints)
}
// MARK: Fixed to constant
func testDeclareWidthOfViewEqualToConstant() {
let constraints = view1[.Width] == 10
XCTAssertEqual([
NSLayoutConstraint(view1, .Width, .Equal, nil, .NotAnAttribute, 1, 10)], constraints)
}
func testDeclareWidthOfViewEqualToOrGreaterThanConstant() {
let constraints = view1[.Width] >= 10
XCTAssertEqual([NSLayoutConstraint(view1, .Width, .GreaterThanOrEqual, nil, .NotAnAttribute, 1, 10)], constraints)
}
func testDeclareWidthOfViewEqualToOrLessThanConstant() {
let constraints = view1[.Width] <= 10
XCTAssertEqual([NSLayoutConstraint(view1, .Width, .LessThanOrEqual, nil, .NotAnAttribute, 1, 10)], constraints)
}
} | 62ad28338403b1c04aa7f393d5012eb3 | 41.155844 | 122 | 0.691525 | false | true | false | false |
suzuki-0000/SKPhotoBrowser | refs/heads/master | SKPhotoBrowser/SKPagingScrollView.swift | mit | 1 | //
// SKPagingScrollView.swift
// SKPhotoBrowser
//
// Created by 鈴木 啓司 on 2016/08/18.
// Copyright © 2016年 suzuki_keishi. All rights reserved.
//
import UIKit
class SKPagingScrollView: UIScrollView {
fileprivate let pageIndexTagOffset: Int = 1000
fileprivate let sideMargin: CGFloat = 10
fileprivate var visiblePages: [SKZoomingScrollView] = []
fileprivate var recycledPages: [SKZoomingScrollView] = []
fileprivate weak var browser: SKPhotoBrowser?
var numberOfPhotos: Int {
return browser?.photos.count ?? 0
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
convenience init(frame: CGRect, browser: SKPhotoBrowser) {
self.init(frame: frame)
self.browser = browser
isPagingEnabled = true
showsHorizontalScrollIndicator = SKPhotoBrowserOptions.displayPagingHorizontalScrollIndicator
showsVerticalScrollIndicator = true
updateFrame(bounds, currentPageIndex: browser.currentPageIndex)
}
func reload() {
visiblePages.forEach({$0.removeFromSuperview()})
visiblePages.removeAll()
recycledPages.removeAll()
}
func loadAdjacentPhotosIfNecessary(_ photo: SKPhotoProtocol, currentPageIndex: Int) {
guard let browser = browser, let page = pageDisplayingAtPhoto(photo) else {
return
}
let pageIndex = (page.tag - pageIndexTagOffset)
if currentPageIndex == pageIndex {
// Previous
if pageIndex > 0 {
let previousPhoto = browser.photos[pageIndex - 1]
if previousPhoto.underlyingImage == nil {
previousPhoto.loadUnderlyingImageAndNotify()
}
}
// Next
if pageIndex < numberOfPhotos - 1 {
let nextPhoto = browser.photos[pageIndex + 1]
if nextPhoto.underlyingImage == nil {
nextPhoto.loadUnderlyingImageAndNotify()
}
}
}
}
func deleteImage() {
// index equals 0 because when we slide between photos delete button is hidden and user cannot to touch on delete button. And visible pages number equals 0
if numberOfPhotos > 0 {
visiblePages[0].captionView?.removeFromSuperview()
}
}
func jumpToPageAtIndex(_ frame: CGRect) {
let point = CGPoint(x: frame.origin.x - sideMargin, y: 0)
setContentOffset(point, animated: true)
}
func updateFrame(_ bounds: CGRect, currentPageIndex: Int) {
var frame = bounds
frame.origin.x -= sideMargin
frame.size.width += (2 * sideMargin)
self.frame = frame
if visiblePages.count > 0 {
for page in visiblePages {
let pageIndex = page.tag - pageIndexTagOffset
page.frame = frameForPageAtIndex(pageIndex)
page.setMaxMinZoomScalesForCurrentBounds()
if page.captionView != nil {
page.captionView.frame = frameForCaptionView(page.captionView, index: pageIndex)
}
}
}
updateContentSize()
updateContentOffset(currentPageIndex)
}
func updateContentSize() {
contentSize = CGSize(width: bounds.size.width * CGFloat(numberOfPhotos), height: bounds.size.height)
}
func updateContentOffset(_ index: Int) {
let pageWidth = bounds.size.width
let newOffset = CGFloat(index) * pageWidth
contentOffset = CGPoint(x: newOffset, y: 0)
}
func tilePages() {
guard let browser = browser else { return }
let firstIndex: Int = getFirstIndex()
let lastIndex: Int = getLastIndex()
visiblePages
.filter({ $0.tag - pageIndexTagOffset < firstIndex || $0.tag - pageIndexTagOffset > lastIndex })
.forEach { page in
recycledPages.append(page)
page.prepareForReuse()
page.removeFromSuperview()
}
let visibleSet: Set<SKZoomingScrollView> = Set(visiblePages)
let visibleSetWithoutRecycled: Set<SKZoomingScrollView> = visibleSet.subtracting(recycledPages)
visiblePages = Array(visibleSetWithoutRecycled)
while recycledPages.count > 2 {
recycledPages.removeFirst()
}
for index: Int in firstIndex...lastIndex {
if visiblePages.filter({ $0.tag - pageIndexTagOffset == index }).count > 0 {
continue
}
let page: SKZoomingScrollView = SKZoomingScrollView(frame: frame, browser: browser)
page.frame = frameForPageAtIndex(index)
page.tag = index + pageIndexTagOffset
let photo = browser.photos[index]
page.photo = photo
if let thumbnail = browser.animator.senderOriginImage,
index == browser.initPageIndex,
photo.underlyingImage == nil {
page.displayImage(thumbnail)
}
visiblePages.append(page)
addSubview(page)
// if exists caption, insert
if let captionView: SKCaptionView = createCaptionView(index) {
captionView.frame = frameForCaptionView(captionView, index: index)
captionView.alpha = browser.areControlsHidden() ? 0 : 1
addSubview(captionView)
// ref val for control
page.captionView = captionView
}
}
}
func frameForCaptionView(_ captionView: SKCaptionView, index: Int) -> CGRect {
let pageFrame = frameForPageAtIndex(index)
let captionSize = captionView.sizeThatFits(CGSize(width: pageFrame.size.width, height: 0))
let paginationFrame = browser?.paginationView.frame ?? .zero
let toolbarFrame = browser?.toolbar.frame ?? .zero
var frameSet = CGRect.zero
switch SKCaptionOptions.captionLocation {
case .basic:
frameSet = paginationFrame
case .bottom:
frameSet = toolbarFrame
}
return CGRect(x: pageFrame.origin.x,
y: pageFrame.size.height - captionSize.height - frameSet.height,
width: pageFrame.size.width, height: captionSize.height)
}
func pageDisplayedAtIndex(_ index: Int) -> SKZoomingScrollView? {
for page in visiblePages where page.tag - pageIndexTagOffset == index {
return page
}
return nil
}
func pageDisplayingAtPhoto(_ photo: SKPhotoProtocol) -> SKZoomingScrollView? {
for page in visiblePages where page.photo === photo {
return page
}
return nil
}
func getCaptionViews() -> Set<SKCaptionView> {
var captionViews = Set<SKCaptionView>()
visiblePages
.filter { $0.captionView != nil }
.forEach { captionViews.insert($0.captionView) }
return captionViews
}
func setControlsHidden(hidden: Bool) {
let captionViews = getCaptionViews()
let alpha: CGFloat = hidden ? 0.0 : 1.0
UIView.animate(withDuration: 0.35,
animations: { () -> Void in
captionViews.forEach { $0.alpha = alpha }
}, completion: nil)
}
}
private extension SKPagingScrollView {
func frameForPageAtIndex(_ index: Int) -> CGRect {
var pageFrame = bounds
pageFrame.size.width -= (2 * sideMargin)
pageFrame.origin.x = (bounds.size.width * CGFloat(index)) + sideMargin
return pageFrame
}
func createCaptionView(_ index: Int) -> SKCaptionView? {
if let delegate = self.browser?.delegate, let ownCaptionView = delegate.captionViewForPhotoAtIndex?(index: index) {
return ownCaptionView
}
guard let photo = browser?.photoAtIndex(index), photo.caption != nil else {
return nil
}
return SKCaptionView(photo: photo)
}
func getFirstIndex() -> Int {
let firstIndex = Int(floor((bounds.minX + sideMargin * 2) / bounds.width))
if firstIndex < 0 {
return 0
}
if firstIndex > numberOfPhotos - 1 {
return numberOfPhotos - 1
}
return firstIndex
}
func getLastIndex() -> Int {
let lastIndex = Int(floor((bounds.maxX - sideMargin * 2 - 1) / bounds.width))
if lastIndex < 0 {
return 0
}
if lastIndex > numberOfPhotos - 1 {
return numberOfPhotos - 1
}
return lastIndex
}
}
| 35ff70ade31fa93dde4f0599ffac95bb | 33.624031 | 163 | 0.585693 | false | false | false | false |
dreamsxin/swift | refs/heads/master | test/DebugInfo/protocolarg.swift | apache-2.0 | 3 | // RUN: %target-swift-frontend %s -emit-ir -g -o - | FileCheck %s
func markUsed<T>(_ t: T) {}
public protocol IGiveOutInts {
func callMe() -> Int64
}
// CHECK: define {{.*}}@_TF11protocolarg16printSomeNumbersFPS_12IGiveOutInts_T_
// CHECK: @llvm.dbg.declare(metadata %P11protocolarg12IGiveOutInts_* %
// CHECK-SAME: metadata ![[VAR:.*]], metadata ![[EMPTY:.*]])
// CHECK: @llvm.dbg.declare(metadata %P11protocolarg12IGiveOutInts_** %
// CHECK-SAME: metadata ![[ARG:.*]], metadata ![[DEREF:.*]])
// CHECK: ![[EMPTY]] = !DIExpression()
// FIXME: Should be DW_TAG_interface_type
// CHECK: ![[PT:.*]] = !DICompositeType(tag: DW_TAG_structure_type, name: "IGiveOutInts"
public func printSomeNumbers(_ gen: IGiveOutInts) {
var gen = gen
// CHECK: ![[VAR]] = !DILocalVariable(name: "gen", {{.*}} line: [[@LINE-1]]
// CHECK: ![[ARG]] = !DILocalVariable(name: "gen", arg: 1,
// CHECK-SAME: line: [[@LINE-4]], type: ![[PT]]
// CHECK: ![[DEREF]] = !DIExpression(DW_OP_deref)
markUsed(gen.callMe())
}
| 9a8c3902e1932ae4be2a7f12e04f9a7a | 38.185185 | 88 | 0.606805 | false | false | false | false |
AHuaner/Gank | refs/heads/master | Gank/Utility/AHNoDataView.swift | mit | 2 | //
// AHNoDataView.swift
// Gank
//
// Created by AHuaner on 2017/3/2.
// Copyright © 2017年 CoderAhuan. All rights reserved.
//
import UIKit
class AHNoDataView: UIView {
/// 跳转到干货界面的闭包
var goGankClouse: (() -> Void)? {
didSet {
goGankBtn.isHidden = false
}
}
fileprivate lazy var describeLabel: UILabel = {
let label = UILabel()
label.text = "还没有收藏的干货"
label.textColor = UIColorTextGray
label.font = UIFont.systemFont(ofSize: 20)
label.sizeToFit()
label.CenterX = self.CenterX
label.CenterY = self.CenterY - 50
return label
}()
fileprivate lazy var goGankBtn: UIButton = {
let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 130, height: 35))
btn.setTitle("去读干货", for: .normal)
btn.setTitleColor(UIColorTextBlue, for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 17)
btn.layer.borderColor = UIColorTextBlue.cgColor
btn.layer.borderWidth = 1
btn.layer.cornerRadius = 17.5
btn.CenterX = self.describeLabel.CenterX
btn.CenterY = self.describeLabel.CenterY + 50
btn.isHidden = true
btn.addTarget(self, action: #selector(goGankAction), for: .touchUpInside)
return btn
}()
init(describeText: String, frame: CGRect) {
super.init(frame: frame)
describeLabel.text = describeText
self.addSubview(describeLabel)
self.addSubview(goGankBtn)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func goGankAction() {
if goGankClouse != nil {
goGankClouse!()
}
}
}
| a2de634b3a66ee7d343fe6ed1e43837f | 26.307692 | 81 | 0.592113 | false | false | false | false |
BrunoMazzo/CocoaHeadsApp | refs/heads/master | CocoaHeadsApp/Classes/Base/Extensions/Unbox+Extensions.swift | mit | 3 | import UIKit
import Unbox
/**
Allow NSDate fields inside Unboxable models
*/
public class UnboxNSDateTransformer: UnboxTransformer {
public typealias RawType = Double
public typealias TransformedType = NSDate
public static func transformUnboxedValue(unboxedValue: RawType) -> TransformedType? {
let seconds = unboxedValue / 1000
let tempo = Tempo(unixOffset: seconds)
return tempo.date
}
public static func fallbackValue() -> TransformedType {
return NSDate()
}
}
extension NSDate: UnboxableByTransform {
public typealias UnboxTransformerType = UnboxNSDateTransformer
} | 1e56896583e28a98d153bc929b5e03b4 | 25.791667 | 89 | 0.721184 | false | false | false | false |
Otbivnoe/Routing | refs/heads/master | Routing/Main/MainViewController.swift | mit | 1 | //
// MainViewController.swift
// Routing
//
// Created by Nikita Ermolenko on 27/09/2017.
// Copyright © 2017 Rosberry. All rights reserved.
//
import UIKit
final class MainViewController: UIViewController {
let viewModel: MainViewModel
private lazy var segmentedControl: UISegmentedControl = {
let segmentedControl = UISegmentedControl(items: ["push", "modal", "modal(custom)", "push(custom)"])
segmentedControl.addTarget(self, action: #selector(segmentedControlValueChanged), for: .valueChanged)
segmentedControl.backgroundColor = .green
return segmentedControl
}()
private lazy var settingsButton: UIButton = {
let button = UIButton()
button.backgroundColor = .red
button.setTitle("Settings", for: .normal)
button.addTarget(self, action: #selector(settingsButtonPressed), for: .touchUpInside)
return button
}()
// MARK: - Lifecycle
init(viewModel: MainViewModel) {
self.viewModel = viewModel
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = .white
view.addSubview(settingsButton)
view.addSubview(segmentedControl)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
segmentedControl.frame = CGRect(x: 0, y: 60, width: 320, height: 50)
settingsButton.frame.size = CGSize(width: 100, height: 50)
settingsButton.center = view.center
}
// MARK: - Actions
@objc private func settingsButtonPressed(_ sender: UIButton) {
viewModel.didTriggerSettingsEvent()
}
@objc private func segmentedControlValueChanged(_ sender: UISegmentedControl) {
UserDefaults.standard.setValue(sender.selectedSegmentIndex, forKey: "index")
}
}
| 0ab705966eec9b81502a9c2c7ea18fac | 29.727273 | 109 | 0.653353 | false | false | false | false |
Ramotion/circle-menu | refs/heads/master | CircleMenuLib/CircleMenuButton/CircleMenuButton.swift | mit | 1 | //
// CircleMenuButton.swift
//
// Copyright (c) 18/01/16. Ramotion Inc. (http://ramotion.com)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
internal class CircleMenuButton: UIButton {
// MARK: properties
weak var container: UIView?
// MARK: life cycle
init(size: CGSize, platform: UIView, distance: Float, angle: Float = 0) {
super.init(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: size))
backgroundColor = UIColor(red: 0.79, green: 0.24, blue: 0.27, alpha: 1)
layer.cornerRadius = size.height / 2.0
let aContainer = createContainer(CGSize(width: size.width, height: CGFloat(distance)), platform: platform)
// hack view for rotate
let view = UIView(frame: CGRect(x: 0, y: 0, width: bounds.width, height: bounds.height))
view.backgroundColor = UIColor.clear
view.addSubview(self)
// ...
aContainer.addSubview(view)
container = aContainer
view.layer.transform = CATransform3DMakeRotation(-CGFloat(angle.degrees), 0, 0, 1)
rotatedZ(angle: angle, animated: false)
}
internal required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: configure
fileprivate func createContainer(_ size: CGSize, platform: UIView) -> UIView {
let container = customize(UIView(frame: CGRect(origin: CGPoint(x: 0, y: 0), size: size))) {
$0.backgroundColor = UIColor.clear
$0.translatesAutoresizingMaskIntoConstraints = false
$0.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
}
platform.addSubview(container)
// added constraints
let height = NSLayoutConstraint(item: container,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1,
constant: size.height)
height.identifier = "height"
container.addConstraint(height)
container.addConstraint(NSLayoutConstraint(item: container,
attribute: .width,
relatedBy: .equal,
toItem: nil,
attribute: .width,
multiplier: 1,
constant: size.width))
platform.addConstraint(NSLayoutConstraint(item: platform,
attribute: .centerX,
relatedBy: .equal,
toItem: container,
attribute: .centerX,
multiplier: 1,
constant: 0))
platform.addConstraint(NSLayoutConstraint(item: platform,
attribute: .centerY,
relatedBy: .equal,
toItem: container,
attribute: .centerY,
multiplier: 1,
constant: 0))
return container
}
// MARK: methods
internal func rotatedZ(angle: Float, animated: Bool, duration: Double = 0, delay: Double = 0) {
guard let container = self.container else {
fatalError("contaner don't create")
}
let rotateTransform = CATransform3DMakeRotation(CGFloat(angle.degrees), 0, 0, 1)
if animated {
UIView.animate(
withDuration: duration,
delay: delay,
options: UIView.AnimationOptions(),
animations: { () -> Void in
container.layer.transform = rotateTransform
},
completion: nil)
} else {
container.layer.transform = rotateTransform
}
}
}
// MARK: Animations
internal extension CircleMenuButton {
func showAnimation(distance: Float, duration: Double, delay: Double = 0) {
guard let heightConstraint = (self.container?.constraints.filter { $0.identifier == "height" })?.first else {
fatalError()
}
transform = CGAffineTransform(scaleX: 0, y: 0)
container?.superview?.layoutIfNeeded()
alpha = 0
heightConstraint.constant = CGFloat(distance)
UIView.animate(
withDuration: duration,
delay: delay,
usingSpringWithDamping: 0.7,
initialSpringVelocity: 0,
options: UIView.AnimationOptions.curveLinear,
animations: { () -> Void in
self.container?.superview?.layoutIfNeeded()
self.transform = CGAffineTransform(scaleX: 1.0, y: 1.0)
self.alpha = 1
}, completion: { (_) -> Void in
})
}
func hideAnimation(distance: Float, duration: Double, delay: Double = 0) {
guard let heightConstraint = (self.container?.constraints.filter { $0.identifier == "height" })?.first else {
return
}
heightConstraint.constant = CGFloat(distance)
UIView.animate(
withDuration: duration,
delay: delay,
options: UIView.AnimationOptions.curveEaseIn,
animations: { () -> Void in
self.container?.superview?.layoutIfNeeded()
self.transform = CGAffineTransform(scaleX: 0.01, y: 0.01)
}, completion: { (_) -> Void in
self.alpha = 0
if let _ = self.container {
self.container?.removeFromSuperview() // remove container
}
})
}
func changeDistance(_ distance: CGFloat, animated _: Bool, duration: Double = 0, delay: Double = 0) {
guard let heightConstraint = (self.container?.constraints.filter { $0.identifier == "height" })?.first else {
fatalError()
}
heightConstraint.constant = distance
UIView.animate(
withDuration: duration,
delay: delay,
options: UIView.AnimationOptions.curveEaseIn,
animations: { () -> Void in
self.container?.superview?.layoutIfNeeded()
},
completion: nil)
}
// MARK: layer animation
func rotationAnimation(_ angle: Float, duration: Double) {
let rotation = customize(CABasicAnimation(keyPath: "transform.rotation")) {
$0.duration = TimeInterval(duration)
$0.toValue = (angle.degrees)
$0.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
}
container?.layer.add(rotation, forKey: "rotation")
}
}
| 125c290f74f650a171a5e0d2fc628873 | 38.295238 | 117 | 0.543262 | false | false | false | false |
nervousnet/nervousnet-HUB-iOS | refs/heads/master | nervousnet-HUB-iOS/BasicSensorConfiguration.swift | gpl-3.0 | 1 | //
// BasicSensorConfiguration.swift
// nervousnet-HUB-iOS
//
// Created by Lewin Könemann on 11.01.17.
// Copyright © 2017 ETH Zurich - COSS. All rights reserved.
//
import Foundation
/* this the specification of the most basic Form sensorConfigurations might take in the real world*/
public class BasicSensorConfiguration : GeneralSensorConfiguration {
//I am not quite sure what the first one is for. The Array takes a number of samplingrates, which can be selected by chosing a state. More details in the constants.
public private(set) var samplingrate : Int64
public private(set) var samplingrates : [Int64]
public private(set) var state : Int
//init and set appropriate state
init(sensorID : Int64, sensorName : String, parameterDef : [String : String], samplingrates : [Int64], state: Int) {
self.samplingrate = 0
self.state = state
self.samplingrates = samplingrates
super.init(sensorID: sensorID, sensorName: sensorName, parameterDef: parameterDef)
self.setState(state: state)
}
//set at which rate the sensor will aggregate data
func setState(state : Int){
switch state{
case VMConstants.SENSOR_STATE_AVAILABLE_BUT_OFF:
self.samplingrate = -1
self.state = state
case VMConstants.SENSOR_STATE_AVAILABLE_DELAY_LOW:
self.samplingrate = samplingrates[0]
self.state = state
case VMConstants.SENSOR_STATE_AVAILABLE_DELAY_MED:
self.samplingrate = samplingrates[1]
self.state = state
case VMConstants.SENSOR_STATE_AVAILABLE_DELAY_HIGH:
self.samplingrate = samplingrates[2]
self.state = state
default:
self.state = VMConstants.SENSOR_STATE_AVAILABLE_BUT_OFF
self.samplingrate = -1
}
}
//TODO
public func getWrapperName () -> String {
return "dummyString"
}
//converts the current configuration to a string for use outside swift
public override func toString() -> String{
var returnString : String = "ConfigurationClass{"
returnString += ("sensorName=" + self.sensorName)
returnString += ("\\" + ", parametersNames=")
returnString += (", parametersNames=" + self.parameterNameToType.keys.elements.joined(separator: ", "))
returnString += (", parametersTypes=" + self.parameterNameToType.values.elements.joined(separator: ", "))
returnString += (", samplingPeriod=" + String(self.samplingrate))
returnString += "}"
return returnString
}
}
| b61962858ec040b11fa8e1c7d849faee | 36.780822 | 168 | 0.622553 | false | true | false | false |
afontanille/MetalLogo | refs/heads/master | Playground/MetalLogo.playground/Sources/MetalRenderer.swift | mit | 1 | //
// MetalRenderer.swift
// MetalLogo renderer
//
// Created by Antonin Fontanille on 21/02/2016.
// Copyright © 2016 Antonin Fontanille. All rights reserved.
//
import MetalKit
enum MetalRendererError: Error {
case LibraryNotLoaded
case BufferError
}
public class MetalRenderer : NSObject {
internal let device = MTLCreateSystemDefaultDevice()
private let commandQueue: MTLCommandQueue?
private let vertexBuffer: MTLBuffer?
private let indexBuffer: MTLBuffer?
private var uniformBuffer: MTLBuffer?
private var pipelineState: MTLRenderPipelineState?
private let drawingObject: MetalLogo = MetalLogo()
private var cameraObject = Camera()
public override init() {
guard let device = self.device else {
print("Device error")
fatalError()
}
self.commandQueue = device.makeCommandQueue()
self.vertexBuffer = device.makeBuffer(bytes: self.drawingObject.vertexData, length: MemoryLayout<Vertex>.size * self.drawingObject.vertexData.count, options: [])
let indices = self.drawingObject.indexData
self.indexBuffer = device.makeBuffer(bytes: indices, length: MemoryLayout<IndexType>.size * indices.count, options: [])
self.uniformBuffer = device.makeBuffer(length: MemoryLayout<matrix_float4x4>.size, options: [])
super.init()
do {
try self.makePipeline()
} catch {
print("Pipeline error")
fatalError()
}
}
func makePipeline() throws {
// Get our shaders from the library
let vertexFunc = try getShaderWithFunction(funcName: "vertex_project")
let fragmentFunc = try getShaderWithFunction(funcName: "fragment_flatcolor")
// Set our pipeline up
let pipelineDescriptor = MTLRenderPipelineDescriptor()
pipelineDescriptor.vertexFunction = vertexFunc
pipelineDescriptor.fragmentFunction = fragmentFunc
pipelineDescriptor.colorAttachments[0].pixelFormat = MTLPixelFormat.bgra8Unorm
// Create our render pipeline state
try self.pipelineState = self.device?.makeRenderPipelineState(descriptor: pipelineDescriptor)
}
func getShaderWithFunction(funcName: String) throws -> MTLFunction? {
let path = Bundle.main.path(forResource: "logo", ofType: "metal")
let input: String?
let library: MTLLibrary
do {
input = try String(contentsOfFile: path!, encoding: String.Encoding.utf8)
library = try device!.makeLibrary(source: input!, options: nil)
return library.makeFunction(name: funcName)
} catch {
Swift.print(error)
throw MetalRendererError.LibraryNotLoaded
}
}
func updateUniformsForView(layer: CAMetalLayer) throws {
guard let uniformBuffer = self.uniformBuffer else {
throw MetalRendererError.BufferError
}
let drawableSize = layer.drawableSize
self.cameraObject.aspect = Float(drawableSize.width / drawableSize.height)
var modelViewProjectionMatrix = self.cameraObject.modelViewProjectionMatrix
memcpy(uniformBuffer.contents(), &modelViewProjectionMatrix, MemoryLayout<matrix_float4x4>.size)
}
func drawInView(drawable: CAMetalDrawable) {
guard let commandQueue = self.commandQueue, let pipelineState = self.pipelineState else { return }
do {
try updateUniformsForView(layer: drawable.layer)
} catch {
fatalError()
}
let commandBuffer = commandQueue.makeCommandBuffer()
let passDescriptor = MTLRenderPassDescriptor()
passDescriptor.colorAttachments[0].texture = drawable.texture
passDescriptor.colorAttachments[0].loadAction = MTLLoadAction.clear
passDescriptor.colorAttachments[0].storeAction = MTLStoreAction.dontCare
passDescriptor.colorAttachments[0].clearColor = MTLClearColorMake(0.55, 0.55, 0.55, 1)
guard let commandEncoder = commandBuffer?.makeRenderCommandEncoder(descriptor: passDescriptor) else {
return
}
commandEncoder.setRenderPipelineState(pipelineState)
commandEncoder.setVertexBuffer(self.vertexBuffer, offset: 0, index: 0)
commandEncoder.setVertexBuffer(self.uniformBuffer, offset: 0, index: 1)
if let indexBuffer = self.indexBuffer {
commandEncoder.drawIndexedPrimitives(type: MTLPrimitiveType.triangle, indexCount: indexBuffer.length / MemoryLayout<IndexType>.size, indexType: MTLIndexType.uint16, indexBuffer: indexBuffer, indexBufferOffset: 0)
}
commandEncoder.endEncoding()
commandBuffer?.present(drawable)
commandBuffer?.commit()
}
}
| 0fa089aa9342677deab75526f87b3f17 | 34.265734 | 224 | 0.6512 | false | false | false | false |
saragiotto/TMDbFramework | refs/heads/master | Example/Tests/TMDbConfigurationsTest.swift | mit | 1 | //
// TMDbConfigurationsTest.swift
// TMDbFramework
//
// Created by Leonardo Augusto N Saragiotto on 09/08/17.
// Copyright © 2017 CocoaPods. All rights reserved.
//
import Foundation
import Quick
import Nimble
import TMDbFramework
class TMDbConfigurationsTest: QuickSpec {
override func spec() {
describe("Test TMDbConfigurationManager and TMDbConfiguration for Low image quality") {
let tmdbPod:TMDb = TMDb.shared
beforeEach {
tmdbPod.imageQuality = .low
tmdbPod.configurations = nil
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
tmdbPod.loadConfiguration({_ in done()})
}
}
}
it("Load Configs Low") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations).notTo(beNil())
done()
}
}
}
it("Check backdrop Low") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.backdropSize).notTo(beNil())
expect(tmdbPod.configurations!.backdropSize!).to(equal("w300"))
done()
}
}
}
it("Check logo Low") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.logoSize).notTo(beNil())
expect(tmdbPod.configurations!.logoSize!).to(equal("w45"))
done()
}
}
}
it("Check poster Low") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.posterSize).notTo(beNil())
expect(tmdbPod.configurations!.posterSize!).to(equal("w92"))
done()
}
}
}
it("Check profile Low") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.profileSize).notTo(beNil())
expect(tmdbPod.configurations!.profileSize!).to(equal("w45"))
done()
}
}
}
it("Check still Low") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.stillSize).notTo(beNil())
expect(tmdbPod.configurations!.stillSize!).to(equal("w92"))
done()
}
}
}
}
describe("Test TMDbConfigurationManager and TMDbConfiguration for Medium image quality") {
let tmdbPod:TMDb! = TMDb.shared
beforeEach {
tmdbPod.imageQuality = .medium
tmdbPod.configurations = nil
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
tmdbPod.loadConfiguration({_ in done()})
}
}
}
it("Load Configs Medium") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations).notTo(beNil())
done()
}
}
}
it("Check backdrop Medium") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.backdropSize).notTo(beNil())
expect(tmdbPod.configurations!.backdropSize!).to(equal("w780"))
done()
}
}
}
it("Check logo Medium") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.logoSize).notTo(beNil())
expect(tmdbPod.configurations!.logoSize!).to(equal("w300"))
done()
}
}
}
it("Check poster Medium") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.posterSize).notTo(beNil())
expect(tmdbPod.configurations!.posterSize!).to(equal("w500"))
done()
}
}
}
it("Check profile Medium") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.profileSize).notTo(beNil())
expect(tmdbPod.configurations!.profileSize!).to(equal("w185"))
done()
}
}
}
it("Check still Medium") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.stillSize).notTo(beNil())
expect(tmdbPod.configurations!.stillSize!).to(equal("w185"))
done()
}
}
}
}
describe("Test TMDbConfigurationManager and TMDbConfiguration for High image quality") {
let tmdbPod:TMDb! = TMDb.shared
beforeEach {
tmdbPod.imageQuality = .high
tmdbPod.configurations = nil
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
tmdbPod.loadConfiguration({_ in done()})
}
}
}
it("Load Configs High") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations).notTo(beNil())
done()
}
}
}
it("Check backdrop High") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.backdropSize).notTo(beNil())
expect(tmdbPod.configurations!.backdropSize!).to(equal("w1280"))
done()
}
}
}
it("Check logo High") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.logoSize).notTo(beNil())
expect(tmdbPod.configurations!.logoSize!).to(equal("w500"))
done()
}
}
}
it("Check poster High") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.posterSize).notTo(beNil())
expect(tmdbPod.configurations!.posterSize!).to(equal("w780"))
done()
}
}
}
it("Check profile High") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.profileSize).notTo(beNil())
expect(tmdbPod.configurations!.profileSize!).to(equal("h632"))
done()
}
}
}
it("Check still High") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.stillSize).notTo(beNil())
expect(tmdbPod.configurations!.stillSize!).to(equal("w300"))
done()
}
}
}
}
describe("Test TMDbConfigurationManager and TMDbConfiguration for VeryHigh image quality") {
let tmdbPod:TMDb! = TMDb.shared
beforeEach {
tmdbPod.imageQuality = .veryHigh
tmdbPod.configurations = nil
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
tmdbPod.loadConfiguration({_ in done()})
}
}
}
it("Load Configs VeryHigh") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations).notTo(beNil())
done()
}
}
}
it("Check backdrop VeryHigh") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.backdropSize).notTo(beNil())
expect(tmdbPod.configurations!.backdropSize!).to(equal("original"))
done()
}
}
}
it("Check logo VeryHigh") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.logoSize).notTo(beNil())
expect(tmdbPod.configurations!.logoSize!).to(equal("original"))
done()
}
}
}
it("Check poster VeryHigh") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.posterSize).notTo(beNil())
expect(tmdbPod.configurations!.posterSize!).to(equal("original"))
done()
}
}
}
it("Check profile VeryHigh") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.profileSize).notTo(beNil())
expect(tmdbPod.configurations!.profileSize!).to(equal("original"))
done()
}
}
}
it("Check still VeryHigh") {
waitUntil(timeout: 12.0) { done in
DispatchQueue.global(qos: .background).async {
expect(tmdbPod.configurations!.stillSize).notTo(beNil())
expect(tmdbPod.configurations!.stillSize!).to(equal("original"))
done()
}
}
}
}
}
}
| 6210b630abcbe627f236ca59e1f0906c | 37.200608 | 100 | 0.423377 | false | true | false | false |
xuech/OMS-WH | refs/heads/master | OMS-WH/Utilities/Libs/XCHPageControl/XCHPageNormal.swift | mit | 1 | //
// XCHPageNormal.swift
// PageControl
//
// Created by xuech on 2017/7/26.
// Copyright © 2017年 xuech. All rights reserved.
//
import UIKit
class XCHPageNormal: UIView {
var numberOfPage: Int = 0, currentOfPage: Int = 0
var f_start_point: CGFloat = 0.0, f_start: CGFloat = 0.0
required init(coder aDecoder: NSCoder) {
super.init(coder:aDecoder)!
}
override init(frame:CGRect) {
super.init(frame:frame)
}
override func layoutSubviews() {
super.layoutSubviews()
}
func setup(_ page: Int, current: Int, tintColor: UIColor) {
numberOfPage = page
currentOfPage = current
let f_all_width: CGFloat = CGFloat((numberOfPage-1)*20 + 25)
guard f_all_width < self.frame.size.width else {
print("frame.Width over Number Of Page")
return
}
var f_width: CGFloat = 10.0, f_height: CGFloat = 10.0
var f_x: CGFloat = (self.frame.size.width-f_all_width)/2.0, f_y: CGFloat = (self.frame.size.height-f_height)/2.0
f_start_point = f_x
for i in 0 ..< numberOfPage {
let img_page = UIImageView()
if i == currentOfPage {
f_width = 25.0
img_page.alpha = 1.0
} else {
f_width = 10.0
img_page.alpha = 0.4
}
img_page.frame = CGRect(x: f_x, y: f_y, width: f_width, height: f_height)
img_page.layer.cornerRadius = img_page.frame.size.height/2.0
img_page.backgroundColor = tintColor
img_page.tag = i+10
self.addSubview(img_page)
f_x += f_width + 10
}
}
func scroll_did(_ scrollView: UIScrollView) {
let f_page = scrollView.contentOffset.x / scrollView.frame.size.width
let tag_value = get_imgView_tag(f_page)+10
let f_next_start: CGFloat = (CGFloat(tag_value-10) * scrollView.frame.size.width)
let f_move: CGFloat = (15*(f_start-scrollView.contentOffset.x)/scrollView.frame.size.width)
let f_alpha: CGFloat = (0.6*(scrollView.contentOffset.x-f_next_start)/scrollView.frame.size.width)
if let iv_page: UIImageView = self.viewWithTag(tag_value) as? UIImageView, tag_value >= 10 && tag_value+1 < 10+numberOfPage {
iv_page.frame = CGRect(x: f_start_point+((CGFloat(tag_value)-10)*20),
y: iv_page.frame.origin.y,
width: 25+(f_move+((CGFloat(tag_value)-10)*15)),
height: iv_page.frame.size.height)
iv_page.alpha = 1-f_alpha
if let iv_page_next: UIImageView = self.viewWithTag(tag_value+1) as? UIImageView {
let f_page_next_x: CGFloat = ((f_start_point+35)+((CGFloat(tag_value)-10)*20))
iv_page_next.frame = CGRect(x: f_page_next_x+(f_move+((CGFloat(tag_value)-10)*15)),
y: iv_page_next.frame.origin.y,
width: 10-(f_move+((CGFloat(tag_value)-10)*15)),
height: iv_page_next.frame.size.height)
iv_page_next.alpha = 0.4+f_alpha
}
}
}
func get_imgView_tag(_ f_page: CGFloat) -> Int {
let f_temp = f_page - 0.02
return Int(f_temp)
}
}
| 8884d6ad55b7e3c35e75e887805c4125 | 34.828283 | 133 | 0.51903 | false | false | false | false |
psharanda/vmc2 | refs/heads/master | 7. SilverMVC/SilverMVCTests/TestContext.swift | mit | 1 | //
// Created by Pavel Sharanda on 20.11.16.
// Copyright © 2016 psharanda. All rights reserved.
//
import UIKit
class TestTextLoader: TextLoaderProtocol {
let text: String
init(text: String) {
self.text = text
}
func loadText(completion: @escaping (String) -> Void) {
completion(text)
}
}
class TestMainView: TestView, MainViewProtocol {
var loadClick = Signal<Void>()
var detailsClick = Signal<Void>()
var state = MainViewState()
var viewController: UIViewController {
fatalError()
}
}
class TestDetailsView: TestView, DetailsViewProtocol {
let text: String
init(text: String) {
self.text = text
}
var viewController: UIViewController {
fatalError()
}
}
class TestContext: AppContext {
struct Config {
var text = "Hello"
}
let config: Config
init(config: Config) {
self.config = config
}
func makeTextLoader() -> TextLoaderProtocol {
return TestTextLoader(text: config.text)
}
func makeMainView() -> MainViewProtocol {
return TestMainView()
}
func makeNavigationView() -> NavigationView {
return TestNavigationView()
}
func makeWindow() -> Window {
return TestWindow()
}
func makeDetailsView(text: String) -> DetailsViewProtocol {
return TestDetailsView(text: text)
}
}
| 7c8ee9272f876c0dced716dee97887e8 | 18.945205 | 63 | 0.605082 | false | true | false | false |
svachmic/ios-url-remote | refs/heads/master | URLRemote/Classes/Controllers/IconCollectionViewController.swift | apache-2.0 | 1 | //
// IconCollectionViewController.swift
// URLRemote
//
// Created by Michal Švácha on 10/01/17.
// Copyright © 2017 Svacha, Michal. All rights reserved.
//
import UIKit
import Material
import Bond
import ReactiveKit
/// View controller taking care of icon selection.
class IconCollectionViewController: UICollectionViewController, Dismissable {
let viewModel = IconCollectionViewModel()
override func viewDidLoad() {
super.viewDidLoad()
self.collectionView?.backgroundColor = UIColor(named: .gray)
self.setupBar()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func viewDidLayoutSubviews() {
let viewFrame = self.view.frame
if let collectionFrame = self.collectionView?.frame, viewFrame.height < collectionFrame.height {
self.collectionView?.frame = CGRect(
x: collectionFrame.origin.x,
y: collectionFrame.origin.y,
width: collectionFrame.width,
height: viewFrame.height)
}
}
// MARK: - Setup
/// Sets up all the buttons in the toolbar.
func setupBar() {
setupDismissButton(with: .cancel)
let done = MaterialFactory.genericIconButton(image: Icon.cm.check)
combineLatest(viewModel.initialSelection, viewModel.userSelection)
.map { $0 != $1 }
.bind(to: done.reactive.isEnabled)
.dispose(in: bag)
done.reactive.tap.bind(to: self) { me, _ in
me.viewModel.done()
self.parent?.dismiss(animated: true, completion: nil)
}.dispose(in: bag)
self.toolbarController?.toolbar.rightViews = [done]
self.toolbarController?.toolbar.titleLabel.textColor = .white
self.toolbarController?.toolbar.title = NSLocalizedString("SELECT_ICON", comment: "")
}
// MARK: UICollectionViewDataSource
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return viewModel.contents.sections.count
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return viewModel.contents[section].items.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(
withReuseIdentifier: Constants.CollectionViewCell.iconCell,
for: indexPath) as! IconCollectionViewCell
cell.backgroundColor = viewModel.iconColor
let imageName = viewModel.contents[indexPath.section].items[indexPath.row]
cell.setIcon(named: imageName)
cell.setIsHighlighted(viewModel.userSelection.value == indexPath)
return cell
}
override func collectionView(_ collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, at indexPath: IndexPath) -> UICollectionReusableView {
let cell = collectionView.dequeueReusableSupplementaryView(
ofKind: UICollectionElementKindSectionHeader,
withReuseIdentifier: Constants.CollectionViewCell.iconsSection,
for: indexPath) as! IconSectionCollectionReusableView
cell.sectionNameLabel.text = NSLocalizedString(viewModel.contents[indexPath.section].metadata, comment: "")
return cell
}
// MARK: UICollectionViewDelegate
override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
viewModel.userSelection.value = indexPath
collectionView.reloadData()
}
}
extension IconCollectionViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: 90, height: 90)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize {
return CGSize(width: self.view.frame.size.width, height: 30)
}
}
| 792232df63e059509af62d881865bee7 | 38.640351 | 171 | 0.693516 | false | false | false | false |
beepscore/RunsLister | refs/heads/master | RunsLister/Run.swift | mit | 1 | //
// Run.swift
// RunsLister
//
// Created by Steve Baker on 2/26/15.
// Copyright (c) 2015 Beepscore LLC. All rights reserved.
//
import Foundation
class Run : Equatable {
var startIndex: Int
var stopIndex: Int
init(startIndex: Int, stopIndex: Int) {
self.startIndex = startIndex
self.stopIndex = stopIndex
}
}
extension Run : CustomStringConvertible, CustomDebugStringConvertible {
var description : String {
return "startIndex: \(self.startIndex) stopIndex: \(self.stopIndex)\n"
}
var debugDescription : String {
return self.description
}
}
// function scope to compare two Run must be outside class Run
func == (lhs: Run, rhs: Run) -> Bool {
return ((lhs.startIndex == rhs.startIndex)
&& (lhs.stopIndex == rhs.stopIndex))
}
func != (lhs: Run, rhs: Run) -> Bool {
return ((lhs.startIndex != rhs.startIndex)
|| (lhs.stopIndex != rhs.stopIndex))
}
| 35510d601cd3d2009b79afd09cf75b55 | 22.170732 | 78 | 0.641053 | false | false | false | false |
1000tip/caravel | refs/heads/master | caravel/Caravel.swift | mit | 2 | //
// Bus.swift
// todolist
//
// Created by Adrien on 23/05/15.
// Copyright (c) 2015 test. All rights reserved.
//
import Foundation
import UIKit
/**
* @class Caravel
* @brief Main class of the library. The only public one.
* Manages all buses and dispatches actions to other components.
*/
public class Caravel: NSObject, UIWebViewDelegate {
private static let DEFAULT_BUS_NAME = "default"
/**
* Default Bus
*/
private static var _default: Caravel?
private static var _buses: [Caravel] = [Caravel]()
private var _name: String
/**
* Bus subscribers
*/
private lazy var _subscribers: [Subscriber] = [Subscriber]()
/**
* Denotes if the bus has received the init event from JS
*/
private var _isInitialized: Bool
// Multithreading locks
private static var _defaultInitLock = NSObject()
private static var _namedBusInitLock = NSObject()
/**
* Pending initialization subscribers
*/
private lazy var _initializers: [(Caravel) -> Void] = []
// Initializers are temporary saved in order to prevent them to be garbage
// collected
private lazy var _onGoingInitializers: [Int: ((Caravel) -> Void)] = [:]
private lazy var _onGoingInitializersId = 0
private var _webView: UIWebView
private init(name: String, webView: UIWebView) {
self._name = name
self._isInitialized = false
self._webView = webView
super.init()
UIWebViewDelegateMediator.subscribe(self._webView, subscriber: self)
}
/**
* Sends event to JS
*/
private func _post(eventName: String, eventData: AnyObject?, type: SupportedType?) {
var toRun: String?
var data: String?
if let d: AnyObject = eventData {
data = DataSerializer.serialize(d, type: type!)
} else {
data = "null"
}
if _name == "default" {
toRun = "Caravel.getDefault().raise(\"\(eventName)\", \(data!))"
} else {
toRun = "Caravel.get(\"\(_name)\").raise(\"\(eventName)\", \(data!))"
}
dispatch_async(dispatch_get_main_queue()) {
self._webView.stringByEvaluatingJavaScriptFromString(toRun!)
}
}
/**
* If the controller is resumed, the webView may have changed.
* Caravel has to watch this new component again
*/
internal func setWebView(webView: UIWebView) {
if webView.hash == _webView.hash {
return
}
// whenReady() should be triggered only after a CaravelInit event
// has been raised (aka wait for JS before calling whenReady)
_isInitialized = false
_webView = webView
UIWebViewDelegateMediator.subscribe(_webView, subscriber: self)
}
internal func synchronized(action: () -> Void) {
let lock = (_name == Caravel.DEFAULT_BUS_NAME) ? Caravel._defaultInitLock : Caravel._namedBusInitLock
objc_sync_enter(lock)
action()
objc_sync_exit(lock)
}
public var name: String {
return _name
}
/**
* Caravel expects the following pattern:
* caravel://host.com?busName=*&eventName=*&eventData=*
*
* Followed argument types are supported:
* int, float, double, string
*/
public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if let scheme: String = request.URL?.scheme {
if scheme == "caravel" {
let args = ArgumentParser.parse(request.URL!.query!)
// All buses are notified about that incoming event. Then, they need to investigate first if they
// are potential receivers
if _name == args.busName {
if args.eventName == "CaravelInit" { // Reserved event name. Triggers whenReady
if !_isInitialized {
synchronized() {
if !self._isInitialized {
self._isInitialized = true
for i in self._initializers {
let index = self._onGoingInitializersId
self._onGoingInitializers[index] = i
self._onGoingInitializersId++
dispatch_async(dispatch_get_main_queue()) {
i(self)
self._onGoingInitializers.removeValueForKey(index)
}
}
self._initializers = Array<(Caravel) -> Void>()
}
}
}
} else {
var eventData: AnyObject? = nil
if let d = args.eventData { // Data are optional
eventData = DataSerializer.deserialize(d)
}
for s in _subscribers {
if s.name == args.eventName {
dispatch_async(dispatch_get_main_queue()) {
s.callback(args.eventName, eventData)
}
}
}
}
}
// As it is a custom URL, we need to prevent the webview to run it
return false
}
return true
}
return true
}
/**
* Returns the current bus when its JS counterpart is ready
*/
public func whenReady(callback: (Caravel) -> Void) {
if _isInitialized {
dispatch_async(dispatch_get_main_queue()) {
callback(self)
}
} else {
synchronized() {
if self._isInitialized {
dispatch_async(dispatch_get_main_queue()) {
callback(self)
}
} else {
self._initializers.append(callback)
}
}
}
}
/**
* Posts event without any argument
*/
public func post(eventName: String) {
_post(eventName, eventData: nil, type: nil)
}
/**
* Posts event with an extra int
*/
public func post(eventName: String, anInt: Int) {
_post(eventName, eventData: anInt, type: .Int)
}
/**
* Posts event with an extra bool
*/
public func post(eventName: String, aBool: Bool) {
_post(eventName, eventData: aBool, type: .Bool)
}
/**
* Posts event with an extra double
*/
public func post(eventName: String, aDouble: Double) {
_post(eventName, eventData: aDouble, type: .Double)
}
/**
* Posts event with an extra float
*/
public func post(eventName: String, aFloat: Float) {
_post(eventName, eventData: aFloat, type: .Float)
}
/**
* Posts event with an extra string
*/
public func post(eventName: String, aString: String) {
_post(eventName, eventData: aString, type: .String)
}
/**
* Posts event with an extra array
*/
public func post(eventName: String, anArray: NSArray) {
_post(eventName, eventData: anArray, type: .Array)
}
/**
* Posts event with an extra dictionary
*/
public func post(eventName: String, aDictionary: NSDictionary) {
_post(eventName, eventData: aDictionary, type: .Dictionary)
}
/**
* Subscribes to provided event. Callback is run with the event's name and extra data
*/
public func register(eventName: String, callback: (String, AnyObject?) -> Void) {
_subscribers.append(Subscriber(name: eventName, callback: callback))
}
/**
* Returns the default bus
*/
public static func getDefault(webView: UIWebView) -> Caravel {
let getExisting = { () -> Caravel? in
if let b = Caravel._default {
b.setWebView(webView)
return b
} else {
return nil
}
}
if let bus = getExisting() {
return bus
} else {
// setWebView must be run within a synchronized block
objc_sync_enter(Caravel._defaultInitLock)
if let bus = getExisting() {
objc_sync_exit(Caravel._defaultInitLock)
return bus
} else {
_default = Caravel(name: Caravel.DEFAULT_BUS_NAME, webView: webView)
objc_sync_exit(Caravel._defaultInitLock)
return _default!
}
}
}
/**
* Returns custom bus
*/
public static func get(name: String, webView: UIWebView) -> Caravel {
if name == Caravel.DEFAULT_BUS_NAME {
return getDefault(webView)
} else {
let getExisting = { () -> Caravel? in
for b in self._buses {
if b.name == name {
b.setWebView(webView)
return b
}
}
return nil
}
if let bus = getExisting() {
return bus
} else {
// setWebView must be run within a synchronized block
objc_sync_enter(Caravel._namedBusInitLock)
if let bus = getExisting() {
objc_sync_exit(Caravel._namedBusInitLock)
return bus
} else {
let newBus = Caravel(name: name, webView: webView)
_buses.append(newBus)
objc_sync_exit(Caravel._namedBusInitLock)
return newBus
}
}
}
}
} | 3fd3b6477f6c0b355c3fc53604f67a91 | 31.171779 | 144 | 0.491942 | false | false | false | false |
getsentry/sentry-swift | refs/heads/master | Tests/SentryTests/SentryClientTests.swift | mit | 1 | import Sentry
import XCTest
// swiftlint:disable file_length
// We are aware that the client has a lot of logic and we should maybe
// move some of it to other classes.
class SentryClientTest: XCTestCase {
private static let dsn = TestConstants.dsnAsString(username: "SentryClientTest")
private class Fixture {
let transport: TestTransport
let transportAdapter: TestTransportAdapter
let debugImageBuilder = SentryDebugImageProvider()
let threadInspector = TestThreadInspector.instance
let session: SentrySession
let event: Event
let environment = "Environment"
let messageAsString = "message"
let message: SentryMessage
let user: User
let fileManager: SentryFileManager
let random = TestRandom(value: 1.0)
let trace = SentryTracer(transactionContext: TransactionContext(name: "SomeTransaction", operation: "SomeOperation"), hub: nil)
let transaction: Transaction
init() {
session = SentrySession(releaseName: "release")
session.incrementErrors()
message = SentryMessage(formatted: messageAsString)
event = Event()
event.message = message
user = User()
user.email = "[email protected]"
user.ipAddress = "127.0.0.1"
let options = Options()
options.dsn = SentryClientTest.dsn
fileManager = try! SentryFileManager(options: options, andCurrentDateProvider: TestCurrentDateProvider())
transaction = Transaction(trace: trace, children: [])
transport = TestTransport()
transportAdapter = TestTransportAdapter(transport: transport, options: options)
}
func getSut(configureOptions: (Options) -> Void = { _ in }) -> Client {
var client: Client!
do {
let options = try Options(dict: [
"dsn": SentryClientTest.dsn
])
configureOptions(options)
client = Client(options: options, transportAdapter: transportAdapter, fileManager: fileManager, threadInspector: threadInspector, random: random)
} catch {
XCTFail("Options could not be created")
}
return client
}
func getSutWithNoDsn() -> Client {
getSut(configureOptions: { options in
options.parsedDsn = nil
})
}
func getSutDisabledSdk() -> Client {
getSut(configureOptions: { options in
options.enabled = false
})
}
var scope: Scope {
get {
let scope = Scope()
scope.setEnvironment(environment)
scope.setTag(value: "value", key: "key")
scope.add(TestData.dataAttachment)
scope.setContext(value: [SentryDeviceContextFreeMemoryKey: 2_000], key: "device")
return scope
}
}
var eventWithCrash: Event {
let event = TestData.event
let exception = Exception(value: "value", type: "type")
let mechanism = Mechanism(type: "mechanism")
mechanism.handled = false
exception.mechanism = mechanism
event.exceptions = [exception]
return event
}
}
private let error = NSError(domain: "domain", code: -20, userInfo: [NSLocalizedDescriptionKey: "Object does not exist"])
private let exception = NSException(name: NSExceptionName("My Custom exception"), reason: "User clicked the button", userInfo: nil)
private var fixture: Fixture!
override func setUp() {
super.setUp()
fixture = Fixture()
fixture.fileManager.deleteAllEnvelopes()
}
override func tearDown() {
super.tearDown()
clearTestState()
}
func tesCaptureMessage() {
let eventId = fixture.getSut().capture(message: fixture.messageAsString)
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
XCTAssertEqual(SentryLevel.info, actual.level)
XCTAssertEqual(fixture.message, actual.message)
assertValidDebugMeta(actual: actual.debugMeta, forThreads: actual.threads)
assertValidThreads(actual: actual.threads)
}
}
func testCaptureMessageWithOutStacktrace() {
let eventId = fixture.getSut(configureOptions: { options in
options.attachStacktrace = false
}).capture(message: fixture.messageAsString)
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
XCTAssertEqual(SentryLevel.info, actual.level)
XCTAssertEqual(fixture.message, actual.message)
XCTAssertNil(actual.debugMeta)
XCTAssertNil(actual.threads)
XCTAssertNotNil(actual.dist)
}
}
func testCaptureEvent() {
let event = Event(level: SentryLevel.warning)
event.message = fixture.message
let scope = Scope()
let expectedTags = ["tagKey": "tagValue"]
scope.setTags(expectedTags)
let eventId = fixture.getSut().capture(event: event, scope: scope)
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
XCTAssertEqual(event.level, actual.level)
XCTAssertEqual(event.message, actual.message)
XCTAssertNotNil(actual.debugMeta)
XCTAssertNotNil(actual.threads)
XCTAssertNotNil(actual.tags)
if let actualTags = actual.tags {
XCTAssertEqual(expectedTags, actualTags)
}
}
}
func testCaptureEventTypeTransactionDoesNotIncludeThreadAndDebugMeta() {
let event = Event(level: SentryLevel.warning)
event.message = fixture.message
event.type = SentryEnvelopeItemTypeTransaction
let scope = Scope()
let expectedTags = ["tagKey": "tagValue"]
scope.setTags(expectedTags)
let eventId = fixture.getSut().capture(event: event, scope: scope)
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
XCTAssertEqual(event.level, actual.level)
XCTAssertEqual(event.message, actual.message)
XCTAssertNil(actual.debugMeta)
XCTAssertNil(actual.threads)
XCTAssertNotNil(actual.tags)
if let actualTags = actual.tags {
XCTAssertEqual(expectedTags, actualTags)
}
}
}
func testCaptureEventWithException() {
let event = Event()
event.exceptions = [ Exception(value: "", type: "")]
fixture.getSut().capture(event: event, scope: fixture.scope)
assertLastSentEventWithAttachment { actual in
assertValidDebugMeta(actual: actual.debugMeta, forThreads: event.threads)
assertValidThreads(actual: actual.threads)
}
}
func testCaptureEventWithNoDsn() {
let event = Event()
let eventId = fixture.getSut(configureOptions: { options in
options.dsn = nil
}).capture(event: event)
eventId.assertIsEmpty()
}
func test_AttachmentProcessor_CaptureEvent() {
let sut = fixture.getSut()
let event = Event()
let extraAttachment = Attachment(data: Data(), filename: "ExtraAttachment")
let expectProcessorCall = expectation(description: "Processor Call")
let processor = TestAttachmentProcessor { atts, e in
var result = atts ?? []
result.append(extraAttachment)
XCTAssertEqual(event, e)
expectProcessorCall.fulfill()
return result
}
sut.attachmentProcessor = processor
sut.capture(event: event)
let sendedAttachments = fixture.transportAdapter.sendEventWithTraceStateInvocations.first?.attachments ?? []
wait(for: [expectProcessorCall], timeout: 1)
XCTAssertEqual(sendedAttachments.count, 1)
XCTAssertEqual(extraAttachment, sendedAttachments.first)
}
func test_AttachmentProcessor_CaptureError_WithSession() {
let sut = fixture.getSut()
let error = NSError(domain: "test", code: -1)
let extraAttachment = Attachment(data: Data(), filename: "ExtraAttachment")
let processor = TestAttachmentProcessor { atts, _ in
var result = atts ?? []
result.append(extraAttachment)
return result
}
sut.attachmentProcessor = processor
sut.captureError(error, with: fixture.session, with: Scope())
let sentAttachments = fixture.transportAdapter.sentEventsWithSessionTraceState.first?.attachments ?? []
XCTAssertEqual(sentAttachments.count, 1)
XCTAssertEqual(extraAttachment, sentAttachments.first)
}
func test_AttachmentProcessor_CaptureError_WithSession_NoReleaseName() {
let sut = fixture.getSut()
let error = NSError(domain: "test", code: -1)
let extraAttachment = Attachment(data: Data(), filename: "ExtraAttachment")
let processor = TestAttachmentProcessor { atts, _ in
var result = atts ?? []
result.append(extraAttachment)
return result
}
sut.attachmentProcessor = processor
sut.captureError(error, with: SentrySession(releaseName: ""), with: Scope())
let sendedAttachments = fixture.transportAdapter.sendEventWithTraceStateInvocations.first?.attachments ?? []
XCTAssertEqual(sendedAttachments.count, 1)
XCTAssertEqual(extraAttachment, sendedAttachments.first)
}
func testCaptureEventWithDsnSetAfterwards() {
let event = Event()
let sut = fixture.getSut(configureOptions: { options in
options.dsn = nil
})
sut.options.dsn = SentryClientTest.dsn
let eventId = sut.capture(event: event)
eventId.assertIsNotEmpty()
}
func testCaptureEventWithDebugMeta_KeepsDebugMeta() {
let sut = fixture.getSut(configureOptions: { options in
options.attachStacktrace = true
})
let event = givenEventWithDebugMeta()
sut.capture(event: event)
assertLastSentEvent { actual in
XCTAssertEqual(event.debugMeta, actual.debugMeta)
assertValidThreads(actual: actual.threads)
}
}
func testCaptureEventWithAttachedThreads_KeepsThreads() {
let sut = fixture.getSut(configureOptions: { options in
options.attachStacktrace = true
})
let event = givenEventWithThreads()
sut.capture(event: event)
assertLastSentEvent { actual in
assertValidDebugMeta(actual: actual.debugMeta, forThreads: event.threads)
XCTAssertEqual(event.threads, actual.threads)
}
}
func testCaptureEventWithAttachStacktrace() {
let event = Event(level: SentryLevel.fatal)
event.message = fixture.message
let eventId = fixture.getSut(configureOptions: { options in
options.attachStacktrace = true
}).capture(event: event)
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
XCTAssertEqual(event.level, actual.level)
XCTAssertEqual(event.message, actual.message)
assertValidDebugMeta(actual: actual.debugMeta, forThreads: event.threads)
assertValidThreads(actual: actual.threads)
}
}
func testCaptureErrorWithoutAttachStacktrace() {
let eventId = fixture.getSut(configureOptions: { options in
options.attachStacktrace = false
}).capture(error: error, scope: fixture.scope)
eventId.assertIsNotEmpty()
assertLastSentEventWithAttachment { actual in
assertValidErrorEvent(actual, error)
}
}
func testCaptureErrorWithEnum() {
let eventId = fixture.getSut().capture(error: TestError.invalidTest)
eventId.assertIsNotEmpty()
let error = TestError.invalidTest as NSError
assertLastSentEvent { actual in
assertValidErrorEvent(actual, error)
}
}
func testCaptureErrorWithComplexUserInfo() {
let url = URL(string: "https://github.com/getsentry")!
let error = NSError(domain: "domain", code: 0, userInfo: ["url": url])
let eventId = fixture.getSut().capture(error: error, scope: fixture.scope)
eventId.assertIsNotEmpty()
assertLastSentEventWithAttachment { actual in
XCTAssertEqual(url.absoluteString, actual.context!["user info"]!["url"] as? String)
}
}
func testCaptureErrorWithSession() {
let eventId = fixture.getSut().captureError(error, with: fixture.session, with: Scope())
eventId.assertIsNotEmpty()
XCTAssertNotNil(fixture.transportAdapter.sentEventsWithSessionTraceState.last)
if let eventWithSessionArguments = fixture.transportAdapter.sentEventsWithSessionTraceState.last {
assertValidErrorEvent(eventWithSessionArguments.event, error)
XCTAssertEqual(fixture.session, eventWithSessionArguments.session)
}
}
func testCaptureErrorWithSession_WithBeforeSendReturnsNil() {
let eventId = fixture.getSut(configureOptions: { options in
options.beforeSend = { _ in return nil }
}).captureError(error, with: fixture.session, with: Scope())
eventId.assertIsEmpty()
assertLastSentEnvelopeIsASession()
}
func testCaptureCrashEventWithSession() {
let eventId = fixture.getSut().captureCrash(fixture.event, with: fixture.session, with: fixture.scope)
eventId.assertIsNotEmpty()
assertLastSentEventWithSession { event, session, _ in
XCTAssertEqual(fixture.event.eventId, event.eventId)
XCTAssertEqual(fixture.event.message, event.message)
XCTAssertEqual("value", event.tags?["key"] ?? "")
XCTAssertEqual(fixture.session, session)
}
}
func testCaptureCrashWithSession_DoesntOverideStacktrace() {
let event = TestData.event
event.threads = nil
event.debugMeta = nil
fixture.getSut().captureCrash(event, with: fixture.session, with: fixture.scope)
assertLastSentEventWithSession { event, _, _ in
XCTAssertNil(event.threads)
XCTAssertNil(event.debugMeta)
}
}
func testCaptureCrashEvent() {
let eventId = fixture.getSut().captureCrash(fixture.event, with: fixture.scope)
eventId.assertIsNotEmpty()
assertLastSentEventWithAttachment { event in
XCTAssertEqual(fixture.event.eventId, event.eventId)
XCTAssertEqual(fixture.event.message, event.message)
XCTAssertEqual("value", event.tags?["key"] ?? "")
}
}
func testCaptureOOMEvent_RemovesFreeMemoryFromContext() {
let oomEvent = TestData.oomEvent
_ = fixture.getSut().captureCrash(oomEvent, with: fixture.scope)
assertLastSentEventWithAttachment { event in
XCTAssertEqual(oomEvent.eventId, event.eventId)
XCTAssertNil(event.context?["device"]?["free_memory"])
}
}
func testCaptureOOMEvent_WithNoContext_ContextNotModified() {
let oomEvent = TestData.oomEvent
_ = fixture.getSut().captureCrash(oomEvent, with: Scope())
assertLastSentEvent { event in
XCTAssertEqual(oomEvent.eventId, event.eventId)
XCTAssertEqual(oomEvent.context?.count, event.context?.count)
}
}
func testCaptureOOMEvent_WithNoDeviceContext_ContextNotModified() {
let oomEvent = TestData.oomEvent
let scope = Scope()
scope.setContext(value: ["some": "thing"], key: "any")
_ = fixture.getSut().captureCrash(oomEvent, with: scope)
assertLastSentEvent { event in
XCTAssertEqual(oomEvent.eventId, event.eventId)
XCTAssertEqual(oomEvent.context?.count, event.context?.count)
}
}
func testCaptureCrash_DoesntOverideStacktraceFor() {
let event = TestData.event
event.threads = nil
event.debugMeta = nil
fixture.getSut().captureCrash(event, with: fixture.scope)
assertLastSentEventWithAttachment { actual in
XCTAssertNil(actual.threads)
XCTAssertNil(actual.debugMeta)
}
}
func testCaptureErrorWithUserInfo() {
let expectedValue = "val"
let error = NSError(domain: "domain", code: 0, userInfo: ["key": expectedValue])
let eventId = fixture.getSut().capture(error: error, scope: fixture.scope)
eventId.assertIsNotEmpty()
assertLastSentEventWithAttachment { actual in
XCTAssertEqual(expectedValue, actual.context!["user info"]!["key"] as? String)
}
}
func testCaptureExceptionWithoutAttachStacktrace() {
let eventId = fixture.getSut(configureOptions: { options in
options.attachStacktrace = false
}).capture(exception: exception, scope: fixture.scope)
eventId.assertIsNotEmpty()
assertLastSentEventWithAttachment { actual in
assertValidExceptionEvent(actual)
}
}
func testCaptureExceptionWithSession() {
let eventId = fixture.getSut().capture(exception, with: fixture.session, with: fixture.scope)
eventId.assertIsNotEmpty()
XCTAssertNotNil(fixture.transportAdapter.sentEventsWithSessionTraceState.last)
if let eventWithSessionArguments = fixture.transportAdapter.sentEventsWithSessionTraceState.last {
assertValidExceptionEvent(eventWithSessionArguments.event)
XCTAssertEqual(fixture.session, eventWithSessionArguments.session)
XCTAssertEqual([TestData.dataAttachment], eventWithSessionArguments.attachments)
}
}
func testCaptureExceptionWithSession_WithBeforeSendReturnsNil() {
let eventId = fixture.getSut(configureOptions: { options in
options.beforeSend = { _ in return nil }
}).capture(exception, with: fixture.session, with: fixture.scope)
eventId.assertIsEmpty()
assertLastSentEnvelopeIsASession()
}
func testCaptureExceptionWithUserInfo() {
let expectedValue = "val"
let exception = NSException(name: NSExceptionName("exception"), reason: "reason", userInfo: ["key": expectedValue])
let eventId = fixture.getSut().capture(exception: exception, scope: fixture.scope)
eventId.assertIsNotEmpty()
assertLastSentEventWithAttachment { actual in
XCTAssertEqual(expectedValue, actual.context!["user info"]!["key"] as? String)
}
}
func testScopeIsNotNil() {
let eventId = fixture.getSut().capture(message: fixture.messageAsString, scope: fixture.scope)
eventId.assertIsNotEmpty()
assertLastSentEventWithAttachment { actual in
XCTAssertEqual(fixture.environment, actual.environment)
}
}
func testCaptureSession() {
let session = SentrySession(releaseName: "release")
fixture.getSut().capture(session: session)
assertLastSentEnvelopeIsASession()
}
func testCaptureSessionWithoutReleaseName() {
let session = SentrySession(releaseName: "")
fixture.getSut().capture(session: session)
fixture.getSut().capture(exception, with: session, with: Scope())
.assertIsNotEmpty()
fixture.getSut().captureCrash(fixture.event, with: session, with: Scope())
.assertIsNotEmpty()
// No sessions sent
XCTAssertTrue(fixture.transport.sentEnvelopes.isEmpty)
XCTAssertEqual(0, fixture.transportAdapter.sentEventsWithSessionTraceState.count)
XCTAssertEqual(2, fixture.transportAdapter.sendEventWithTraceStateInvocations.count)
}
func testBeforeSendReturnsNil_EventNotSent() {
beforeSendReturnsNil { $0.capture(message: fixture.messageAsString) }
assertNoEventSent()
}
func testBeforeSendReturnsNil_LostEventRecorded() {
beforeSendReturnsNil { $0.capture(message: fixture.messageAsString) }
assertLostEventRecorded(category: .error, reason: .beforeSend)
}
func testBeforeSendReturnsNilForTransaction_TransactionNotSend() {
beforeSendReturnsNil { $0.capture(event: fixture.transaction) }
assertLostEventRecorded(category: .transaction, reason: .beforeSend)
}
func testBeforeSendReturnsNilForTransaction_LostEventRecorded() {
beforeSendReturnsNil { $0.capture(event: fixture.transaction) }
assertLostEventRecorded(category: .transaction, reason: .beforeSend)
}
func testBeforeSendReturnsNewEvent_NewEventSent() {
let newEvent = Event()
let releaseName = "1.0.0"
let eventId = fixture.getSut(configureOptions: { options in
options.beforeSend = { _ in
newEvent
}
options.releaseName = releaseName
}).capture(message: fixture.messageAsString)
XCTAssertEqual(newEvent.eventId, eventId)
assertLastSentEvent { actual in
XCTAssertEqual(newEvent.eventId, actual.eventId)
XCTAssertNil(actual.releaseName)
}
}
func testBeforeSendModifiesEvent_ModifiedEventSent() {
fixture.getSut(configureOptions: { options in
options.beforeSend = { event in
event.threads = []
event.debugMeta = []
return event
}
options.attachStacktrace = true
}).capture(message: fixture.messageAsString)
assertLastSentEvent { actual in
XCTAssertEqual([], actual.debugMeta)
XCTAssertEqual([], actual.threads)
}
}
func testNoDsn_MessageNotSent() {
let sut = fixture.getSutWithNoDsn()
let eventId = sut.capture(message: fixture.messageAsString)
eventId.assertIsEmpty()
assertNothingSent()
}
func testDisabled_MessageNotSent() {
let sut = fixture.getSutDisabledSdk()
let eventId = sut.capture(message: fixture.messageAsString)
eventId.assertIsEmpty()
assertNothingSent()
}
func testNoDsn_ExceptionNotSent() {
let sut = fixture.getSutWithNoDsn()
let eventId = sut.capture(exception: exception)
eventId.assertIsEmpty()
assertNothingSent()
}
func testNoDsn_ErrorNotSent() {
let sut = fixture.getSutWithNoDsn()
let eventId = sut.capture(error: error)
eventId.assertIsEmpty()
assertNothingSent()
}
func testNoDsn_SessionsNotSent() {
_ = SentryEnvelope(event: Event())
fixture.getSut(configureOptions: { options in
options.dsn = nil
}).capture(session: fixture.session)
assertNothingSent()
}
func testNoDsn_EventWithSessionsNotSent() {
_ = SentryEnvelope(event: Event())
let eventId = fixture.getSut(configureOptions: { options in
options.dsn = nil
}).captureCrash(Event(), with: fixture.session, with: fixture.scope)
eventId.assertIsEmpty()
assertNothingSent()
}
func testNoDsn_ExceptionWithSessionsNotSent() {
_ = SentryEnvelope(event: Event())
let eventId = fixture.getSut(configureOptions: { options in
options.dsn = nil
}).capture(self.exception, with: fixture.session, with: fixture.scope)
eventId.assertIsEmpty()
assertNothingSent()
}
func testNoDsn_ErrorWithSessionsNotSent() {
_ = SentryEnvelope(event: Event())
let eventId = fixture.getSut(configureOptions: { options in
options.dsn = nil
}).captureError(self.error, with: fixture.session, with: fixture.scope)
eventId.assertIsEmpty()
assertNothingSent()
}
func testSampleRateNil_EventNotSampled() {
testSampleRate(sampleRate: nil, randomValue: 0, isSampled: false)
}
func testSampleRateBiggerRandom_EventNotSampled() {
testSampleRate(sampleRate: 0.5, randomValue: 0.49, isSampled: false)
}
func testSampleRateEqualsRandom_EventNotSampled() {
testSampleRate(sampleRate: 0.5, randomValue: 0.5, isSampled: false)
}
func testSampleRateSmallerRandom_EventSampled() {
testSampleRate(sampleRate: 0.50, randomValue: 0.51, isSampled: true)
}
private func testSampleRate( sampleRate: NSNumber?, randomValue: Double, isSampled: Bool) {
fixture.random.value = randomValue
let eventId = fixture.getSut(configureOptions: { options in
options.sampleRate = sampleRate
}).capture(event: TestData.event)
if isSampled {
eventId.assertIsEmpty()
assertNothingSent()
} else {
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
XCTAssertEqual(eventId, actual.eventId)
}
}
}
func testSampleRateDoesNotImpactTransactions() {
fixture.random.value = 0.51
let eventId = fixture.getSut(configureOptions: { options in
options.sampleRate = 0.00
}).capture(event: fixture.transaction)
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
XCTAssertEqual(eventId, actual.eventId)
}
}
func testEventSampled_RecordsLostEvent() {
fixture.getSut(configureOptions: { options in
options.sampleRate = 0.00
}).capture(event: TestData.event)
assertLostEventRecorded(category: .error, reason: .sampleRate)
}
func testEventDroppedByEventProcessor_RecordsLostEvent() {
SentryGlobalEventProcessor.shared().add { _ in return nil }
beforeSendReturnsNil { $0.capture(message: fixture.messageAsString) }
assertLostEventRecorded(category: .error, reason: .eventProcessor)
}
func testTransactionDroppedByEventProcessor_RecordsLostEvent() {
SentryGlobalEventProcessor.shared().add { _ in return nil }
beforeSendReturnsNil { $0.capture(event: fixture.transaction) }
assertLostEventRecorded(category: .transaction, reason: .eventProcessor)
}
func testNoDsn_UserFeedbackNotSent() {
let sut = fixture.getSutWithNoDsn()
sut.capture(userFeedback: UserFeedback(eventId: SentryId()))
assertNothingSent()
}
func testDisabled_UserFeedbackNotSent() {
let sut = fixture.getSutDisabledSdk()
sut.capture(userFeedback: UserFeedback(eventId: SentryId()))
assertNothingSent()
}
func testCaptureUserFeedback_WithEmptyEventId() {
let sut = fixture.getSut()
sut.capture(userFeedback: UserFeedback(eventId: SentryId.empty))
assertNothingSent()
}
func testDistIsSet() {
let dist = "dist"
let eventId = fixture.getSut(configureOptions: { options in
options.dist = dist
}).capture(message: fixture.messageAsString)
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
XCTAssertEqual(dist, actual.dist)
}
}
func testEnvironmentDefaultToProduction() {
let eventId = fixture.getSut().capture(message: fixture.messageAsString)
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
XCTAssertEqual("production", actual.environment)
}
}
func testEnvironmentIsSetViaOptions() {
let environment = "environment"
let eventId = fixture.getSut(configureOptions: { options in
options.environment = environment
}).capture(message: fixture.messageAsString)
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
XCTAssertEqual(environment, actual.environment)
}
}
func testEnvironmentIsSetInEventTakesPrecedenceOverOptions() {
let optionsEnvironment = "environment"
let event = Event()
event.environment = "event"
let scope = fixture.scope
scope.setEnvironment("scope")
let eventId = fixture.getSut(configureOptions: { options in
options.environment = optionsEnvironment
}).capture(event: event, scope: scope)
eventId.assertIsNotEmpty()
assertLastSentEventWithAttachment { actual in
XCTAssertEqual("event", actual.environment)
}
}
func testEnvironmentIsSetInEventTakesPrecedenceOverScope() {
let optionsEnvironment = "environment"
let event = Event()
event.environment = "event"
let eventId = fixture.getSut(configureOptions: { options in
options.environment = optionsEnvironment
}).capture(event: event)
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
XCTAssertEqual("event", actual.environment)
}
}
func testSetSDKIntegrations() {
let eventId = fixture.getSut().capture(message: fixture.messageAsString)
let expected = shortenIntegrations(Options().integrations)
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
assertArrayEquals(expected: expected, actual: actual.sdk?["integrations"] as? [String])
}
}
func testSetSDKIntegrations_CustomIntegration() {
var integrations = Options().integrations
integrations?.append("Custom")
let eventId = fixture.getSut(configureOptions: { options in
options.integrations = integrations
}).capture(message: fixture.messageAsString)
let expected = shortenIntegrations(integrations)
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
assertArrayEquals(expected: expected, actual: actual.sdk?["integrations"] as? [String])
}
}
func testSetSDKIntegrations_NoIntegrations() {
let expected: [String] = []
let eventId = fixture.getSut(configureOptions: { options in
options.integrations = expected
}).capture(message: fixture.messageAsString)
eventId.assertIsNotEmpty()
assertLastSentEvent { actual in
assertArrayEquals(expected: expected, actual: actual.sdk?["integrations"] as? [String])
}
}
func testFileManagerCantBeInit() {
SentryFileManager.prepareInitError()
let options = Options()
options.dsn = SentryClientTest.dsn
let client = Client(options: options)
XCTAssertNil(client)
SentryFileManager.tearDownInitError()
}
func testInstallationIdSetWhenNoUserId() {
fixture.getSut().capture(message: "any message")
assertLastSentEvent { actual in
XCTAssertEqual(SentryInstallation.id(), actual.user?.userId)
}
}
func testInstallationIdNotSetWhenUserIsSetWithoutId() {
let scope = fixture.scope
scope.setUser(fixture.user)
fixture.getSut().capture(message: "any message", scope: scope)
assertLastSentEventWithAttachment { actual in
XCTAssertEqual(fixture.user.userId, actual.user?.userId)
XCTAssertEqual(fixture.user.email, actual.user?.email)
}
}
func testInstallationIdNotSetWhenUserIsSetWithId() {
let scope = Scope()
let user = fixture.user
user.userId = "id"
scope.setUser(user)
fixture.getSut().capture(message: "any message", scope: scope)
assertLastSentEvent { actual in
XCTAssertEqual(user.userId, actual.user?.userId)
XCTAssertEqual(fixture.user.email, actual.user?.email)
}
}
func testSendDefaultPiiEnabled_GivenNoIP_AutoIsSet() {
fixture.getSut(configureOptions: { options in
options.sendDefaultPii = true
}).capture(message: "any")
assertLastSentEvent { actual in
XCTAssertEqual("{{auto}}", actual.user?.ipAddress)
}
}
func testSendDefaultPiiEnabled_GivenIP_IPAddressNotChanged() {
let scope = Scope()
scope.setUser(fixture.user)
fixture.getSut(configureOptions: { options in
options.sendDefaultPii = true
}).capture(message: "any", scope: scope)
assertLastSentEvent { actual in
XCTAssertEqual(fixture.user.ipAddress, actual.user?.ipAddress)
}
}
func testSendDefaultPiiDisabled_GivenIP_IPAddressNotChanged() {
let scope = Scope()
scope.setUser(fixture.user)
fixture.getSut().capture(message: "any", scope: scope)
assertLastSentEvent { actual in
XCTAssertEqual(fixture.user.ipAddress, actual.user?.ipAddress)
}
}
func testStoreEnvelope_StoresEnvelopeToDisk() {
fixture.getSut().store(SentryEnvelope(event: Event()))
XCTAssertEqual(1, fixture.fileManager.getAllEnvelopes().count)
}
func testOnCrashedLastRun_OnCaptureCrashWithSession() {
let event = TestData.event
var onCrashedLastRunCalled = false
fixture.getSut(configureOptions: { options in
options.onCrashedLastRun = { _ in
onCrashedLastRunCalled = true
}
}).captureCrash(event, with: fixture.session, with: fixture.scope)
XCTAssertTrue(onCrashedLastRunCalled)
}
func testOnCrashedLastRun_WithTwoCrashes_OnlyInvokeCallbackOnce() {
let event = TestData.event
var onCrashedLastRunCalled = false
let client = fixture.getSut(configureOptions: { options in
options.onCrashedLastRun = { crashEvent in
onCrashedLastRunCalled = true
XCTAssertEqual(event.eventId, crashEvent.eventId)
}
})
client.captureCrash(event, with: fixture.scope)
client.captureCrash(TestData.event, with: fixture.scope)
XCTAssertTrue(onCrashedLastRunCalled)
}
func testOnCrashedLastRun_WithoutCallback_DoesNothing() {
let client = fixture.getSut()
client.captureCrash(TestData.event, with: fixture.scope)
}
func testOnCrashedLastRun_CallingCaptureCrash_OnlyInvokeCallbackOnce() {
let event = TestData.event
let callbackExpectation = expectation(description: "onCrashedLastRun called")
var captureCrash: (() -> Void)?
let client = fixture.getSut(configureOptions: { options in
options.onCrashedLastRun = { crashEvent in
callbackExpectation.fulfill()
XCTAssertEqual(event.eventId, crashEvent.eventId)
captureCrash!()
}
})
captureCrash = { client.captureCrash(event, with: self.fixture.scope) }
client.captureCrash(event, with: fixture.scope)
wait(for: [callbackExpectation], timeout: 0.1)
}
func testCaptureTransactionEvent_sendTraceState() {
let transaction = fixture.transaction
let client = fixture.getSut()
client.options.experimentalEnableTraceSampling = true
client.capture(event: transaction)
XCTAssertNotNil(fixture.transportAdapter.sendEventWithTraceStateInvocations.first?.traceState)
}
func testCaptureTransactionEvent_dontSendTraceState() {
let transaction = fixture.transaction
let client = fixture.getSut()
client.capture(event: transaction)
XCTAssertNil(fixture.transportAdapter.sendEventWithTraceStateInvocations.first?.traceState)
}
func testCaptureEvent_traceInScope_sendTraceState() {
let event = Event(level: SentryLevel.warning)
event.message = fixture.message
let scope = Scope()
scope.span = fixture.trace
let client = fixture.getSut()
client.options.experimentalEnableTraceSampling = true
client.capture(event: event, scope: scope)
client.capture(event: event)
XCTAssertNotNil(fixture.transportAdapter.sendEventWithTraceStateInvocations.first?.traceState)
}
func testCaptureEvent_traceInScope_dontSendTraceState() {
let event = Event(level: SentryLevel.warning)
event.message = fixture.message
let scope = Scope()
scope.span = SentryTracer()
let client = fixture.getSut()
client.capture(event: event, scope: scope)
client.capture(event: event)
XCTAssertNil(fixture.transportAdapter.sendEventWithTraceStateInvocations.first?.traceState)
}
func testCaptureEvent_withAdditionalEnvelopeItem() {
let event = Event(level: SentryLevel.warning)
event.message = fixture.message
let attachment = "{}"
let data = attachment.data(using: .utf8)!
let itemHeader = SentryEnvelopeItemHeader(type: "attachment", length: UInt(data.count))
let item = SentryEnvelopeItem(header: itemHeader, data: data)
let client = fixture.getSut()
client.capture(event: event, scope: Scope(), additionalEnvelopeItems: [item])
XCTAssertEqual(item, fixture.transportAdapter.sendEventWithTraceStateInvocations.first?.additionalEnvelopeItems.first)
}
private func givenEventWithDebugMeta() -> Event {
let event = Event(level: SentryLevel.fatal)
let debugMeta = DebugMeta()
debugMeta.name = "Me"
let debugMetas = [debugMeta]
event.debugMeta = debugMetas
return event
}
private func givenEventWithThreads() -> Event {
let event = Event(level: SentryLevel.fatal)
let thread = Sentry.Thread(threadId: 1)
thread.crashed = true
let threads = [thread]
event.threads = threads
return event
}
private func beforeSendReturnsNil(capture: (Client) -> Void) {
capture(fixture.getSut(configureOptions: { options in
options.beforeSend = { _ in
nil
}
}))
}
private func assertNoEventSent() {
XCTAssertEqual(0, fixture.transportAdapter.sendEventWithTraceStateInvocations.count, "No events should have been sent.")
}
private func assertEventNotSent(eventId: SentryId?) {
let eventWasSent = fixture.transportAdapter.sendEventWithTraceStateInvocations.invocations.contains { eventArguments in
eventArguments.event.eventId == eventId
}
XCTAssertFalse(eventWasSent)
}
private func assertLastSentEvent(assert: (Event) -> Void) {
XCTAssertNotNil(fixture.transportAdapter.sendEventWithTraceStateInvocations.last)
if let lastSentEventArguments = fixture.transportAdapter.sendEventWithTraceStateInvocations.last {
assert(lastSentEventArguments.event)
}
}
private func assertLastSentEventWithAttachment(assert: (Event) -> Void) {
XCTAssertNotNil(fixture.transportAdapter.sendEventWithTraceStateInvocations.last)
if let lastSentEventArguments = fixture.transportAdapter.sendEventWithTraceStateInvocations.last {
assert(lastSentEventArguments.event)
XCTAssertEqual([TestData.dataAttachment], lastSentEventArguments.attachments)
}
}
private func assertLastSentEventWithSession(assert: (Event, SentrySession, SentryTraceState?) -> Void) {
XCTAssertNotNil(fixture.transportAdapter.sentEventsWithSessionTraceState.last)
if let args = fixture.transportAdapter.sentEventsWithSessionTraceState.last {
assert(args.event, args.session, args.traceState)
}
}
private func assertValidErrorEvent(_ event: Event, _ error: NSError) {
XCTAssertEqual(SentryLevel.error, event.level)
XCTAssertEqual(error, event.error as NSError?)
guard let exceptions = event.exceptions else {
XCTFail("Event should contain one exception"); return
}
XCTAssertEqual(1, exceptions.count)
let exception = exceptions[0]
XCTAssertEqual(error.domain, exception.type)
XCTAssertEqual("Code: \(error.code)", exception.value)
XCTAssertNil(exception.threadId)
XCTAssertNil(exception.stacktrace)
guard let mechanism = exception.mechanism else {
XCTFail("Exception doesn't contain a mechanism"); return
}
XCTAssertEqual("NSError", mechanism.type)
XCTAssertNotNil(mechanism.meta?.error)
XCTAssertEqual(error.domain, mechanism.meta?.error?.domain)
XCTAssertEqual(error.code, mechanism.meta?.error?.code)
assertValidDebugMeta(actual: event.debugMeta, forThreads: event.threads)
assertValidThreads(actual: event.threads)
}
private func assertValidExceptionEvent(_ event: Event) {
XCTAssertEqual(SentryLevel.error, event.level)
XCTAssertEqual(exception.reason, event.exceptions!.first!.value)
XCTAssertEqual(exception.name.rawValue, event.exceptions!.first!.type)
assertValidDebugMeta(actual: event.debugMeta, forThreads: event.threads)
assertValidThreads(actual: event.threads)
}
private func assertLastSentEnvelope(assert: (SentryEnvelope) -> Void) {
XCTAssertNotNil(fixture.transport.sentEnvelopes)
if let lastSentEnvelope = fixture.transport.sentEnvelopes.last {
assert(lastSentEnvelope)
}
}
private func assertLastSentEnvelopeIsASession() {
assertLastSentEnvelope { actual in
XCTAssertEqual(1, actual.items.count)
XCTAssertEqual("session", actual.items[0].header.type)
}
}
private func assertValidDebugMeta(actual: [DebugMeta]?, forThreads threads: [Sentry.Thread]?) {
let debugMetas = fixture.debugImageBuilder.getDebugImages(for: threads ?? [])
XCTAssertEqual(debugMetas, actual ?? [])
}
private func assertValidThreads(actual: [Sentry.Thread]?) {
let expected = fixture.threadInspector.getCurrentThreads()
XCTAssertEqual(expected.count, actual?.count)
XCTAssertEqual(expected, actual)
}
private func shortenIntegrations(_ integrations: [String]?) -> [String]? {
return integrations?.map { $0.replacingOccurrences(of: "Sentry", with: "").replacingOccurrences(of: "Integration", with: "") }
}
private func assertNothingSent() {
XCTAssertTrue(fixture.transport.sentEnvelopes.isEmpty)
XCTAssertEqual(0, fixture.transportAdapter.sentEventsWithSessionTraceState.count)
XCTAssertEqual(0, fixture.transportAdapter.sendEventWithTraceStateInvocations.count)
XCTAssertEqual(0, fixture.transportAdapter.userFeedbackInvocations.count)
}
private func assertLostEventRecorded(category: SentryDataCategory, reason: SentryDiscardReason) {
XCTAssertEqual(1, fixture.transport.recordLostEvents.count)
let lostEvent = fixture.transport.recordLostEvents.first
XCTAssertEqual(category, lostEvent?.category)
XCTAssertEqual(reason, lostEvent?.reason)
}
private enum TestError: Error {
case invalidTest
case testIsFailing
case somethingElse
}
class TestAttachmentProcessor: NSObject, SentryClientAttachmentProcessor {
var callback: (([Attachment]?, Event) -> [Attachment]?)
init(callback: @escaping ([Attachment]?, Event) -> [Attachment]?) {
self.callback = callback
}
func processAttachments(_ attachments: [Attachment]?, for event: Event) -> [Attachment]? {
return callback(attachments, event)
}
}
}
// swiftlint:enable file_length
| cf0c5b3efcdd416fbb069a94d180fb33 | 35.200806 | 161 | 0.637261 | false | true | false | false |
avito-tech/Paparazzo | refs/heads/master | Paparazzo/Core/VIPER/MediaPicker/View/MediaPickerView.swift | mit | 1 | import ImageSource
import UIKit
final class MediaPickerView: UIView, ThemeConfigurable {
typealias ThemeType = MediaPickerRootModuleUITheme
// MARK: - Subviews
private let notchMaskingView = UIView()
private let cameraControlsView = CameraControlsView()
private let photoControlsView = PhotoControlsView()
private let closeButton = UIButton()
private let topRightContinueButton = ButtonWithActivity()
private let bottomContinueButton = UIButton()
private let photoTitleLabel = UILabel()
private let flashView = UIView()
private let thumbnailRibbonView: ThumbnailsView
private let photoPreviewView: PhotoPreviewView
private var closeAndContinueButtonsSwapped = false
// MARK: - Layout constants
private let topRightContinueButtonHeight = CGFloat(38)
private let topRightContinueButtonContentInsets = UIEdgeInsets(top: 0, left: 16, bottom: 0, right: 16)
private let fakeNavigationBarMinimumYOffset = CGFloat(20)
private let fakeNavigationBarContentTopInset = CGFloat(8)
// MARK: - MediaPickerTitleStyle
private var photoTitleLabelLightTextColor = UIColor.white
private var photoTitleLabelDarkTextColor = UIColor.black
// MARK: - State
private var theme: ThemeType?
// MARK: - Helpers
private var mode = MediaPickerViewMode.camera
private var deviceOrientation = DeviceOrientation.portrait
private let infoMessageDisplayer = InfoMessageDisplayer()
private var continueButtonPlacement = MediaPickerContinueButtonPlacement.topRight {
didSet {
switch continueButtonPlacement {
case .topRight:
bottomContinueButton.removeFromSuperview()
addSubview(topRightContinueButton)
case .bottom:
topRightContinueButton.removeFromSuperview()
addSubview(bottomContinueButton)
}
}
}
private var showsPreview: Bool = true {
didSet {
thumbnailRibbonView.isHidden = !showsPreview
}
}
// MARK: - UIView
override init(frame: CGRect) {
thumbnailRibbonView = ThumbnailsView()
photoPreviewView = PhotoPreviewView()
super.init(frame: .zero)
backgroundColor = .white
notchMaskingView.backgroundColor = .black
flashView.backgroundColor = .white
flashView.alpha = 0
setUpButtons()
setUpThumbnailRibbonView()
photoTitleLabel.textColor = .white
photoTitleLabel.layer.shadowOffset = .zero
photoTitleLabel.layer.shadowOpacity = 0.5
photoTitleLabel.layer.shadowRadius = 2
photoTitleLabel.layer.masksToBounds = false
photoTitleLabel.alpha = 0
addSubview(notchMaskingView)
addSubview(photoPreviewView)
addSubview(flashView)
addSubview(cameraControlsView)
addSubview(photoControlsView)
addSubview(thumbnailRibbonView)
addSubview(closeButton)
addSubview(photoTitleLabel)
addSubview(topRightContinueButton)
setMode(.camera)
setUpAccessibilityIdentifiers()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Layout
override func layoutSubviews() {
super.layoutSubviews()
let cameraAspectRatio = CGFloat(4) / 3
layOutNotchMaskingView()
layOutFakeNavigationBarButtons()
layOutBottomContinueButton()
let controlsIdealFrame = CGRect(
left: bounds.left,
right: bounds.right,
bottom: (continueButtonPlacement == .bottom)
? bottomContinueButton.top
: bounds.bottom - paparazzoSafeAreaInsets.bottom,
height: 93
)
/// Ideal height of photoPreviewView is when it's aspect ratio is 4:3 (same as camera output)
let previewIdealHeight = bounds.width * cameraAspectRatio
let previewIdealBottom = notchMaskingView.bottom + previewIdealHeight
let thumbnailRibbonUnderPreviewHeight = max(controlsIdealFrame.top - previewIdealBottom, 74)
let previewTargetHeight = controlsIdealFrame.top - thumbnailRibbonUnderPreviewHeight - notchMaskingView.bottom
let isIPhone = (UIDevice.current.userInterfaceIdiom == .phone)
// If we are going to shrink preview area so that less than 80% of the ideal height is visible (iPhone 4 case),
// then we'd rather lay out thumbnail ribbon at the bottom of the preview area
// and shrink controls height as well.
if previewTargetHeight / previewIdealHeight < 0.8 && isIPhone {
layOutMainAreaWithThumbnailRibbonOverlappingPreview()
} else {
layOutMainAreaWithThumbnailRibbonUnderPreview(
controlsFrame: controlsIdealFrame,
thumbnailRibbonHeight: thumbnailRibbonUnderPreviewHeight
)
}
// Flash view
//
flashView.frame = photoPreviewView.frame
}
private func layOutNotchMaskingView() {
let height = UIDevice.current.hasNotch ? paparazzoSafeAreaInsets.top : 0
notchMaskingView.layout(
left: bounds.left,
right: bounds.right,
top: bounds.top,
height: height
)
}
private func layOutFakeNavigationBarButtons() {
let leftButton = closeAndContinueButtonsSwapped ? topRightContinueButton : closeButton
let rightButton = closeAndContinueButtonsSwapped ? closeButton : topRightContinueButton
leftButton.frame = CGRect(
x: bounds.left + 8,
y: max(notchMaskingView.bottom, fakeNavigationBarMinimumYOffset) + fakeNavigationBarContentTopInset,
width: leftButton.width,
height: leftButton.height
)
rightButton.frame = CGRect(
x: bounds.right - 8 - rightButton.width,
y: max(notchMaskingView.bottom, fakeNavigationBarMinimumYOffset) + fakeNavigationBarContentTopInset,
width: rightButton.width,
height: rightButton.height
)
}
private func layOutBottomContinueButton() {
bottomContinueButton.layout(
left: bounds.left + 16,
right: bounds.right - 16,
bottom: bounds.bottom - max(14, paparazzoSafeAreaInsets.bottom),
height: 36
)
}
private func layOutMainAreaWithThumbnailRibbonOverlappingPreview() {
let hasBottomContinueButton = (continueButtonPlacement == .bottom)
// Controls
//
cameraControlsView.layout(
left: bounds.left,
right: bounds.right,
bottom: hasBottomContinueButton
? bottomContinueButton.top - 8
: bounds.bottom - paparazzoSafeAreaInsets.bottom,
height: 54
)
photoControlsView.frame = cameraControlsView.frame
let previewTargetBottom = cameraControlsView.top - (hasBottomContinueButton ? 8 : 0)
// Thumbnail ribbon
//
thumbnailRibbonView.backgroundColor = theme?.thumbnailsViewBackgroundColor.withAlphaComponent(0.6)
thumbnailRibbonView.contentInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
thumbnailRibbonView.layout(
left: bounds.left,
right: bounds.right,
bottom: previewTargetBottom,
height: 72
)
// Camera stream / photo preview area
//
photoPreviewView.layout(
left: bounds.left,
right: bounds.right,
top: notchMaskingView.bottom,
bottom: previewTargetBottom
)
}
private func layOutMainAreaWithThumbnailRibbonUnderPreview(
controlsFrame: CGRect,
thumbnailRibbonHeight: CGFloat)
{
// Controls
//
cameraControlsView.frame = controlsFrame
photoControlsView.frame = controlsFrame
// Thumbnail ribbon
//
thumbnailRibbonView.backgroundColor = theme?.thumbnailsViewBackgroundColor
thumbnailRibbonView.contentInsets = UIEdgeInsets(top: 8, left: 8, bottom: 0, right: 8)
thumbnailRibbonView.layout(
left: bounds.left,
right: bounds.right,
bottom: cameraControlsView.top,
height: thumbnailRibbonHeight
)
// Camera stream / photo preview area
//
photoPreviewView.layout(
left: bounds.left,
right: bounds.right,
top: notchMaskingView.bottom,
bottom: thumbnailRibbonView.top
)
}
private func layOutPhotoTitleLabel() {
photoTitleLabel.sizeToFit()
photoTitleLabel.left = ceil(bounds.centerX - photoTitleLabel.width / 2)
photoTitleLabel.top = max(notchMaskingView.bottom, fakeNavigationBarMinimumYOffset) + fakeNavigationBarContentTopInset + 9
}
// MARK: - ThemeConfigurable
func setTheme(_ theme: ThemeType) {
self.theme = theme
backgroundColor = theme.mediaPickerBackgroundColor
photoPreviewView.backgroundColor = theme.photoPreviewBackgroundColor
photoPreviewView.collectionViewBackgroundColor = theme.photoPreviewCollectionBackgroundColor
photoTitleLabelLightTextColor = theme.mediaPickerTitleLightColor
photoTitleLabelDarkTextColor = theme.mediaPickerTitleDarkColor
cameraControlsView.setTheme(theme)
photoControlsView.setTheme(theme)
thumbnailRibbonView.setTheme(theme)
topRightContinueButton.setTitleColor(theme.cameraContinueButtonTitleColor, for: .normal)
topRightContinueButton.titleLabel?.font = theme.cameraContinueButtonTitleFont
topRightContinueButton.setTitleColor(
theme.cameraContinueButtonTitleColor,
for: .normal
)
topRightContinueButton.setTitleColor(
theme.cameraContinueButtonTitleHighlightedColor,
for: .highlighted
)
let onePointSize = CGSize(width: 1, height: 1)
for button in [topRightContinueButton, closeButton] {
button.setBackgroundImage(
UIImage.imageWithColor(theme.cameraButtonsBackgroundNormalColor, imageSize: onePointSize),
for: .normal
)
button.setBackgroundImage(
UIImage.imageWithColor(theme.cameraButtonsBackgroundHighlightedColor, imageSize: onePointSize),
for: .highlighted
)
button.setBackgroundImage(
UIImage.imageWithColor(theme.cameraButtonsBackgroundDisabledColor, imageSize: onePointSize),
for: .disabled
)
}
bottomContinueButton.backgroundColor = theme.cameraBottomContinueButtonBackgroundColor
bottomContinueButton.titleLabel?.font = theme.cameraBottomContinueButtonFont
bottomContinueButton.setTitleColor(theme.cameraBottomContinueButtonTitleColor, for: .normal)
}
// MARK: - MediaPickerView
var onShutterButtonTap: (() -> ())? {
get { return cameraControlsView.onShutterButtonTap }
set { cameraControlsView.onShutterButtonTap = newValue }
}
var onPhotoLibraryButtonTap: (() -> ())? {
get { return cameraControlsView.onPhotoLibraryButtonTap }
set { cameraControlsView.onPhotoLibraryButtonTap = newValue }
}
var onFlashToggle: ((Bool) -> ())? {
get { return cameraControlsView.onFlashToggle }
set { cameraControlsView.onFlashToggle = newValue }
}
var onItemSelect: ((MediaPickerItem) -> ())?
var onRemoveButtonTap: (() -> ())? {
get { return photoControlsView.onRemoveButtonTap }
set { photoControlsView.onRemoveButtonTap = newValue }
}
var onAutocorrectButtonTap: (() -> ())? {
get { return photoControlsView.onAutocorrectButtonTap }
set { photoControlsView.onAutocorrectButtonTap = newValue }
}
var onCropButtonTap: (() -> ())? {
get { return photoControlsView.onCropButtonTap }
set { photoControlsView.onCropButtonTap = newValue }
}
var onCameraThumbnailTap: (() -> ())? {
get { return photoControlsView.onCameraButtonTap }
set { photoControlsView.onCameraButtonTap = newValue }
}
var onItemMove: ((Int, Int) -> ())?
var onSwipeToItem: ((MediaPickerItem) -> ())? {
get { return photoPreviewView.onSwipeToItem }
set { photoPreviewView.onSwipeToItem = newValue }
}
var onSwipeToCamera: (() -> ())? {
get { return photoPreviewView.onSwipeToCamera }
set { photoPreviewView.onSwipeToCamera = newValue }
}
var onSwipeToCameraProgressChange: ((CGFloat) -> ())? {
get { return photoPreviewView.onSwipeToCameraProgressChange }
set { photoPreviewView.onSwipeToCameraProgressChange = newValue }
}
var previewSize: CGSize {
return photoPreviewView.size
}
func setMode(_ mode: MediaPickerViewMode) {
switch mode {
case .camera:
cameraControlsView.isHidden = false
photoControlsView.isHidden = true
thumbnailRibbonView.selectCameraItem()
photoPreviewView.scrollToCamera()
case .photoPreview(let photo):
photoPreviewView.scrollToMediaItem(photo)
cameraControlsView.isHidden = true
photoControlsView.isHidden = false
}
self.mode = mode
adjustForDeviceOrientation(deviceOrientation)
}
func setAutocorrectionStatus(_ status: MediaPickerAutocorrectionStatus) {
switch status {
case .original:
photoControlsView.setAutocorrectButtonSelected(false)
case .corrected:
photoControlsView.setAutocorrectButtonSelected(true)
}
}
func setCameraControlsEnabled(_ enabled: Bool) {
cameraControlsView.setCameraControlsEnabled(enabled)
}
func setCameraButtonVisible(_ visible: Bool) {
photoPreviewView.setCameraVisible(visible)
thumbnailRibbonView.setCameraItemVisible(visible)
}
func setHapticFeedbackEnabled(_ enabled: Bool) {
photoPreviewView.hapticFeedbackEnabled = enabled
thumbnailRibbonView.setHapticFeedbackEnabled(enabled)
}
func setLatestPhotoLibraryItemImage(_ image: ImageSource?) {
cameraControlsView.setLatestPhotoLibraryItemImage(image)
}
func setFlashButtonVisible(_ visible: Bool) {
cameraControlsView.setFlashButtonVisible(visible)
}
func setFlashButtonOn(_ isOn: Bool) {
cameraControlsView.setFlashButtonOn(isOn)
}
func animateFlash() {
flashView.alpha = 1
UIView.animate(
withDuration: 0.3,
delay: 0,
options: [.curveEaseOut],
animations: {
self.flashView.alpha = 0
},
completion: nil
)
}
var onCloseButtonTap: (() -> ())?
var onContinueButtonTap: (() -> ())?
var onCameraToggleButtonTap: (() -> ())? {
get { return cameraControlsView.onCameraToggleButtonTap }
set { cameraControlsView.onCameraToggleButtonTap = newValue }
}
func setCameraToggleButtonVisible(_ visible: Bool) {
cameraControlsView.setCameraToggleButtonVisible(visible)
}
func setShutterButtonEnabled(_ enabled: Bool) {
cameraControlsView.setShutterButtonEnabled(enabled)
}
func setPhotoLibraryButtonEnabled(_ enabled: Bool) {
cameraControlsView.setPhotoLibraryButtonEnabled(enabled)
}
func setPhotoLibraryButtonVisible(_ visible: Bool) {
cameraControlsView.setPhotoLibraryButtonVisible(visible)
}
func setContinueButtonVisible(_ isVisible: Bool) {
topRightContinueButton.isHidden = !isVisible
bottomContinueButton.isHidden = !isVisible
}
func setContinueButtonStyle(_ style: MediaPickerContinueButtonStyle) {
guard topRightContinueButton.style != style else { return }
UIView.animate(
withDuration: 0.3,
animations: {
self.topRightContinueButton.style = style
if self.deviceOrientation == .portrait {
self.topRightContinueButton.size = CGSize(
width: self.topRightContinueButton.sizeThatFits().width,
height: self.topRightContinueButtonHeight
)
} else {
self.topRightContinueButton.size = CGSize(
width: self.topRightContinueButtonHeight,
height: self.topRightContinueButton.sizeThatFits().width
)
}
self.layOutFakeNavigationBarButtons()
}
)
}
func setContinueButtonPlacement(_ placement: MediaPickerContinueButtonPlacement) {
continueButtonPlacement = placement
}
func addItems(_ items: [MediaPickerItem], animated: Bool, completion: @escaping () -> ()) {
photoPreviewView.addItems(items)
thumbnailRibbonView.addItems(items, animated: animated, completion: completion)
}
func updateItem(_ item: MediaPickerItem) {
photoPreviewView.updateItem(item)
thumbnailRibbonView.updateItem(item)
}
func removeItem(_ item: MediaPickerItem) {
photoPreviewView.removeItem(item, animated: false)
thumbnailRibbonView.removeItem(item, animated: true)
}
func selectItem(_ item: MediaPickerItem) {
thumbnailRibbonView.selectMediaItem(item)
}
func moveItem(from sourceIndex: Int, to destinationIndex: Int) {
photoPreviewView.moveItem(from: sourceIndex, to: destinationIndex)
}
func scrollToItemThumbnail(_ item: MediaPickerItem, animated: Bool) {
thumbnailRibbonView.scrollToItemThumbnail(item, animated: animated)
}
func selectCamera() {
thumbnailRibbonView.selectCameraItem()
}
func scrollToCameraThumbnail(animated: Bool) {
thumbnailRibbonView.scrollToCameraThumbnail(animated: animated)
}
func adjustForDeviceOrientation(_ orientation: DeviceOrientation) {
deviceOrientation = orientation
var orientation = orientation
if UIDevice.current.userInterfaceIdiom == .phone, case .photoPreview = mode {
orientation = .portrait
}
let transform = CGAffineTransform(deviceOrientation: orientation)
closeAndContinueButtonsSwapped = (orientation == .landscapeLeft)
closeButton.transform = transform
topRightContinueButton.transform = transform
cameraControlsView.setControlsTransform(transform)
photoControlsView.setControlsTransform(transform)
thumbnailRibbonView.setControlsTransform(transform)
}
func setCameraView(_ view: UIView) {
photoPreviewView.setCameraView(view)
}
func setCameraOutputParameters(_ parameters: CameraOutputParameters) {
thumbnailRibbonView.setCameraOutputParameters(parameters)
}
func setCameraOutputOrientation(_ orientation: ExifOrientation) {
thumbnailRibbonView.setCameraOutputOrientation(orientation)
}
func setPhotoTitle(_ title: String) {
photoTitleLabel.text = title
photoTitleLabel.accessibilityValue = title
layOutPhotoTitleLabel()
}
func setPreferredPhotoTitleStyle(_ style: MediaPickerTitleStyle) {
switch style {
// TODO: (ayutkin) don't allow presenter to set title style directly
case .light where !UIDevice.current.hasTopSafeAreaInset:
photoTitleLabel.textColor = photoTitleLabelLightTextColor
photoTitleLabel.layer.shadowOpacity = 0.5
case .dark, .light:
photoTitleLabel.textColor = photoTitleLabelDarkTextColor
photoTitleLabel.layer.shadowOpacity = 0
}
}
func setPhotoTitleAlpha(_ alpha: CGFloat) {
photoTitleLabel.alpha = alpha
}
func setCloseButtonImage(_ image: UIImage?) {
closeButton.setImage(image, for: .normal)
}
func setContinueButtonTitle(_ title: String) {
topRightContinueButton.setTitle(title, for: .normal)
topRightContinueButton.accessibilityValue = title
topRightContinueButton.size = CGSize(width: topRightContinueButton.sizeThatFits().width, height: topRightContinueButtonHeight)
bottomContinueButton.setTitle(title, for: .normal)
bottomContinueButton.accessibilityValue = title
}
func setContinueButtonEnabled(_ isEnabled: Bool) {
topRightContinueButton.isEnabled = isEnabled
bottomContinueButton.isEnabled = isEnabled
}
func setShowsCropButton(_ showsCropButton: Bool) {
if showsCropButton {
photoControlsView.mode.insert(.hasCropButton)
} else {
photoControlsView.mode.remove(.hasCropButton)
}
}
func setShowsAutocorrectButton(_ showsAutocorrectButton: Bool) {
if showsAutocorrectButton {
photoControlsView.mode.insert(.hasAutocorrectButton)
} else {
photoControlsView.mode.remove(.hasAutocorrectButton)
}
}
func setShowsPreview(_ showsPreview: Bool) {
self.showsPreview = showsPreview
}
func setViewfinderOverlay(_ overlay: UIView?) {
photoPreviewView.setViewfinderOverlay(overlay)
}
func reloadCamera() {
photoPreviewView.reloadCamera()
thumbnailRibbonView.reloadCamera()
}
func showInfoMessage(_ message: String, timeout: TimeInterval) {
let viewData = InfoMessageViewData(text: message, timeout: timeout, font: theme?.infoMessageFont)
infoMessageDisplayer.display(viewData: viewData, in: photoPreviewView)
}
// MARK: - Private
private func setUpThumbnailRibbonView() {
thumbnailRibbonView.onPhotoItemSelect = { [weak self] mediaPickerItem in
self?.onItemSelect?(mediaPickerItem)
}
thumbnailRibbonView.onCameraItemSelect = { [weak self] in
self?.onCameraThumbnailTap?()
}
thumbnailRibbonView.onItemMove = { [weak self] sourceIndex, destinationIndex in
self?.onItemMove?(sourceIndex, destinationIndex)
}
thumbnailRibbonView.onDragStart = { [weak self] in
self?.isUserInteractionEnabled = false
}
thumbnailRibbonView.onDragFinish = { [weak self] in
self?.isUserInteractionEnabled = true
}
}
private func setUpButtons() {
let closeButtonSize = CGSize(width: 38, height: 38)
closeButton.layer.cornerRadius = closeButtonSize.height / 2
closeButton.layer.masksToBounds = true
closeButton.size = closeButtonSize
closeButton.addTarget(
self,
action: #selector(onCloseButtonTap(_:)),
for: .touchUpInside
)
topRightContinueButton.layer.cornerRadius = topRightContinueButtonHeight / 2
topRightContinueButton.layer.masksToBounds = true
topRightContinueButton.contentEdgeInsets = topRightContinueButtonContentInsets
topRightContinueButton.addTarget(
self,
action: #selector(onContinueButtonTap(_:)),
for: .touchUpInside
)
bottomContinueButton.layer.cornerRadius = 5
bottomContinueButton.titleEdgeInsets = UIEdgeInsets(top: 6, left: 16, bottom: 8, right: 16)
bottomContinueButton.addTarget(
self,
action: #selector(onContinueButtonTap(_:)),
for: .touchUpInside
)
}
private func setUpAccessibilityIdentifiers() {
closeButton.setAccessibilityId(.closeButton)
topRightContinueButton.setAccessibilityId(.continueButton)
bottomContinueButton.setAccessibilityId(.continueButton)
photoTitleLabel.setAccessibilityId(.titleLabel)
accessibilityIdentifier = AccessibilityId.mediaPicker.rawValue
}
@objc private func onCloseButtonTap(_: UIButton) {
onCloseButtonTap?()
}
@objc private func onContinueButtonTap(_: UIButton) {
onContinueButtonTap?()
}
}
| fc0af59da9b61d73312a5196af803255 | 34.311707 | 134 | 0.642395 | false | false | false | false |
amraboelela/swift | refs/heads/master | test/SILGen/lying_about_optional_return_objc.swift | apache-2.0 | 12 | // RUN: %target-swift-emit-silgen(mock-sdk: %clang-importer-sdk) -enable-objc-interop -import-objc-header %S/Inputs/block_property_in_objc_class.h %s | %FileCheck %s
// CHECK-LABEL: sil hidden [ossa] @$s32lying_about_optional_return_objc0C37ChainingForeignFunctionTypeProperties{{[_0-9a-zA-Z]*}}F
func optionalChainingForeignFunctionTypeProperties(b: BlockProperty?) {
// CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $()
b?.readWriteBlock()
// CHECK: enum $Optional
_ = b?.readWriteBlock
// CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $()
b?.readOnlyBlock()
// CHECK: enum $Optional
_ = b?.readOnlyBlock
// CHECK: unchecked_trivial_bit_cast
_ = b?.selector
// CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $()
_ = b?.voidReturning()
// CHECK: unchecked_trivial_bit_cast
_ = b?.voidPointerReturning()
// CHECK: unchecked_trivial_bit_cast
_ = b?.opaquePointerReturning()
// CHECK: unchecked_trivial_bit_cast
_ = b?.pointerReturning()
// CHECK: unchecked_trivial_bit_cast
_ = b?.constPointerReturning()
// CHECK: unchecked_trivial_bit_cast
_ = b?.selectorReturning()
// CHECK: unchecked_ref_cast
_ = b?.objectReturning()
// CHECK: enum $Optional<{{.*}} -> {{.*}}>
_ = b?.voidReturning
// CHECK: enum $Optional<{{.*}} -> {{.*}}>
_ = b?.voidPointerReturning
// CHECK: enum $Optional<{{.*}} -> {{.*}}>
_ = b?.opaquePointerReturning
// CHECK: enum $Optional<{{.*}} -> {{.*}}>
_ = b?.pointerReturning
// CHECK: enum $Optional<{{.*}} -> {{.*}}>
_ = b?.constPointerReturning
// CHECK: enum $Optional<{{.*}} -> {{.*}}>
_ = b?.selectorReturning
// CHECK: enum $Optional<{{.*}} -> {{.*}}>
_ = b?.objectReturning
// CHECK-LABEL: debug_value {{.*}} name "dynamic"
let dynamic: AnyObject? = b!
// CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $()
_ = dynamic?.voidReturning()
// CHECK: unchecked_trivial_bit_cast {{.*}} $UnsafeMutableRawPointer to $Optional
_ = dynamic?.voidPointerReturning()
// CHECK: unchecked_trivial_bit_cast {{.*}} $OpaquePointer to $Optional
_ = dynamic?.opaquePointerReturning()
// CHECK: unchecked_trivial_bit_cast {{.*}} $UnsafeMutablePointer{{.*}} to $Optional
_ = dynamic?.pointerReturning()
// CHECK: unchecked_trivial_bit_cast {{.*}} $UnsafePointer{{.*}} to $Optional
_ = dynamic?.constPointerReturning()
// CHECK: unchecked_trivial_bit_cast {{.*}} $Selector to $Optional
_ = dynamic?.selectorReturning()
// CHECK: unchecked_ref_cast {{.*}} $BlockProperty to $Optional
_ = dynamic?.objectReturning()
// FIXME: Doesn't opaquely cast the selector result!
// C/HECK: unchecked_trivial_bit_cast {{.*}} $Selector to $Optional
_ = dynamic?.selector
// CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> ()>, #Optional.some
_ = dynamic?.voidReturning
// CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> UnsafeMutableRawPointer>, #Optional.some
_ = dynamic?.voidPointerReturning
// CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> OpaquePointer>, #Optional.some
_ = dynamic?.opaquePointerReturning
// CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> UnsafeMutablePointer{{.*}}>, #Optional.some
_ = dynamic?.pointerReturning
// CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> UnsafePointer{{.*}}>, #Optional.some
_ = dynamic?.constPointerReturning
// CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> Selector>, #Optional.some
_ = dynamic?.selectorReturning
// CHECK: inject_enum_addr {{%.*}} : $*Optional<{{.*}} -> @owned BlockProperty>, #Optional.some
_ = dynamic?.objectReturning
// CHECK: enum $Optional<()>, #Optional.some!enumelt.1, {{%.*}} : $()
_ = dynamic?.voidReturning?()
// CHECK: unchecked_trivial_bit_cast
_ = dynamic?.voidPointerReturning?()
// CHECK: unchecked_trivial_bit_cast
_ = dynamic?.opaquePointerReturning?()
// CHECK: unchecked_trivial_bit_cast
_ = dynamic?.pointerReturning?()
// CHECK: unchecked_trivial_bit_cast
_ = dynamic?.constPointerReturning?()
// CHECK: unchecked_trivial_bit_cast
_ = dynamic?.selectorReturning?()
_ = dynamic?.objectReturning?()
}
| 845d9c6b089c6826ced59a102a74be12 | 40.336634 | 165 | 0.630898 | false | false | false | false |
e78l/swift-corelibs-foundation | refs/heads/master | Foundation/NSCFSet.swift | apache-2.0 | 2 | // This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
import CoreFoundation
internal final class _NSCFSet : NSMutableSet {
deinit {
_CFDeinit(self)
_CFZeroUnsafeIvars(&_storage)
}
required init() {
fatalError()
}
required init?(coder aDecoder: NSCoder) {
fatalError()
}
required init(capacity numItems: Int) {
fatalError()
}
override var classForCoder: AnyClass {
return NSMutableSet.self
}
override var count: Int {
return CFSetGetCount(_cfObject)
}
override func member(_ object: Any) -> Any? {
guard let value = CFSetGetValue(_cfObject, unsafeBitCast(__SwiftValue.store(object), to: UnsafeRawPointer.self)) else {
return nil
}
return __SwiftValue.fetch(nonOptional: unsafeBitCast(value, to: AnyObject.self))
}
override func objectEnumerator() -> NSEnumerator {
var objArray: [AnyObject] = []
let cf = _cfObject
let count = CFSetGetCount(cf)
let objects = UnsafeMutablePointer<UnsafeRawPointer?>.allocate(capacity: count)
CFSetGetValues(cf, objects)
for idx in 0..<count {
let obj = unsafeBitCast(objects.advanced(by: idx).pointee!, to: AnyObject.self)
objArray.append(obj)
}
objects.deinitialize(count: 1)
objects.deallocate()
return NSGeneratorEnumerator(objArray.makeIterator())
}
override func add(_ object: Any) {
CFSetAddValue(_cfMutableObject, unsafeBitCast(__SwiftValue.store(object), to: UnsafeRawPointer.self))
}
override func remove(_ object: Any) {
CFSetRemoveValue(_cfMutableObject, unsafeBitCast(__SwiftValue.store(object), to: UnsafeRawPointer.self))
}
}
internal func _CFSwiftSetGetCount(_ set: AnyObject) -> CFIndex {
return (set as! NSSet).count
}
internal func _CFSwiftSetGetCountOfValue(_ set: AnyObject, value: AnyObject) -> CFIndex {
if _CFSwiftSetContainsValue(set, value: value) {
return 1
} else {
return 0
}
}
internal func _CFSwiftSetContainsValue(_ set: AnyObject, value: AnyObject) -> Bool {
return _CFSwiftSetGetValue(set, value: value, key: value) != nil
}
internal func _CFSwiftSetGetValues(_ set: AnyObject, _ values: UnsafeMutablePointer<Unmanaged<AnyObject>?>?) {
var idx = 0
if values == nil {
return
}
let set = set as! NSSet
if type(of: set) === NSSet.self || type(of: set) === NSMutableSet.self {
for obj in set._storage {
values?[idx] = Unmanaged<AnyObject>.passUnretained(obj)
idx += 1
}
} else {
set.enumerateObjects( { v, _ in
let value = __SwiftValue.store(v)
values?[idx] = Unmanaged<AnyObject>.passUnretained(value)
set._storage.update(with: value)
idx += 1
})
}
}
internal func _CFSwiftSetGetValue(_ set: AnyObject, value: AnyObject, key: AnyObject) -> Unmanaged<AnyObject>? {
let set = set as! NSSet
if type(of: set) === NSSet.self || type(of: set) === NSMutableSet.self {
if let idx = set._storage.firstIndex(of: value as! NSObject){
return Unmanaged<AnyObject>.passUnretained(set._storage[idx])
}
} else {
let v = __SwiftValue.store(set.member(value))
if let obj = v {
set._storage.update(with: obj)
return Unmanaged<AnyObject>.passUnretained(obj)
}
}
return nil
}
internal func _CFSwiftSetGetValueIfPresent(_ set: AnyObject, object: AnyObject, value: UnsafeMutablePointer<Unmanaged<AnyObject>?>?) -> Bool {
if let val = _CFSwiftSetGetValue(set, value: object, key: object) {
value?.pointee = val
return true
} else {
value?.pointee = nil
return false
}
}
internal func _CFSwiftSetApplyFunction(_ set: AnyObject, applier: @convention(c) (AnyObject, UnsafeMutableRawPointer) -> Void, context: UnsafeMutableRawPointer) {
(set as! NSSet).enumerateObjects({ value, _ in
applier(__SwiftValue.store(value), context)
})
}
internal func _CFSwiftSetMember(_ set: CFTypeRef, _ object: CFTypeRef) -> Unmanaged<CFTypeRef>? {
return _CFSwiftSetGetValue(set, value: object, key: object)
}
internal func _CFSwiftSetAddValue(_ set: AnyObject, value: AnyObject) {
(set as! NSMutableSet).add(value)
}
internal func _CFSwiftSetReplaceValue(_ set: AnyObject, value: AnyObject) {
let set = set as! NSMutableSet
if (set.contains(value)){
set.remove(value)
set.add(value)
}
}
internal func _CFSwiftSetSetValue(_ set: AnyObject, value: AnyObject) {
let set = set as! NSMutableSet
set.remove(value)
set.add(value)
}
internal func _CFSwiftSetRemoveValue(_ set: AnyObject, value: AnyObject) {
(set as! NSMutableSet).remove(value)
}
internal func _CFSwiftSetRemoveAllValues(_ set: AnyObject) {
(set as! NSMutableSet).removeAllObjects()
}
internal func _CFSwiftSetCreateCopy(_ set: AnyObject) -> Unmanaged<AnyObject> {
return Unmanaged<AnyObject>.passRetained((set as! NSSet).copy() as! NSObject)
}
| 3ce84e1ea59d301a3b264352c8a91ee0 | 29.505495 | 162 | 0.635086 | false | false | false | false |
webim/webim-client-sdk-ios | refs/heads/master | Example/WebimClientLibrary/ViewControllers/ChatViewController/Views/WMToolbarView/WMNewMessageView.swift | mit | 1 | //
// WMNewMessageView.swift
// Webim.Ru
//
// Created by Anna Frolova on 16.02.2022.
// Copyright © 2021 _webim_. 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 WebimClientLibrary
protocol WMNewMessageViewDelegate: AnyObject {
func inputTextChanged()
func sendMessage()
func showSendFileMenu(_ sender: UIButton)
}
class WMNewMessageView: UIView {
static let maxInputTextViewHeight: CGFloat = 90
static let minInputTextViewHeight: CGFloat = 344
weak var delegate: WMNewMessageViewDelegate?
@IBOutlet var sendButton: UIButton!
@IBOutlet private var fileButton: UIButton!
@IBOutlet private var messagePlaceholder: UILabel!
@IBOutlet var messageText: UITextView!
@IBOutlet private var inputTextFieldConstraint: NSLayoutConstraint!
func resignMessageViewFirstResponder() {
self.messageText.resignFirstResponder()
}
func getMessage() -> String {
return self.messageText.text
}
func setMessageText(_ message: String) {
self.messageText.text = message
// Workaround to trigger textViewDidChange
self.messageText.replace(
self.messageText.textRange(
from: self.messageText.beginningOfDocument,
to: self.messageText.endOfDocument) ?? UITextRange(),
withText: message
)
recountViewHeight()
}
func recountViewHeight() {
let size = messageText.sizeThatFits(CGSize(width: messageText.frame.width, height: CGFloat(MAXFLOAT)))
inputTextFieldConstraint.constant = min(size.height, WMNewMessageView.maxInputTextViewHeight)
}
override func loadXibViewSetup() {
messageText.layer.cornerRadius = 17
messageText.layer.borderWidth = 1
messageText.layer.borderColor = wmGreyMessage
messageText.isScrollEnabled = true
messageText.textColor = .black
messageText.contentInset.left = 10
messageText.textContainerInset.right = 40
let topBorder = CALayer()
topBorder.frame = CGRect(x: 0, y: 0, width: max(UIScreen.main.bounds.width, UIScreen.main.bounds.height), height: 1)
topBorder.backgroundColor = wmGreyMessage
layer.addSublayer(topBorder)
messageText.delegate = self
translatesAutoresizingMaskIntoConstraints = false
recountViewHeight()
}
var textInputTextViewBufferString: String?
var alreadyPutTextFromBufferString = false
@IBAction func sendMessage() {
self.delegate?.sendMessage()
}
@IBAction func sendFile(_ sender: UIButton) {
self.delegate?.showSendFileMenu(sender)
}
func insertText(_ text: String) {
self.messageText.replace(self.messageText.selectedRange.toTextRange(textInput: self.messageText)!, withText: text)
}
}
extension WMNewMessageView: UITextViewDelegate {
func textViewDidEndEditing(_ textView: UITextView) {
showHidePlaceholder(in: textView)
}
func textViewDidChange(_ textView: UITextView) {
recountViewHeight()
showHidePlaceholder(in: textView)
self.delegate?.inputTextChanged()
}
func showHidePlaceholder(in textView: UITextView) {
let check = textView.hasText && !textView.text.isEmpty
messageText.layer.borderColor = check ? wmLayerColor : wmGreyMessage
messagePlaceholder.isHidden = check
sendButton.isEnabled = check
}
}
| a4495701a512e20742c0b59120689da6 | 34.851563 | 124 | 0.70037 | false | false | false | false |
fs/ios-base-swift | refs/heads/master | Swift-Base/Tools/Event/EventListener.swift | mit | 1 | //
// EventListener.swift
// Tools
//
// Created by Almaz Ibragimov on 12.05.2018.
// Copyright © 2018 Flatstack. All rights reserved.
//
import Foundation
public final class EventListener<T> {
// MARK: - Instance Properties
public fileprivate(set) weak var receiver: AnyObject?
public let event: Event<T>
public let handler: Event<T>.Handler
public let connection: EventConnection
// MARK: - Initializers
init(receiver: AnyObject, event: Event<T>, handler: @escaping Event<T>.Handler) {
self.receiver = receiver
self.event = event
self.handler = handler
self.connection = EventListenerConnection(event: event)
}
// MARK: - Instance Methods
public func emit(data: T) {
if (self.receiver != nil) && (!self.connection.isPaused) {
self.handler(data)
}
}
}
| fc72647fa1feed73b499d2fb1fee7a0d | 20.825 | 85 | 0.63803 | false | false | false | false |
SereivoanYong/Charts | refs/heads/master | Source/Charts/Charts/CombinedChartView.swift | apache-2.0 | 1 | //
// CombinedChartView.swift
// Charts
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import UIKit
/// This chart class allows the combination of lines, bars, scatter and candle data all displayed in one chart area.
open class CombinedChartView: BaseBarLineChartView, CombinedChartDataProvider {
/// the fill-formatter used for determining the position of the fill-line
internal var _fillFormatter: IFillFormatter!
/// enum that allows to specify the order in which the different data objects for the combined-chart are drawn
public enum DrawOrder: Int {
case bar
case bubble
case line
case candle
case scatter
}
open override func initialize() {
super.initialize()
highlighter = CombinedHighlighter(chart: self, barDataProvider: self)
// Old default behaviour
isHighlightFullBarEnabled = true
_fillFormatter = DefaultFillFormatter()
renderer = CombinedChartRenderer(chart: self, animator: animator, viewPortHandler: viewPortHandler)
}
open override var data: ChartData? {
didSet {
highlighter = CombinedHighlighter(chart: self, barDataProvider: self)
(renderer as! CombinedChartRenderer?)!.createRenderers()
renderer?.initBuffers()
}
}
open var fillFormatter: IFillFormatter {
get {
return _fillFormatter
}
set {
_fillFormatter = newValue
if _fillFormatter == nil {
_fillFormatter = DefaultFillFormatter()
}
}
}
/// - returns: The Highlight object (contains x-index and DataSet index) of the selected value at the given touch point inside the CombinedChart.
open override func getHighlightByTouchPoint(_ pt: CGPoint) -> Highlight? {
if data == nil {
print("Can't select by touch. No data set.")
return nil
}
guard let h = highlighter?.highlight(at: pt) else {
return nil
}
if !isHighlightFullBarEnabled {
return h
}
// For isHighlightFullBarEnabled, remove stackIndex
return Highlight(
x: h.x, y: h.y,
xPx: h.xPx, yPx: h.yPx,
dataSetIndex: h.dataSetIndex,
stackIndex: -1,
axis: h.axis)
}
// MARK: - CombinedChartDataProvider
open var combinedData: CombinedData? {
return data as? CombinedData
}
// MARK: - LineChartDataProvider
open var lineData: LineData? {
return (data as? CombinedData)?.lineData
}
// MARK: - BarChartDataProvider
open var barData: BarData? {
return (data as? CombinedData)?.barData
}
// MARK: - ScatterChartDataProvider
open var scatterData: ScatterData? {
return (data as? CombinedData)?.scatterData
}
// MARK: - CandleChartDataProvider
open var candleData: CandleData? {
return (data as? CombinedData)?.candleData
}
// MARK: - BubbleChartDataProvider
open var bubbleData: BubbleData? {
return (data as? CombinedData)?.bubbleData
}
// MARK: - Accessors
/// if set to true, all values are drawn above their bars, instead of below their top
open var drawValueAboveBarEnabled: Bool {
get { return (renderer as! CombinedChartRenderer!).isDrawValueAboveBarEnabled }
set { (renderer as! CombinedChartRenderer!).isDrawValueAboveBarEnabled = newValue }
}
/// if set to true, a grey area is drawn behind each bar that indicates the maximum value
open var drawBarShadowEnabled: Bool {
get { return (renderer as! CombinedChartRenderer!).isDrawBarShadowEnabled }
set { (renderer as! CombinedChartRenderer!).isDrawBarShadowEnabled = newValue }
}
/// - returns: `true` if drawing values above bars is enabled, `false` ifnot
open var isDrawValueAboveBarEnabled: Bool { return (renderer as! CombinedChartRenderer!).isDrawValueAboveBarEnabled }
/// - returns: `true` if drawing shadows (maxvalue) for each bar is enabled, `false` ifnot
open var isDrawBarShadowEnabled: Bool { return (renderer as! CombinedChartRenderer!).isDrawBarShadowEnabled }
/// the order in which the provided data objects should be drawn.
/// The earlier you place them in the provided array, the further they will be in the background.
/// e.g. if you provide [DrawOrder.Bar, DrawOrder.Line], the bars will be drawn behind the lines.
open var drawOrder: [Int] {
get {
return (renderer as! CombinedChartRenderer!).drawOrder.map { $0.rawValue }
}
set {
(renderer as! CombinedChartRenderer!).drawOrder = newValue.map { DrawOrder(rawValue: $0)! }
}
}
/// Set this to `true` to make the highlight operation full-bar oriented, `false` to make it highlight single values
open var isHighlightFullBarEnabled: Bool = false
}
| d0809599d02e4eecfda48c2c0ebe0f5a | 29.544304 | 147 | 0.688976 | false | false | false | false |
jpsim/SourceKitten | refs/heads/main | Source/SourceKittenFramework/Structure.swift | mit | 1 | /// Represents the structural information in a Swift source file.
public struct Structure {
/// Structural information as an [String: SourceKitRepresentable].
public let dictionary: [String: SourceKitRepresentable]
/**
Create a Structure from a SourceKit `editor.open` response.
- parameter sourceKitResponse: SourceKit `editor.open` response.
*/
public init(sourceKitResponse: [String: SourceKitRepresentable]) {
var sourceKitResponse = sourceKitResponse
_ = sourceKitResponse.removeValue(forKey: SwiftDocKey.syntaxMap.rawValue)
dictionary = sourceKitResponse
}
/**
Initialize a Structure by passing in a File.
- parameter file: File to parse for structural information.
- throws: Request.Error
*/
public init(file: File) throws {
self.init(sourceKitResponse: try Request.editorOpen(file: file).send())
}
}
// MARK: CustomStringConvertible
extension Structure: CustomStringConvertible {
/// A textual JSON representation of `Structure`.
public var description: String { return toJSON(toNSDictionary(dictionary)) }
}
// MARK: Equatable
extension Structure: Equatable {}
/**
Returns true if `lhs` Structure is equal to `rhs` Structure.
- parameter lhs: Structure to compare to `rhs`.
- parameter rhs: Structure to compare to `lhs`.
- returns: True if `lhs` Structure is equal to `rhs` Structure.
*/
public func == (lhs: Structure, rhs: Structure) -> Bool {
return lhs.dictionary.isEqualTo(rhs.dictionary)
}
| 74fda63e346017346a7ddcd0ff971a57 | 30.142857 | 81 | 0.711664 | false | false | false | false |
IngmarStein/swift | refs/heads/master | benchmark/single-source/PopFront.swift | apache-2.0 | 4 | //===--- PopFront.swift ---------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import TestsUtils
let reps = 1
let arrayCount = 1024
@inline(never)
public func run_PopFrontArray(_ N: Int) {
let orig = Array(repeating: 1, count: arrayCount)
var a = [Int]()
for _ in 1...20*N {
for _ in 1...reps {
var result = 0
a.append(contentsOf: orig)
while a.count != 0 {
result += a[0]
a.remove(at: 0)
}
CheckResults(result == arrayCount, "IncorrectResults in StringInterpolation: \(result) != \(arrayCount)")
}
}
}
@inline(never)
public func run_PopFrontUnsafePointer(_ N: Int) {
var orig = Array(repeating: 1, count: arrayCount)
let a = UnsafeMutablePointer<Int>.allocate(capacity: arrayCount)
for _ in 1...100*N {
for _ in 1...reps {
for i in 0..<arrayCount {
a[i] = orig[i]
}
var result = 0
var count = arrayCount
while count != 0 {
result += a[0]
a.assign(from: a + 1, count: count - 1)
count -= 1
}
CheckResults(result == arrayCount, "IncorrectResults in StringInterpolation: \(result) != \(arrayCount)")
}
}
a.deallocate(capacity: arrayCount)
}
| 4f12bee00014bfe01d046c7973b53dac | 28.214286 | 111 | 0.570905 | false | false | false | false |
nodekit-io/nodekit-darwin-lite | refs/heads/master | src/nodekit/NKScriptingLite/NKJSContext.swift | apache-2.0 | 1 | /*
* nodekit.io
*
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
* Portions Copyright 2015 XWebView
* Portions Copyright (c) 2014 Intel Corporation. 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 JavaScriptCore
open class NKJSContext: NSObject {
fileprivate let _jsContext: JSContext
fileprivate let _id: Int
private var plugins: [String: NKNativePlugin] = [:] //namespace -> plugin
private var sources: [String: NKScriptSource] = [:] //filename -> source
internal init(_ jsContext: JSContext, id: Int) {
_jsContext = jsContext
_id = id
super.init()
}
internal func prepareEnvironment() -> Void {
let logjs: @convention(block) (String, String, [String: AnyObject] ) -> () = { body, severity, labels in
NKLogging.log(body, level: NKLogging.Level(description: severity), labels: labels);
}
_jsContext.exceptionHandler = { (ctx: JSContext?, value: JSValue?) in
NKLogging.log("JavaScript Error");
// type of String
let stacktrace = value?.objectForKeyedSubscript("stack").toString() ?? "No stack trace"
// type of Number
let lineNumber: Any = value?.objectForKeyedSubscript("line") ?? "Unknown"
// type of Number
let column: Any = value?.objectForKeyedSubscript("column") ?? "Unknown"
let moreInfo = "in method \(stacktrace) Line number: \(lineNumber), column: \(column)"
let errorString = value.map { $0.description } ?? "null"
NKLogging.log("JavaScript Error: \(errorString) \(moreInfo)")
}
guard let _ = NKStorage.getResource("lib-scripting.nkar/lib-scripting/timer.js", NKJSContext.self) else {
NKLogging.die("Failed to read provision script: timer")
}
loadPlugin(NKJSTimer())
let scriptingBridge = JSValue(newObjectIn: _jsContext)
scriptingBridge?.setObject(logjs as AnyObject, forKeyedSubscript: "log" as NSString)
_jsContext.setObject(scriptingBridge, forKeyedSubscript: "NKScriptingBridge" as NSString)
let appjs = NKStorage.getResource("lib-scripting.nkar/lib-scripting/init_jsc.js", NKJSContext.self)
let script = "function loadinit(){\n" + appjs! + "\n}\n" + "loadinit();" + "\n"
self.injectJavaScript(NKScriptSource(source: script, asFilename: "io.nodekit.scripting/init_jsc", namespace: "io.nodekit.scripting.init"))
guard let promiseSource = NKStorage.getResource("lib-scripting.nkar/lib-scripting/promise.js", NKJSContext.self) else {
NKLogging.die("Failed to read provision script: promise")
}
self.injectJavaScript(
NKScriptSource(
source: promiseSource,
asFilename: "io.nodekit.scripting/NKScripting/promise.js",
namespace: "Promise"
)
)
NKStorage.attachTo(self)
}
}
extension NKJSContext: NKScriptContext {
public var id: Int {
get { return self._id }
}
public func loadPlugin(_ plugin: NKNativePlugin) -> Void {
if let jsValue = setObjectForNamespace(plugin, namespace: plugin.namespace),
let proxy = plugin as? NKNativeProxy {
proxy.nkScriptObject = jsValue
}
NKLogging.log("+Plugin object \(plugin) is bound to \(plugin.namespace) with NKScriptingLite (JSExport) channel")
plugins[plugin.namespace] = plugin
guard let jspath: String = plugin.sourceJS else { return }
guard let js = NKStorage.getResource(jspath, type(of: plugin)) else { return }
self.injectJavaScript(
NKScriptSource(
source: js,
asFilename: jspath,
namespace: plugin.namespace
)
)
}
public func injectJavaScript(_ script: NKScriptSource) -> Void {
script.inject(self)
sources[script.filename] = script
}
public func evaluateJavaScript(_ javaScriptString: String,
completionHandler: ((AnyObject?,
NSError?) -> Void)?) {
let result = self._jsContext.evaluateScript(javaScriptString)
completionHandler?(result, nil)
}
public func stop() -> Void {
for plugin in plugins.values {
if let proxy = plugin as? NKNativeProxy {
proxy.nkScriptObject = nil
}
if let disposable = plugin as? NKDisposable {
disposable.dispose()
}
}
for script in sources.values {
script.eject()
}
plugins.removeAll()
sources.removeAll()
}
public func serialize(_ object: AnyObject?) -> String {
var obj: AnyObject? = object
if let val = obj as? NSValue {
obj = val as? NSNumber ?? val.nonretainedObjectValue as AnyObject?
}
if let s = obj as? String {
let d = try? JSONSerialization.data(withJSONObject: [s], options: JSONSerialization.WritingOptions(rawValue: 0))
let json = NSString(data: d!, encoding: String.Encoding.utf8.rawValue)!
return json.substring(with: NSMakeRange(1, json.length - 2))
} else if let n = obj as? NSNumber {
if CFGetTypeID(n) == CFBooleanGetTypeID() {
return n.boolValue.description
}
return n.stringValue
} else if let date = obj as? Date {
return "\"\(date.toJSONDate())\""
} else if let _ = obj as? Data {
// TODO: map to Uint8Array object
} else if let a = obj as? [AnyObject] {
return "[" + a.map(self.serialize).joined(separator: ", ") + "]"
} else if let d = obj as? [String: AnyObject] {
return "{" + d.keys.map {"\"\($0)\": \(self.serialize(d[$0]!))"}.joined(separator: ", ") + "}"
} else if obj === NSNull() {
return "null"
} else if obj == nil {
return "undefined"
}
return "'\(obj!)'"
}
// private methods
fileprivate func setObjectForNamespace(_ object: AnyObject, namespace: String) -> JSValue? {
let global = _jsContext.globalObject
var fullNameArr = namespace.split {$0 == "."}.map(String.init)
let lastItem = fullNameArr.removeLast()
if (fullNameArr.isEmpty) {
_jsContext.setObject(object, forKeyedSubscript: lastItem as NSString)
return nil
}
let jsv = fullNameArr.reduce(global, {previous, current in
if (previous?.hasProperty(current))! {
return previous?.objectForKeyedSubscript(current)
}
let _jsv = JSValue(newObjectIn: _jsContext)
previous?.setObject(_jsv, forKeyedSubscript: current as NSString)
return _jsv
})
jsv?.setObject(object, forKeyedSubscript: lastItem as NSString)
let selfjsv = (jsv?.objectForKeyedSubscript(lastItem))! as JSValue
return selfjsv
}
}
| 1ab18f70a7964d480badf08a6e1ad150 | 31.73494 | 146 | 0.565697 | false | false | false | false |
louisdh/microcontroller-kit | refs/heads/master | Sources/MicrocontrollerKit/SevenSegmentDisplay.swift | mit | 1 | //
// SevenSegmentDisplay.swift
// MicrocontrollerKit
//
// Created by Louis D'hauwe on 14/08/2017.
// Copyright © 2017 Silver Fox. All rights reserved.
//
import Foundation
/// A Seven-segment display (SSD), or seven-segment indicator,
/// is a form of electronic display device for displaying decimal
/// numerals that is an alternative to the more complex dot matrix displays.
///
/// *More info*: [Wikipedia](https://en.wikipedia.org/wiki/Seven-segment_display)
public struct SevenSegmentDisplay: Hashable {
public let a: Bit
public let b: Bit
public let c: Bit
public let d: Bit
public let e: Bit
public let f: Bit
public let g: Bit
/// Sets bits to show the hexadecimal value from a `Nibble`.
public init(nibble: Nibble) {
let A = nibble.b3
let B = nibble.b2
let C = nibble.b1
let D = nibble.b0
// These formulas were determined using K-map simplification.
a = A + C + (B & D) + (~B & ~D)
b = ~B + (~C & ~D) + (C & D)
c = B + ~C + D
d = (~B & ~D) + (C & ~D) + (B & ~C & D) + (~B & C) + A
e = (~B & ~D) + (C & ~D)
f = A + (~C & ~D) + (B & ~C) + (B & ~D)
g = A + (B & ~C) + (~B & C) + (C & ~D)
}
}
extension SevenSegmentDisplay: CustomStringConvertible {
public var description: String {
var out = ""
let onChar = "⚪️"
let offChar = "⚫️"
if a == .one {
out += "\(offChar)\(onChar)\(onChar)\(onChar)\(onChar)\(offChar)\n"
} else {
out += "\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\n"
}
for _ in 1...4 {
if f == .one && b == .one {
out += "\(onChar)\(offChar)\(offChar)\(offChar)\(offChar)\(onChar)\n"
} else if f == .one {
out += "\(onChar)\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\n"
} else if b == .one {
out += "\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\(onChar)\n"
} else {
out += "\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\n"
}
}
if g == .one {
out += "\(offChar)\(onChar)\(onChar)\(onChar)\(onChar)\(offChar)\n"
} else {
out += "\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\n"
}
for _ in 1...4 {
if e == .one && c == .one {
out += "\(onChar)\(offChar)\(offChar)\(offChar)\(offChar)\(onChar)\n"
} else if e == .one {
out += "\(onChar)\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\n"
} else if c == .one {
out += "\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\(onChar)\n"
} else {
out += "\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\n"
}
}
if d == .one {
out += "\(offChar)\(onChar)\(onChar)\(onChar)\(onChar)\(offChar)\n"
} else {
out += "\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\(offChar)\n"
}
return out
}
}
| e8c64f2398784a10ef410569fbc38c27 | 24.083333 | 81 | 0.566261 | false | false | false | false |
narner/AudioKit | refs/heads/master | AudioKit/macOS/AudioKit/User Interface/AKKeyboardView.swift | mit | 1 | //
// AKKeyboardView.swift
// AudioKit for macOS
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import Cocoa
public protocol AKKeyboardDelegate: class {
func noteOn(note: MIDINoteNumber)
func noteOff(note: MIDINoteNumber)
}
public class AKKeyboardView: NSView, AKMIDIListener {
override public var isFlipped: Bool {
return true
}
var size = CGSize.zero
@IBInspectable open var octaveCount: Int = 2
@IBInspectable open var firstOctave: Int = 4
@IBInspectable open var topKeyHeightRatio: CGFloat = 0.55
@IBInspectable open var polyphonicButton: NSColor = #colorLiteral(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)
@IBInspectable open var whiteKeyOff: NSColor = #colorLiteral(red: 1.000, green: 1.000, blue: 1.000, alpha: 1.000)
@IBInspectable open var blackKeyOff: NSColor = #colorLiteral(red: 0.000, green: 0.000, blue: 0.000, alpha: 1.000)
@IBInspectable open var keyOnColor: NSColor = #colorLiteral(red: 1.000, green: 0.000, blue: 0.000, alpha: 1.000)
@IBInspectable open var topWhiteKeyOff: NSColor = #colorLiteral(red: 1.000, green: 1.000, blue: 1.000, alpha: 0.000)
open weak var delegate: AKKeyboardDelegate?
var oneOctaveSize = CGSize.zero
var xOffset: CGFloat = 1
var onKeys = Set<MIDINoteNumber>()
public var polyphonicMode = false {
didSet {
for note in onKeys {
delegate?.noteOff(note: note)
}
onKeys.removeAll()
needsDisplay = true
}
}
let midi = AKMIDI()
let naturalNotes = ["C", "D", "E", "F", "G", "A", "B"]
let notesWithSharps = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"]
let topKeyNotes = [0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 11]
let whiteKeyNotes = [0, 2, 4, 5, 7, 9, 11]
override public func draw(_ dirtyRect: NSRect) {
for i in 0 ..< octaveCount {
drawOctaveCanvas(octaveNumber: i)
}
let backgroundPath = NSBezierPath(rect: NSRect(x: size.width * CGFloat(octaveCount),
y: 0,
width: size.width / 7,
height: size.height))
NSColor.black.setFill()
backgroundPath.fill()
let lastC = NSBezierPath(rect:
CGRect(x: whiteKeyX(n: 0, octaveNumber: octaveCount),
y: 1,
width: whiteKeySize.width - 2,
height: whiteKeySize.height))
whiteKeyColor(n: 0, octaveNumber: octaveCount).setFill()
lastC.fill()
}
var whiteKeySize: NSSize {
return NSSize(width: size.width / 7.0,
height: size.height - 2)
}
var topKeySize: NSSize {
return NSSize(width: size.width / (4 * 7),
height: size.height * topKeyHeightRatio)
}
func whiteKeyX(n: Int, octaveNumber: Int) -> CGFloat {
return CGFloat(n) * whiteKeySize.width + xOffset + size.width * CGFloat(octaveNumber)
}
func topKeyX(n: Int, octaveNumber: Int) -> CGFloat {
return CGFloat(n) * topKeySize.width + xOffset + size.width * CGFloat(octaveNumber)
}
func whiteKeyColor(n: Int, octaveNumber: Int) -> NSColor {
return onKeys.contains(MIDINoteNumber((firstOctave + octaveNumber) * 12 + whiteKeyNotes[n])) ?
keyOnColor : whiteKeyOff
}
func topKeyColor(n: Int, octaveNumber: Int) -> NSColor {
if notesWithSharps[topKeyNotes[n]].range(of: "#") != nil {
return onKeys.contains(MIDINoteNumber((firstOctave + octaveNumber) * 12 + topKeyNotes[n])) ?
keyOnColor : blackKeyOff
}
return topWhiteKeyOff
}
func drawOctaveCanvas(octaveNumber: Int) {
//// background Drawing
let backgroundPath = NSBezierPath(rect: NSRect(x: 0 + size.width * CGFloat(octaveNumber),
y: 0,
width: size.width,
height: size.height))
NSColor.black.setFill()
backgroundPath.fill()
var whiteKeysPaths = [NSBezierPath]()
for i in 0 ..< 7 {
whiteKeysPaths.append(
NSBezierPath(rect: NSRect(x: whiteKeyX(n: i, octaveNumber: octaveNumber),
y: 1,
width: whiteKeySize.width - 1,
height: whiteKeySize.height))
)
whiteKeyColor(n: i, octaveNumber: octaveNumber).setFill()
whiteKeysPaths[i].fill()
}
var topKeyPaths = [NSBezierPath]()
for i in 0 ..< 28 {
topKeyPaths.append(
NSBezierPath(rect: NSRect(x: topKeyX(n: i, octaveNumber: octaveNumber),
y: 1,
width: topKeySize.width,
height: topKeySize.height))
)
topKeyColor(n: i, octaveNumber: octaveNumber).setFill()
topKeyPaths[i].fill()
}
}
public init(width: Int,
height: Int,
firstOctave: Int = 4,
octaveCount: Int = 3,
polyphonic: Bool = false) {
self.octaveCount = octaveCount
self.firstOctave = firstOctave
super.init(frame: CGRect(x: 0, y: 0, width: width, height: height))
size = CGSize(width: width / octaveCount - width / (octaveCount * octaveCount * 7), height: Double(height))
needsDisplay = true
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Storyboard Rendering
override open func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
let width = Int(self.frame.width)
let height = Int(self.frame.height)
oneOctaveSize = CGSize(width: Double(width / octaveCount - width / (octaveCount * octaveCount * 7)),
height: Double(height))
}
override open var intrinsicContentSize: CGSize {
return CGSize(width: 1_024, height: 84)
}
public func getNoteName(note: Int) -> String {
let keyInOctave = note % 12
return notesWithSharps[keyInOctave]
}
func noteFromEvent(event: NSEvent) -> MIDINoteNumber {
let x = event.locationInWindow.x - self.frame.origin.x - xOffset
let y = event.locationInWindow.y - self.frame.origin.y
var note = 0
if y < size.height * (1.0 - topKeyHeightRatio) {
let octNum = Int(x / size.width)
let scaledX = x - CGFloat(octNum) * size.width
note = (firstOctave + octNum) * 12 + whiteKeyNotes[max(0, Int(scaledX / whiteKeySize.width))]
} else {
let octNum = Int(x / size.width)
let scaledX = x - CGFloat(octNum) * size.width
note = (firstOctave + octNum) * 12 + topKeyNotes[max(0, Int(scaledX / topKeySize.width))]
}
return MIDINoteNumber(note)
}
override public func mouseDown(with event: NSEvent) {
let note = noteFromEvent(event: event)
if polyphonicMode && onKeys.contains(note) {
onKeys.remove(note)
delegate?.noteOff(note: note)
} else {
onKeys.insert(note)
delegate?.noteOn(note: note)
}
needsDisplay = true
}
override public func mouseUp(with event: NSEvent) {
if !polyphonicMode {
let note = noteFromEvent(event: event)
onKeys.remove(note)
delegate?.noteOff(note: note)
}
needsDisplay = true
}
override public func mouseDragged(with event: NSEvent) {
if polyphonicMode {
return
} // no response for 'drawing cursor' in polyphonic mode
let note = noteFromEvent(event: event)
if !onKeys.contains(note) {
let currentNote = onKeys.first
onKeys.removeAll()
onKeys.insert(note)
delegate?.noteOn(note: note)
if let currNote = currentNote {
delegate?.noteOff(note: currNote)
}
needsDisplay = true
}
}
// MARK: - MIDI
public func receivedMIDINoteOn(noteNumber: MIDINoteNumber,
velocity: MIDIVelocity,
channel: MIDIChannel) {
DispatchQueue.main.async(execute: {
self.onKeys.insert(noteNumber)
self.delegate?.noteOn(note: noteNumber)
self.needsDisplay = true
})
}
public func receivedMIDINoteOff(noteNumber: MIDINoteNumber,
velocity: MIDIVelocity,
channel: MIDIChannel) {
DispatchQueue.main.async(execute: {
self.onKeys.remove(noteNumber)
self.delegate?.noteOff(note: noteNumber)
self.needsDisplay = true
})
}
public func receivedMIDIController(_ controller: MIDIByte,
value: MIDIByte,
channel: MIDIChannel) {
if controller == MIDIByte(AKMIDIControl.damperOnOff.rawValue) && value == 0 {
for note in onKeys {
delegate?.noteOff(note: note)
}
}
}
public func receivedMIDIProgramChange(_ program: MIDIByte, channel: MIDIChannel) {
// do nothing
}
}
| c9ef7fc3e424afefe15befc885a1f87e | 34.803636 | 122 | 0.548345 | false | false | false | false |
pawrsccouk/Stereogram | refs/heads/master | Stereogram-iPad/NSError+Alert.swift | mit | 1 | //
// NSError+Alert.swift
// Stereogram-iPad
//
// Created by Patrick Wallace on 16/01/2015.
// Copyright (c) 2015 Patrick Wallace. All rights reserved.
//
import UIKit
private let kLocation = "Location", kCaller = "Caller", kTarget = "Target", kSelector = "Selector"
extension NSError {
/// Display the error in an alert view.
///
/// Gets the error text from some known places in the NSError description.
/// The alert will just have a close button and no extra specifications.
///
/// :param: title The title to display above the alert.
/// :param: parent The view controller to present the alert on top of.
func showAlertWithTitle(title: String, parentViewController parent: UIViewController) {
var errorText = self.localizedDescription
if let t = self.helpAnchor { errorText = t }
else if let t = self.localizedFailureReason { errorText = t }
NSLog("Showing error \(self) final text \(errorText)")
let alertController = UIAlertController(title: title
, message: errorText
, preferredStyle: .Alert)
alertController.addAction(UIAlertAction(title: "Close", style: .Default, handler: nil))
parent.presentViewController(alertController, animated: true, completion: nil)
}
/// Convenience initializer.
/// Create a new error object using the photo store error domain and code.
///
/// :param: errorCode The PhotoStore error code to return.
/// :param: userInfo NSDicationary with info to associate with this error.
convenience init(errorCode code: ErrorCode
, userInfo: [String: AnyObject]?) {
self.init(domain: ErrorDomain.PhotoStore.rawValue
, code: code.rawValue
, userInfo: userInfo)
}
/// Class function to create an error to return when something failed but didn't say why.
///
/// :param: location A string included in the error text and returned in the userInfo dict.
/// This should give a clue as to what operation was being performed.
/// :param: target A string included in the error text and returned in the userInfo dict.
/// This should give a clue as to which function returned this error
/// (i.e. the function in 3rd party code that returned the unexpected error.)
class func unknownErrorWithLocation(location: String, target: String = "") -> NSError {
var errorMessage = "Unknown error at location \(location)"
if target != "" {
errorMessage = "\(errorMessage) calling \(target)"
}
let userInfo = [
NSLocalizedDescriptionKey : errorMessage,
kLocation : location,
kTarget : target]
return NSError(errorCode:.UnknownError, userInfo:userInfo)
}
/// Class function to create an error to return when a method call failed but didn't say why.
///
/// :param: target The object we called a method on.
/// :param: selector Selector for the method we called on TARGET.
/// :param: caller The method or function which called the method that went wrong.
/// I.e. where in my code it is.
class func unknownErrorWithTarget(target: AnyObject
, method: String
, caller: String) -> NSError {
let callee = "\(target).(\(method))"
let errorText = "Unknown error calling \(callee) from caller \(caller)"
let userInfo = [
NSLocalizedDescriptionKey : errorText,
kCaller : caller,
kTarget : target,
kSelector : method]
return NSError(errorCode: .UnknownError, userInfo: userInfo)
}
}
| 90f652554df76672ed874846675d9c7e | 40.75 | 98 | 0.61911 | false | false | false | false |
vimac/BearRemoter-iOS | refs/heads/master | BearRemoter/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// BearRemoter
//
// Created by Mac on 8/15/15.
// Copyright (c) 2015 vifix.cn. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
APService.registerForRemoteNotificationTypes(UIUserNotificationType.Badge.rawValue | UIUserNotificationType.Sound.rawValue | UIUserNotificationType.Alert.rawValue , categories: nil)
APService.setupWithOption(launchOptions)
application.applicationIconBadgeNumber = 0
APService.setBadge(0)
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.
application.applicationIconBadgeNumber = 0
APService.setBadge(0)
}
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:.
}
func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {
APService.registerDeviceToken(deviceToken)
}
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject], fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
let aps:NSDictionary = userInfo["aps"] as! NSDictionary
let from:String = userInfo["from"] as! String
let content:String = userInfo["message"] as! String
let sound:String = aps["sound"] as! String
let badge:Int = aps["badge"] as! Int
application.applicationIconBadgeNumber = 0
APService.setBadge(0)
let alert = UIAlertController(title: "来自\(from)的指令", message: content, preferredStyle: UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title: "确认", style: UIAlertActionStyle.Default, handler: nil))
self.window!.rootViewController!.presentViewController(alert, animated: true, completion: nil)
APService.handleRemoteNotification(userInfo)
}
}
| 01b874387e326690bb83b3caef9d5ec5 | 50.71831 | 285 | 0.744009 | false | false | false | false |
reuterm/CalendarAPI | refs/heads/master | iOS Frontend/Calendar/Event.swift | mit | 1 | //
// Event.swift
// Calendar
//
// Created by Max Reuter on 19/11/15.
// Copyright © 2015 reuterm. All rights reserved.
//
import Foundation
class Event {
// MARK: Properties
var id: String?
var title: String
var description: String
var start: NSDate
var end: NSDate
var venue: String
// MARK: Initialisation
init(id: String?, title: String, description: String, start: NSDate, end: NSDate, venue: String) {
self.id = id
self.title = title
self.description = description
self.start = start
self.end = end
self.venue = venue
}
} | cd023df5090cf7444b36837853c29b1d | 20.655172 | 102 | 0.607656 | false | false | false | false |
Nana-Muthuswamy/TwitterLite | refs/heads/master | Pods/FaveButton/Source/Spark.swift | apache-2.0 | 5 | //
// Spark.swift
// FaveButton
//
// Copyright © 2016 Jansel Valentin.
//
// 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
internal typealias DotRadius = (first: Double, second: Double)
class Spark: UIView {
fileprivate struct Const{
static let distance = (vertical: 4.0, horizontal: 0.0)
static let expandKey = "expandKey"
static let dotSizeKey = "dotSizeKey"
}
var radius: CGFloat
var firstColor: UIColor
var secondColor: UIColor
var angle: Double
var dotRadius: DotRadius!
fileprivate var dotFirst: UIView!
fileprivate var dotSecond: UIView!
fileprivate var distanceConstraint: NSLayoutConstraint?
init(radius: CGFloat, firstColor: UIColor, secondColor: UIColor, angle: Double, dotRadius: DotRadius){
self.radius = radius
self.firstColor = firstColor
self.secondColor = secondColor
self.angle = angle
self.dotRadius = dotRadius
super.init(frame: CGRect.zero)
applyInit()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// MARK: create
extension Spark{
class func createSpark(_ faveButton: FaveButton, radius: CGFloat, firstColor: UIColor, secondColor: UIColor, angle: Double, dotRadius: DotRadius) -> Spark{
let spark = Init(Spark(radius: radius, firstColor: firstColor, secondColor: secondColor, angle: angle, dotRadius: dotRadius)){
$0.translatesAutoresizingMaskIntoConstraints = false
$0.backgroundColor = .clear
$0.layer.anchorPoint = CGPoint(x: 0.5, y: 1)
$0.alpha = 0.0
}
faveButton.superview?.insertSubview(spark, belowSubview: faveButton)
(spark, faveButton) >>- [.centerX, .centerY]
let width = CGFloat((dotRadius.first * 2.0 + dotRadius.second * 2.0) + Const.distance.horizontal)
spark >>- {
$0.attribute = .width
$0.constant = width
}
let height = CGFloat(Double(radius) + (dotRadius.first * 2.0 + dotRadius.second * 2.0))
spark >>- {
$0.attribute = .height
$0.constant = height
$0.identifier = Const.expandKey
}
return spark
}
fileprivate func applyInit(){
dotFirst = createDotView(dotRadius.first, fillColor: firstColor)
dotSecond = createDotView(dotRadius.second, fillColor: secondColor)
(dotFirst, self) >>- [.trailing]
attributes(.width, .height).forEach{ attr in
dotFirst >>- {
$0.attribute = attr
$0.constant = CGFloat(dotRadius.first * 2.0)
$0.identifier = Const.dotSizeKey
}
}
(dotSecond,self) >>- [.leading]
attributes(.width,.height).forEach{ attr in
dotSecond >>- {
$0.attribute = attr
$0.constant = CGFloat(dotRadius.second * 2.0)
$0.identifier = Const.dotSizeKey
}
}
(dotSecond,self) >>- {
$0.attribute = .top
$0.constant = CGFloat(dotRadius.first * 2.0 + Const.distance.vertical)
}
distanceConstraint = (dotFirst, dotSecond) >>- {
$0.attribute = .bottom
$0.secondAttribute = .top
$0.constant = 0
}
self.transform = CGAffineTransform(rotationAngle: CGFloat(angle.degrees))
}
fileprivate func createDotView(_ radius: Double, fillColor: UIColor) -> UIView{
let dot = Init(UIView(frame: CGRect.zero)){
$0.translatesAutoresizingMaskIntoConstraints = false
$0.backgroundColor = fillColor
$0.layer.cornerRadius = CGFloat(radius)
}
self.addSubview(dot)
return dot
}
}
// MARK: animation
extension Spark{
func animateIgniteShow(_ radius: CGFloat, duration:Double, delay: Double = 0){
self.layoutIfNeeded()
let diameter = (dotRadius.first * 2.0) + (dotRadius.second * 2.0)
let height = CGFloat(Double(radius) + diameter + Const.distance.vertical)
if let constraint = self.constraints.filter({ $0.identifier == Const.expandKey }).first{
constraint.constant = height
}
UIView.animate(withDuration: 0, delay: delay, options: .curveLinear, animations: {
self.alpha = 1
}, completion: nil)
UIView.animate(withDuration: duration * 0.7, delay: delay, options: .curveEaseOut, animations: {
self.layoutIfNeeded()
}, completion: nil)
}
func animateIgniteHide(_ duration: Double, delay: Double = 0){
self.layoutIfNeeded()
distanceConstraint?.constant = CGFloat(-Const.distance.vertical)
UIView.animate(
withDuration: duration*0.5,
delay: delay,
options: .curveEaseOut,
animations: {
self.layoutIfNeeded()
}, completion: { succeed in
})
UIView.animate(
withDuration: duration,
delay: delay,
options: .curveEaseOut,
animations: {
self.dotSecond.backgroundColor = self.firstColor
self.dotFirst.backgroundColor = self.secondColor
}, completion: nil)
for dot in [dotFirst, dotSecond]{
dot?.setNeedsLayout()
dot?.constraints.filter{ $0.identifier == Const.dotSizeKey }.forEach{
$0.constant = 0
}
}
UIView.animate(
withDuration: duration,
delay: delay,
options: .curveEaseOut,
animations: {
self.dotSecond.layoutIfNeeded()
}, completion:nil)
UIView.animate(
withDuration: duration*1.7,
delay: delay ,
options: .curveEaseOut,
animations: {
self.dotFirst.layoutIfNeeded()
}, completion: { succeed in
self.removeFromSuperview()
})
}
}
| c6597f4d30700e351033cf4d441120e5 | 32.200873 | 159 | 0.568591 | false | false | false | false |
EdwaRen/Recycle_Can_iOS | refs/heads/final | Bipeople/Pods/GooglePlacePicker/Example/GooglePlacePickerDemos/ShadowLineView.swift | apache-2.0 | 12 | /*
* Copyright 2016 Google Inc. 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 UIKit
/// A UIView subclass which draws a horizontal line of drop-shadow above and below the view's
/// bounds. The view should be given a height of 0 when added to a view hierarchy.
class ShadowLineView: UIView {
private let shadowView = ShadowView()
/// The opacity of the drop-shadow line, defaults to 0.
var shadowOpacity = Float() { didSet { shadowView.shadowOpacity = shadowOpacity } }
/// The color of the drop-shadow. defaults to black.
var shadowColor = UIColor.black { didSet { shadowView.shadowColor = shadowColor } }
/// Whether to display the drop-shadow or not, defaults to false.
var enableShadow = false { didSet { update() } }
/// The size of the shadow. This extends above and beneath the view. Defaults to 0.
var shadowSize = CGFloat() { didSet { update() } }
override init(frame: CGRect) {
super.init(frame: frame)
self.setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.setup()
}
private func setup() {
addSubview(shadowView)
shadowView.autoresizingMask = [.flexibleWidth]
}
private func update() {
// Pass on our enabled state to the shadow view.
shadowView.enableShadow = enableShadow
// Adjust the positioning of the shadow view so that it is centered in our bounds, but has a
// height of shadow size, and a width which is 2*shadow size larger.
shadowView.frame = bounds.insetBy(dx: -shadowSize, dy: -shadowSize/2)
// Make the shadow radius be half of the requested size. As the shadow view itself is half the
// size of the requested shadow size once you add this value the shadow will be the correct
// height.
shadowView.shadowRadius = shadowSize/2
}
}
| 33102f24352fdc1529a8ffeb3f2fdee4 | 39.275862 | 98 | 0.714897 | false | false | false | false |
rallahaseh/RALocalization | refs/heads/master | RALocalization/Classes/RALanguage.swift | mit | 1 | //
// RALanguage.swift
// RALocalization
//
// Created by Rashed Al Lahaseh on 10/17/17.
//
import Foundation
import UIKit
let APPLE_LANGUAGE_KEY = "AppleLanguages"
let FONT_TYPE = "Lato-LightItalic"
public enum RALanguages: String {
case english = "en"
case french = "fr"
case spanish = "es"
case german = "de"
case arabic = "ar"
case hebrew = "he"
case japanese = "ja"
case chineseSimplified = "zh-Hans"
case chineseTraditional = "zh-Hant"
}
open class RALanguage {
// Get Current App language
open class func currentLanguage(withLocale: Bool = true) -> String{
let userDefault = UserDefaults.standard
let languageArray = userDefault.object(forKey: APPLE_LANGUAGE_KEY) as! NSArray
let current = languageArray.firstObject as! String
let index = current.index(current.startIndex, offsetBy: 2)
let currentWithoutLocale = String(current[..<index])
return withLocale ? currentWithoutLocale : current
}
/// set @lang to be the first in App Languages List
open class func setLanguage(language: RALanguages) {
let userDefault = UserDefaults.standard
userDefault.set([language.rawValue, currentLanguage()], forKey: APPLE_LANGUAGE_KEY)
userDefault.synchronize()
}
open class var isRTL: Bool {
if RALanguage.currentLanguage() == RALanguages.arabic.rawValue {
return true
} else if RALanguage.currentLanguage() == RALanguages.hebrew.rawValue {
return true
} else {
return false
}
}
}
| efe89d4205746adb4ad4d67a495bb9f2 | 31.722222 | 96 | 0.591964 | false | false | false | false |
skedgo/tripkit-ios | refs/heads/main | Sources/TripKitUI/helper/RxTripKit/TKServer+Rx.swift | apache-2.0 | 1 | //
// TKServer+Rx.swift
// TripKit
//
// Created by Adrian Schoenig on 1/08/2016.
// Copyright © 2016 SkedGo. All rights reserved.
//
import Foundation
import MapKit
import RxSwift
import RxCocoa
import TripKit
extension Reactive where Base: TKRegionManager {
public func requireRegion(_ coordinate: CLLocationCoordinate2D) -> Single<TKRegion> {
return requireRegions()
.map {
TKRegionManager.shared.region(containing: coordinate, coordinate)
}
}
public func requireRegion(_ coordinateRegion: MKCoordinateRegion) -> Single<TKRegion> {
return requireRegions()
.map {
TKRegionManager.shared.region(containing: coordinateRegion)
}
}
public func requireRegions() -> Single<Void> {
return Single.create { subscriber in
self.base.requireRegions(completion: subscriber)
return Disposables.create()
}
}
}
extension TKServer: ReactiveCompatible {}
extension Reactive where Base: TKServer {
public func hit(_ method: TKServer.HTTPMethod = .GET, url: URL, parameters: [String: Any]? = nil) -> Single<(Int, [String: Any], Data)> {
return Single.create { single in
base.hit(method, url: url, parameters: parameters) { code, responseHeader, result in
single(result.map { (code, responseHeader, $0) })
}
return Disposables.create()
}
}
public func hit<Model: Decodable>(
_ type: Model.Type,
_ method: TKServer.HTTPMethod = .GET,
url: URL,
parameters: [String: Any] = [:],
decoderConfig: @escaping (JSONDecoder) -> Void = { _ in }
) -> Single<(Int, [String: Any], Model)>
{
Single.create { subscriber in
base.hit(type, method, url: url, parameters: parameters, decoderConfig: decoderConfig) { status, headers, result in
subscriber(result.map { (status, headers, $0) })
}
return Disposables.create()
}
}
public func hit(
_ method: TKServer.HTTPMethod = .GET,
path: String,
parameters: [String: Any] = [:],
headers: [String: String] = [:],
region: TKRegion? = nil
) -> Single<(Int?, [String: Any], Data?)>
{
Single.create { subscriber in
base.hit(method, path: path, parameters: parameters, headers: headers, region: region
) { status, headers, result in
do {
let data = try result.get()
subscriber(.success((status, headers, data)))
} catch {
if let serverError = error as? TKServer.ServerError, serverError == .noData {
subscriber(.success((status, headers, nil)))
} else {
subscriber(.failure(error))
}
}
}
return Disposables.create()
}
}
public func stream(
_ method: TKServer.HTTPMethod = .GET,
path: String,
parameters: [String: Any] = [:],
headers: [String: String] = [:],
region: TKRegion? = nil,
repeatHandler: ((Int?, Data?) -> TKServer.RepeatHandler?)? = nil
) -> Observable<(Int?, [String: Any], Data?)>
{
return Observable.create { subscriber in
let stopper = Stopper()
self.hit(
method,
path: path,
parameters: parameters,
headers: headers,
region: region,
repeatHandler: { code, responseHeaders, result in
if stopper.stop {
// we got disposed
return nil
}
let hitAgain: TKServer.RepeatHandler?
let model = try? result.get()
if let repeatHandler = repeatHandler {
hitAgain = repeatHandler(code, model)
} else {
hitAgain = nil
}
subscriber.onNext((code, responseHeaders, model))
if hitAgain == nil {
subscriber.onCompleted()
}
return hitAgain
}
)
return Disposables.create() {
stopper.stop = true
}
}
}
/// Hit a SkedGo endpoint, using a variety of options
///
/// - parameter method: Duh
/// - parameter path: The endpoint, e.g., `routing.json`
/// - parameter parameters: The parameters which will either be send in the query (for GET) or as the JSON body (for POST and alike)
/// - parameter headers: Additional headers to add to the request
/// - parameter region: The region for which to hit a server. In most cases, you want to set this as not every SkedGo server has data for every region.
/// - returns: An observable with the status code, headers and data from hitting the endpoint, all status and data will be the same as the last call to the `repeatHandler`.
public func hit<Model: Decodable>(
_ type: Model.Type,
_ method: TKServer.HTTPMethod = .GET,
path: String,
parameters: [String: Any] = [:],
headers: [String: String] = [:],
region: TKRegion? = nil
) -> Single<(Int?, [String: Any], Model)>
{
return Single.create { subscriber in
let stopper = Stopper()
self.hit(
method,
path: path,
parameters: parameters,
headers: headers,
region: region,
repeatHandler: { code, responseHeaders, result in
if stopper.stop {
// we got disposed while waiting for response
return nil
}
subscriber(Result {
let data = try result.get()
let model = try JSONDecoder().decode(Model.self, from: data)
return (code, responseHeaders, model)
})
// Never repeat
return nil
}
)
return Disposables.create() {
stopper.stop = true
}
}
}
/// Hit a SkedGo endpoint, using a variety of options
///
/// - parameter method: Duh
/// - parameter path: The endpoint, e.g., `routing.json`
/// - parameter parameters: The parameters which will either be send in the query (for GET) or as the JSON body (for POST and alike)
/// - parameter headers: Additional headers to add to the request
/// - parameter region: The region for which to hit a server. In most cases, you want to set this as not every SkedGo server has data for every region.
/// - parameter repeatHandler: Implement and return a non-negative time interval from this handler to fire the Observable again, or `nil` to stop firing.
/// - returns: An observable with the status code, headers and data from hitting the endpoint, all status and data will be the same as the last call to the `repeatHandler`. Note: This will be called on a background thread.
public func stream<Model: Decodable>(
_ type: Model.Type,
_ method: TKServer.HTTPMethod = .GET,
path: String,
parameters: [String: Any] = [:],
headers: [String: String] = [:],
region: TKRegion? = nil,
repeatHandler: ((Int?, Model?) -> TKServer.RepeatHandler?)? = nil
) -> Observable<(Int?, [String: Any], Model?)>
{
let stream: Observable<(Int?, [String: Any], Data?)> = stream(
method,
path: path,
parameters: parameters,
headers: headers,
region: region
) { status, maybeData in
repeatHandler?(status, maybeData.flatMap { try? JSONDecoder().decode(Model.self, from: $0) })
}
return stream.map { status, header, maybeData in
(status, headers, maybeData.flatMap { try? JSONDecoder().decode(Model.self, from: $0) })
}
}
private func hit<Model: Decodable>(
_ type: Model.Type,
_ method: TKServer.HTTPMethod = .GET,
path: String,
parameters: [String: Any] = [:],
headers: [String: String] = [:],
region: TKRegion? = nil,
repeatHandler: @escaping (Int?, [String: Any], Result<Model, Error>) -> TKServer.RepeatHandler?
) {
hit(
method,
path: path,
parameters: parameters,
headers: headers,
region: region,
repeatHandler: { status, headers, dataResult in
repeatHandler(status, headers, Result {
let data = try dataResult.get()
return try JSONDecoder().decode(Model.self, from: data)
})
}
)
}
private func hit(
_ method: TKServer.HTTPMethod = .GET,
path: String,
parameters: [String: Any] = [:],
headers: [String: String] = [:],
region: TKRegion? = nil,
repeatHandler: @escaping (Int?, [String: Any], Result<Data, Error>) -> TKServer.RepeatHandler?
) {
self.base.hit(
method,
path: path,
parameters: parameters,
headers: headers,
region: region,
callbackOnMain: false
) { status, responseHeaders, result in
if let hitAgain = repeatHandler(status, responseHeaders, result) {
// These are the variables that control how a request is repeated
// 1. retryIn: tells us when we can try again, in seconds.
// 2. newParameters: tells us when we do retry, what parameters to use. This
// may be different from the original request.
let retryIn: TimeInterval
let newParameters: [String : Any]
switch hitAgain {
case .repeatIn(let seconds):
retryIn = seconds
newParameters = parameters
case .repeatWithNewParameters(let seconds, let paras):
retryIn = seconds
newParameters = paras
}
if retryIn > 0 {
let queue = DispatchQueue.global(qos: .userInitiated)
queue.asyncAfter(deadline: DispatchTime.now() + retryIn) {
self.hit(
method,
path: path,
parameters: newParameters,
headers: headers,
region: region,
repeatHandler: repeatHandler
)
}
}
}
}
}
}
private class Stopper {
var stop = false
}
| a2ea6fc444c4c1f68bc7f200a89cf908 | 30.960784 | 224 | 0.597546 | false | false | false | false |
chrisjmendez/swift-exercises | refs/heads/master | Video/SKVideoNode/SKVideoNode/GameViewController.swift | mit | 1 | //
// GameViewController.swift
// SKVideoNode
//
// Created by Tommy Trojan on 10/2/15.
// Copyright (c) 2015 Chris Mendez. All rights reserved.
//
import UIKit
import SpriteKit
class GameViewController: UIViewController {
var textView: UITextView!
override func viewDidLoad() {
super.viewDidLoad()
if let scene = GameScene(fileNamed:"GameScene") {
// Configure the view.
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
/* Sprite Kit applies additional optimizations to improve rendering performance */
skView.ignoresSiblingOrder = true
/* Set the scale mode to scale to fit the window */
scene.scaleMode = .AspectFill
skView.presentScene(scene)
}
checkDevice()
}
func message(){
textView = UITextView(frame: self.view.frame)
textView.font = UIFont(name: "Arial", size: 40)
textView.center = CGPointMake(CGRectGetMidX(self.view.frame), CGRectGetMidY(self.view.frame))
textView.textAlignment = NSTextAlignment.Center
textView.text = "Video will not appear while in Simulator mode. Please use an actual device"
self.view.addSubview(textView)
}
func checkDevice(){
let deviceType = UIDevice.currentDevice().deviceType
if( String(deviceType) == "Simulator" ){
message()
}
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return .AllButUpsideDown
} else {
return .All
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
| 8f8ae69206b244a11697acf224e6f05d | 27.671233 | 101 | 0.609173 | false | false | false | false |
tredds/pixelthoughts | refs/heads/master | PixelThoughts/ResultsController.swift | mit | 1 | //
// ResultsController.swift
// PixelThoughts
//
// Created by Victor Tatarasanu on 22/12/15.
// Copyright © 2015 Victor Tatarasanu. All rights reserved.
//
import UIKit
public protocol ResultsControllerSelection : NSObjectProtocol {
func resultsControllerSelectionSelect(string: String)
}
class ResultsController: UITableViewController, UISearchResultsUpdating {
let tableViewCellIdentifier = "cellID"
var allItems = DataProvider.sharedInstance().tagsProvider.tags()
var filtered = [String]()
weak var delegate: ResultsControllerSelection?
var filterString = "" {
didSet {
// Return if the filter string hasn't changed.
guard filterString != oldValue else { return }
if filterString.isEmpty {
filtered = allItems
}
else {
filtered = allItems.filter { $0.containsString(filterString.lowercaseString) }
if filtered.isEmpty {
filtered = [filterString]
}
}
tableView?.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
self.filtered = self.allItems
tableView.registerClass(UITableViewCell.classForCoder(), forCellReuseIdentifier: tableViewCellIdentifier)
}
// MARK: Configuration
func configureCell(cell: UITableViewCell, forTitle title: String) {
cell.textLabel?.text = title
cell.textLabel?.textAlignment = .Center
}
// MARK: UITableViewDataSource
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filtered.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(tableViewCellIdentifier)!
let title = filtered[indexPath.row]
configureCell(cell, forTitle: title)
return cell
}
func updateSearchResultsForSearchController(searchController: UISearchController) {
filterString = searchController.searchBar.text ?? ""
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
self.dismissViewControllerAnimated(true) { () -> Void in
if (self.delegate?.respondsToSelector("resultsControllerSelectionSelect:") == true) {
self.delegate?.resultsControllerSelectionSelect(self.filtered[indexPath.row])
// custom
if (!self.allItems.contains(self.filtered[indexPath.row])) {
DataProvider.sharedInstance().tagsProvider.prepend(self.filtered[indexPath.row]);
}
}
}
}
}
| 4586e686b00f3d79d280ecfd17039871 | 32.310345 | 118 | 0.631815 | false | false | false | false |
maximkhatskevich/MKHUniFlow | refs/heads/master | Sources/_Essentials/SomeFeature.swift | mit | 1 | /*
MIT License
Copyright (c) 2016 Maxim Khatskevich ([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.
*/
public
protocol SomeFeature: SomeStateful {}
//---
public
extension SomeFeature
{
typealias Itself = Self
}
//---
public
enum InitializationStatusCheckError: Error
{
case alreadyInitialized(SomeStateful.Type)
case notInitializedYet(SomeStateful.Type)
}
//---
public
extension SomeFeature where Self: FeatureBase
{
func ensureAwaitingInitialization() throws
{
guard
!_dispatcher.hasValue(withKey: Self.self)
else
{
throw InitializationStatusCheckError.alreadyInitialized(Self.self)
}
}
func ensureAlreadyInitialized() throws
{
guard
_dispatcher.hasValue(withKey: Self.self)
else
{
throw InitializationStatusCheckError.notInitializedYet(Self.self)
}
}
@discardableResult
func fetch<V: SomeState>(
_ valueOfType: V.Type = V.self
) throws -> V {
try _dispatcher.fetch(
valueOfType: V.self
)
}
func store<V: SomeState>(
scope: String = #file,
context: String = #function,
location: Int = #line,
_ value: V
) throws where V.Feature == Self {
try _dispatcher.access(scope: scope, context: context, location: location) {
try $0.store(value)
}
}
func initialize<V: SomeState>(
scope: String = #file,
context: String = #function,
location: Int = #line,
with newValue: V
) throws where V.Feature == Self {
try _dispatcher.access(scope: scope, context: context, location: location) {
try $0.initialize(with: newValue)
}
}
func actualize<V: SomeState>(
scope: String = #file,
context: String = #function,
location: Int = #line,
_ valueOfType: V.Type = V.self,
via mutationHandler: (inout V) throws -> Void
) throws where V.Feature == Self {
try _dispatcher.access(scope: scope, context: context, location: location) {
try $0.actualize(V.self, via: mutationHandler)
}
}
func actualize<V: SomeState>(
scope: String = #file,
context: String = #function,
location: Int = #line,
with newValue: V
) throws where V.Feature == Self {
try _dispatcher.access(scope: scope, context: context, location: location) {
try $0.actualize(with: newValue)
}
}
func transition<O: SomeState, N: SomeState>(
scope: String = #file,
context: String = #function,
location: Int = #line,
from oldValueInstance: O,
into newValue: N
) throws where O.Feature == Self, N.Feature == Self {
try _dispatcher.access(scope: scope, context: context, location: location) {
try $0.transition(from: oldValueInstance, into: newValue)
}
}
func transition<O: SomeState, N: SomeState>(
scope: String = #file,
context: String = #function,
location: Int = #line,
from oldValueType: O.Type,
into newValue: N
) throws where O.Feature == Self, N.Feature == Self {
try _dispatcher.access(scope: scope, context: context, location: location) {
try $0.transition(from: O.self, into: newValue)
}
}
func transition<V: SomeState>(
scope: String = #file,
context: String = #function,
location: Int = #line,
into newValue: V
) throws where V.Feature == Self {
try _dispatcher.access(scope: scope, context: context, location: location) {
try $0.transition(into: newValue)
}
}
func deinitialize(
scope: String = #file,
context: String = #function,
location: Int = #line,
strict: Bool = true
) throws {
try _dispatcher.access(scope: scope, context: context, location: location) {
try $0.deinitialize(Self.self, fromValueType: nil, strict: strict)
}
}
func deinitialize<V: SomeState>(
scope: String = #file,
context: String = #function,
location: Int = #line,
from fromValueType: V.Type
) throws where V.Feature == Self {
try _dispatcher.access(scope: scope, context: context, location: location) {
try $0.deinitialize(Self.self, fromValueType: fromValueType, strict: true)
}
}
}
| e81e13f358899113372fcd9bfd2bbda7 | 27.681592 | 86 | 0.59948 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.