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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
HabitRPG/habitrpg-ios | refs/heads/develop | HabitRPG/Views/ChallengeTaskListView.swift | gpl-3.0 | 1 | //
// ChallengeTaskListView.swift
// Habitica
//
// Created by Phillip Thelen on 14/03/2017.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import Foundation
import Habitica_Models
@IBDesignable
class ChallengeTaskListView: UIView {
static let verticalSpacing = CGFloat(integerLiteral: 12)
static let borderColor = UIColor.gray400
let titleLabel = UILabel()
let borderView = UIView()
var taskViews = [UIView]()
@IBInspectable var taskType: String? {
didSet {
updateTitle()
}
}
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setupView()
}
private func setupView() {
self.addSubview(titleLabel)
self.clipsToBounds = true
self.addSubview(borderView)
borderView.layer.borderColor = ChallengeTaskListView.borderColor.cgColor
borderView.layer.borderWidth = 1
}
func configure(tasks: [TaskProtocol]?) {
removeAllTaskViews()
guard let tasks = tasks else {
return
}
for (index, task) in tasks.enumerated() {
let taskView = createTaskView(task: task, isFirst: index == 0)
self.addSubview(taskView)
taskViews.append(taskView)
}
updateTitle()
self.setNeedsLayout()
self.invalidateIntrinsicContentSize()
}
override func layoutSubviews() {
let frame = self.frame
var titleHeight = titleLabel.sizeThatFits(frame.size).height
titleLabel.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: titleHeight)
titleHeight += 8
var nextTaskViewPos = titleHeight
let labelSize = CGSize(width: frame.size.width-80, height: frame.size.height)
for taskView in taskViews {
if let label = taskView.viewWithTag(1) {
let height = label.sizeThatFits(labelSize).height
label.frame = CGRect(x: 40, y: ChallengeTaskListView.verticalSpacing, width: frame.size.width-80, height: height)
taskView.frame = CGRect(x: 0, y: nextTaskViewPos, width: frame.size.width, height: height+ChallengeTaskListView.verticalSpacing*2)
if let plusImageView = taskView.viewWithTag(2) {
plusImageView.frame = CGRect(x: 0, y: 0, width: 40, height: height+ChallengeTaskListView.verticalSpacing*2)
}
if let minusImageView = taskView.viewWithTag(3) {
minusImageView.frame = CGRect(x: frame.size.width-40, y: 0, width: 40, height: height+ChallengeTaskListView.verticalSpacing*2)
}
nextTaskViewPos += height+ChallengeTaskListView.verticalSpacing*2
}
}
borderView.frame = CGRect(x: 0, y: titleHeight, width: frame.size.width, height: nextTaskViewPos-titleHeight)
super.layoutSubviews()
}
override var intrinsicContentSize: CGSize {
if taskViews.isEmpty {
return CGSize.zero
}
var height = titleLabel.intrinsicContentSize.height + 8
let labelSize = CGSize(width: frame.size.width-80, height: frame.size.height)
for taskView in taskViews {
if let label = taskView.viewWithTag(1) as? UILabel {
height += label.sizeThatFits(labelSize).height+ChallengeTaskListView.verticalSpacing*2
}
}
return CGSize(width: self.frame.size.width, height: height)
}
private func removeAllTaskViews() {
for view in taskViews {
view.removeFromSuperview()
}
taskViews.removeAll()
}
private func createTaskView(task: TaskProtocol, isFirst: Bool) -> UIView {
let taskView = UIView()
let titleView = UILabel()
if !isFirst {
let borderView = UIView(frame: CGRect(x: 0, y: 0, width: frame.size.width, height: 1))
borderView.backgroundColor = ChallengeTaskListView.borderColor
taskView.addSubview(borderView)
}
titleView.tag = 1
taskView.addSubview(titleView)
titleView.text = task.text?.unicodeEmoji
titleView.numberOfLines = 0
titleView.font = UIFont.preferredFont(forTextStyle: .caption1)
titleView.textColor = UIColor(white: 0, alpha: 0.5)
if task.type == "habit" {
let plusImageView = UIImageView(image: #imageLiteral(resourceName: "plus_gray"))
plusImageView.tag = 2
plusImageView.contentMode = .center
taskView.addSubview(plusImageView)
if task.up {
plusImageView.alpha = 0.3
}
let minusImageView = UIImageView(image: #imageLiteral(resourceName: "minus_gray"))
minusImageView.tag = 3
minusImageView.contentMode = .center
taskView.addSubview(minusImageView)
if task.down {
minusImageView.alpha = 0.3
}
}
return taskView
}
private func updateTitle() {
titleLabel.font = UIFont.preferredFont(forTextStyle: .headline)
titleLabel.textColor = UIColor(white: 0, alpha: 0.5)
if let taskType = self.taskType {
var title: String?
switch taskType {
case "habit":
title = L10n.Tasks.habits
case "daily":
title = L10n.Tasks.dailies
case "todo":
title = L10n.Tasks.todos
case "reward":
title = L10n.Tasks.rewards
default:
title = ""
}
if let title = title {
self.titleLabel.text = "\(taskViews.count) \(title)"
}
}
}
}
| 5737a711a97232e5563f888b13d658d7 | 34.865031 | 146 | 0.5987 | false | false | false | false |
wuleijun/Zeus | refs/heads/master | Zeus/Views/BorderButton.swift | mit | 1 | //
// BorderButton.swift
// Zeus
//
// Created by 吴蕾君 on 16/4/12.
// Copyright © 2016年 rayjuneWu. All rights reserved.
//
import UIKit
@IBDesignable
class BorderButton: UIButton {
lazy var topLineLayer:CAShapeLayer = {
let topLayer = CAShapeLayer()
topLayer.lineWidth = 1
topLayer.strokeColor = UIColor.zeusBorderColor().CGColor
return topLayer
}()
override func didMoveToSuperview() {
super.didMoveToSuperview()
layer.addSublayer(topLineLayer)
}
override func layoutSubviews() {
super.layoutSubviews()
let topPath = UIBezierPath()
topPath.moveToPoint(CGPoint(x: 0, y: 0.5))
topPath.addLineToPoint(CGPoint(x: CGRectGetWidth(bounds), y: 0.5))
topLineLayer.path = topPath.CGPath
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
override func drawRect(rect: CGRect) {
// Drawing code
}
*/
}
| 679c8f263856ea2e9d6520efcee731d7 | 23.55814 | 78 | 0.63447 | false | false | false | false |
soapyigu/Swift30Projects | refs/heads/master | Project 07 - PokedexGo/PokedexGo/MasterTableViewCell.swift | apache-2.0 | 1 | //
// MasterTableViewCell.swift
// PokedexGo
//
// Created by Yi Gu on 7/10/16.
// Copyright © 2016 yigu. All rights reserved.
//
import UIKit
class MasterTableViewCell: UITableViewCell {
@IBOutlet weak var idLabel: UILabel!
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var pokeImageView: UIImageView!
fileprivate var indicator: UIActivityIndicatorView!
func awakeFromNib(_ id: Int, name: String, pokeImageUrl: String) {
super.awakeFromNib()
setupUI(id, name: name)
setupNotification(pokeImageUrl)
}
deinit {
pokeImageView.removeObserver(self, forKeyPath: "image")
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
}
fileprivate func setupUI(_ id: Int, name: String) {
idLabel.text = NSString(format: "#%03d", id) as String
nameLabel.text = name
pokeImageView.image = UIImage(named: "default_img")
indicator = UIActivityIndicatorView()
indicator.center = CGPoint(x: pokeImageView.bounds.midX, y: pokeImageView.bounds.midY)
indicator.activityIndicatorViewStyle = .whiteLarge
indicator.startAnimating()
pokeImageView.addSubview(indicator)
pokeImageView.addObserver(self, forKeyPath: "image", options: [], context: nil)
}
fileprivate func setupNotification(_ pokeImageUrl: String) {
NotificationCenter.default.post(name: Notification.Name(rawValue: downloadImageNotification), object: self, userInfo: ["pokeImageView":pokeImageView, "pokeImageUrl" : pokeImageUrl])
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "image" {
indicator.stopAnimating()
}
}
}
| 748fe5bfea3bf96aece9cf018c9f57e1 | 31.363636 | 185 | 0.718539 | false | false | false | false |
18775134221/SwiftBase | refs/heads/develop | 02-observable-pg/challenge/Challenge1-Starter/Pods/RxSwift/RxSwift/Observables/Implementations/CombineLatest+Collection.swift | apache-2.0 | 46 | //
// CombineLatest+Collection.swift
// RxSwift
//
// Created by Krunoslav Zaher on 8/29/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
class CombineLatestCollectionTypeSink<C: Collection, R, O: ObserverType>
: Sink<O> where C.Iterator.Element : ObservableConvertibleType, O.E == R {
typealias Parent = CombineLatestCollectionType<C, R>
typealias SourceElement = C.Iterator.Element.E
let _parent: Parent
let _lock = NSRecursiveLock()
// state
var _numberOfValues = 0
var _values: [SourceElement?]
var _isDone: [Bool]
var _numberOfDone = 0
var _subscriptions: [SingleAssignmentDisposable]
init(parent: Parent, observer: O, cancel: Cancelable) {
_parent = parent
_values = [SourceElement?](repeating: nil, count: parent._count)
_isDone = [Bool](repeating: false, count: parent._count)
_subscriptions = Array<SingleAssignmentDisposable>()
_subscriptions.reserveCapacity(parent._count)
for _ in 0 ..< parent._count {
_subscriptions.append(SingleAssignmentDisposable())
}
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceElement>, atIndex: Int) {
_lock.lock(); defer { _lock.unlock() } // {
switch event {
case .next(let element):
if _values[atIndex] == nil {
_numberOfValues += 1
}
_values[atIndex] = element
if _numberOfValues < _parent._count {
let numberOfOthersThatAreDone = self._numberOfDone - (_isDone[atIndex] ? 1 : 0)
if numberOfOthersThatAreDone == self._parent._count - 1 {
forwardOn(.completed)
dispose()
}
return
}
do {
let result = try _parent._resultSelector(_values.map { $0! })
forwardOn(.next(result))
}
catch let error {
forwardOn(.error(error))
dispose()
}
case .error(let error):
forwardOn(.error(error))
dispose()
case .completed:
if _isDone[atIndex] {
return
}
_isDone[atIndex] = true
_numberOfDone += 1
if _numberOfDone == self._parent._count {
forwardOn(.completed)
dispose()
}
else {
_subscriptions[atIndex].dispose()
}
}
// }
}
func run() -> Disposable {
var j = 0
for i in _parent._sources {
let index = j
let source = i.asObservable()
let disposable = source.subscribe(AnyObserver { event in
self.on(event, atIndex: index)
})
_subscriptions[j].setDisposable(disposable)
j += 1
}
return Disposables.create(_subscriptions)
}
}
class CombineLatestCollectionType<C: Collection, R> : Producer<R> where C.Iterator.Element : ObservableConvertibleType {
typealias ResultSelector = ([C.Iterator.Element.E]) throws -> R
let _sources: C
let _resultSelector: ResultSelector
let _count: Int
init(sources: C, resultSelector: @escaping ResultSelector) {
_sources = sources
_resultSelector = resultSelector
_count = Int(self._sources.count.toIntMax())
}
override func run<O : ObserverType>(_ observer: O, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where O.E == R {
let sink = CombineLatestCollectionTypeSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
| 40be97b509faee36a20919d500af9fc8 | 31.732283 | 139 | 0.521049 | false | false | false | false |
chamander/Sampling-Reactive | refs/heads/master | Source/Models/Weather.swift | mit | 2 | // Copyright © 2016 Gavan Chan. All rights reserved.
import Argo
import Curry
import Runes
typealias Temperature = Double
typealias Percentage = Double
struct Weather {
let city: City
let current: Temperature
let cloudiness: Percentage
}
extension Weather: Decodable {
static func decode(_ json: JSON) -> Decoded<Weather> {
let city: Decoded<City> = City.decode(json)
let current: Decoded<Temperature> = json <| ["main", "temp"]
let cloudiness: Decoded<Percentage> = json <| ["clouds", "all"]
let initialiser: ((City) -> (Temperature) -> (Percentage) -> Weather) = curry(Weather.init)
return initialiser <^> city <*> current <*> cloudiness
}
}
| a7603ba1aa4b88edc8bf5b8138d17118 | 25.192308 | 95 | 0.687225 | false | false | false | false |
kuruvilla6970/Zoot | refs/heads/master | Source/Web View/WebViewController.swift | mit | 1 | //
// WebViewController.swift
// THGHybridWeb
//
// Created by Angelo Di Paolo on 4/16/15.
// Copyright (c) 2015 TheHolyGrail. All rights reserved.
//
import Foundation
import JavaScriptCore
import UIKit
#if NOFRAMEWORKS
#else
import THGBridge
#endif
/**
Defines methods that a delegate of a WebViewController object can optionally
implement to interact with the web view's loading cycle.
*/
@objc public protocol WebViewControllerDelegate {
/**
Sent before the web view begins loading a frame.
:param: webViewController The web view controller loading the web view frame.
:param: request The request that will load the frame.
:param: navigationType The type of user action that started the load.
:returns: Return true to
*/
optional func webViewController(webViewController: WebViewController, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
/**
Sent before the web view begins loading a frame.
:param: webViewController The web view controller that has begun loading the frame.
*/
optional func webViewControllerDidStartLoad(webViewController: WebViewController)
/**
Sent after the web view as finished loading a frame.
:param: webViewController The web view controller that has completed loading the frame.
*/
optional func webViewControllerDidFinishLoad(webViewController: WebViewController)
/**
Sent if the web view fails to load a frame.
:param: webViewController The web view controller that failed to load the frame.
:param: error The error that occured during loading.
*/
optional func webViewController(webViewController: WebViewController, didFailLoadWithError error: NSError)
/**
Sent when the web view creates the JS context for the frame.
:param: webViewController The web view controller that failed to load the frame.
:param: context The newly created JavaScript context.
*/
optional func webViewControllerDidCreateJavaScriptContext(webViewController: WebViewController, context: JSContext)
}
/**
A view controller that integrates a web view with the hybrid JavaScript API.
# Usage
Initialize a web view controller and call `loadURL()` to asynchronously load
the web view with a URL.
```
let webController = WebViewController()
webController.loadURL(NSURL(string: "foo")!)
window?.rootViewController = webController
```
Call `addHybridAPI()` to add the bridged JavaScript API to the web view.
The JavaScript API will be accessible to any web pages that are loaded in the
web view controller.
```
let webController = WebViewController()
webController.addHybridAPI()
webController.loadURL(NSURL(string: "foo")!)
window?.rootViewController = webController
```
To utilize the navigation JavaScript API you must provide a navigation
controller for the web view controller.
```
let webController = WebViewController()
webController.addHybridAPI()
webController.loadURL(NSURL(string: "foo")!)
let navigationController = UINavigationController(rootViewController: webController)
window?.rootViewController = navigationController
```
*/
public class WebViewController: UIViewController {
enum AppearenceCause {
case Unknown, WebPush, WebPop, WebModal, WebDismiss
}
/// The URL that was loaded with `loadURL()`
private(set) public var url: NSURL?
/// The web view used to load and render the web content.
private(set) public lazy var webView: UIWebView = {
let webView = UIWebView(frame: CGRectZero)
webView.delegate = self
webViews.addObject(webView)
return webView
}()
/// JavaScript bridge for the web view's JSContext
private(set) public var bridge = Bridge()
private var storedScreenshotGUID: String? = nil
private var goBackInWebViewOnAppear = false
private var firstLoadCycleCompleted = true
private var disappearedBy = AppearenceCause.Unknown
private var storedAppearence = AppearenceCause.WebPush
private var appearedFrom: AppearenceCause {
get {
switch disappearedBy {
case .WebPush: return .WebPop
case .WebModal: return .WebDismiss
default: return storedAppearence
}
}
set {
storedAppearence = newValue
}
}
private lazy var placeholderImageView: UIImageView = {
return UIImageView(frame: self.view.bounds)
}()
private var errorView: UIView?
private var errorLabel: UILabel?
private var reloadButton: UIButton?
public weak var hybridAPI: HybridAPI?
public var navigationCallback: JSValue?
/// Handles web view controller events.
public weak var delegate: WebViewControllerDelegate?
/// Set `false` to disable error message UI.
public var showErrorDisplay = true
/**
Initialize a web view controller instance with a web view and JavaScript
bridge. The newly initialized web view controller becomes the delegate of
the web view.
:param: webView The web view to use in the web view controller.
:param: bridge The bridge instance to integrate int
*/
public required init(webView: UIWebView, bridge: Bridge) {
super.init(nibName: nil, bundle: nil)
self.bridge = bridge
self.webView = webView
self.webView.delegate = self
}
public override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
}
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
deinit {
if webView.delegate === self {
webView.delegate = nil
}
}
public override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.whiteColor()
edgesForExtendedLayout = .None
view.addSubview(placeholderImageView)
}
public override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
hybridAPI?.parentViewController = self
switch appearedFrom {
case .WebPush, .WebModal, .WebPop, .WebDismiss:
if goBackInWebViewOnAppear {
goBackInWebViewOnAppear = false
webView.goBack() // go back before remove/adding web view
}
webView.delegate = self
webView.removeFromSuperview()
webView.frame = view.bounds
view.addSubview(webView)
view.removeDoubleTapGestures()
// if we have a screenshot stored, load it.
if let guid = storedScreenshotGUID {
placeholderImageView.image = UIImage.loadImageFromGUID(guid)
placeholderImageView.frame = view.bounds
view.bringSubviewToFront(placeholderImageView)
}
if appearedFrom == .WebModal || appearedFrom == .WebPush {
navigationCallback?.asValidValue?.callWithArguments(nil)
}
case .Unknown: break
}
}
public override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
hybridAPI?.view.appeared()
switch appearedFrom {
case .WebPop, .WebDismiss:
showWebView()
addBridgeAPIObject()
case .WebPush, .WebModal, .Unknown: break
}
}
public override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
switch disappearedBy {
case .WebPop, .WebDismiss, .WebPush, .WebModal:
// only store screen shot when disappearing by web transition
placeholderImageView.frame = webView.frame // must align frames for image capture
let image = webView.captureImage()
placeholderImageView.image = image
storedScreenshotGUID = image.saveImageToGUID()
view.bringSubviewToFront(placeholderImageView)
webView.hidden = true
case .Unknown: break
}
hybridAPI?.view.disappeared() // needs to be called in viewWillDisappear not Did
}
public override func viewDidDisappear(animated: Bool) {
super.viewDidDisappear(animated)
switch disappearedBy {
case .WebPop, .WebDismiss, .WebPush, .WebModal:
// we're gone. dump the screenshot, we'll load it later if we need to.
placeholderImageView.image = nil
case .Unknown:
// we don't know how it will appear if we don't know how it disappeared
appearedFrom = .Unknown
}
}
public final func showWebView() {
webView.hidden = false
placeholderImageView.image = nil
view.sendSubviewToBack(placeholderImageView)
}
}
// MARK: - Request Loading
extension WebViewController {
/**
Load the web view with the provided URL.
:param: url The URL used to load the web view.
*/
final public func loadURL(url: NSURL) {
webView.stopLoading()
hybridAPI = nil
firstLoadCycleCompleted = false
self.url = url
webView.loadRequest(requestWithURL(url))
}
/**
Create a request with the provided URL.
:param: url The URL for the request.
*/
public func requestWithURL(url: NSURL) -> NSURLRequest {
return NSURLRequest(URL: url)
}
}
// MARK: - UIWebViewDelegate
extension WebViewController: UIWebViewDelegate {
final public func webViewDidStartLoad(webView: UIWebView) {
delegate?.webViewControllerDidStartLoad?(self)
}
public func webViewDidFinishLoad(webView: UIWebView) {
delegate?.webViewControllerDidFinishLoad?(self)
if self.errorView != nil {
self.removeErrorDisplay()
}
}
final public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
if pushesWebViewControllerForNavigationType(navigationType) {
pushWebViewController()
}
return delegate?.webViewController?(self, shouldStartLoadWithRequest: request, navigationType: navigationType) ?? true
}
final public func webView(webView: UIWebView, didFailLoadWithError error: NSError) {
if error.code != NSURLErrorCancelled {
if showErrorDisplay {
renderFeatureErrorDisplayWithError(error, featureName: featureNameForError(error))
}
}
delegate?.webViewController?(self, didFailLoadWithError: error)
}
}
// MARK: - JavaScript Context
extension WebViewController {
/**
Update the bridge's JavaScript context by attempting to retrieve a context
from the web view.
*/
final public func updateBridgeContext() {
if let context = webView.javaScriptContext {
configureBridgeContext(context)
} else {
println("Failed to retrieve JavaScript context from web view.")
}
}
private func didCreateJavaScriptContext(context: JSContext) {
configureBridgeContext(context)
delegate?.webViewControllerDidCreateJavaScriptContext?(self, context: context)
configureContext(context)
if let hybridAPI = hybridAPI {
var readyCallback = bridge.contextValueForName("nativeBridgeReady")
if !readyCallback.isUndefined() {
readyCallback.callWithData(hybridAPI)
}
}
}
/**
Explictly set the bridge's JavaScript context.
*/
final public func configureBridgeContext(context: JSContext) {
bridge.context = context
}
public func configureContext(context: JSContext) {
addBridgeAPIObject()
}
}
// MARK: - Web Controller Navigation
extension WebViewController {
/**
Push a new web view controller on the navigation stack using the existing
web view instance. Does not affect web view history. Uses animation.
*/
public func pushWebViewController() {
pushWebViewController(hideBottomBar: false, callback: nil)
}
/**
Push a new web view controller on the navigation stack using the existing
web view instance. Does not affect web view history. Uses animation.
:param: hideBottomBar Hides the bottom bar of the view controller when true.
*/
public func pushWebViewController(#hideBottomBar: Bool, callback: JSValue?) {
goBackInWebViewOnAppear = true
disappearedBy = .WebPush
let webViewController = newWebViewController()
webViewController.appearedFrom = .WebPush
webViewController.navigationCallback = callback
webViewController.hidesBottomBarWhenPushed = hideBottomBar
navigationController?.pushViewController(webViewController, animated: true)
}
/**
Pop a web view controller off of the navigation. Does not affect
web view history. Uses animation.
*/
public func popWebViewController() {
if let navController = self.navigationController
where navController.viewControllers.count > 1 {
(navController.viewControllers[navController.viewControllers.count - 1] as? WebViewController)?.goBackInWebViewOnAppear = false
navController.popViewControllerAnimated(true)
}
}
/**
Present a navigation controller containing a new web view controller as the
root view controller. The existing web view instance is reused.
*/
public func presentModalWebViewController(callback: JSValue?) {
goBackInWebViewOnAppear = false
disappearedBy = .WebModal
let webViewController = newWebViewController()
webViewController.appearedFrom = .WebModal
webViewController.navigationCallback = callback
let navigationController = UINavigationController(rootViewController: webViewController)
if let tabBarController = tabBarController {
tabBarController.presentViewController(navigationController, animated: true, completion: nil)
} else {
presentViewController(navigationController, animated: true, completion: nil)
}
}
/// Pops until there's only a single view controller left on the navigation stack.
public func popToRootWebViewController() {
navigationController?.popToRootViewControllerAnimated(true)
}
/**
Return `true` to have the web view controller push a new web view controller
on the stack for a given navigation type of a request.
*/
public func pushesWebViewControllerForNavigationType(navigationType: UIWebViewNavigationType) -> Bool {
return false
}
public func newWebViewController() -> WebViewController {
let webViewController = self.dynamicType(webView: webView, bridge: bridge)
webViewController.addBridgeAPIObject()
return webViewController
}
}
// MARK: - Error UI
extension WebViewController {
private func createErrorLabel() -> UILabel? {
let height = CGFloat(50)
let y = CGRectGetMidY(view.bounds) - (height / 2) - 100
var label = UILabel(frame: CGRectMake(0, y, CGRectGetWidth(view.bounds), height))
label.lineBreakMode = NSLineBreakMode.ByWordWrapping
label.numberOfLines = 0
label.textAlignment = NSTextAlignment.Center
label.backgroundColor = view.backgroundColor
label.font = UIFont.systemFontOfSize(12, weight: 2)
return label
}
private func createReloadButton() -> UIButton? {
if let button = UIButton.buttonWithType(UIButtonType.Custom) as? UIButton {
let size = CGSizeMake(170, 38)
let x = CGRectGetMidX(view.bounds) - (size.width / 2)
var y = CGRectGetMidY(view.bounds) - (size.height / 2)
if let label = errorLabel {
y = CGRectGetMaxY(label.frame) + 20
}
button.setTitle(NSLocalizedString("Try again", comment: "Try again"), forState: UIControlState.Normal)
button.frame = CGRectMake(x, y, size.width, size.height)
button.backgroundColor = UIColor.lightGrayColor()
button.titleLabel?.backgroundColor = UIColor.lightGrayColor()
button.titleLabel?.textColor = UIColor.whiteColor()
return button
}
return nil
}
}
// MARK: - Error Display Events
extension WebViewController {
/// Override to completely customize error display. Must also override `removeErrorDisplay`
public func renderErrorDisplayWithError(error: NSError, message: String) {
let errorView = UIView(frame: view.bounds)
view.addSubview(errorView)
self.errorView = errorView
self.errorLabel = createErrorLabel()
self.reloadButton = createReloadButton()
if let errorLabel = errorLabel {
errorLabel.text = NSLocalizedString(message, comment: "Web View Load Error")
errorView.addSubview(errorLabel)
}
if let button = reloadButton {
button.addTarget(self, action: "reloadButtonTapped:", forControlEvents: .TouchUpInside)
errorView.addSubview(button)
}
}
/// Override to handle custom error display removal.
public func removeErrorDisplay() {
errorView?.removeFromSuperview()
errorView = nil
}
/// Override to customize the feature name that appears in the error display.
public func featureNameForError(error: NSError) -> String {
return "This feature"
}
/// Override to customize the error message text.
public func renderFeatureErrorDisplayWithError(error: NSError, featureName: String) {
let message = "Sorry!\n \(featureName) isn't working right now."
renderErrorDisplayWithError(error, message: message)
}
/// Removes the error display and attempts to reload the web view.
public func reloadButtonTapped(sender: AnyObject) {
map(url) {self.loadURL($0)}
}
}
// MARK: - Bridge API
extension WebViewController {
public func addBridgeAPIObject() {
if let bridgeObject = hybridAPI {
bridge.context.setObject(bridgeObject, forKeyedSubscript: HybridAPI.exportName)
} else {
let platform = HybridAPI(parentViewController: self)
bridge.context.setObject(platform, forKeyedSubscript: HybridAPI.exportName)
hybridAPI = platform
}
}
}
// MARK: - UIView Utils
extension UIView {
func captureImage() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, opaque, 0.0)
layer.renderInContext(UIGraphicsGetCurrentContext())
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
func removeDoubleTapGestures() {
for view in self.subviews {
view.removeDoubleTapGestures()
}
if let gestureRecognizers = gestureRecognizers {
for gesture in gestureRecognizers {
if let gesture = gesture as? UITapGestureRecognizer
where gesture.numberOfTapsRequired == 2 {
removeGestureRecognizer(gesture)
}
}
}
}
}
// MARK: - UIImage utils
extension UIImage {
// saves image to temp directory and returns a GUID so you can fetch it later.
func saveImageToGUID() -> String? {
let guid = String.GUID()
// do this shit in the background.
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) { () -> Void in
let data = UIImageJPEGRepresentation(self, 1.0)
if let data = data {
let fileManager = NSFileManager.defaultManager()
let fullPath = NSTemporaryDirectory().stringByAppendingPathComponent(guid)
fileManager.createFileAtPath(fullPath, contents: data, attributes: nil)
}
}
return guid
}
class func loadImageFromGUID(guid: String?) -> UIImage? {
if let guid = guid {
let fileManager = NSFileManager.defaultManager()
let fullPath = NSTemporaryDirectory().stringByAppendingPathComponent(guid)
let image = UIImage(contentsOfFile: fullPath)
return image
}
return nil
}
}
// MARK: - JSContext Event
private var webViews = NSHashTable.weakObjectsHashTable()
private struct Statics {
static var webViewOnceToken: dispatch_once_t = 0
}
extension NSObject {
func webView(webView: AnyObject, didCreateJavaScriptContext context: JSContext, forFrame frame: AnyObject) {
if let webFrameClass: AnyClass = NSClassFromString("WebFrame")
where !(frame.dynamicType === webFrameClass) {
return
}
if let allWebViews = webViews.allObjects as? [UIWebView] {
for webView in allWebViews {
webView.didCreateJavaScriptContext(context)
}
}
}
}
extension UIWebView {
func didCreateJavaScriptContext(context: JSContext) {
(delegate as? WebViewController)?.didCreateJavaScriptContext(context)
}
}
| a37ecc13f27e349d2bab021b26cc2e33 | 32.519142 | 172 | 0.651818 | false | false | false | false |
qianyu09/AppLove | refs/heads/master | App Love/WHC_Lib/Swift_Lib/WHC_MoreMenuItemVC.swift | mit | 1 | //
// WHC_MoreMenuItemVC.swift
// WHC_MenuViewDemo
//
// Created by 吴海超 on 15/10/20.
// Copyright © 2015年 吴海超. All rights reserved.
//
/*
* qq:712641411
* gitHub:https://github.com/netyouli
* csdn:http://blog.csdn.net/windwhc/article/category/3117381
*/
import UIKit
protocol WHC_MoreMenuItemVCDelegate{
func WHCMoreMenuItemVC(moreVC: WHC_MoreMenuItemVC , addTitles: [String]! , addImageNames: [String]!);
}
class WHC_MoreMenuItemVC: UIViewController{
/// 缓存菜单key
var cacheWHCMenuKey: String!;
var AppCategoryList:[AppCategoryItem]!
/// 菜单项标题集合
var menuItemTitles: [String]!;
/// 菜单项图片名称集合
var menuItemImageNames: [String]!;
/// 代理
var delegate: WHC_MoreMenuItemVCDelegate!;
/// 边距
var pading: CGFloat = 0;
/// 菜单对象
private var menuView: WHC_MenuView!;
override func viewDidLoad() {
super.viewDidLoad()
self.initData();
self.layoutUI();
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
private func initData(){
}
private func layoutUI(){
self.navigationItem.title = "更多";
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor();
self.view.backgroundColor = UIColor.themeBackgroundColor();
let cancelBarItem = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: #selector(WHC_MoreMenuItemVC.clickCancelItem(_:)));
self.navigationItem.leftBarButtonItem = cancelBarItem;
let menuViewParam = WHC_MenuViewParam.getWHCMenuViewDefaultParam(titles: self.menuItemTitles, imageNames: self.menuItemImageNames, cacheWHCMenuKey: self.cacheWHCMenuKey);
//by louis
// let menuViewParam = WHC_MenuViewParam.getWHCMenuViewDefaultParam(self.AppCategoryList, cacheWHCMenuKey: self.cacheWHCMenuKey);
menuViewParam.canDelete = false;
menuViewParam.canAdd = true;
menuViewParam.canSort = true;
menuViewParam.cacheWHCMenuKey = self.cacheWHCMenuKey;
menuViewParam.isMoreMenuItem = true;
self.menuView = WHC_MenuView(frame: UIScreen.mainScreen().bounds, menuViewParam: menuViewParam);
self.view.addSubview(self.menuView);
}
func clickCancelItem(sender: UIBarButtonItem){
self.delegate?.WHCMoreMenuItemVC(self,
addTitles: self.menuView.getInsertTitles(),
addImageNames: self.menuView.getInsertImageNames());
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.
}
*/
}
| f6bb808d43600b415e82048ecf71f0ab | 33.431818 | 178 | 0.686799 | false | false | false | false |
JGiola/swift | refs/heads/main | test/Frontend/dump-parse.swift | apache-2.0 | 7 | // RUN: not %target-swift-frontend -dump-parse %s | %FileCheck %s
// RUN: not %target-swift-frontend -dump-ast %s | %FileCheck %s -check-prefix=CHECK-AST
// CHECK-LABEL: (func_decl{{.*}}"foo(_:)"
// CHECK-AST-LABEL: (func_decl{{.*}}"foo(_:)"
func foo(_ n: Int) -> Int {
// CHECK: (brace_stmt
// CHECK: (return_stmt
// CHECK: (integer_literal_expr type='<null>' value=42 {{.*}})))
// CHECK-AST: (brace_stmt
// CHECK-AST: (return_stmt
// CHECK-AST: (integer_literal_expr type='{{[^']+}}' {{.*}} value=42 {{.*}})
return 42
}
// -dump-parse should print an AST even though this code is invalid.
// CHECK-LABEL: (func_decl{{.*}}"bar()"
// CHECK-AST-LABEL: (func_decl{{.*}}"bar()"
func bar() {
// CHECK: (brace_stmt
// CHECK-NEXT: (unresolved_decl_ref_expr type='{{[^']+}}' name=foo
// CHECK-NEXT: (unresolved_decl_ref_expr type='{{[^']+}}' name=foo
// CHECK-NEXT: (unresolved_decl_ref_expr type='{{[^']+}}' name=foo
// CHECK-AST: (brace_stmt
// CHECK-AST-NEXT: (declref_expr type='{{[^']+}}' {{.*}} decl=main.(file).foo
// CHECK-AST-NEXT: (declref_expr type='{{[^']+}}' {{.*}} decl=main.(file).foo
// CHECK-AST-NEXT: (declref_expr type='{{[^']+}}' {{.*}} decl=main.(file).foo
foo foo foo
}
// CHECK-LABEL: (enum_decl{{.*}}trailing_semi "TrailingSemi"
enum TrailingSemi {
// CHECK-LABEL: (enum_case_decl{{.*}}trailing_semi
// CHECK-NOT: (enum_element_decl{{.*}}trailing_semi
// CHECK: (enum_element_decl{{.*}}"A")
// CHECK: (enum_element_decl{{.*}}"B")
case A,B;
// CHECK-LABEL: (subscript_decl{{.*}}trailing_semi
// CHECK-NOT: (func_decl{{.*}}trailing_semi 'anonname={{.*}}' get_for=subscript(_:)
// CHECK: (accessor_decl{{.*}}'anonname={{.*}}' get_for=subscript(_:)
subscript(x: Int) -> Int {
// CHECK-LABEL: (pattern_binding_decl{{.*}}trailing_semi
// CHECK-NOT: (var_decl{{.*}}trailing_semi "y"
// CHECK: (var_decl{{.*}}"y"
var y = 1;
// CHECK-LABEL: (sequence_expr {{.*}} trailing_semi
y += 1;
// CHECK-LABEL: (return_stmt{{.*}}trailing_semi
return y;
};
};
// The substitution map for a declref should be relatively unobtrusive.
// CHECK-AST-LABEL: (func_decl{{.*}}"generic(_:)" <T : Hashable> interface type='<T where T : Hashable> (T) -> ()' access=internal captures=(<generic> )
func generic<T: Hashable>(_: T) {}
// CHECK-AST: (pattern_binding_decl
// CHECK-AST: (declref_expr type='(Int) -> ()' location={{.*}} range={{.*}} decl=main.(file).generic@{{.*}} [with (substitution_map generic_signature=<T where T : Hashable> (substitution T -> Int))] function_ref=unapplied))
let _: (Int) -> () = generic
// Closures should be marked as escaping or not.
func escaping(_: @escaping (Int) -> Int) {}
escaping({ $0 })
// CHECK-AST: (declref_expr type='(@escaping (Int) -> Int) -> ()'
// CHECK-AST-NEXT: (argument_list
// CHECK-AST-NEXT: (argument
// CHECK-AST-NEXT: (closure_expr type='(Int) -> Int' {{.*}} discriminator=0 escaping single-expression
func nonescaping(_: (Int) -> Int) {}
nonescaping({ $0 })
// CHECK-AST: (declref_expr type='((Int) -> Int) -> ()'
// CHECK-AST-NEXT: (argument_list
// CHECK-AST-NEXT: (argument
// CHECK-AST-NEXT: (closure_expr type='(Int) -> Int' {{.*}} discriminator=1 single-expression
// CHECK-LABEL: (struct_decl range=[{{.+}}] "MyStruct")
struct MyStruct {}
// CHECK-LABEL: (enum_decl range=[{{.+}}] "MyEnum"
enum MyEnum {
// CHECK-LABEL: (enum_case_decl range=[{{.+}}]
// CHECK-NEXT: (enum_element_decl range=[{{.+}}] "foo(x:)"
// CHECK-NEXT: (parameter_list range=[{{.+}}]
// CHECK-NEXT: (parameter "x" apiName=x)))
// CHECK-NEXT: (enum_element_decl range=[{{.+}}] "bar"))
// CHECK-NEXT: (enum_element_decl range=[{{.+}}] "foo(x:)"
// CHECK-NEXT: (parameter_list range=[{{.+}}]
// CHECK-NEXT: (parameter "x" apiName=x)))
// CHECK-NEXT: (enum_element_decl range=[{{.+}}] "bar"))
case foo(x: MyStruct), bar
}
// CHECK-LABEL: (top_level_code_decl range=[{{.+}}]
// CHECK-NEXT: (brace_stmt implicit range=[{{.+}}]
// CHECK-NEXT: (sequence_expr type='<null>'
// CHECK-NEXT: (discard_assignment_expr type='<null>')
// CHECK-NEXT: (assign_expr type='<null>'
// CHECK-NEXT: (**NULL EXPRESSION**)
// CHECK-NEXT: (**NULL EXPRESSION**))
// CHECK-NEXT: (closure_expr type='<null>' discriminator={{[0-9]+}}
// CHECK-NEXT: (parameter_list range=[{{.+}}]
// CHECK-NEXT: (parameter "v"))
// CHECK-NEXT: (brace_stmt range=[{{.+}}])))))
_ = { (v: MyEnum) in }
// CHECK-LABEL: (struct_decl range=[{{.+}}] "SelfParam"
struct SelfParam {
// CHECK-LABEL: (func_decl range=[{{.+}}] "createOptional()" type
// CHECK-NEXT: (parameter "self")
// CHECK-NEXT: (parameter_list range=[{{.+}}])
// CHECK-NEXT: (result
// CHECK-NEXT: (type_optional
// CHECK-NEXT: (type_ident
// CHECK-NEXT: (component id='SelfParam' bind=none))))
static func createOptional() -> SelfParam? {
// CHECK-LABEL: (call_expr type='<null>'
// CHECK-NEXT: (unresolved_decl_ref_expr type='<null>' name=SelfParam function_ref=unapplied)
// CHECK-NEXT: (argument_list)
SelfParam()
}
}
| 6e8bae0bbc2432ed9883e758d99a7b93 | 40.944882 | 231 | 0.56636 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial | refs/heads/master | v2.x/Examples/SciChartSwiftDemo/SciChartSwiftDemo/Views/SpeedTesting/NxMSeriesSpeedTestSciChart.swift | mit | 1 | //******************************************************************************
// SCICHART® Copyright SciChart Ltd. 2011-2018. All rights reserved.
//
// Web: http://www.scichart.com
// Support: [email protected]
// Sales: [email protected]
//
// NxMSeriesSpeedTestSciChart.swift is part of the SCICHART® Examples. Permission is hereby granted
// to modify, create derivative works, distribute and publish any part of this source
// code whether for commercial, private or personal use.
//
// The SCICHART® examples are distributed in the hope that they will be useful, but
// without any warranty. It is provided "AS IS" without warranty of any kind, either
// expressed or implied.
//******************************************************************************
class NxMSeriesSpeedTestSciChart: SingleChartLayout {
let PointsCount: Int32 = 100
let SeriesCount: Int32 = 100
var _timer: Timer!
let _yAxis = SCINumericAxis()
var _updateNumber = 0
var _rangeMin = Double.nan
var _rangeMax = Double.nan
override func initExample() {
let xAxis = SCINumericAxis()
let randomWalk = RandomWalkGenerator()!
SCIUpdateSuspender.usingWithSuspendable(surface) {
self.surface.xAxes.add(xAxis)
self.surface.yAxes.add(self._yAxis)
var color: Int64 = 0xFF0F0505
for _ in 0..<self.SeriesCount {
randomWalk.reset()
let doubleSeries = randomWalk.getRandomWalkSeries(self.PointsCount)
let dataSeries = SCIXyDataSeries(xType: .double, yType: .double)
dataSeries.appendRangeX(doubleSeries!.xValues, y: doubleSeries!.yValues, count: doubleSeries!.size)
color = color + 0x00000101
let rSeries = SCIFastLineRenderableSeries()
rSeries.dataSeries = dataSeries
rSeries.strokeStyle = SCISolidPenStyle(colorCode: UInt32(color), withThickness: 0.5)
self.surface.renderableSeries.add(rSeries)
}
}
_timer = Timer.scheduledTimer(timeInterval: 0.02, target: self, selector: #selector(updateData), userInfo: nil, repeats: true)
}
@objc fileprivate func updateData(_ timer: Timer) {
if (_rangeMin.isNaN) {
_rangeMin = _yAxis.visibleRange.minAsDouble()
_rangeMax = _yAxis.visibleRange.maxAsDouble()
}
let scaleFactor = fabs(sin(Double(_updateNumber) * 0.1)) + 0.5;
_yAxis.visibleRange = SCIDoubleRange(min: SCIGeneric(_rangeMin * scaleFactor), max: SCIGeneric(_rangeMax * scaleFactor))
_updateNumber += 1
}
override func willMove(toWindow newWindow: UIWindow?) {
super.willMove(toWindow: newWindow)
if (newWindow == nil) {
_timer.invalidate()
_timer = nil
}
}
}
| 82f2ae09c22db4c22f057232b898bd65 | 38.306667 | 134 | 0.591927 | false | false | false | false |
robpeach/test | refs/heads/master | SwiftPages/AboutVC.swift | mit | 1 | //
// AboutVC.swift
// Britannia v2
//
// Created by Rob Mellor on 10/08/2016.
// Copyright © 2016 Robert Mellor. All rights reserved.
//
import UIKit
import Foundation
import MessageUI
class AboutVC: UIViewController, MFMailComposeViewControllerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func findusButton(sender: AnyObject) {
UIApplication.sharedApplication().openURL(NSURL(string: "http://maps.apple.com/?address=198,HighStreet,Scunthorpe.DN156EA")!)
}
@IBAction func sendEmailButtonTapped(sender: AnyObject) {
let mailComposeViewController = configuredMailComposeViewController()
if MFMailComposeViewController.canSendMail() {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
self.view.window!.rootViewController?.presentViewController(mailComposeViewController, animated: true, completion: nil)
})
} else {
self.showSendMailErrorAlert()
}
}
func configuredMailComposeViewController() -> MFMailComposeViewController {
let mailComposerVC = MFMailComposeViewController()
mailComposerVC.mailComposeDelegate = self // Extremely important to set the --mailComposeDelegate-- property, NOT the --delegate-- property
mailComposerVC.setToRecipients(["[email protected]"])
mailComposerVC.setSubject("")
mailComposerVC.setMessageBody("Sent from The Britannia App - We aim to reply within 24 hours.", isHTML: false)
return mailComposerVC
}
func showSendMailErrorAlert() {
let sendMailErrorAlert = UIAlertView(title: "Could Not Send Email", message: "Your device could not send e-mail. Please check e-mail configuration and try again.", delegate: self, cancelButtonTitle: "OK")
sendMailErrorAlert.show()
}
// MARK: MFMailComposeViewControllerDelegate
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func movetoChatBtn(sender: AnyObject) {
print("button pressed")
let storyboard : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
let vc : ChatVC = storyboard.instantiateViewControllerWithIdentifier("ChatView") as! ChatVC
// vc.teststring = "hello"
let navigationController = UINavigationController(rootViewController: vc)
self.presentViewController(navigationController, animated: 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.
}
*/
}
| 7a77630c8dbfefc34728554464215797 | 33.183673 | 213 | 0.676119 | false | false | false | false |
Bargetor/beak | refs/heads/master | Beak/Beak/extension/BBStringExtension.swift | mit | 1 | //
// BBStringExtension.swift
// Beak
//
// Created by 马进 on 2016/12/6.
// Copyright © 2016年 马进. All rights reserved.
//
import Foundation
extension String {
public func substringWithRange(_ range: NSRange) -> String! {
let r = (self.index(self.startIndex, offsetBy: range.location) ..< self.index(self.startIndex, offsetBy: range.location + range.length))
return String(self[r])
}
public func urlencode() -> String {
let urlEncoded = self.replacingOccurrences(of: " ", with: "+")
let chartset = NSMutableCharacterSet(bitmapRepresentation: (CharacterSet.urlQueryAllowed as NSCharacterSet).bitmapRepresentation)
chartset.removeCharacters(in: "!*'();:@&=$,/?%#[]")
return urlEncoded.addingPercentEncoding(withAllowedCharacters: chartset as CharacterSet)!
}
public func length() -> Int{
return self.count
}
public func format(arguments: CVarArg...) -> String{
return String(format: self, arguments: arguments)
}
public mutating func replaceSubrange(_ range: NSRange, with replacementString: String) -> String {
if(range.location >= self.count){
self.append(replacementString)
return self
}
if let newRange: Range<String.Index> = self.range(for: range){
self.replaceSubrange(newRange, with: replacementString)
}
return self
}
func range(for range: NSRange) -> Range<String.Index>? {
guard range.location != NSNotFound else { return nil }
guard let fromUTFIndex = self.utf16.index(self.utf16.startIndex, offsetBy: range.location, limitedBy: self.utf16.endIndex) else { return nil }
guard let toUTFIndex = self.utf16.index(fromUTFIndex, offsetBy: range.length, limitedBy: self.utf16.endIndex) else { return nil }
guard let fromIndex = String.Index(fromUTFIndex, within: self) else { return nil }
guard let toIndex = String.Index(toUTFIndex, within: self) else { return nil }
return fromIndex ..< toIndex
}
}
| 16c1085034327c641097b968575b3c75 | 35.016949 | 150 | 0.64 | false | false | false | false |
tensorflow/examples | refs/heads/master | lite/examples/gesture_classification/ios/GestureClassification/ModelDataHandler/ModelDataHandler.swift | apache-2.0 | 1 | // Copyright 2019 The TensorFlow Authors. 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 Accelerate
import CoreImage
import TensorFlowLite
import UIKit
// MARK: Structures That hold results
/**
Stores inference results for a particular frame that was successfully run through the
TensorFlow Lite Interpreter.
*/
struct Result{
let inferenceTime: Double
let inferences: [Inference]
}
/**
Stores one formatted inference.
*/
struct Inference {
let confidence: Float
let label: String
}
/// Information about a model file or labels file.
typealias FileInfo = (name: String, extension: String)
// Information about the model to be loaded.
enum Model {
static let modelInfo: FileInfo = (name: "model", extension: "tflite")
static let labelsInfo: FileInfo = (name: "labels", extension: "txt")
}
/**
This class handles all data preprocessing and makes calls to run inference on
a given frame through the TensorFlow Lite Interpreter. It then formats the
inferences obtained and returns the top N results for a successful inference.
*/
class ModelDataHandler {
// MARK: Paremeters on which model was trained
let batchSize = 1
let wantedInputChannels = 3
let wantedInputWidth = 224
let wantedInputHeight = 224
let stdDeviation: Float = 127.0
let mean: Float = 1.0
// MARK: Constants
let threadCountLimit: Int32 = 10
// MARK: Instance Variables
/// The current thread count used by the TensorFlow Lite Interpreter.
let threadCount: Int
var labels: [String] = []
private let resultCount = 1
private let threshold = 0.5
/// TensorFlow Lite `Interpreter` object for performing inference on a given model.
private var interpreter: Interpreter
private let bgraPixel = (channels: 4, alphaComponent: 3, lastBgrComponent: 2)
private let rgbPixelChannels = 3
private let colorStrideValue = 10
/// Information about the alpha component in RGBA data.
private let alphaComponent = (baseOffset: 4, moduloRemainder: 3)
// MARK: Initializer
/**
This is a failable initializer for ModelDataHandler. It successfully initializes an object of the class if the model file and labels file is found, labels can be loaded and the interpreter of TensorflowLite can be initialized successfully.
*/
init?(modelFileInfo: FileInfo, labelsFileInfo: FileInfo, threadCount: Int = 1) {
// Construct the path to the model file.
guard let modelPath = Bundle.main.path(
forResource: modelFileInfo.name,
ofType: modelFileInfo.extension
) else {
print("Failed to load the model file with name: \(modelFileInfo.name).")
return nil
}
// Specify the options for the `Interpreter`.
self.threadCount = threadCount
var options = InterpreterOptions()
options.threadCount = threadCount
do {
// Create the `Interpreter`.
interpreter = try Interpreter(modelPath: modelPath, options: options)
// Allocate memory for the model's input `Tensor`s.
try interpreter.allocateTensors()
} catch let error {
print("Failed to create the interpreter with error: \(error.localizedDescription)")
return nil
}
// Opens and loads the classes listed in labels file
loadLabels(fromFileName: Model.labelsInfo.name, fileExtension: Model.labelsInfo.extension)
}
// MARK: Methods for data preprocessing and post processing.
/**
Performs image preprocessing, calls the TensorFlow Lite Interpreter methods
to feed the pixel buffer into the input tensor and run inference
on the pixel buffer.
*/
func runModel(onFrame pixelBuffer: CVPixelBuffer) -> Result? {
let sourcePixelFormat = CVPixelBufferGetPixelFormatType(pixelBuffer)
assert(sourcePixelFormat == kCVPixelFormatType_32ARGB ||
sourcePixelFormat == kCVPixelFormatType_32BGRA || sourcePixelFormat == kCVPixelFormatType_32RGBA)
let imageChannels = 4
assert(imageChannels >= wantedInputChannels)
// Crops the image to the biggest square in the center and scales it down to model dimensions.
guard let thumbnailPixelBuffer = centerThumbnail(from: pixelBuffer, size: CGSize(width: wantedInputWidth, height: wantedInputHeight)) else {
return nil
}
CVPixelBufferLockBaseAddress(thumbnailPixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
let interval: TimeInterval
let outputTensor: Tensor
do {
let inputTensor = try interpreter.input(at: 0)
// Remove the alpha component from the image buffer to get the RGB data.
guard let rgbData = rgbDataFromBuffer(
thumbnailPixelBuffer,
byteCount: batchSize * wantedInputWidth * wantedInputHeight * wantedInputChannels,
isModelQuantized: inputTensor.dataType == .uInt8
) else {
print("Failed to convert the image buffer to RGB data.")
return nil
}
// Copy the RGB data to the input `Tensor`.
try interpreter.copy(rgbData, toInputAt: 0)
// Run inference by invoking the `Interpreter`.
let startDate = Date()
try interpreter.invoke()
interval = Date().timeIntervalSince(startDate) * 1000
// Get the output `Tensor` to process the inference results.
outputTensor = try interpreter.output(at: 0)
} catch let error {
print("Failed to invoke the interpreter with error: \(error.localizedDescription)")
return nil
}
let results: [Float]
switch outputTensor.dataType {
case .uInt8:
guard let quantization = outputTensor.quantizationParameters else {
print("No results returned because the quantization values for the output tensor are nil.")
return nil
}
let quantizedResults = [UInt8](outputTensor.data)
results = quantizedResults.map {
quantization.scale * Float(Int($0) - quantization.zeroPoint)
}
case .float32:
results = [Float32](unsafeData: outputTensor.data) ?? []
default:
print("Output tensor data type \(outputTensor.dataType) is unsupported for this example app.")
return nil
}
// Process the results.
let topNInferences = getTopN(results: results)
// Return the inference time and inference results.
return Result(inferenceTime: interval, inferences: topNInferences)
}
/// Returns the RGB data representation of the given image buffer with the specified `byteCount`.
///
/// - Parameters
/// - buffer: The BGRA pixel buffer to convert to RGB data.
/// - byteCount: The expected byte count for the RGB data calculated using the values that the
/// model was trained on: `batchSize * imageWidth * imageHeight * componentsCount`.
/// - isModelQuantized: Whether the model is quantized (i.e. fixed point values rather than
/// floating point values).
/// - Returns: The RGB data representation of the image buffer or `nil` if the buffer could not be
/// converted.
private func rgbDataFromBuffer(
_ buffer: CVPixelBuffer,
byteCount: Int,
isModelQuantized: Bool
) -> Data? {
CVPixelBufferLockBaseAddress(buffer, .readOnly)
defer { CVPixelBufferUnlockBaseAddress(buffer, .readOnly) }
let pixelBufferFormat = CVPixelBufferGetPixelFormatType(buffer)
assert(pixelBufferFormat == kCVPixelFormatType_32BGRA)
guard let sourceData = CVPixelBufferGetBaseAddress(buffer) else {
return nil
}
let width = CVPixelBufferGetWidth(buffer)
let height = CVPixelBufferGetHeight(buffer)
let sourceBytesPerRow = CVPixelBufferGetBytesPerRow(buffer)
let destinationChannelCount = 3
let destinationBytesPerRow = destinationChannelCount * width
var sourceBuffer = vImage_Buffer(data: sourceData,
height: vImagePixelCount(height),
width: vImagePixelCount(width),
rowBytes: sourceBytesPerRow)
guard let destinationData = malloc(height * destinationBytesPerRow) else {
print("Error: out of memory")
return nil
}
defer {
free(destinationData)
}
var destinationBuffer = vImage_Buffer(data: destinationData,
height: vImagePixelCount(height),
width: vImagePixelCount(width),
rowBytes: destinationBytesPerRow)
vImageConvert_BGRA8888toRGB888(&sourceBuffer, &destinationBuffer, UInt32(kvImageNoFlags))
let byteData = Data(bytes: destinationBuffer.data, count: destinationBuffer.rowBytes * height)
if isModelQuantized {
return byteData
}
// Not quantized, convert to floats
let bytes = Array<UInt8>(unsafeData: byteData)!
var floats = [Float]()
for i in 0..<bytes.count {
floats.append(Float(bytes[i]) / 255.0)
}
return Data(copyingBufferOf: floats)
}
/// Returns the top N inference results sorted in descending order.
private func getTopN(results: [Float]) -> [Inference] {
// Create a zipped array of tuples [(labelIndex: Int, confidence: Float)].
let zippedResults = zip(labels.indices, results)
// Sort the zipped results by confidence value in descending order.
let sortedResults = zippedResults.sorted { $0.1 > $1.1 }.prefix(resultCount)
// Return the `Inference` results.
return sortedResults.map { result in Inference(confidence: result.1, label: labels[result.0]) }
}
/**
Returns thumbnail by cropping pixel buffer to biggest square and scaling the cropped image to model dimensions.
*/
private func centerThumbnail(from pixelBuffer: CVPixelBuffer, size: CGSize ) -> CVPixelBuffer? {
let imageWidth = CVPixelBufferGetWidth(pixelBuffer)
let imageHeight = CVPixelBufferGetHeight(pixelBuffer)
let pixelBufferType = CVPixelBufferGetPixelFormatType(pixelBuffer)
assert(pixelBufferType == kCVPixelFormatType_32BGRA)
let inputImageRowBytes = CVPixelBufferGetBytesPerRow(pixelBuffer)
let imageChannels = 4
let thumbnailSize = min(imageWidth, imageHeight)
CVPixelBufferLockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
var originX = 0
var originY = 0
if imageWidth > imageHeight {
originX = (imageWidth - imageHeight) / 2
}
else {
originY = (imageHeight - imageWidth) / 2
}
// Finds the biggest square in the pixel buffer and advances rows based on it.
guard let inputBaseAddress = CVPixelBufferGetBaseAddress(pixelBuffer)?.advanced(by: originY * inputImageRowBytes + originX * imageChannels) else {
return nil
}
// Gets vImage Buffer from input image
var inputVImageBuffer = vImage_Buffer(data: inputBaseAddress, height: UInt(thumbnailSize), width: UInt(thumbnailSize), rowBytes: inputImageRowBytes)
let thumbnailRowBytes = Int(size.width) * imageChannels
guard let thumbnailBytes = malloc(Int(size.height) * thumbnailRowBytes) else {
return nil
}
// Allocates a vImage buffer for thumbnail image.
var thumbnailVImageBuffer = vImage_Buffer(data: thumbnailBytes, height: UInt(size.height), width: UInt(size.width), rowBytes: thumbnailRowBytes)
// Performs the scale operation on input image buffer and stores it in thumbnail image buffer.
let scaleError = vImageScale_ARGB8888(&inputVImageBuffer, &thumbnailVImageBuffer, nil, vImage_Flags(0))
CVPixelBufferUnlockBaseAddress(pixelBuffer, CVPixelBufferLockFlags(rawValue: 0))
guard scaleError == kvImageNoError else {
return nil
}
let releaseCallBack: CVPixelBufferReleaseBytesCallback = {mutablePointer, pointer in
if let pointer = pointer {
free(UnsafeMutableRawPointer(mutating: pointer))
}
}
var thumbnailPixelBuffer: CVPixelBuffer?
// Converts the thumbnail vImage buffer to CVPixelBuffer
let conversionStatus = CVPixelBufferCreateWithBytes(nil, Int(size.width), Int(size.height), pixelBufferType, thumbnailBytes, thumbnailRowBytes, releaseCallBack, nil, nil, &thumbnailPixelBuffer)
guard conversionStatus == kCVReturnSuccess else {
free(thumbnailBytes)
return nil
}
return thumbnailPixelBuffer
}
/**
Loads the labels from the labels file and stores it in an instance variable
*/
func loadLabels(fromFileName fileName: String, fileExtension: String) {
guard let fileURL = Bundle.main.url(forResource: fileName, withExtension: fileExtension) else {
fatalError("Labels file not found in bundle. Please add a labels file with name \(fileName).\(fileExtension) and try again")
}
do {
let contents = try String(contentsOf: fileURL, encoding: .utf8)
self.labels = contents.components(separatedBy: ",")
self.labels.removeAll { (label) -> Bool in
return label == ""
}
}
catch {
fatalError("Labels file named \(fileName).\(fileExtension) cannot be read. Please add a valid labels file and try again.")
}
}
}
// MARK: - Extensions
extension Data {
/// Creates a new buffer by copying the buffer pointer of the given array.
///
/// - Warning: The given array's element type `T` must be trivial in that it can be copied bit
/// for bit with no indirection or reference-counting operations; otherwise, reinterpreting
/// data from the resulting buffer has undefined behavior.
/// - Parameter array: An array with elements of type `T`.
init<T>(copyingBufferOf array: [T]) {
self = array.withUnsafeBufferPointer(Data.init)
}
}
extension Array {
/// Creates a new array from the bytes of the given unsafe data.
///
/// - Warning: The array's `Element` type must be trivial in that it can be copied bit for bit
/// with no indirection or reference-counting operations; otherwise, copying the raw bytes in
/// the `unsafeData`'s buffer to a new array returns an unsafe copy.
/// - Note: Returns `nil` if `unsafeData.count` is not a multiple of
/// `MemoryLayout<Element>.stride`.
/// - Parameter unsafeData: The data containing the bytes to turn into an array.
init?(unsafeData: Data) {
guard unsafeData.count % MemoryLayout<Element>.stride == 0 else { return nil }
#if swift(>=5.0)
self = unsafeData.withUnsafeBytes { .init($0.bindMemory(to: Element.self)) }
#else
self = unsafeData.withUnsafeBytes {
.init(UnsafeBufferPointer<Element>(
start: $0,
count: unsafeData.count / MemoryLayout<Element>.stride
))
}
#endif // swift(>=5.0)
}
}
| 678c7e010272b855ab4baf77f4a8b0fe | 36.293532 | 242 | 0.702708 | false | false | false | false |
JonMercer/burritoVSWHackathon | refs/heads/master | Burrito/ViewController.swift | mit | 1 | //
// ViewController.swift
// Burrito
//
// Created by Odin on 2016-09-23.
// Copyright © 2016 TeamAlpaka. All rights reserved.
//
import UIKit
import STZPopupView
class ViewController: UIViewController, CardViewDelegate {
var cardView: CardView!
@IBOutlet weak var minutesLabel: UILabel!
@IBOutlet weak var secondsLabel: UILabel!
var timer = NSTimer()
var secondsLeft = 60*40 // 40min
let CHANGE_MODE_DELAY = 2.0
let LOADING_DELAY = 2.5
override func viewDidLoad() {
super.viewDidLoad()
self.tabBarController?.tabBar.tintColor = UIColor.whiteColor()
self.tabBarController?.tabBar.backgroundImage = UIImage.fromColor(DARK_BLUR_COLOR)
//self.tabBarController?.tabBar.backgroundColor = UIColor.redColor()
//self.tabBarController?.tabBar.translucent = false
updateTimerLabel()
let one:NSTimeInterval = 1.0
timer = NSTimer.scheduledTimerWithTimeInterval(one, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
}
@IBAction func onTestButtonTapped(sender: AnyObject) {
showItem()
}
@IBAction func onNotificationButtonTapped(sender: AnyObject) {
sendLocalNotification()
}
func timerAction() {
if(secondsLeft > 0) {
secondsLeft -= 1
} else {
timer.invalidate()
}
updateTimerLabel()
}
func updateTimerLabel() {
minutesLabel.text = String(format: "%02d",(secondsLeft / 60) % 60)
secondsLabel.text = String(format: "%02d", secondsLeft % 60)
}
func showItem(){
let item = Item(name: "15% Off", restaurant: "Deer Island Bakery", image: UIImage(named: "deerislandwin")!)
cardView = CardView.instanceFromNib(CGRectMake(0, 0, 300, 300))
cardView.item = item
cardView.win = false
cardView.initializeView()
cardView.delegate = self
let popupConfig = STZPopupViewConfig()
popupConfig.dismissTouchBackground = true
popupConfig.cornerRadius = 5.0
cardView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(ViewController.onCardTapped(_:))))
presentPopupView(cardView, config: popupConfig)
cardView.showLoading()
delay(LOADING_DELAY){
self.cardView.stopLoading()
delay(self.CHANGE_MODE_DELAY){
if !self.cardView.showingQRCode {
self.cardView.changeModes()
}
}
}
}
func onCardTapped(sender: AnyObject){
cardView.changeModes()
}
func dismissCard() {
dismissPopupView()
}
@IBAction func onRestaurantButtonTapped(sender: AnyObject) {
performSegueWithIdentifier("vcToLoginVC", sender: nil)
}
}
extension UIViewController {
func hideKeyboardWhenTappedAround() {
let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard))
tap.cancelsTouchesInView = false
view.addGestureRecognizer(tap)
}
func dismissKeyboard() {
view.endEditing(true)
}
}
extension UIImage {
static func fromColor(color: UIColor) -> UIImage {
let rect = CGRect(x: 0, y: 0, width: 1, height: 1)
UIGraphicsBeginImageContext(rect.size)
let context = UIGraphicsGetCurrentContext()
CGContextSetFillColorWithColor(context, color.CGColor)
CGContextFillRect(context, rect)
let img = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return img
}
}
| cfad4bf9dd7a6040a829411d8baabbc9 | 28.732283 | 137 | 0.627648 | false | false | false | false |
storehouse/Advance | refs/heads/master | Sources/Advance/SpringFunction.swift | bsd-2-clause | 1 | /// Implements a simple spring acceleration function.
public struct SpringFunction<T>: SimulationFunction where T: VectorConvertible {
/// The target of the spring.
public var target: T
/// Strength of the spring.
public var tension: Double
/// How damped the spring is.
public var damping: Double
/// The minimum Double distance used for settling the spring simulation.
public var threshold: Double
/// Creates a new `SpringFunction` instance.
///
/// - parameter target: The target of the new instance.
public init(target: T, tension: Double = 120.0, damping: Double = 12.0, threshold: Double = 0.1) {
self.target = target
self.tension = tension
self.damping = damping
self.threshold = threshold
}
/// Calculates acceleration for a given state of the simulation.
public func acceleration(value: T.AnimatableData, velocity: T.AnimatableData) -> T.AnimatableData {
let delta = value - target.animatableData
var deltaAccel = delta
deltaAccel.scale(by: -tension)
var dampingAccel = velocity
dampingAccel.scale(by: damping)
return deltaAccel - dampingAccel
}
public func convergence(value: T.AnimatableData, velocity: T.AnimatableData) -> Convergence<T> {
if velocity.magnitudeSquared > threshold*threshold {
return .keepRunning
}
let valueDelta = value - target.animatableData
if valueDelta.magnitudeSquared > threshold*threshold {
return .keepRunning
}
return .converge(atValue: target.animatableData)
}
}
| 797c7a0a38c06f6534152ebeb2de0932 | 31.961538 | 103 | 0.634772 | false | false | false | false |
alvarorgtr/swift_data_structures | refs/heads/master | DataStructures/TreeMapCollection.swift | gpl-3.0 | 1 | //
// TreeCollection.swift
// DataStructures
//
// Created by Álvaro Rodríguez García on 27/12/16.
// Copyright © 2016 DeltaApps. All rights reserved.
//
import Foundation
public protocol TreeMapCollection: BidirectionalCollection, DictionaryCollection {
associatedtype Iterator: TreeIterator
associatedtype Index = Self.Iterator.Index
associatedtype Node = Self.Iterator.Index.Node
associatedtype Element = (Self.Iterator.Index.Node.Key, Self.Iterator.Index.Node.Value)
associatedtype Key = Self.Iterator.Index.Node.Key
associatedtype Value = Self.Iterator.Index.Node.Value
var root: Node? { get }
var startNode: Node { get }
var endNode: Node { get }
var height: Int { get }
}
public extension TreeMapCollection where Node: TreeNode {
var height: Int {
get {
return root?.height ?? -1
}
}
}
| d7b88efeac1072cb36a7c6f9f1238f54 | 23.294118 | 88 | 0.74092 | false | false | false | false |
blindsey/Swift-BoxOffice | refs/heads/master | BoxOffice/MasterViewController.swift | mit | 1 | //
// MasterViewController.swift
// BoxOffice
//
// Created by Ben Lindsey on 7/14/14.
// Copyright (c) 2014 Ben Lindsey. All rights reserved.
//
import UIKit
class MasterViewController: UITableViewController {
let API_KEY = "esm6sfwy2f2x8brqh3gv6ukk"
var hud = MBProgressHUD()
var movies = [NSDictionary]()
override func awakeFromNib() {
super.awakeFromNib()
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.tableFooterView = UIView()
self.refreshControl = UIRefreshControl()
self.refreshControl.addTarget(self, action: "fetchBoxOffice", forControlEvents: UIControlEvents.ValueChanged)
fetchBoxOffice()
}
// #pragma mark - Segues
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if segue.identifier == "showDetail" {
let indexPath = self.tableView.indexPathForSelectedRow()
(segue.destinationViewController as DetailViewController).detailItem = movies[indexPath.row]
}
}
// #pragma mark - Table View
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
let movie = movies[indexPath.row]
cell.detailTextLabel.text = movie["synopsis"] as? String
cell.textLabel.text = movie["title"] as? String
if let posters = movie["posters"] as? NSDictionary {
if let thumb = posters["thumbnail"] as? String {
let request = NSURLRequest(URL: NSURL(string: thumb))
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { response, data, error in
if data {
cell.imageView.image = UIImage(data: data)
cell.setNeedsLayout()
}
}
}
}
return cell
}
// #pragma mark - Private
func fetchBoxOffice() {
self.refreshControl.endRefreshing()
hud = MBProgressHUD.showHUDAddedTo(view, animated: true)
var url : String
if self.tabBarController.tabBar.selectedItem.title == "Box Office" {
url = "http://api.rottentomatoes.com/api/public/v1.0/lists/movies/box_office.json?apikey=\(API_KEY)";
} else {
url = "http://api.rottentomatoes.com/api/public/v1.0/lists/dvds/top_rentals.json?apikey=\(API_KEY)";
}
let request = NSURLRequest(URL: NSURL(string: url))
NSURLConnection.sendAsynchronousRequest(request, queue: NSOperationQueue.mainQueue()) { response, data, error in
self.hud.hide(true)
if error {
println(error.description)
return self.displayError("Network Error")
}
var error: NSError?
let object = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error:&error) as? NSDictionary
if let e = error {
println(e.description)
return self.displayError("Error parsing JSON")
} else if let dict = object {
if let e = dict["error"] as? String {
self.displayError(e)
} else if let movies = dict["movies"] as? [NSDictionary] {
self.movies = movies
self.tableView.reloadData()
}
}
}
}
func displayError(error: String) {
let label = UILabel(frame: CGRect(x: 0, y: -44, width:320, height: 44))
label.text = "⚠️ \(error)"
label.textColor = UIColor.whiteColor()
label.backgroundColor = UIColor.blackColor()
label.adjustsFontSizeToFitWidth = true
label.minimumScaleFactor = 0.5
label.alpha = 0.8
label.textAlignment = .Center
self.view.addSubview(label)
UIView.animateWithDuration(2.0, animations: {
label.frame.origin.y = 0
}, completion: { completed in
UIView.animateWithDuration(2.0, animations: {
label.alpha = 0
}, completion: { completed in
label.removeFromSuperview()
})
})
}
}
| 26a697ff2a8d246c08f2cce0f38edcbc | 35.868852 | 146 | 0.604936 | false | false | false | false |
Ben21hao/edx-app-ios-enterprise-new | refs/heads/master | Source/AuthenticatedWebViewController.swift | apache-2.0 | 3 | //
// AuthenticatedWebViewController.swift
// edX
//
// Created by Akiva Leffert on 5/26/15.
// Copyright (c) 2015 edX. All rights reserved.
//
import UIKit
import WebKit
class HeaderViewInsets : ContentInsetsSource {
weak var insetsDelegate : ContentInsetsSourceDelegate?
var view : UIView?
var currentInsets : UIEdgeInsets {
return UIEdgeInsets(top : view?.frame.size.height ?? 0, left : 0, bottom : 0, right : 0)
}
var affectsScrollIndicators : Bool {
return true
}
}
private protocol WebContentController {
var view : UIView {get}
var scrollView : UIScrollView {get}
var alwaysRequiresOAuthUpdate : Bool { get}
var initialContentState : AuthenticatedWebViewController.State { get }
func loadURLRequest(request : NSURLRequest)
func clearDelegate()
func resetState()
}
private class WKWebViewContentController : WebContentController {
private let webView = WKWebView(frame: CGRectZero)
var view : UIView {
return webView
}
var scrollView : UIScrollView {
return webView.scrollView
}
func clearDelegate() {
return webView.navigationDelegate = nil
}
func loadURLRequest(request: NSURLRequest) {
webView.loadRequest(request)
}
func resetState() {
webView.stopLoading()
webView.loadHTMLString("", baseURL: nil)
}
var alwaysRequiresOAuthUpdate : Bool {
return false
}
var initialContentState : AuthenticatedWebViewController.State {
return AuthenticatedWebViewController.State.LoadingContent
}
}
private let OAuthExchangePath = "/oauth2/login/"
// Allows access to course content that requires authentication.
// Forwarding our oauth token to the server so we can get a web based cookie
public class AuthenticatedWebViewController: UIViewController, WKNavigationDelegate {
private enum State {
case CreatingSession
case LoadingContent
case NeedingSession
}
public typealias Environment = protocol<OEXAnalyticsProvider, OEXConfigProvider, OEXSessionProvider>
internal let environment : Environment
private let loadController : LoadStateViewController
private let insetsController : ContentInsetsController
private let headerInsets : HeaderViewInsets
private lazy var webController : WebContentController = {
let controller = WKWebViewContentController()
controller.webView.navigationDelegate = self
return controller
}()
private var state = State.CreatingSession
private var contentRequest : NSURLRequest? = nil
var currentUrl: NSURL? {
return contentRequest?.URL
}
public init(environment : Environment) {
self.environment = environment
loadController = LoadStateViewController()
insetsController = ContentInsetsController()
headerInsets = HeaderViewInsets()
insetsController.addSource(headerInsets)
super.init(nibName: nil, bundle: nil)
automaticallyAdjustsScrollViewInsets = false
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
// Prevent crash due to stale back pointer, since WKWebView's UIScrollView apparently doesn't
// use weak for its delegate
webController.scrollView.delegate = nil
webController.clearDelegate()
}
override public func viewDidLoad() {
self.state = webController.initialContentState
self.view.addSubview(webController.view)
webController.view.snp_makeConstraints {make in
make.edges.equalTo(self.view)
}
self.loadController.setupInController(self, contentView: webController.view)
webController.view.backgroundColor = OEXStyles.sharedStyles().standardBackgroundColor()
webController.scrollView.backgroundColor = OEXStyles.sharedStyles().standardBackgroundColor()
self.insetsController.setupInController(self, scrollView: webController.scrollView)
if let request = self.contentRequest {
loadRequest(request)
}
}
private func resetState() {
loadController.state = .Initial
state = .CreatingSession
}
public override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
if view.window == nil {
webController.resetState()
}
resetState()
}
public override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
insetsController.updateInsets()
}
public func showError(error : NSError?, icon : Icon? = nil, message : String? = nil) {
loadController.state = LoadState.failed(error, icon : icon, message : message)
}
// MARK: Header View
var headerView : UIView? {
get {
return headerInsets.view
}
set {
headerInsets.view?.removeFromSuperview()
headerInsets.view = newValue
if let headerView = newValue {
webController.view.addSubview(headerView)
headerView.snp_makeConstraints {make in
if #available(iOS 9.0, *) {
make.top.equalTo(self.topLayoutGuide.bottomAnchor)
}
else {
make.top.equalTo(self.snp_topLayoutGuideBottom)
}
make.leading.equalTo(webController.view)
make.trailing.equalTo(webController.view)
}
webController.view.setNeedsLayout()
webController.view.layoutIfNeeded()
}
}
}
private func loadOAuthRefreshRequest() {
if let hostURL = environment.config.apiHostURL() {
guard let URL = hostURL.URLByAppendingPathComponent(OAuthExchangePath) else { return }
let exchangeRequest = NSMutableURLRequest(URL: URL)
exchangeRequest.HTTPMethod = HTTPMethod.POST.rawValue
for (key, value) in self.environment.session.authorizationHeaders {
exchangeRequest.addValue(value, forHTTPHeaderField: key)
}
self.webController.loadURLRequest(exchangeRequest)
}
}
// MARK: Request Loading
public func loadRequest(request : NSURLRequest) {
contentRequest = request
loadController.state = .Initial
state = webController.initialContentState
if webController.alwaysRequiresOAuthUpdate {
loadOAuthRefreshRequest()
}
else {
webController.loadURLRequest(request)
}
}
// MARK: WKWebView delegate
public func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
switch navigationAction.navigationType {
case .LinkActivated, .FormSubmitted, .FormResubmitted:
if let URL = navigationAction.request.URL {
UIApplication.sharedApplication().openURL(URL)
}
decisionHandler(.Cancel)
default:
decisionHandler(.Allow)
}
}
public func webView(webView: WKWebView, decidePolicyForNavigationResponse navigationResponse: WKNavigationResponse, decisionHandler: (WKNavigationResponsePolicy) -> Void) {
if let
httpResponse = navigationResponse.response as? NSHTTPURLResponse,
statusCode = OEXHTTPStatusCode(rawValue: httpResponse.statusCode),
errorGroup = statusCode.errorGroup
where state == .LoadingContent
{
switch errorGroup {
case .Http4xx:
self.state = .NeedingSession
case .Http5xx:
self.loadController.state = LoadState.failed()
decisionHandler(.Cancel)
}
}
decisionHandler(.Allow)
}
public func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
switch state {
case .CreatingSession:
if let request = contentRequest {
state = .LoadingContent
webController.loadURLRequest(request)
}
else {
loadController.state = LoadState.failed()
}
case .LoadingContent:
loadController.state = .Loaded
case .NeedingSession:
state = .CreatingSession
loadOAuthRefreshRequest()
}
}
public func webView(webView: WKWebView, didFailNavigation navigation: WKNavigation!, withError error: NSError) {
showError(error)
}
public func webView(webView: WKWebView, didFailProvisionalNavigation navigation: WKNavigation!, withError error: NSError) {
showError(error)
}
public func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
// Don't use basic auth on exchange endpoint. That is explicitly non protected
// and it screws up the authorization headers
if let URL = webView.URL where ((URL.absoluteString?.hasSuffix(OAuthExchangePath)) != nil) {
completionHandler(.PerformDefaultHandling, nil)
}
else if let credential = environment.config.URLCredentialForHost(challenge.protectionSpace.host) {
completionHandler(.UseCredential, credential)
}
else {
completionHandler(.PerformDefaultHandling, nil)
}
}
}
| a56c8b0b7437ba23c14b5ab1b1d7c328 | 31.825083 | 205 | 0.637442 | false | false | false | false |
kar/challenges | refs/heads/master | hackerrank-algorithms-dynamic-programming/sherlock-and-cost.swift | apache-2.0 | 1 | // Sherlock and Cost
//
// The key observation is that each Ai has to be either 1 or Bi
// (values in between do not lead to the maximum sum), so that
// the result subsequence will have a zigzag pattern:
//
// 1 B2 1 B4 1 B6 ... (or B1 1 B3 1 B5 ...).
//
// In some cases, selecting same value twice next to each other
// may lead to a higher sum (lets call it the jump):
//
// B1 1 1 B4 1 B5 ... (or B1 1 B3 B3 1 B6 ...).
//
// The sums matrix keeps partial sums for each element in the
// subsequence, starting either with B1 (row 0) or 1 (row 1).
// For each cell, we pick the maximum partial sum between
// the zigzag pattern or the jump. You can imagine each cell
// corresponding to the following subsequence pattern:
//
// 0 1 2
// 0 | - | B1 1 | B1 1 1 or 1 B2 1 | ...
// 1 | - | 1 B2 | B1 1 B3 or 1 B2 B2 | ...
//
// Note: This solution scores at 31.25/50 because some test
// cases time out (and I am not sure why).
import Foundation
func solve(n: Int, b: [Int]) -> Int {
var sums = [[Int]](repeating: [Int](repeating: 0, count: 2), count: n)
for i in 1..<n {
var a = sums[i - 1][0]
var y = sums[i - 1][1] + b[i - 1] - 1
sums[i][0] = a
if a < y {
sums[i][0] = y
}
a = sums[i - 1][0] + b[i] - 1
y = sums[i - 1][1]
sums[i][1] = a
if a < y {
sums[i][1] = y
}
}
return max(sums[n - 1][0], sums[n - 1][1])
}
if let cases = Int(readLine()!) {
for c in 0..<cases {
if let n = Int(readLine()!) {
let b = readLine()!.components(separatedBy: " ").map { num in Int(num)! }
let solution = solve(n: n, b: b)
print(solution)
}
}
}
| 278cb3bd1b95200cf0bc402cc0219b32 | 28.2 | 85 | 0.52911 | false | false | false | false |
scoremedia/Fisticuffs | refs/heads/master | Sources/Fisticuffs/TransformBindingHandler.swift | mit | 1 | //
// TransformBindingHandler.swift
// Fisticuffs
//
// Created by Darren Clark on 2016-02-12.
// Copyright © 2016 theScore. All rights reserved.
//
import Foundation
private struct NoReverseTransformError: Error {}
open class TransformBindingHandler<Control: AnyObject, InDataValue, OutDataValue, PropertyValue>: BindingHandler<Control, InDataValue, PropertyValue> {
let bindingHandler: BindingHandler<Control, OutDataValue, PropertyValue>
let transform: (InDataValue) -> OutDataValue
let reverseTransform: ((OutDataValue) -> InDataValue)?
init(_ transform: @escaping (InDataValue) -> OutDataValue, reverse: ((OutDataValue) -> InDataValue)?, bindingHandler: BindingHandler<Control, OutDataValue, PropertyValue>) {
self.bindingHandler = bindingHandler
self.transform = transform
self.reverseTransform = reverse
}
open override func set(control: Control, oldValue: InDataValue?, value: InDataValue, propertySetter: @escaping PropertySetter) {
bindingHandler.set(control: control, oldValue: oldValue.map(transform), value: transform(value), propertySetter: propertySetter)
}
open override func get(control: Control, propertyGetter: @escaping PropertyGetter) throws -> InDataValue {
guard let reverseTransform = reverseTransform else {
throw NoReverseTransformError()
}
let value = try bindingHandler.get(control: control, propertyGetter: propertyGetter)
return reverseTransform(value)
}
override open func dispose() {
bindingHandler.dispose()
super.dispose()
}
}
public extension BindingHandlers {
static func transform<Control, DataValue, PropertyValue>(_ block: @escaping (DataValue) -> PropertyValue) -> TransformBindingHandler<Control, DataValue, PropertyValue, PropertyValue> {
TransformBindingHandler(block, reverse: nil, bindingHandler: DefaultBindingHandler())
}
static func transform<Control, DataValue, PropertyValue>(_ block: @escaping (DataValue) -> PropertyValue, reverse: @escaping (PropertyValue) -> DataValue) -> TransformBindingHandler<Control, DataValue, PropertyValue, PropertyValue> {
TransformBindingHandler(block, reverse: reverse, bindingHandler: DefaultBindingHandler())
}
static func transform<Control, InDataValue, OutDataValue, PropertyValue>(_ block: @escaping (InDataValue) -> OutDataValue, reverse: ((OutDataValue) -> InDataValue)?, bindingHandler: BindingHandler<Control, OutDataValue, PropertyValue>)
-> TransformBindingHandler<Control, InDataValue, OutDataValue, PropertyValue> {
TransformBindingHandler<Control, InDataValue, OutDataValue, PropertyValue>(block, reverse: reverse, bindingHandler: bindingHandler)
}
}
| 30eb5b23e11c387ba4d7bf30af8960ca | 47.403509 | 239 | 0.742298 | false | false | false | false |
yaobanglin/viossvc | refs/heads/master | viossvc/Scenes/Chat/ChatLocation/ChatLocationAnotherCell.swift | apache-2.0 | 1 | //
// ChatLocationAnotherCell.swift
// TestAdress
//
// Created by J-bb on 16/12/29.
// Copyright © 2016年 J-bb. All rights reserved.
//
import UIKit
class ChatLocationAnotherCell: ChatLocationCell {
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
bundleImageView.tintColor = UIColor(red: 19/255.0, green: 31/255.0, blue: 50/255.0, alpha: 1.0)
titleLabel.textColor = UIColor.whiteColor()
adressLabel.textColor = UIColor.whiteColor()
bundleImageView.snp_remakeConstraints { (make) in
make.left.equalTo(10)
make.top.equalTo(5)
make.right.equalTo(-100)
make.bottom.equalTo(-5)
}
}
override func setupDataWithContent(content: String?) {
super.setupDataWithContent(content)
var image = UIImage(named: "msg-bubble-another")
image = image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
bundleImageView.image = image?.resizableImageWithCapInsets(UIEdgeInsetsMake(17, 23 , 17, 23), resizingMode: UIImageResizingMode.Stretch)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| ca230abe8990ee9644953c2fd0bf56ac | 30.853659 | 145 | 0.666156 | false | false | false | false |
sully10024/There-Yet | refs/heads/master | Geotify/Geotification.swift | mit | 1 | import UIKit
import MapKit
import CoreLocation
struct GeoKey {
static let latitude = "latitude"
static let longitude = "longitude"
static let radius = "radius"
static let identifier = "identifier"
static let note = "note"
}
class Geotification: NSObject, NSCoding, MKAnnotation {
var coordinate: CLLocationCoordinate2D
var radius: CLLocationDistance
var identifier: String
var note: String
var title: String? {
if note.isEmpty {
return "No Note"
}
return note
}
var subtitle: String? {
return "Radius: \(radius)m - On Entry"
}
init(coordinate: CLLocationCoordinate2D, radius: CLLocationDistance, identifier: String, note: String) {
self.coordinate = coordinate
self.radius = radius
self.identifier = identifier
self.note = note
}
// MARK: NSCoding
required init?(coder decoder: NSCoder) {
let latitude = decoder.decodeDouble(forKey: GeoKey.latitude)
let longitude = decoder.decodeDouble(forKey: GeoKey.longitude)
coordinate = CLLocationCoordinate2D(latitude: latitude, longitude: longitude)
radius = decoder.decodeDouble(forKey: GeoKey.radius)
identifier = decoder.decodeObject(forKey: GeoKey.identifier) as! String
note = decoder.decodeObject(forKey: GeoKey.note) as! String
}
func encode(with coder: NSCoder) {
coder.encode(coordinate.latitude, forKey: GeoKey.latitude)
coder.encode(coordinate.longitude, forKey: GeoKey.longitude)
coder.encode(radius, forKey: GeoKey.radius)
coder.encode(identifier, forKey: GeoKey.identifier)
coder.encode(note, forKey: GeoKey.note)
}
}
| f2c7937cd8416a18734e11182d1c459c | 27.892857 | 106 | 0.717553 | false | false | false | false |
NoryCao/zhuishushenqi | refs/heads/master | zhuishushenqi/TXTReader/BookDetail/Views/ToolBar.swift | mit | 1 | //
// ToolBar.swift
// PageViewController
//
// Created by Nory Cao on 16/10/10.
// Copyright © 2016年 QS. All rights reserved.
//
import UIKit
typealias ZSBgViewHandler = ()->Void
enum ToolBarFontChangeAction {
case plus
case minimus
}
protocol ToolBarDelegate{
func backButtonDidClicked()
func catagoryClicked()
func changeSourceClicked()
func toolBarDidShow()
func toolBarDidHidden()
func readBg(type:Reader)
func fontChange(action:ToolBarFontChangeAction)
func brightnessChange(value:CGFloat)
func cacheAll()
func toolbar(toolbar:ToolBar, clickMoreSetting:UIView)
func listen()
}
class ToolBar: UIView {
private let kBottomBtnTag = 12345
private let TopBarHeight:CGFloat = kNavgationBarHeight
private let BottomBarHeight:CGFloat = 49 + CGFloat(kTabbarBlankHeight)
var toolBarDelegate:ToolBarDelegate?
var topBar:UIView?
var bottomBar:UIView?
var midBar:UIView?
var isShow:Bool = false
var showMid:Bool = false
var whiteBtn:UIButton!
var yellowBtn:UIButton!
var greenBtn:UIButton!
var mode_bgView:UIScrollView!
var fontSize:Int = QSReaderSetting.shared.fontSize
var titleLabel:UILabel!
var title:String = "" {
didSet{
titleLabel.text = self.title
}
}
var bgItemViews:[ZSModeBgItemView] = []
var progressView:ProgressView!
override init(frame: CGRect) {
super.init(frame: frame)
fontSize = QSReaderSetting.shared.fontSize
initSubview()
}
private func initSubview(){
topBar = UIView(frame: CGRect(x: 0, y: -TopBarHeight, width: UIScreen.main.bounds.size.width, height: TopBarHeight))
topBar?.backgroundColor = UIColor(white: 0.0, alpha: 1.0)
addSubview(topBar!)
bottomBar = UIView(frame: CGRect(x:0,y:UIScreen.main.bounds.size.height,width:UIScreen.main.bounds.size.width,height:BottomBarHeight))
bottomBar?.backgroundColor = UIColor(white: 0.0, alpha: 1.0)
addSubview(bottomBar!)
midBar = UIView(frame: CGRect(x:0,y:UIScreen.main.bounds.size.height - 180 - BottomBarHeight,width:UIScreen.main.bounds.size.width,height:180))
midBar?.backgroundColor = UIColor(white: 0.0, alpha: 0.7)
midBarSubviews()
bottomSubviews()
let backBtn = UIButton(type: .custom)
backBtn.setImage(UIImage(named: "sm_exit"), for: .normal)
backBtn.addTarget(self, action: #selector(backAction(btn:)), for: .touchUpInside)
backBtn.frame = CGRect(x:self.bounds.width - 55, y: STATEBARHEIGHT,width: 49,height: 49)
topBar?.addSubview(backBtn)
let changeSourceBtn = UIButton(type: .custom)
changeSourceBtn.setTitle("换源", for: .normal)
changeSourceBtn.setTitleColor(UIColor.white, for: .normal)
changeSourceBtn.addTarget(self, action: #selector(changeSourceAction(btn:)), for: .touchUpInside)
changeSourceBtn.frame = CGRect(x:self.bounds.width - 65, y: 27,width: 50,height: 30)
changeSourceBtn.frame = CGRect(x:10, y:STATEBARHEIGHT + 7,width: 50,height: 30)
topBar?.addSubview(changeSourceBtn)
let listenBtn = UIButton(type: .custom)
listenBtn.setImage(UIImage(named: "readAloud"), for: .normal)
listenBtn.addTarget(self, action: #selector(listenAction(btn:)), for: .touchUpInside)
listenBtn.frame = CGRect(x:self.bounds.width - 104, y: STATEBARHEIGHT,width: 49,height: 49)
topBar?.addSubview(listenBtn)
titleLabel = UILabel(frame: CGRect(x: self.bounds.width/2 - 100, y: STATEBARHEIGHT+7, width: 200, height: 30))
titleLabel.textColor = UIColor.white
titleLabel.textAlignment = .center
topBar?.addSubview(titleLabel)
let tap = UITapGestureRecognizer(target: self, action:#selector(hideWithAnimations(animation:)) )
addGestureRecognizer(tap)
}
func midBarSubviews(){
let progressBar = UISlider(frame: CGRect(x: 50, y: 25, width: self.bounds.width - 100, height: 15))
progressBar.minimumTrackTintColor = UIColor.orange
progressBar.value = Float(UIScreen.main.brightness)
progressBar.addTarget(self, action: #selector(brightnessChange(btn:)), for: .valueChanged)
let leftImg = UIImageView(frame: CGRect(x: 25, y: 25, width: 15, height: 15))
leftImg.image = UIImage(named: "brightess_white_low")
let rightImg = UIImageView(frame: CGRect(x: self.bounds.width - 40, y: 23, width: 25, height: 25))
rightImg.image = UIImage(named: "brightess_white_high")
let fontminus = button(with: UIImage(named:"font_decrease"), selectedImage: nil, title: nil, frame: CGRect(x: 13, y: 55, width: 60, height: 60), selector: #selector(fontMinusAction(btn:)), font: nil)
let fontPlus = button(with: UIImage(named:"font_increase"), selectedImage: nil, title: nil, frame: CGRect(x: fontminus.frame.maxX + 13, y: fontminus.frame.minY, width: 60, height: 60), selector: #selector(fontPlusAction(btn:)), font: nil)
let landscape = button(with: UIImage(named:"landscape"), selectedImage: nil, title: nil, frame: CGRect(x: fontPlus.frame.maxX, y: fontminus.frame.minY + 5, width: 60, height: 50), selector: #selector(landscape(btn:)), font: nil)
let autoReading = button(with: UIImage(named:"autoreading_start"), selectedImage: nil, title: "自动阅读", frame: CGRect(x: landscape.frame.maxX, y: landscape.frame.minY + 10, width: 115, height: 30), selector: #selector(autoReading(btn:)), font: UIFont.systemFont(ofSize: 15))
mode_bgView = UIScrollView(frame: CGRect(x: 0, y: 115, width: self.bounds.width - 140, height: 60))
mode_bgView.isUserInteractionEnabled = true
// mode_bgView.backgroundColor = UIColor.orange
mode_bgView.showsHorizontalScrollIndicator = true
midBar?.addSubview(mode_bgView)
let itemImages = ["white_mode_bg","yellow_mode_bg","green_mode_bg","blackGreen_mode_bg","pink_mode_bg","sheepskin_mode_bg","violet_mode_bg","water_mode_bg","weekGreen_mode_bg","weekPink_mode_bg","coffee_mode_bg"]
var index = 0
for image in itemImages {
let bgView = ZSModeBgItemView(frame: CGRect(x: 25*(index + 1) + 60 * index, y: 0, width: 60, height: 60))
bgView.setImage(image: UIImage(named: image))
bgView.index = index
bgView.selectHandler = {
self.itemAction(index: bgView.index)
}
mode_bgView.addSubview(bgView)
bgItemViews.append(bgView)
index += 1
}
mode_bgView.contentSize = CGSize(width: itemImages.count * (60 + 25), height: 60)
let senior = button(with: UIImage(named:"reading_more_setting"), selectedImage: nil, title: "高级设置", frame: CGRect(x: self.bounds.width - 140, y: 130, width: 115, height: 30), selector: #selector(seniorSettingAction(btn:)), font: UIFont.systemFont(ofSize: 15))
progressView = ProgressView(frame: CGRect(x: 0, y: self.bounds.height - 49 - 20, width: self.bounds.width, height: 20))
progressView.backgroundColor = UIColor.black
progressView.isHidden = true
progressView.alpha = 0.7
addSubview(progressView)
midBar?.addSubview(leftImg)
midBar?.addSubview(rightImg)
midBar?.addSubview(progressBar)
midBar?.addSubview(fontminus)
midBar?.addSubview(fontPlus)
midBar?.addSubview(landscape)
midBar?.addSubview(autoReading)
midBar?.addSubview(senior)
let type = AppStyle.shared.reader
if type.rawValue >= 0 && type.rawValue < bgItemViews.count {
var index = 0
for bgView in bgItemViews {
if type.rawValue == index {
bgView.select(select: true)
} else {
bgView.select(select: false)
}
index += 1
}
}
}
func bottomSubviews(){
let width = UIScreen.main.bounds.width/5
let btnWidth:CGFloat = 30.0
let btnHeight:CGFloat = 34.0
let images = ["night_mode","feedback","directory","preview_btn","reading_setting"]
let titles = ["夜间","反馈","目录","缓存","设置"]
for item in 0..<5 {
let x = (width - btnWidth)/2*CGFloat(item*2 + 1) + btnWidth*CGFloat(item)
let y = 49/2 - btnHeight/2
let btn = CategoryButton(type: .custom)
btn.setImage(UIImage(named: images[item]), for: .normal)
btn.setTitle(titles[item], for: .normal)
btn.titleLabel?.font = UIFont.systemFont(ofSize: 9)
btn.frame = CGRect(x:x,y: y,width: btnWidth,height: btnHeight)
btn.addTarget(self, action: #selector(bottomBtnAction(btn:)), for: .touchUpInside)
btn.tag = kBottomBtnTag + item
bottomBar?.addSubview(btn)
}
}
func button(with image:UIImage?,selectedImage:UIImage?,title:String?,frame:CGRect,selector:Selector,font:UIFont?)->UIButton{
let button = UIButton(frame: frame)
button.setImage(selectedImage, for: .selected)
button.setImage(image, for: .normal)
button.setTitle(title, for: .normal)
button.addTarget(self, action: selector, for: .touchUpInside)
button.titleLabel?.font = font
return button
}
func showWithAnimations(animation:Bool,inView:UIView){
self.isShow = true
inView.addSubview(self)
UIView.animate(withDuration: 0.35, animations: {
self.topBar?.frame = CGRect(x:0, y:0,width: self.bounds.size.width,height: self.TopBarHeight)
self.bottomBar?.frame = CGRect(x:0,y: self.bounds.size.height - self.BottomBarHeight,width: self.bounds.size.width,height: self.BottomBarHeight)
self.progressView.frame = CGRect(x: 0, y: self.bounds.height - 49 - 20, width: self.bounds.width, height: 20)
}) { (finished) in
}
toolBarDelegate?.toolBarDidShow()
}
@objc func hideWithAnimations(animation:Bool){
midBar?.removeFromSuperview()
showMid = false
UIView.animate(withDuration: 0.35, animations: {
self.topBar?.frame = CGRect(x:0,y: -self.TopBarHeight,width: self.bounds.size.width,height: self.TopBarHeight)
self.bottomBar?.frame = CGRect(x:0, y:self.bounds.size.height + 20, width:self.bounds.size.width, height:self.BottomBarHeight)
self.progressView.frame = CGRect(x: 0, y: self.bounds.height, width: self.bounds.width, height: 20)
}) { (finished) in
self.isShow = false
self.removeFromSuperview()
}
toolBarDelegate?.toolBarDidHidden()
}
@objc private func brightnessChange(btn:UISlider){
//调节屏幕亮度
self.toolBarDelegate?.brightnessChange(value: CGFloat(btn.value))
}
@objc private func fontMinusAction(btn:UIButton){
self.toolBarDelegate?.fontChange(action: .minimus)
}
@objc private func fontPlusAction(btn:UIButton){
self.toolBarDelegate?.fontChange(action: .plus)
}
@objc private func landscape(btn:UIButton){
}
@objc private func autoReading(btn:UIButton){
}
@objc private func whiteAction(btn:UIButton){
btn.isSelected = true
yellowBtn.isSelected = false
greenBtn.isSelected = false
self.toolBarDelegate?.readBg(type: .white)
}
@objc private func yellowAction(btn:UIButton){
btn.isSelected = true
whiteBtn.isSelected = false
greenBtn.isSelected = false
self.toolBarDelegate?.readBg(type: .yellow)
}
@objc private func greenAction(btn:UIButton){
btn.isSelected = true
whiteBtn.isSelected = false
yellowBtn.isSelected = false
self.toolBarDelegate?.readBg(type: .green)
}
@objc private func itemAction(index:Int) {
var viewIndex = 0
for bgView in bgItemViews {
if viewIndex != index {
bgView.select(select: false)
}
viewIndex += 1
}
self.toolBarDelegate?.readBg(type: Reader(rawValue: index) ?? .white)
}
@objc private func seniorSettingAction(btn:UIButton){
self.toolBarDelegate?.toolbar(toolbar: self, clickMoreSetting: btn)
}
@objc private func bottomBtnAction(btn:UIButton){
let tag = btn.tag - kBottomBtnTag
switch tag {
case 0:
darkNight(btn: btn)
break
case 1:
feedback(btn: btn)
break
case 2:
catalogAction(btn: btn)
break
case 3:
cache(btn: btn)
break
case 4:
setting(btn: btn)
break
default:
darkNight(btn: btn)
}
}
@objc private func darkNight(btn:UIButton){
}
@objc private func feedback(btn:UIButton){
}
@objc private func catalogAction(btn:UIButton){
toolBarDelegate?.catagoryClicked()
}
@objc private func cache(btn:UIButton){
toolBarDelegate?.cacheAll()
}
@objc private func setting(btn:UIButton){
showMid = !showMid
if showMid {
self.addSubview(midBar!)
}else{
midBar?.removeFromSuperview()
}
}
@objc private func backAction(btn:UIButton){
toolBarDelegate?.backButtonDidClicked()
}
@objc private func listenAction(btn:UIButton){
toolBarDelegate?.listen()
}
@objc private func changeSourceAction(btn:UIButton){
toolBarDelegate?.changeSourceClicked()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
class ZSModeBgItemView: UIView {
var backgroundImage:UIImageView!
private var selectedImage:UIImageView!
var selectHandler:ZSBgViewHandler?
var index:Int = 0
override init(frame: CGRect) {
super.init(frame: frame)
setupSubviews()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupSubviews() {
isUserInteractionEnabled = true
backgroundImage = UIImageView(frame: self.bounds)
backgroundImage.isUserInteractionEnabled = true
backgroundImage.layer.cornerRadius = self.bounds.width/2
backgroundImage.layer.masksToBounds = true
selectedImage = UIImageView(frame: CGRect(x: self.bounds.width/2 - 18, y: self.bounds.width/2 - 18, width: 36, height: 36))
selectedImage.isUserInteractionEnabled = true
selectedImage.image = UIImage(named: "cell_selected_tip")
selectedImage.isHidden = true
addSubview(backgroundImage)
addSubview(selectedImage)
let tap = UITapGestureRecognizer(target: self, action: #selector(selectAction))
backgroundImage.addGestureRecognizer(tap)
}
@objc
private func selectAction() {
selectedImage.isHidden = false
selectHandler?()
}
func select(select:Bool) {
selectedImage.isHidden = !select
}
func setImage(image:UIImage?) {
backgroundImage.image = image
}
}
| 8031bcfe4164180d55d8f8f52080b3cd | 37.167076 | 280 | 0.629329 | false | false | false | false |
muenzpraeger/salesforce-einstein-vision-swift | refs/heads/master | SalesforceEinsteinVision/Classes/http/parts/MultiPartExample.swift | apache-2.0 | 1 | //
// MultiPartExample.swift
// Pods
//
// Created by René Winkelmeyer on 02/28/2017.
//
//
import Alamofire
import Foundation
public struct MultiPartExample : MultiPart {
private let MAX_NAME = 180
private var _name:String?
private var _labelId:Int?
private var _file:URL?
public init() {}
public mutating func build(name: String, labelId: Int, file: URL) throws {
if name.isEmpty {
throw ModelError.noFieldValue(field: "name")
}
if (name.characters.count>MAX_NAME) {
throw ModelError.stringTooLong(field: "name", maxValue: MAX_NAME, currentValue: name.characters.count)
}
if (labelId<0) {
throw ModelError.intTooSmall(field: "labelId", minValue: 0, currentValue: labelId)
}
if file.absoluteString.isEmpty {
throw ModelError.noFieldValue(field: "file")
}
_name = name
_labelId = labelId
_file = file
}
public func form(multipart: MultipartFormData) {
let nameData = _name?.data(using: String.Encoding.utf8)
multipart.append(nameData!, withName: "name")
let labelIdData = String(describing: _labelId).data(using: String.Encoding.utf8)
multipart.append(labelIdData!, withName: "labelId")
multipart.append(_file!, withName: "data")
}
}
| 82c59945d9b3c581c570d085398281bf | 25.254545 | 114 | 0.590028 | false | false | false | false |
Coderian/SwiftedGPX | refs/heads/master | SwiftedGPX/Elements/LatitudeType.swift | mit | 1 | //
// Latitude.swift
// SwiftedGPX
//
// Created by 佐々木 均 on 2016/02/16.
// Copyright © 2016年 S-Parts. All rights reserved.
//
import Foundation
/// GPX LatitudeType
///
/// [GPX 1.1 schema](http://www.topografix.com/GPX/1/1/gpx.xsd)
///
/// <xsd:simpleType name="latitudeType">
/// <xsd:annotation>
/// <xsd:documentation>
/// The latitude of the point. Decimal degrees, WGS84 datum.
/// </xsd:documentation>
/// </xsd:annotation>
/// <xsd:restriction base="xsd:decimal">
/// <xsd:minInclusive value="-90.0"/>
/// <xsd:maxInclusive value="90.0"/>
/// </xsd:restriction>
/// </xsd:simpleType>
public class LatitudeType {
var value:Double = 0.0
var originalValue:String!
public init( latitude: String ){
self.originalValue = latitude
self.value = Double(latitude)!
}
} | ad0467070f05cc42db526b1747ec257c | 25.727273 | 71 | 0.592509 | false | false | false | false |
magicien/MMDSceneKit | refs/heads/master | Source/Common/MMDIKConstraint.swift | mit | 1 | //
// MMDIKNode.swift
// MMDSceneKit
//
// Created by magicien on 12/20/15.
// Copyright © 2015 DarkHorse. All rights reserved.
//
import SceneKit
open class MMDIKConstraint {
public var boneArray: [MMDNode]! = []
var minAngleArray: [Float]! = []
var maxAngleArray: [Float]! = []
public var ikBone: MMDNode! = nil
public var targetBone: MMDNode! = nil
var iteration: Int = 0
var weight: Float = 0.0
var linkNo: Int = -1
var isEnable: Bool = true
var angle: SCNVector3! = SCNVector3()
var orgTargetPos: SCNVector3! = SCNVector3()
var rotAxis: SCNVector3! = SCNVector3()
var rotQuat: SCNVector4! = SCNVector4()
var inverseMat: SCNMatrix4! = SCNMatrix4()
var diff: SCNVector3! = SCNVector3()
var effectorPos: SCNVector3! = SCNVector3()
var targetPos: SCNVector3! = SCNVector3()
/*
let ikConstraintBlock = { (node: SCNNode, matrix: SCNMatrix4) -> SCNMatrix4 in
let mmdNode = node as? MMDNode
if(mmdNode == nil){
return matrix
}
let optionalIK = mmdNode!.ikConstraint
if(optionalIK == nil){
return matrix
}
let ik = optionalIK as MMDIKConstraint!
let zeroThreshold = 0.00000001
//let targetMat = matrix
let orgTargetPos = ik.targetBone.position
let pos = SCNVector3(matrix.m41, matrix.m42, matrix.m43)
let rotAxis = ik.rotAxis
let rotQuat = ik.rotQuat
let inverseMat = ik.inverseMat
let diff = ik.diff
let effectorPos = ik.effectorPos
let targetPos = ik.targetPos
/*
for var i = ik!.boneArray.count; i>=0; i-- {
ik.boneArray[i].updateMatrix()
}
ik.effectorBone.updateMatrix()
*/
for calcCount in 0..<ik!.iteration {
for linkIndex in 0..<ik.boneArray.count {
let linkedBone = ik.boneArray[linkIndex]
let effectorMat = ik.effectorBone.representNode.transform
effectorPos.x = effectorMat.m41
effectorPos.y = effectorMat.m42
effectorPos.z = effectorMat.m43
// inverseMat.inverseMatrix(linkedBone.representNode.transform)
effectorPos = effectorPos * inverseMat
targetPos = orgTargetPos * inverseMat
diff = effectorPos - targetPos
if diff.length() < zeroThreshold {
return matrix
}
effectorPos.normalize()
targetPos.normalize()
var eDotT = effectorPos.dot(targetPos)
if(eDotT > 1.0) {
eDotT = 1.0
}
if(eDotT < -1.0) {
edotT = -1.0
}
var rotAngle = acos(eDotT)
if rotAngle > ik.weight * (linkIndex + 1) * 4 {
rotAngle = ik.weight * (linkIndex + 1) * 4
}
rotAxis.cross(effectPos, targetPos)
if rotAxis.length() < zeroThreshold) {
break
}
rotAxis.normalize()
rotQuat.createAxis(rotAxis, rotAngle)
rotQuat.normalize()
if ik.minAngleArray[linkIndex] {
ik.limitAngle(ik.minAngleArray[linkIndex], ik.maxAngleArray[linkIndex])
}
linkedBone.rotate.cross(linkedBone.rotate, rotQuat)
linkedBone.rotate.normalize()
for var i = linkIndex; i>=0; i-- {
ik.boneList[i].updateMatrix()
}
ik.effectorBone.updateMatrix()
}
}
}
*/
func printInfo() {
print("boneArray: \(self.boneArray.count)")
for bone in self.boneArray {
print(" \(String(describing: bone.name))")
}
print("minAngleArray: \(self.minAngleArray.count)")
for val in self.minAngleArray {
print(" \(val)")
}
print("maxAngleArray: \(self.maxAngleArray.count)")
for val in self.maxAngleArray {
print(" \(val)")
}
print("ikBone: \(String(describing: self.ikBone.name))")
print("targetBone: \(String(describing: self.targetBone.name))")
print("iteration: \(self.iteration)")
print("weight: \(self.weight)")
print("isEnable: \(self.isEnable)")
print("")
}
}
| 56ac9738a070229a03bbb714608240d9 | 32.248227 | 91 | 0.515145 | false | false | false | false |
Czajnikowski/TrainTrippin | refs/heads/master | LibrarySample/Pods/RxSwift/RxSwift/Schedulers/CurrentThreadScheduler.swift | mit | 3 | //
// CurrentThreadScheduler.swift
// RxSwift
//
// Created by Krunoslav Zaher on 8/30/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
import Foundation
import Dispatch
let CurrentThreadSchedulerKeyInstance = "RxSwift.CurrentThreadScheduler.SchedulerKey"
let CurrentThreadSchedulerQueueKeyInstance = "RxSwift.CurrentThreadScheduler.Queue"
typealias CurrentThreadSchedulerValue = NSString
let CurrentThreadSchedulerValueInstance = "RxSwift.CurrentThreadScheduler.SchedulerKey" as NSString
/**
Represents an object that schedules units of work on the current thread.
This is the default scheduler for operators that generate elements.
This scheduler is also sometimes called `trampoline scheduler`.
*/
public class CurrentThreadScheduler : ImmediateSchedulerType {
typealias ScheduleQueue = RxMutableBox<Queue<ScheduledItemType>>
/**
The singleton instance of the current thread scheduler.
*/
public static let instance = CurrentThreadScheduler()
static var queue : ScheduleQueue? {
get {
return Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerQueueKeyInstance)
}
set {
Thread.setThreadLocalStorageValue(newValue, forKey: CurrentThreadSchedulerQueueKeyInstance)
}
}
/**
Gets a value that indicates whether the caller must call a `schedule` method.
*/
public static fileprivate(set) var isScheduleRequired: Bool {
get {
let value: CurrentThreadSchedulerValue? = Thread.getThreadLocalStorageValueForKey(CurrentThreadSchedulerKeyInstance)
return value == nil
}
set(isScheduleRequired) {
Thread.setThreadLocalStorageValue(isScheduleRequired ? nil : CurrentThreadSchedulerValueInstance, forKey: CurrentThreadSchedulerKeyInstance)
}
}
/**
Schedules an action to be executed as soon as possible on current thread.
If this method is called on some thread that doesn't have `CurrentThreadScheduler` installed, scheduler will be
automatically installed and uninstalled after all work is performed.
- parameter state: State passed to the action to be executed.
- parameter action: Action to be executed.
- returns: The disposable object used to cancel the scheduled action (best effort).
*/
public func schedule<StateType>(_ state: StateType, action: @escaping (StateType) -> Disposable) -> Disposable {
if CurrentThreadScheduler.isScheduleRequired {
CurrentThreadScheduler.isScheduleRequired = false
let disposable = action(state)
defer {
CurrentThreadScheduler.isScheduleRequired = true
CurrentThreadScheduler.queue = nil
}
guard let queue = CurrentThreadScheduler.queue else {
return disposable
}
while let latest = queue.value.dequeue() {
if latest.isDisposed {
continue
}
latest.invoke()
}
return disposable
}
let existingQueue = CurrentThreadScheduler.queue
let queue: RxMutableBox<Queue<ScheduledItemType>>
if let existingQueue = existingQueue {
queue = existingQueue
}
else {
queue = RxMutableBox(Queue<ScheduledItemType>(capacity: 1))
CurrentThreadScheduler.queue = queue
}
let scheduledItem = ScheduledItem(action: action, state: state)
queue.value.enqueue(scheduledItem)
return scheduledItem
}
}
| 54b73359d85644164379cf550fbe5970 | 33.216981 | 152 | 0.682106 | false | false | false | false |
SuperAwesomeLTD/sa-mobile-sdk-ios | refs/heads/develop | Pod/Classes/Common/Model/CreativeModels.swift | lgpl-3.0 | 1 | //
// CreativeModels.swift
// SuperAwesome
//
// Created by Gunhan Sancar on 16/04/2020.
//
public struct Creative: Codable {
public let id: Int
let name: String?
let format: CreativeFormatType
public let clickUrl: String?
let details: CreativeDetail
let bumper: Bool?
public let payload: String?
enum CodingKeys: String, CodingKey {
case id
case name
case format
case clickUrl = "click_url"
case details
case bumper
case payload = "customPayload"
}
}
struct CreativeDetail: Codable {
let url: String?
let image: String?
let video: String?
let placementFormat: String
let tag: String?
let width: Int
let height: Int
let duration: Int
let vast: String?
enum CodingKeys: String, CodingKey {
case url
case image
case video
case placementFormat = "placement_format"
case tag
case width
case height
case duration
case vast
}
}
enum CreativeFormatType: String, Codable, DecodableDefaultLastItem {
case video
case imageWithLink = "image_with_link"
case tag
case richMedia = "rich_media"
case unknown
}
| 79285f3b257c80b9f567dc6d8f4a52eb | 20.293103 | 68 | 0.621862 | false | false | false | false |
Kezuino/SMPT31 | refs/heads/master | NOtification/NOKit/Location.swift | mit | 1 | //
// Location.swift
// NOtification
//
// Created by Bas on 29/05/2015.
// Copyright (c) 2015 Bas. All rights reserved.
//
import Foundation
import SwiftSerializer
public typealias VIP = User
public class Location: Serializable {
/// Name of the location
public var name: String!
/// The network tied to the location.
public var ssid: SSID! {
didSet {
self.addToManager(self)
}
}
/// The VIPs for the location.
public var vips = [VIP]()
/**
The designated initializer.
:param: name The name of the location.
:param: network The network tied to the location.
*/
public init(name: String, ssid: SSID) {
self.name = name
self.ssid = ssid
}
/**
Initializes a location with a specified array of VIPs.
:param: name The name of the location.
:param: network The network tied to the location.
:param: vips The array of VIPs to add to the location.
*/
public convenience init(name: String, ssid: SSID, vips: [VIP]) {
self.init(name: name, ssid: ssid)
self.vips = vips
}
/**
Initializes a location with one or more VIPs.
:param: name The name of the location.
:param: network The network tied to the location.
:param: vips One or more VIPs to add to the location.
*/
public convenience init(name: String, ssid: SSID, vips: VIP...) {
self.init(name: name, ssid: ssid)
self.vips = vips
}
/**
Adds a VIP to the list of VIPs.
:param: vip The VIP to add to the VIPs.
:returns: VIP if successfully added, nil if already in VIPs.
*/
public func addVIP(vip newVIP: VIP) -> VIP? {
for vip in self.vips {
if vip == newVIP {
return nil
}
}
self.vips.append(newVIP)
return newVIP
}
/**
Removes a VIP from the list of VIPs.
:param: user The VIP to remove from the VIPs.
:returns: VIP if successfully removed, nil if not.
*/
public func removeVIP(vip removeVIP: VIP) -> VIP? {
return self.vips.removeObject(removeVIP) ? removeVIP : nil
}
}
// MARK: - Hashable
extension Location: Hashable {
/// The hash value.
public override var hashValue: Int {
return ssid.hashValue
}
}
public func ==(lhs: Location, rhs: Location) -> Bool {
return lhs.name == rhs.name && lhs.ssid == rhs.ssid && lhs.vips == rhs.vips
}
// MARK: - Printable
extension Location: Printable {
/// A textual representation of `self`.
public override var description: String {
return "Name: \(self.name) on network \(self.ssid), with vips: (\(self.vips))"
}
}
// MARK: - Manageable
extension Location: Manageable {
/**
Adds the location to its manager.
:param: object The Location instance to add.
:returns: True if the location could be added, else false.
*/
public func addToManager(object: Manageable) -> Bool {
return LocationManager.sharedInstance.addLocation(object)
}
/**
Removes the location from its manager.
:param: object The Location instance to remove.
:returns: True if the location could be removed, else false.
*/
public func removeFromManager(object: Manageable) -> Bool {
return LocationManager.sharedInstance.removeLocation(object)
}
} | 62dff341ec5567b5308c19aba05d8a82 | 20.692308 | 80 | 0.676233 | false | false | false | false |
StreamOneNL/AppleTV-Demo | refs/heads/master | AppleTV-Demo/Item.swift | mit | 1 | //
// Item.swift
// AppleTV-Demo
//
// Created by Nicky Gerritsen on 09-01-16.
// Copyright © 2016 StreamOne. All rights reserved.
//
import Foundation
import Argo
import Curry
import StreamOneSDK
struct Item {
let id: String
let title: String
let type: ItemType
let description: String?
let duration: String
let dateCreated: String?
let dateAired: String?
let views: Int
let thumbnail: String?
let progressiveLink: String?
let hlsLink: String?
let account: BasicAccount
var playbackLink: String? {
return hlsLink ?? progressiveLink
}
}
extension Item: Decodable {
static func decode(json: JSON) -> Decoded<Item> {
let i = curry(Item.init)
return i
<^> json <| "id"
<*> json <| "title"
<*> json <| "type"
<*> json <|? "description"
<*> json <| "duration"
<*> json <|? "datecreated"
<*> json <|? "dateaired"
<*> json <| "views"
<*> json <|? "selectedthumbnailurl"
<*> json <|? ["medialink", "progressive"]
<*> json <|? ["medialink", "hls"]
<*> json <| "account"
}
}
extension Item {
func toDictionary() -> [String: AnyObject] {
var result: [String: AnyObject] = [:]
result["id"] = id
result["title"] = title
result["type"] = type.stringValue
result["description"] = description
result["duration"] = duration
result["datecreated"] = dateCreated
result["dateaired"] = dateAired
result["views"] = views
result["selectedthumbnailurl"] = thumbnail
var medialinks: [String: String] = [:]
if let hlsLink = hlsLink {
medialinks["hls"] = hlsLink
}
if let progressiveLink = progressiveLink {
medialinks["progressive"] = progressiveLink
}
result["medialink"] = medialinks
result["account"] = ["id": account.id, "name": account.name]
return result
}
}
extension Item : Equatable {}
func ==(lhs: Item, rhs: Item) -> Bool {
return lhs.id == rhs.id
} | 4dd2d7a3ef5523098cc0161527d7823d | 24.435294 | 68 | 0.553447 | false | false | false | false |
neilpa/List | refs/heads/master | List/ForwardList.swift | mit | 1 | // Copyright (c) 2015 Neil Pankey. All rights reserved.
import Dumpster
/// A singly-linked list of values.
public struct ForwardList<T> {
// MARK: Constructors
/// Initializes an empty `ForwardList`.
public init() {
}
/// Initializes a `ForwardList` with a single `value`.
public init(value: T) {
self.init(Node(value))
}
/// Initializes a `ForwardList` with a collection of `values`.
public init<S: SequenceType where S.Generator.Element == T>(_ values: S) {
// TODO This should return the tail of the list as well so we don't rely on `head.last`
self.init(Node.create(values))
}
/// Initializes `ForwardList` with `head`.
private init(_ head: Node?) {
self.init(head, head?.last)
}
/// Initializes `ForwardList` with a new set of `ends`
private init(_ ends: ListEnds<Node>?) {
self.init(ends?.head, ends?.tail)
}
/// Initializes `ForwardList` with `head` and `tail`.
private init(_ head: Node?, _ tail: Node?) {
self.head = head
self.tail = tail
}
// MARK: Primitive operations
/// Replace nodes at the given insertion point
private mutating func spliceList(prefixTail: Node?, _ replacementHead: Node?, _ replacementTail: Node?, _ suffixHead: Node?) {
if prefixTail == nil {
head = replacementHead ?? suffixHead
} else {
prefixTail?.next = replacementHead ?? suffixHead
}
if suffixHead == nil {
tail = replacementTail
} else {
replacementTail?.next = suffixHead
}
}
/// Replace the nodes at `subRange` with the given replacements.
private mutating func spliceList(subRange: Range<Index>, _ replacementHead: Node?, _ replacementTail: Node?) {
spliceList(subRange.startIndex.previous, replacementHead, replacementTail, subRange.endIndex.node)
}
/// Inserts a new `node` between `prefix` and `suffix`.
private mutating func insertNode(prefix: Node?, _ node: Node, _ suffix: Node?) {
spliceList(prefix, node, node, suffix)
}
/// Removes the `node` that follows `previous`.
private mutating func removeNode(node: Node, previous: Node?) -> T {
precondition(previous?.next == node || previous == nil)
let value = node.value
spliceList(previous, nil, nil, node.next)
return value
}
/// The type of nodes in `ForwardList`.
private typealias Node = ForwardListNode<T>
/// The first node of `ForwardList`.
private var head: Node?
/// The last node of `ForwardList`.
private var tail: Node?
}
// MARK: Queue/Stack
extension ForwardList : QueueType, StackType {
public typealias Element = T
/// Returns true iff `ForwardList` is empty.
public var isEmpty: Bool {
return head == nil
}
/// Returns the value at the head of `ForwardList`, `nil` if empty.
public var first: T? {
return head?.value
}
/// Returns the value at the tail of `ForwardList`, `nil` if empty.
public var last: T? {
return tail?.value
}
/// Removes the `first` value at the head of `ForwardList` and returns it, `nil` if empty.
public mutating func removeFirst() -> T {
return removeNode(head!, previous: nil)
}
/// Inserts a new `value` _before_ the `first` value.
public mutating func insertFirst(value: T) {
insertNode(nil, Node(value), head)
}
/// Inserts a new `value` _after_ the `last` value.
public mutating func insertLast(value: T) {
insertNode(tail, Node(value), nil)
}
}
// MARK: ArrayLiteralConvertible
extension ForwardList : ArrayLiteralConvertible {
/// Initializes a `ForwardList` with the `elements` from array.
public init(arrayLiteral elements: T...) {
self.init(elements)
}
}
// MARK: SequenceType
extension ForwardList : SequenceType {
public typealias Generator = GeneratorOf<T>
/// Create a `Generator` that enumerates all the values in `ForwardList`.
public func generate() -> Generator {
return head?.values() ?? Generator { nil }
}
}
// MARK: CollectionType, MutableCollectionType
extension ForwardList : CollectionType, MutableCollectionType {
public typealias Index = ForwardListIndex<T>
/// Index to the first element of `ForwardList`.
public var startIndex: Index {
return Index(head)
}
/// Index past the last element of `ForwardList`.
public var endIndex: Index {
return Index(nil, tail)
}
/// Retrieves or updates the element in `ForwardList` at `index`.
public subscript(index: Index) -> T {
get {
return index.node!.value
}
set {
index.node!.value = newValue
}
}
}
// MARK: Sliceable, MutableSliceable
extension ForwardList : Sliceable, MutableSliceable {
public typealias SubSlice = ForwardList
/// Extract a slice of `ForwardList` from bounds.
public subscript (bounds: Range<Index>) -> SubSlice {
get {
// TODO Defer cloning the nodes until modification
var head = bounds.startIndex.node
var tail = bounds.endIndex.node
return head == tail ? ForwardList() : ForwardList(head?.takeUntil(tail))
}
set(newList) {
spliceList(bounds, newList.head, newList.tail)
}
}
}
// MARK: ExtensibleCollectionType
extension ForwardList : ExtensibleCollectionType {
/// Does nothing.
public mutating func reserveCapacity(amount: Index.Distance) {
}
/// Appends `value to the end of `ForwardList`.
public mutating func append(value: T) {
self.insertLast(value)
}
/// Appends multiple elements to the end of `ForwardList`.
public mutating func extend<S: SequenceType where S.Generator.Element == T>(values: S) {
Swift.map(values) { self.insertLast($0) }
}
}
// MARK: RangeReplaceableCollectionType
extension ForwardList : RangeReplaceableCollectionType {
/// Replace the given `subRange` of elements with `values`.
public mutating func replaceRange<C : CollectionType where C.Generator.Element == T>(subRange: Range<Index>, with values: C) {
var replacement = Node.create(values)
spliceList(subRange, replacement.head, replacement.tail)
}
/// Insert `value` at `index`.
public mutating func insert(value: T, atIndex index: Index) {
insertNode(index.previous, Node(value), index.node)
}
/// Insert `values` at `index`.
public mutating func splice<C : CollectionType where C.Generator.Element == T>(values: C, atIndex index: Index) {
var replacement = Node.create(values)
spliceList(index.previous, replacement.head, replacement.tail, index.node)
}
/// Remove the element at `index` and returns it.
public mutating func removeAtIndex(index: Index) -> T {
return removeNode(index.node!, previous: index.previous)
}
/// Remove the indicated `subRange` of values.
public mutating func removeRange(subRange: Range<Index>) {
spliceList(subRange.startIndex.previous, nil, nil, subRange.endIndex.node)
}
/// Remove all values from `ForwardList`.
public mutating func removeAll(#keepCapacity: Bool) {
spliceList(nil, nil, nil, nil)
}
}
// MARK: Printable
extension ForwardList : Printable, DebugPrintable {
/// String representation of `ForwardList`.
public var description: String {
return describe(toString)
}
/// Debug string representation of `ForwardList`.
public var debugDescription: String {
return describe(toDebugString)
}
/// Formats elements of list for printing.
public func describe(stringify: T -> String) -> String {
let string = join(", ", lazy(self).map(stringify))
return "[\(string)]"
}
}
// MARK: Higher-order functions
extension ForwardList {
/// Maps values in `ForwardList` with `transform` to create a new `ForwardList`
public func map<U>(transform: T -> U) -> ForwardList<U> {
return ForwardList<U>(head?.map(transform))
}
/// Filters values from `ForwardList` with `predicate` to create a new `ForwardList`
public func filter(predicate: T -> Bool) -> ForwardList {
return ForwardList(head?.filter(predicate))
}
}
| 9f9627310c5e2f303b85149874ca35b3 | 29.794872 | 130 | 0.6403 | false | false | false | false |
buyiyang/iosstar | refs/heads/master | iOSStar/Scenes/Discover/Controllers/VoiceManagerVC.swift | gpl-3.0 | 3 |
//
// VoiceManagerVC.swift
// iOSStar
//
// Created by mu on 2017/9/8.
// Copyright © 2017年 YunDian. All rights reserved.
//
import UIKit
class VoiceManagerVC: UIViewController {
@IBOutlet weak var contentViewtest: UIView!
@IBOutlet weak var askBtn: UIButton!
var videoVC: VoiceQuestionVC?
var starModel: StarSortListModel = StarSortListModel()
override func viewDidLoad() {
super.viewDidLoad()
initUI()
initNav()
}
func initNav() {
let rightItem = UIBarButtonItem.init(title: "历史定制", style: .plain, target: self, action: #selector(rightItemTapped(_:)))
navigationItem.rightBarButtonItem = rightItem
navigationItem.rightBarButtonItem?.tintColor = UIColor.init(hexString: AppConst.Color.titleColor)
}
func rightItemTapped(_ sender: Any) {
if let vc = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: VoiceHistoryVC.className()) as? VoiceHistoryVC{
vc.starModel = starModel
_ = self.navigationController?.pushViewController(vc, animated: true)
}
}
func initUI() {
title = "语音定制"
if let vc = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: "VoiceQuestionVC") as? VoiceQuestionVC{
videoVC = vc
vc.starModel = starModel
contentViewtest.addSubview(vc.view)
// vc.view.backgroundColor = UIColor.red
self.addChildViewController(vc)
vc.view.snp.makeConstraints({ (make) in
make.edges.equalToSuperview()
})
}
}
@IBAction func askBtnTapped(_ sender: UIButton) {
if let vc = UIStoryboard.init(name: "Discover", bundle: nil).instantiateViewController(withIdentifier: "VoiceAskVC") as? VoiceAskVC{
vc.starModel = starModel
self.navigationController?.pushViewController(vc, animated: true)
}
}
}
| b8efadec2f027f1552986170b3fb4022 | 33.169492 | 158 | 0.642361 | false | false | false | false |
hetefe/MyNews | refs/heads/master | MyNews/MyNews/Module/side/LeftViewController.swift | mit | 1 | //
// LeftViewController.swift
// MyNews
//
// Created by 赫腾飞 on 15/12/27.
// Copyright © 2015年 hetefe. All rights reserved.
//
import UIKit
let LeftCellID = "LeftCellID"
class LeftViewController: UIViewController,UITableViewDataSource,UITableViewDelegate {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
private func setupUI(){
view.addSubview(personalView)
personalView.addSubview(heardImageView)
personalView.addSubview(nameBtn)
view.addSubview(tableView)
personalView.snp_makeConstraints { (make) -> Void in
make.top.equalTo(view.snp_top).offset(80)
make.height.equalTo(100)
make.width.equalTo(200)
make.left.equalTo(view.snp_left)
}
heardImageView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(personalView.snp_left).offset(10)
make.top.equalTo(personalView.snp_top).offset(10)
make.width.height.equalTo(60)
}
nameBtn.snp_makeConstraints { (make) -> Void in
make.top.equalTo(heardImageView.snp_top)
make.left.equalTo(heardImageView.snp_right).offset(10)
}
tableView.snp_makeConstraints { (make) -> Void in
make.left.equalTo(view.snp_left)
make.top.equalTo(personalView.snp_bottom).offset(50)
make.width.equalTo(200)
make.bottom.equalTo(view.snp_bottom).offset(-100)
}
}
//MARK:- 数据源方法
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 4
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(LeftCellID, forIndexPath: indexPath)
// cell.backgroundColor = indexPath.row % 2 == 0 ? UIColor.darkGrayColor() : UIColor.lightGrayColor()
cell.backgroundColor = UIColor.clearColor()
cell.selectionStyle = .None
switch indexPath.row{
case 0:
cell.imageView?.image = UIImage(named: "IconProfile")
cell.textLabel?.text = "我"
case 1:
cell.imageView?.image = UIImage(named: "IconSettings")
cell.textLabel?.text = "设置"
case 2:
cell.imageView?.image = UIImage(named: "IconHome")
cell.textLabel?.text = "主页"
case 3:
cell.imageView?.image = UIImage(named: "IconCalendar")
cell.textLabel?.text = "日历"
default :
cell.imageView?.image = UIImage(named: "IconProfile")
cell.textLabel?.text = "我"
}
return cell
}
//MARK:- 代理方法监控Cell的点击事件
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch (indexPath.row) {
case 0:
print("Model到个人信息控制器")
case 1:
print("Model到设置界面")
case 2:
print("Model到主页面")
case 3:
print("Model日历界面")
default :
print("其他情况")
}
}
//MARK:- 懒加载视图
private lazy var tableView: UITableView = {
let tableView = UITableView()
tableView.rowHeight = 50
tableView.dataSource = self
tableView.delegate = self
tableView.separatorStyle = UITableViewCellSeparatorStyle.None
tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: LeftCellID)
tableView.backgroundColor = UIColor.clearColor()
return tableView
}()
private lazy var personalView: UIView = {
let personalView = UIView()
return personalView
}()
//头像
private lazy var heardImageView : UIImageView = {
let headImageView = UIImageView(image: UIImage(named: "pa"))
headImageView.layer.masksToBounds = true
headImageView.layer.cornerRadius = 30
return headImageView
}()
private lazy var nameBtn: UIButton = {
let btn = UIButton()
btn.setTitle("MyNews", forState: .Normal)
btn.setTitleColor(UIColor.blackColor(), forState: .Normal)
return btn
}()
}
| 75bed38cdb3799fd2cb755d057ea98dd | 27.832258 | 109 | 0.576192 | false | false | false | false |
cwwise/CWWeChat | refs/heads/master | CWWeChat/Vendor/FPSLabel.swift | mit | 2 | //
// FPSLabel.swift
// SAC
//
// Created by SAGESSE on 2/1/16.
// Copyright © 2016-2017 Sagesse. All rights reserved.
//
// Reference: ibireme/YYKit/YYFPSLabel
//
import UIKit
///
/// Show Screen FPS.
///
/// The maximum fps in OSX/iOS Simulator is 60.00.
/// The maximum fps on iPhone is 59.97.
/// The maxmium fps on iPad is 60.0.
///
public class FPSLabel: UILabel {
public override init(frame: CGRect) {
super.init(frame: frame)
build()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
build()
}
public override var intrinsicContentSize: CGSize {
return CGSize(width: 55, height: 20)
}
public override func willMove(toWindow newWindow: UIWindow?) {
super.willMove(toWindow: newWindow)
if newWindow == nil {
_link.invalidate()
} else {
_link.add(to: RunLoop.main, forMode: RunLoopMode.commonModes)
}
}
private func build() {
text = "calc..."
font = UIFont.systemFont(ofSize: 14)
textColor = UIColor.white
textAlignment = .center
backgroundColor = UIColor(white: 0, alpha: 0.7)
layer.cornerRadius = 5
layer.masksToBounds = true
}
@objc private func tack(_ link: CADisplayLink) {
guard let lastTime = _lastTime else {
_lastTime = link.timestamp
return
}
_count += 1
let delta = link.timestamp - lastTime
guard delta >= 1 else {
return
}
let fps = Double(_count) / delta + 0.03
let progress = CGFloat(fps / 60)
let color = UIColor(hue: 0.27 * (progress - 0.2), saturation: 1, brightness: 0.9, alpha: 1)
let text = NSMutableAttributedString(string: "\(Int(fps)) FPS")
text.addAttribute(NSAttributedStringKey.foregroundColor, value: color, range: NSMakeRange(0, text.length - 3))
attributedText = text
_count = 0
_lastTime = link.timestamp
}
private var _count: Int = 0
private var _lastTime: TimeInterval?
private lazy var _link: CADisplayLink = {
return CADisplayLink(target: self, selector: #selector(tack(_:)))
}()
}
| 0f53ca1a5efb89deeaf57156746fe2b4 | 26.650602 | 118 | 0.579521 | false | false | false | false |
hackcity2017/iOS-client-application | refs/heads/master | Pods/Socket.IO-Client-Swift/Source/SocketEngine.swift | mit | 1 | //
// SocketEngine.swift
// Socket.IO-Client-Swift
//
// Created by Erik Little on 3/3/15.
//
// 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 final class SocketEngine : NSObject, URLSessionDelegate, SocketEnginePollable, SocketEngineWebsocket {
public let emitQueue = DispatchQueue(label: "com.socketio.engineEmitQueue", attributes: [])
public let handleQueue = DispatchQueue(label: "com.socketio.engineHandleQueue", attributes: [])
public let parseQueue = DispatchQueue(label: "com.socketio.engineParseQueue", attributes: [])
public var connectParams: [String: Any]? {
didSet {
(urlPolling, urlWebSocket) = createURLs()
}
}
public var postWait = [String]()
public var waitingForPoll = false
public var waitingForPost = false
public private(set) var closed = false
public private(set) var connected = false
public private(set) var cookies: [HTTPCookie]?
public private(set) var doubleEncodeUTF8 = false
public private(set) var extraHeaders: [String: String]?
public private(set) var fastUpgrade = false
public private(set) var forcePolling = false
public private(set) var forceWebsockets = false
public private(set) var invalidated = false
public private(set) var polling = true
public private(set) var probing = false
public private(set) var session: URLSession?
public private(set) var sid = ""
public private(set) var socketPath = "/engine.io/"
public private(set) var urlPolling = URL(string: "http://localhost/")!
public private(set) var urlWebSocket = URL(string: "http://localhost/")!
public private(set) var websocket = false
public private(set) var ws: WebSocket?
public weak var client: SocketEngineClient?
private weak var sessionDelegate: URLSessionDelegate?
private let logType = "SocketEngine"
private let url: URL
private var pingInterval: Double?
private var pingTimeout = 0.0 {
didSet {
pongsMissedMax = Int(pingTimeout / (pingInterval ?? 25))
}
}
private var pongsMissed = 0
private var pongsMissedMax = 0
private var probeWait = ProbeWaitQueue()
private var secure = false
private var security: SSLSecurity?
private var selfSigned = false
private var voipEnabled = false
public init(client: SocketEngineClient, url: URL, config: SocketIOClientConfiguration) {
self.client = client
self.url = url
for option in config {
switch option {
case let .connectParams(params):
connectParams = params
case let .cookies(cookies):
self.cookies = cookies
case let .doubleEncodeUTF8(encode):
doubleEncodeUTF8 = encode
case let .extraHeaders(headers):
extraHeaders = headers
case let .sessionDelegate(delegate):
sessionDelegate = delegate
case let .forcePolling(force):
forcePolling = force
case let .forceWebsockets(force):
forceWebsockets = force
case let .path(path):
socketPath = path
if !socketPath.hasSuffix("/") {
socketPath += "/"
}
case let .voipEnabled(enable):
voipEnabled = enable
case let .secure(secure):
self.secure = secure
case let .selfSigned(selfSigned):
self.selfSigned = selfSigned
case let .security(security):
self.security = security
default:
continue
}
}
super.init()
sessionDelegate = sessionDelegate ?? self
(urlPolling, urlWebSocket) = createURLs()
}
public convenience init(client: SocketEngineClient, url: URL, options: NSDictionary?) {
self.init(client: client, url: url, config: options?.toSocketConfiguration() ?? [])
}
deinit {
DefaultSocketLogger.Logger.log("Engine is being released", type: logType)
closed = true
stopPolling()
}
private func checkAndHandleEngineError(_ msg: String) {
do {
let dict = try msg.toNSDictionary()
guard let error = dict["message"] as? String else { return }
/*
0: Unknown transport
1: Unknown sid
2: Bad handshake request
3: Bad request
*/
didError(reason: error)
} catch {
client?.engineDidError(reason: "Got unknown error from server \(msg)")
}
}
private func handleBase64(message: String) {
// binary in base64 string
let noPrefix = message[message.index(message.startIndex, offsetBy: 2)..<message.endIndex]
if let data = NSData(base64Encoded: noPrefix, options: .ignoreUnknownCharacters) {
client?.parseEngineBinaryData(data as Data)
}
}
private func closeOutEngine(reason: String) {
sid = ""
closed = true
invalidated = true
connected = false
ws?.disconnect()
stopPolling()
client?.engineDidClose(reason: reason)
}
/// Starts the connection to the server
public func connect() {
if connected {
DefaultSocketLogger.Logger.error("Engine tried opening while connected. Assuming this was a reconnect", type: logType)
disconnect(reason: "reconnect")
}
DefaultSocketLogger.Logger.log("Starting engine. Server: %@", type: logType, args: url)
DefaultSocketLogger.Logger.log("Handshaking", type: logType)
resetEngine()
if forceWebsockets {
polling = false
websocket = true
createWebsocketAndConnect()
return
}
let reqPolling = NSMutableURLRequest(url: urlPolling)
if cookies != nil {
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
reqPolling.allHTTPHeaderFields = headers
}
if let extraHeaders = extraHeaders {
for (headerName, value) in extraHeaders {
reqPolling.setValue(value, forHTTPHeaderField: headerName)
}
}
doLongPoll(for: reqPolling as URLRequest)
}
private func createURLs() -> (URL, URL) {
if client == nil {
return (URL(string: "http://localhost/")!, URL(string: "http://localhost/")!)
}
var urlPolling = URLComponents(string: url.absoluteString)!
var urlWebSocket = URLComponents(string: url.absoluteString)!
var queryString = ""
urlWebSocket.path = socketPath
urlPolling.path = socketPath
if secure {
urlPolling.scheme = "https"
urlWebSocket.scheme = "wss"
} else {
urlPolling.scheme = "http"
urlWebSocket.scheme = "ws"
}
if connectParams != nil {
for (key, value) in connectParams! {
let keyEsc = key.urlEncode()!
let valueEsc = "\(value)".urlEncode()!
queryString += "&\(keyEsc)=\(valueEsc)"
}
}
urlWebSocket.percentEncodedQuery = "transport=websocket" + queryString
urlPolling.percentEncodedQuery = "transport=polling&b64=1" + queryString
return (urlPolling.url!, urlWebSocket.url!)
}
private func createWebsocketAndConnect() {
ws = WebSocket(url: urlWebSocketWithSid as URL)
if cookies != nil {
let headers = HTTPCookie.requestHeaderFields(with: cookies!)
for (key, value) in headers {
ws?.headers[key] = value
}
}
if extraHeaders != nil {
for (headerName, value) in extraHeaders! {
ws?.headers[headerName] = value
}
}
ws?.callbackQueue = handleQueue
ws?.voipEnabled = voipEnabled
ws?.delegate = self
ws?.disableSSLCertValidation = selfSigned
ws?.security = security
ws?.connect()
}
public func didError(reason: String) {
DefaultSocketLogger.Logger.error("%@", type: logType, args: reason)
client?.engineDidError(reason: reason)
disconnect(reason: reason)
}
public func disconnect(reason: String) {
guard connected else { return closeOutEngine(reason: reason) }
DefaultSocketLogger.Logger.log("Engine is being closed.", type: logType)
if closed {
return closeOutEngine(reason: reason)
}
if websocket {
sendWebSocketMessage("", withType: .close, withData: [])
closeOutEngine(reason: reason)
} else {
disconnectPolling(reason: reason)
}
}
// We need to take special care when we're polling that we send it ASAP
// Also make sure we're on the emitQueue since we're touching postWait
private func disconnectPolling(reason: String) {
emitQueue.sync {
self.postWait.append(String(SocketEnginePacketType.close.rawValue))
let req = self.createRequestForPostWithPostWait()
self.doRequest(for: req) {_, _, _ in }
self.closeOutEngine(reason: reason)
}
}
public func doFastUpgrade() {
if waitingForPoll {
DefaultSocketLogger.Logger.error("Outstanding poll when switched to WebSockets," +
"we'll probably disconnect soon. You should report this.", type: logType)
}
sendWebSocketMessage("", withType: .upgrade, withData: [])
websocket = true
polling = false
fastUpgrade = false
probing = false
flushProbeWait()
}
private func flushProbeWait() {
DefaultSocketLogger.Logger.log("Flushing probe wait", type: logType)
emitQueue.async {
for waiter in self.probeWait {
self.write(waiter.msg, withType: waiter.type, withData: waiter.data)
}
self.probeWait.removeAll(keepingCapacity: false)
if self.postWait.count != 0 {
self.flushWaitingForPostToWebSocket()
}
}
}
// We had packets waiting for send when we upgraded
// Send them raw
public func flushWaitingForPostToWebSocket() {
guard let ws = self.ws else { return }
for msg in postWait {
ws.write(string: msg)
}
postWait.removeAll(keepingCapacity: false)
}
private func handleClose(_ reason: String) {
client?.engineDidClose(reason: reason)
}
private func handleMessage(_ message: String) {
client?.parseEngineMessage(message)
}
private func handleNOOP() {
doPoll()
}
private func handleOpen(openData: String) {
guard let json = try? openData.toNSDictionary() else {
didError(reason: "Error parsing open packet")
return
}
guard let sid = json["sid"] as? String else {
didError(reason: "Open packet contained no sid")
return
}
let upgradeWs: Bool
self.sid = sid
connected = true
pongsMissed = 0
if let upgrades = json["upgrades"] as? [String] {
upgradeWs = upgrades.contains("websocket")
} else {
upgradeWs = false
}
if let pingInterval = json["pingInterval"] as? Double, let pingTimeout = json["pingTimeout"] as? Double {
self.pingInterval = pingInterval / 1000.0
self.pingTimeout = pingTimeout / 1000.0
}
if !forcePolling && !forceWebsockets && upgradeWs {
createWebsocketAndConnect()
}
sendPing()
if !forceWebsockets {
doPoll()
}
client?.engineDidOpen(reason: "Connect")
}
private func handlePong(with message: String) {
pongsMissed = 0
// We should upgrade
if message == "3probe" {
upgradeTransport()
}
}
public func parseEngineData(_ data: Data) {
DefaultSocketLogger.Logger.log("Got binary data: %@", type: "SocketEngine", args: data)
client?.parseEngineBinaryData(data.subdata(in: 1..<data.endIndex))
}
public func parseEngineMessage(_ message: String, fromPolling: Bool) {
DefaultSocketLogger.Logger.log("Got message: %@", type: logType, args: message)
let reader = SocketStringReader(message: message)
let fixedString: String
if message.hasPrefix("b4") {
return handleBase64(message: message)
}
guard let type = SocketEnginePacketType(rawValue: Int(reader.currentCharacter) ?? -1) else {
checkAndHandleEngineError(message)
return
}
if fromPolling && type != .noop && doubleEncodeUTF8 {
fixedString = fixDoubleUTF8(message)
} else {
fixedString = message
}
switch type {
case .message:
handleMessage(String(fixedString.characters.dropFirst()))
case .noop:
handleNOOP()
case .pong:
handlePong(with: fixedString)
case .open:
handleOpen(openData: String(fixedString.characters.dropFirst()))
case .close:
handleClose(fixedString)
default:
DefaultSocketLogger.Logger.log("Got unknown packet type", type: logType)
}
}
// Puts the engine back in its default state
private func resetEngine() {
closed = false
connected = false
fastUpgrade = false
polling = true
probing = false
invalidated = false
session = Foundation.URLSession(configuration: .default, delegate: sessionDelegate, delegateQueue: OperationQueue.main)
sid = ""
waitingForPoll = false
waitingForPost = false
websocket = false
}
private func sendPing() {
guard connected else { return }
// Server is not responding
if pongsMissed > pongsMissedMax {
client?.engineDidClose(reason: "Ping timeout")
return
}
guard let pingInterval = pingInterval else { return }
pongsMissed += 1
write("", withType: .ping, withData: [])
let time = DispatchTime.now() + Double(Int64(pingInterval * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC)
DispatchQueue.main.asyncAfter(deadline: time) {[weak self] in self?.sendPing() }
}
// Moves from long-polling to websockets
private func upgradeTransport() {
if ws?.isConnected ?? false {
DefaultSocketLogger.Logger.log("Upgrading transport to WebSockets", type: logType)
fastUpgrade = true
sendPollMessage("", withType: .noop, withData: [])
// After this point, we should not send anymore polling messages
}
}
/// Write a message, independent of transport.
public func write(_ msg: String, withType type: SocketEnginePacketType, withData data: [Data]) {
emitQueue.async {
guard self.connected else { return }
if self.websocket {
DefaultSocketLogger.Logger.log("Writing ws: %@ has data: %@",
type: self.logType, args: msg, data.count != 0)
self.sendWebSocketMessage(msg, withType: type, withData: data)
} else if !self.probing {
DefaultSocketLogger.Logger.log("Writing poll: %@ has data: %@",
type: self.logType, args: msg, data.count != 0)
self.sendPollMessage(msg, withType: type, withData: data)
} else {
self.probeWait.append((msg, type, data))
}
}
}
// Delegate methods
public func websocketDidConnect(socket: WebSocket) {
if !forceWebsockets {
probing = true
probeWebSocket()
} else {
connected = true
probing = false
polling = false
}
}
public func websocketDidDisconnect(socket: WebSocket, error: NSError?) {
probing = false
if closed {
client?.engineDidClose(reason: "Disconnect")
return
}
if websocket {
connected = false
websocket = false
if let reason = error?.localizedDescription {
didError(reason: reason)
} else {
client?.engineDidClose(reason: "Socket Disconnected")
}
} else {
flushProbeWait()
}
}
}
extension SocketEngine {
public func URLSession(session: URLSession, didBecomeInvalidWithError error: NSError?) {
DefaultSocketLogger.Logger.error("Engine URLSession became invalid", type: "SocketEngine")
didError(reason: "Engine URLSession became invalid")
}
}
| e57c37ec184712cbfa99b77b7a5d9787 | 31.732143 | 130 | 0.592908 | false | false | false | false |
PrashntS/sleepygeeks | refs/heads/master | Sleepy/Sleepy/RootViewController.swift | mit | 1 | //
// RootViewController.swift
// Sleepy
//
// Created by Prashant Sinha on 18/01/15.
// Copyright (c) 2015 Prashant Sinha. All rights reserved.
//
import UIKit
class RootViewController: UIViewController, UIPageViewControllerDelegate {
var pageViewController: UIPageViewController?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
// Configure the page view controller and add it as a child view controller.
self.pageViewController = UIPageViewController(transitionStyle: .PageCurl, navigationOrientation: .Horizontal, options: nil)
self.pageViewController!.delegate = self
let startingViewController: DataViewController = self.modelController.viewControllerAtIndex(0, storyboard: self.storyboard!)!
let viewControllers: NSArray = [startingViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: false, completion: {done in })
self.pageViewController!.dataSource = self.modelController
self.addChildViewController(self.pageViewController!)
self.view.addSubview(self.pageViewController!.view)
// Set the page view controller's bounds using an inset rect so that self's view is visible around the edges of the pages.
var pageViewRect = self.view.bounds
self.pageViewController!.view.frame = pageViewRect
self.pageViewController!.didMoveToParentViewController(self)
// Add the page view controller's gesture recognizers to the book view controller's view so that the gestures are started more easily.
self.view.gestureRecognizers = self.pageViewController!.gestureRecognizers
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var modelController: ModelController {
// Return the model controller object, creating it if necessary.
// In more complex implementations, the model controller may be passed to the view controller.
if _modelController == nil {
_modelController = ModelController()
}
return _modelController!
}
var _modelController: ModelController? = nil
// MARK: - UIPageViewController delegate methods
func pageViewController(pageViewController: UIPageViewController, spineLocationForInterfaceOrientation orientation: UIInterfaceOrientation) -> UIPageViewControllerSpineLocation {
// Set the spine position to "min" and the page view controller's view controllers array to contain just one view controller. Setting the spine position to 'UIPageViewControllerSpineLocationMid' in landscape orientation sets the doubleSided property to true, so set it to false here.
let currentViewController = self.pageViewController!.viewControllers[0] as UIViewController
let viewControllers: NSArray = [currentViewController]
self.pageViewController!.setViewControllers(viewControllers, direction: .Forward, animated: true, completion: {done in })
self.pageViewController!.doubleSided = false
return .Min
}
}
| f83076d965cf012df9aece67edeab8f9 | 43.847222 | 291 | 0.738619 | false | false | false | false |
letvargo/LVGSwiftAudioFileServices | refs/heads/master | Source/AudioFileType.swift | mit | 1 | //
// AudioFileType.swift
// SwiftAudioToolbox
//
// Created by doof nugget on 1/10/16.
// Copyright © 2016 letvargo. All rights reserved.
//
import Foundation
import AudioToolbox
import LVGUtilities
public enum AudioFileType: CodedPropertyType {
/// The equivalent of `kAudioFileAAC_ADTSType`.
case aac_ADTS
/// The equivalent of `kAudioFileAC3Type`.
case ac3
/// The equivalent of `kAudioFileAIFCType`.
case aifc
/// The equivalent of `kAudioFileAIFFType`.
case aiff
/// The equivalent of `kAudioFileAMRType`.
case amr
/// The equivalent of `kAudioFileCAFType`.
case caf
/// The equivalent of `kAudioFileM4AType`.
case m4A
/// The equivalent of `kAudioFileMP1Type`.
case mp1
/// The equivalent of `kAudioFileMP2Type`.
case mp2
/// The equivalent of `kAudioFileMP3Type`.
case mp3
/// The equivalent of `kAudioFileMPEG4Type`.
case mpeg4
/// The equivalent of `kAudioFileNextType`.
case neXT
/// The equivalent of `kAudioFile3GPType`.
case threeGP
/// The equivalent of `kAudioFile3GP2Type`.
case threeGP2
/// The equivalent of `kAudioFileSoundDesigner2Type`.
case soundDesigner2
/// The equivalent of `kAudioFileWAVEType`.
case wave
/// Initializes an `AudioFileType` using an `AudioFileTypeID`
/// defined by Audio File Services.
public init?(code: AudioFileTypeID) {
switch code {
case kAudioFileAIFFType : self = .aiff
case kAudioFileAIFCType : self = .aifc
case kAudioFileWAVEType : self = .wave
case kAudioFileSoundDesigner2Type : self = .soundDesigner2
case kAudioFileNextType : self = .neXT
case kAudioFileMP3Type : self = .mp3
case kAudioFileMP2Type : self = .mp2
case kAudioFileMP1Type : self = .mp1
case kAudioFileAC3Type : self = .ac3
case kAudioFileAAC_ADTSType : self = .aac_ADTS
case kAudioFileMPEG4Type : self = .mpeg4
case kAudioFileM4AType : self = .m4A
case kAudioFileCAFType : self = .caf
case kAudioFile3GPType : self = .threeGP
case kAudioFile3GP2Type : self = .threeGP2
case kAudioFileAMRType : self = .amr
default : return nil
}
}
/// The `AudioFileTypeID` associated with the `AudioFileType`.
public var code: AudioFileTypeID {
switch self {
case .aiff : return kAudioFileAIFFType
case .aifc : return kAudioFileAIFCType
case .wave : return kAudioFileWAVEType
case .soundDesigner2 : return kAudioFileSoundDesigner2Type
case .neXT : return kAudioFileNextType
case .mp3 : return kAudioFileMP3Type
case .mp2 : return kAudioFileMP2Type
case .mp1 : return kAudioFileMP1Type
case .ac3 : return kAudioFileAC3Type
case .aac_ADTS : return kAudioFileAAC_ADTSType
case .mpeg4 : return kAudioFileMPEG4Type
case .m4A : return kAudioFileM4AType
case .caf : return kAudioFileCAFType
case .threeGP : return kAudioFile3GPType
case .threeGP2 : return kAudioFile3GP2Type
case .amr : return kAudioFileAMRType
}
}
/// Returns "Audio File Services Audio File Type" for all cases.
public var domain: String {
return "Audio File Services Audio File Type"
}
/// A short description of the file type.
public var shortDescription: String {
switch self {
case .aac_ADTS: return "An Advanced Audio Coding (AAC) Audio Data Transport Stream (ADTS) file."
case .ac3: return "An AC-3 file."
case .aifc: return "An Audio Interchange File Format Compressed (AIFF-C) file."
case .aiff: return "An Audio Interchange File Format (AIFF) file."
case .amr: return "An AMR (Adaptive Multi-Rate) file suitable for compressed speech."
case .caf: return "A Core Audio File Format file."
case .neXT: return "A NeXT or Sun Microsystems file."
case .m4A: return "An M4A file."
case .mp1: return "An MPEG Audio Layer 1 (.mp1) file."
case .mp2: return "An MPEG Audio Layer 2 (.mp2) file."
case .mp3: return "An MPEG Audio Layer 3 (.mp3) file."
case .mpeg4: return "An MPEG 4 file."
case .threeGP: return "A 3GPP file, suitable for video content on GSM mobile phones."
case .threeGP2: return "A 3GPP2 file, suitable for video content on CDMA mobile phones."
case .soundDesigner2: return "A Sound Designer II file."
case .wave: return "A Microsoft WAVE file."
}
}
}
| 2f87a0174bb2f9df9cb69c3f8eaf803f | 37.918519 | 112 | 0.572707 | false | false | false | false |
danwood/Resolutionary | refs/heads/master | Sources/Acronym.swift | apache-2.0 | 1 | import StORM
import PostgresStORM
class Acronym: PostgresStORM {
var id: Int = 0
var short: String = ""
var long: String = ""
override open func table() -> String { return "acronyms" }
override func to(_ this: StORMRow) {
id = this.data["id"] as? Int ?? 0
short = this.data["short"] as? String ?? ""
long = this.data["long"] as? String ?? ""
}
func rows() -> [Acronym] {
var rows = [Acronym]()
for i in 0..<self.results.rows.count {
let row = Acronym()
row.to(self.results.rows[i])
rows.append(row)
}
return rows
}
func asDictionary() -> [String: Any] {
return [
"id": self.id,
"short": self.short,
"long": self.long
]
}
static func all() throws -> [Acronym] {
let getObj = Acronym()
try getObj.findAll()
return getObj.rows()
}
static func getAcronym(matchingId id:Int) throws -> Acronym {
let getObj = Acronym()
var findObj = [String: Any]()
findObj["id"] = "\(id)"
try getObj.find(findObj)
return getObj
}
static func getAcronyms(matchingShort short:String) throws -> [Acronym] {
let getObj = Acronym()
var findObj = [String: Any]()
findObj["short"] = short
try getObj.find(findObj)
return getObj.rows()
}
static func getAcronyms(notMatchingShort short:String) throws -> [Acronym] {
let getObj = Acronym()
try getObj.select(whereclause: "short != $1", params: [short], orderby: ["id"])
return getObj.rows()
}
}
| 5521dbcfe33a7ba3b55bd309001e0826 | 21.9375 | 83 | 0.609673 | false | false | false | false |
aKirill1942/NetRoute | refs/heads/master | NetRoute/NetRequestQueue.swift | apache-2.0 | 1 | //
// NetRequestQueue.swift
// NetRoute
//
// Created by Kirill Averkiev on 15.04.16.
// Copyright © 2016 Kirill Averkiev. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// Queue of requests.
public class NetRequestQueue: NetRouteObject {
/// MARK: Variables
/// Array of requests.
private var requests: Array<NetRequest> = []
/// Status of the queue.
private var status = NetRequestQueueStatus.stopped
/// Descriprion for converting to string.
public override var description: String {
return "\(requests)"
}
// MARK: - Working with requests.
/// Adds a new request to the queue.
/// - Warning: This method should not be used to add requests. Use `passToQueue(queue: NRRequestQueue)` of a request object.
/// - Parameter request: A request to add to the queue.
internal func add(request: NetRequest) {
// Blocking the method if queue if executing.
if status == .stopped {
// Check the priority.
switch request.priority {
// If it is low, just add the request to the end of the queue.
case .low:
requests.append(request)
// Find a place to put the request depending on its priority.
default:
let index = index(for: request.priority)
requests.insert(request, at: index)
}
} else {
// Notify about the eroor.
print("The queue is already executing!")
}
}
/// Runs all requests in the queue.
public func run() {
// Get the request.
for request in requests {
// Set the right executing status for the queue.
switch request.priority {
case .background:
status = .inBackgroundExecution
case .high:
status = .executingHigh
case .medium:
status = .executingDefault
case .low:
status = .executingLow
}
// Run the request remove it from the queue.
request.run(completionHandler: nil)
requests.remove(at: requests.index(of: request)!)
}
// Clear the status to make the queue reusable.
status = .stopped
}
// MARK: - Getting the position
/// Gets the position for the request in the queue based on priority.
/// - Parameter priority: Priority that is used to find the right position.
/// - Returns: An index of the requests array to insert the request with given priority.
private func index(for priority: NetRequestPriority) -> Int {
// A flag to know when the place is found.
var found = false
// Do the search.
for index in 0..<requests.count {
if requests[index].priority.rawValue < priority.rawValue {
found = true
return index
}
}
// Handle if a place not found.
if !found {
return requests.count - 1
}
}
}
| 2bb341e29085c8772913543b18297e26 | 27.244604 | 128 | 0.553999 | false | false | false | false |
JGiola/swift | refs/heads/main | stdlib/public/core/DurationProtocol.swift | apache-2.0 | 9 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that defines a duration for a given `InstantProtocol` type.
@available(SwiftStdlib 5.7, *)
public protocol DurationProtocol: Comparable, AdditiveArithmetic, Sendable {
static func / (_ lhs: Self, _ rhs: Int) -> Self
static func /= (_ lhs: inout Self, _ rhs: Int)
static func * (_ lhs: Self, _ rhs: Int) -> Self
static func *= (_ lhs: inout Self, _ rhs: Int)
static func / (_ lhs: Self, _ rhs: Self) -> Double
}
@available(SwiftStdlib 5.7, *)
extension DurationProtocol {
@available(SwiftStdlib 5.7, *)
public static func /= (_ lhs: inout Self, _ rhs: Int) {
lhs = lhs / rhs
}
@available(SwiftStdlib 5.7, *)
public static func *= (_ lhs: inout Self, _ rhs: Int) {
lhs = lhs * rhs
}
}
| 01a2f011fbcff158724d2f6e05fbc875 | 34.628571 | 80 | 0.580593 | false | false | false | false |
adamshin/SwiftReorder | refs/heads/master | Source/ReorderController+SnapshotView.swift | mit | 1 | //
// Copyright (c) 2016 Adam Shin
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
extension ReorderController {
func createSnapshotViewForCell(at indexPath: IndexPath) {
guard let tableView = tableView, let superview = tableView.superview else { return }
removeSnapshotView()
tableView.reloadRows(at: [indexPath], with: .none)
guard let cell = tableView.cellForRow(at: indexPath) else { return }
let cellFrame = tableView.convert(cell.frame, to: superview)
UIGraphicsBeginImageContextWithOptions(cell.bounds.size, false, 0)
cell.layer.render(in: UIGraphicsGetCurrentContext()!)
let cellImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
let view = UIImageView(image: cellImage)
view.frame = cellFrame
view.layer.masksToBounds = false
view.layer.opacity = Float(cellOpacity)
view.layer.transform = CATransform3DMakeScale(cellScale, cellScale, 1)
view.layer.shadowColor = shadowColor.cgColor
view.layer.shadowOpacity = Float(shadowOpacity)
view.layer.shadowRadius = shadowRadius
view.layer.shadowOffset = shadowOffset
superview.addSubview(view)
snapshotView = view
}
func removeSnapshotView() {
snapshotView?.removeFromSuperview()
snapshotView = nil
}
func updateSnapshotViewPosition() {
guard case .reordering(let context) = reorderState, let tableView = tableView else { return }
var newCenterY = context.touchPosition.y + context.snapshotOffset
let safeAreaFrame: CGRect
if #available(iOS 11, *) {
safeAreaFrame = tableView.frame.inset(by: tableView.safeAreaInsets)
} else {
safeAreaFrame = tableView.frame.inset(by: tableView.scrollIndicatorInsets)
}
newCenterY = min(newCenterY, safeAreaFrame.maxY)
newCenterY = max(newCenterY, safeAreaFrame.minY)
snapshotView?.center.y = newCenterY
}
func animateSnapshotViewIn() {
guard let snapshotView = snapshotView else { return }
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fromValue = 1
opacityAnimation.toValue = cellOpacity
opacityAnimation.duration = animationDuration
let shadowAnimation = CABasicAnimation(keyPath: "shadowOpacity")
shadowAnimation.fromValue = 0
shadowAnimation.toValue = shadowOpacity
shadowAnimation.duration = animationDuration
let transformAnimation = CABasicAnimation(keyPath: "transform.scale")
transformAnimation.fromValue = 1
transformAnimation.toValue = cellScale
transformAnimation.duration = animationDuration
transformAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
snapshotView.layer.add(opacityAnimation, forKey: nil)
snapshotView.layer.add(shadowAnimation, forKey: nil)
snapshotView.layer.add(transformAnimation, forKey: nil)
}
func animateSnapshotViewOut() {
guard let snapshotView = snapshotView else { return }
let opacityAnimation = CABasicAnimation(keyPath: "opacity")
opacityAnimation.fromValue = cellOpacity
opacityAnimation.toValue = 1
opacityAnimation.duration = animationDuration
let shadowAnimation = CABasicAnimation(keyPath: "shadowOpacity")
shadowAnimation.fromValue = shadowOpacity
shadowAnimation.toValue = 0
shadowAnimation.duration = animationDuration
let transformAnimation = CABasicAnimation(keyPath: "transform.scale")
transformAnimation.fromValue = cellScale
transformAnimation.toValue = 1
transformAnimation.duration = animationDuration
transformAnimation.timingFunction = CAMediaTimingFunction(name: .easeInEaseOut)
snapshotView.layer.add(opacityAnimation, forKey: nil)
snapshotView.layer.add(shadowAnimation, forKey: nil)
snapshotView.layer.add(transformAnimation, forKey: nil)
snapshotView.layer.opacity = 1
snapshotView.layer.shadowOpacity = 0
snapshotView.layer.transform = CATransform3DIdentity
}
}
| 831e14cc5b874c557cdb207c6fc266ed | 40.318182 | 101 | 0.690869 | false | false | false | false |
SteveRohrlack/CitySimCore | refs/heads/master | src/Model/TileableAttributes/MapStatistic.swift | mit | 1 | //
// MapStatistic.swift
// CitySimCore
//
// Created by Steve Rohrlack on 17.05.16.
// Copyright © 2016 Steve Rohrlack. All rights reserved.
//
import Foundation
/**
provides specific statistic types
each type consists of:
- radius: Int
- value: Int
*/
public enum MapStatistic {
/// regards the Landvalue statistic layer
case Landvalue(radius: Int, value: Int)
/// regards the Noise statistic layer
case Noise(radius: Int, value: Int)
/// regards the Firesafety statistic layer
case Firesafety(radius: Int, value: Int)
/// regards the Crime statistic layer
case Crime(radius: Int, value: Int)
/// regards the Health statistic layer
case Health(radius: Int, value: Int)
}
/// MapStatistic is Equatable
extension MapStatistic: Equatable {
}
/**
operator "==" to allow comparing MapStatistics
- parameter lhs: MapStatistic
- parameter rhs: MapStatistic
- returns: comparison result
*/
public func == (lhs: MapStatistic, rhs: MapStatistic) -> Bool {
switch (lhs, rhs) {
case (.Landvalue(let a1, let b1), .Landvalue(let a2, let b2)) where a1 == a2 && b1 == b2:
return true
case (.Noise(let a1, let b1), .Landvalue(let a2, let b2)) where a1 == a2 && b1 == b2:
return true
case (.Firesafety(let a1, let b1), .Landvalue(let a2, let b2)) where a1 == a2 && b1 == b2:
return true
case (.Crime(let a1, let b1), .Landvalue(let a2, let b2)) where a1 == a2 && b1 == b2:
return true
case (.Health(let a1, let b1), .Landvalue(let a2, let b2)) where a1 == a2 && b1 == b2:
return true
default:
return false
}
} | d104b7dfb7e0a013186cb7ae5414e90b | 24.676923 | 94 | 0.628897 | false | false | false | false |
CoderST/DYZB | refs/heads/master | DYZB/DYZB/Class/Room/Controller/ShowAnchorListVC.swift | mit | 1 | //
// ShowAnchorListVC.swift
// DYZB
//
// Created by xiudou on 16/11/5.
// Copyright © 2016年 xiudo. All rights reserved.
//
import UIKit
import MJRefresh
import SVProgressHUD
class ShowAnchorListVC: UIViewController {
// MARK:- 属性
// @IBOutlet weak var collectionView: UICollectionView!
// MARK:- 常量
fileprivate let ShowAnchorListCellInden = "ShowAnchorListCellInden"
// MARK:- 变量
fileprivate var page : Int = 1
// MARK:- 懒加载
fileprivate let roomAnchorVM : RoomAnchorVM = RoomAnchorVM()
fileprivate let collectionView : UICollectionView = {
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.itemSize = CGSize(width: sScreenW, height: sScreenH - sNavatationBarH - sStatusBarH)
let collectionView = UICollectionView(frame: CGRect(x: 0, y: 0, width: sScreenW, height: sScreenH), collectionViewLayout: layout)
collectionView.backgroundColor = UIColor.white
return collectionView
}()
@IBAction func quickTopButton(_ sender: UIButton) {
UIView.animate(withDuration: 0.5, animations: { () -> Void in
let indexPath = IndexPath(item: 0, section: 0)
self.collectionView.scrollToItem(at: indexPath, at: .top, animated: true)
})
}
// MARK:- 系统回调
override func viewDidLoad() {
super.viewDidLoad()
setupCollectionView()
setupCollectionDownReloadData()
setupCollectionUpLoadMore()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
SVProgressHUD.dismiss()
}
func setupCollectionDownReloadData(){
let refreshGifHeader = DYRefreshGifHeader(refreshingTarget: self, refreshingAction: #selector(ShowAnchorListVC.downReloadData))
refreshGifHeader?.stateLabel?.isHidden = true
refreshGifHeader?.setTitle("", for: .pulling)
refreshGifHeader?.setTitle("", for: .idle)
collectionView.mj_header = refreshGifHeader
collectionView.mj_header.isAutomaticallyChangeAlpha = true
collectionView.mj_header.beginRefreshing()
}
func setupCollectionUpLoadMore(){
// MJRefreshAutoFooterIdleText
let foot = DYRefreshAutoNormalFooter(refreshingTarget: self, refreshingAction: #selector(ShowAnchorListVC.upLoadMore))
collectionView.mj_footer = foot
}
}
// MARK:- 网络请求
extension ShowAnchorListVC {
// 下拉刷新
func downReloadData(){
page = 1
roomAnchorVM.getRoomAnchorData(page, finishCallBack: { () -> () in
self.collectionView.mj_header.endRefreshing()
self.collectionView.reloadData()
}) { () -> () in
print("没有啦")
}
}
// 上拉加载更多
func upLoadMore(){
page += 1
roomAnchorVM.getRoomAnchorData(page, finishCallBack: { () -> () in
self.collectionView.mj_footer.endRefreshing()
self.collectionView.reloadData()
}) { () -> () in
print("没有数据了")
SVProgressHUD.setDefaultStyle(.dark)
SVProgressHUD.showInfo(withStatus: "没有了哦~~")
}
}
}
// MARK:- UI设置
extension ShowAnchorListVC {
// 1 初始化collectionView
fileprivate func setupCollectionView(){
view.addSubview(collectionView)
collectionView.register(UINib(nibName: "ShowAnchorListCell", bundle: nil), forCellWithReuseIdentifier: ShowAnchorListCellInden)
collectionView.dataSource = self
collectionView.delegate = self
}
}
// MARK:- UICollectionViewDataSource
extension ShowAnchorListVC : UICollectionViewDataSource{
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return roomAnchorVM.roomYKModelArray.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ShowAnchorListCellInden, for: indexPath) as! ShowAnchorListCell
let model = roomAnchorVM.roomYKModelArray[indexPath.item]
cell.anchorModel = model
return cell
}
}
// MARK:- UICollectionViewDelegate
extension ShowAnchorListVC : UICollectionViewDelegate {
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
// 1 创建主播界面
let showAnchorVC = ShowAnchorVC()
// 2 传递主播数组
showAnchorVC.getShowDatasAndIndexPath(roomAnchorVM.roomYKModelArray, indexPath: indexPath)
// 3 弹出主播界面
present(showAnchorVC, animated: true, completion: nil)
}
}
| 7de94f3ccf08f07e46a529c719c6d6fe | 29.85 | 138 | 0.646272 | false | false | false | false |
binarylevel/Tinylog-iOS | refs/heads/master | Tinylog/Views/TLIListsFooterView.swift | mit | 1 | //
// TLIListsFooterView.swift
// Tinylog
//
// Created by Spiros Gerokostas on 18/10/15.
// Copyright © 2015 Spiros Gerokostas. All rights reserved.
//
import UIKit
import TTTAttributedLabel
class TLIListsFooterView: UIView {
var infoLabel:TTTAttributedLabel? = {
let infoLabel = TTTAttributedLabel.newAutoLayoutView()
infoLabel.font = UIFont.regularFontWithSize(14.0)
infoLabel.textColor = UIColor.tinylogTextColor()
infoLabel.verticalAlignment = TTTAttributedLabelVerticalAlignment.Top
infoLabel.text = ""
return infoLabel
}()
var borderLineView:UIView = {
let borderLineView = UIView.newAutoLayoutView()
borderLineView.backgroundColor = UIColor(red: 213.0 / 255.0, green: 213.0 / 255.0, blue: 213.0 / 255.0, alpha: 1.0)
return borderLineView
}()
var currentText:String?
let footerView:UIView = UIView.newAutoLayoutView()
var didSetupContraints = false
lazy var addListButton:TLIAddListButton? = {
let addListButton = TLIAddListButton.newAutoLayoutView()
return addListButton
}()
lazy var archiveButton:TLIArchiveButton? = {
let archiveButton = TLIArchiveButton.newAutoLayoutView()
return archiveButton
}()
override init(frame: CGRect) {
super.init(frame: frame)
footerView.backgroundColor = UIColor(red: 244.0 / 255.0, green: 244.0 / 255.0, blue: 244.0 / 255.0, alpha: 1.0)
self.addSubview(footerView)
self.addSubview(borderLineView)
self.addSubview(infoLabel!)
self.addSubview(addListButton!)
self.addSubview(archiveButton!)
updateInfoLabel("")
setNeedsUpdateConstraints()
}
func updateInfoLabel(str:String) {
currentText = str
infoLabel?.text = str
setNeedsUpdateConstraints()
}
override func layoutSubviews() {
super.layoutSubviews()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func updateConstraints() {
let smallPadding:CGFloat = 16.0
if !didSetupContraints {
footerView.autoMatchDimension(.Width, toDimension: .Width, ofView: self)
footerView.autoSetDimension(.Height, toSize: 51.0)
footerView.autoPinEdgeToSuperviewEdge(.Bottom)
borderLineView.autoMatchDimension(.Width, toDimension: .Width, ofView: self)
borderLineView.autoSetDimension(.Height, toSize: 0.5)
borderLineView.autoPinEdgeToSuperviewEdge(.Top)
addListButton?.autoSetDimensionsToSize(CGSize(width: 18.0, height: 18.0))
addListButton?.autoAlignAxisToSuperviewAxis(.Horizontal)
addListButton?.autoPinEdgeToSuperviewEdge(.Left, withInset: smallPadding)
archiveButton?.autoSetDimensionsToSize(CGSize(width: 28.0, height: 26.0))
archiveButton?.autoAlignAxisToSuperviewAxis(.Horizontal)
archiveButton?.autoPinEdgeToSuperviewEdge(.Right, withInset: smallPadding)
infoLabel?.autoCenterInSuperview()
didSetupContraints = true
}
super.updateConstraints()
}
}
| 6f76e6f905ae3853d0820383e4e16a5f | 31.84466 | 123 | 0.6376 | false | false | false | false |
LuAndreCast/iOS_WatchProjects | refs/heads/master | watchOS3/HealthKit Workout/Utilities.swift | mit | 1 | /*
Copyright (C) 2016 Apple Inc. All Rights Reserved.
See LICENSE.txt for this sample’s licensing information
Abstract:
Utilites for workout management and string formatting.
*/
import Foundation
import HealthKit
//MARK: -
@objc enum workoutState:Int {
case running
case paused
case notStarted
case ended
func toString()->String
{
switch self {
case .running:
return "running"
case .paused:
return "paused"
case .notStarted:
return "notStarted"
case .ended:
return "ended"
}
}//eom
}
//MARK: -
func computeDurationOfWorkout(withEvents workoutEvents: [HKWorkoutEvent]?,
startDate: Date?,
endDate: Date?) -> TimeInterval
{
var duration = 0.0
if var lastDate = startDate {
var paused = false
if let events = workoutEvents {
for event in events {
switch event.type {
case .pause:
duration += event.date.timeIntervalSince(lastDate)
paused = true
case .resume:
lastDate = event.date
paused = false
default:
continue
}
}
}
if !paused {
if let end = endDate {
duration += end.timeIntervalSince(lastDate)
} else {
duration += NSDate().timeIntervalSince(lastDate)
}
}
}
print("\(duration)")
return duration
}
func format(duration: TimeInterval) -> String {
let durationFormatter = DateComponentsFormatter()
durationFormatter.unitsStyle = .positional
durationFormatter.allowedUnits = [.second, .minute, .hour]
durationFormatter.zeroFormattingBehavior = .pad
if let string = durationFormatter.string(from: duration) {
return string
} else {
return ""
}
}
func format(activityType: HKWorkoutActivityType) -> String {
let formattedType : String
switch activityType {
case .walking:
formattedType = "Walking"
case .running:
formattedType = "Running"
case .hiking:
formattedType = "Hiking"
default:
formattedType = "Workout"
}
return formattedType
}
func format(locationType: HKWorkoutSessionLocationType) -> String {
let formattedType : String
switch locationType {
case .indoor:
formattedType = "Indoor"
case .outdoor:
formattedType = "Outdoor"
case .unknown:
formattedType = "Unknown"
}
return formattedType
}
| 91ac987980ee4aed4e94d632518db144 | 21.789063 | 74 | 0.522797 | false | false | false | false |
ianyh/Highball | refs/heads/master | Highball/PostLinkTableViewCell.swift | mit | 1 | //
// PostLinkTableViewCell.swift
// Highball
//
// Created by Ian Ynda-Hummel on 8/31/14.
// Copyright (c) 2014 ianynda. All rights reserved.
//
import UIKit
import Cartography
import WCFastCell
class PostLinkTableViewCell: WCFastCell {
var bubbleView: UIView!
var titleLabel: UILabel!
var urlLabel: UILabel!
var post: Post? {
didSet {
guard let post = post else {
return
}
self.titleLabel.text = post.title
self.urlLabel.text = post.url.host
}
}
override required init(style: UITableViewCellStyle, reuseIdentifier: String!) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
setUpCell()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setUpCell()
}
func setUpCell() {
bubbleView = UIView()
titleLabel = UILabel()
urlLabel = UILabel()
bubbleView.backgroundColor = UIColor(red: 86.0/255.0, green: 188.0/255.0, blue: 138.0/255.0, alpha: 1)
bubbleView.clipsToBounds = true
titleLabel.font = UIFont.boldSystemFontOfSize(19)
titleLabel.textColor = UIColor.whiteColor()
titleLabel.numberOfLines = 0
titleLabel.textAlignment = NSTextAlignment.Center
urlLabel.font = UIFont.systemFontOfSize(12)
urlLabel.textColor = UIColor(white: 1, alpha: 0.7)
urlLabel.numberOfLines = 1
urlLabel.textAlignment = NSTextAlignment.Center
contentView.addSubview(bubbleView)
contentView.addSubview(titleLabel)
contentView.addSubview(urlLabel)
constrain(bubbleView, contentView) { bubbleView, contentView in
bubbleView.edges == contentView.edges
}
constrain(titleLabel, bubbleView) { titleLabel, bubbleView in
titleLabel.left == bubbleView.left + 10
titleLabel.right == bubbleView.right - 10
titleLabel.top == bubbleView.top + 14
}
constrain(urlLabel, titleLabel, bubbleView) { urlLabel, titleLabel, bubbleView in
urlLabel.left == bubbleView.left + 20
urlLabel.right == bubbleView.right - 20
urlLabel.top == titleLabel.bottom + 4
urlLabel.height == 16
}
}
class func heightForPost(post: Post!, width: CGFloat!) -> CGFloat {
let extraHeight: CGFloat = 14 + 4 + 16 + 14
let modifiedWidth = width - 16
let constrainedSize = CGSize(width: modifiedWidth, height: CGFloat.max)
let titleAttributes = [ NSFontAttributeName : UIFont.boldSystemFontOfSize(19) ]
if let title = post.title as NSString? {
let titleRect = title.boundingRectWithSize(constrainedSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: titleAttributes, context: nil)
return extraHeight + ceil(titleRect.size.height)
} else {
let title = "" as NSString
let titleRect = title.boundingRectWithSize(constrainedSize, options: NSStringDrawingOptions.UsesLineFragmentOrigin, attributes: titleAttributes, context: nil)
return extraHeight + ceil(titleRect.size.height)
}
}
}
| b1d7bfba86496aefc60c174f2cd35c36 | 28.34375 | 161 | 0.738729 | false | false | false | false |
eTilbudsavis/native-ios-eta-sdk | refs/heads/master | Demos/SharedSource/PublicationListContentsViewController.swift | mit | 1 | //
// ┌────┬─┐ ┌─────┐
// │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐
// ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │
// └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘
// └─┘
//
// Copyright (c) 2019 ShopGun. All rights reserved.
import UIKit
import ShopGunSDK
class PublicationListContentsViewController: UITableViewController {
let publications: [CoreAPI.PagedPublication]
let shouldOpenIncito: (CoreAPI.PagedPublication) -> Void
let shouldOpenPagedPub: (CoreAPI.PagedPublication) -> Void
init(publications: [CoreAPI.PagedPublication],
shouldOpenIncito: @escaping (CoreAPI.PagedPublication) -> Void,
shouldOpenPagedPub: @escaping (CoreAPI.PagedPublication) -> Void
) {
self.publications = publications
self.shouldOpenIncito = shouldOpenIncito
self.shouldOpenPagedPub = shouldOpenPagedPub
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.register(PublicationListCell.self, forCellReuseIdentifier: "PublicationListCell")
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return publications.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let publication = publications[indexPath.row]
let hasIncito = publication.incitoId != nil
let cell = tableView.dequeueReusableCell(withIdentifier: "PublicationListCell", for: indexPath) as! PublicationListCell
cell.selectionStyle = .none
cell.textLabel?.text = publication.branding.name
cell.incitoPubButton.isHidden = !hasIncito
cell.didTapIncitoButton = { [weak self] in
self?.shouldOpenIncito(publication)
}
cell.didTapPagedPubButton = { [weak self] in
self?.shouldOpenPagedPub(publication)
}
return cell
}
}
class PublicationListCell: UITableViewCell {
var didTapIncitoButton: (() -> Void)?
var didTapPagedPubButton: (() -> Void)?
lazy var incitoPubButton: UIButton = {
let btn = UIButton()
btn.setTitle("Incito", for: .normal)
btn.backgroundColor = .orange
btn.setTitleColor(.white, for: .normal)
btn.layer.cornerRadius = 4
btn.contentEdgeInsets = UIEdgeInsets(top: 4, left: 6, bottom: 4, right: 6)
btn.addTarget(self, action: #selector(didTapIncito(_:)), for: .touchUpInside)
return btn
}()
lazy var pagedPubButton: UIButton = {
let btn = UIButton()
btn.setTitle("PDF", for: .normal)
btn.backgroundColor = .orange
btn.setTitleColor(.white, for: .normal)
btn.layer.cornerRadius = 4
btn.contentEdgeInsets = UIEdgeInsets(top: 4, left: 6, bottom: 4, right: 6)
btn.addTarget(self, action: #selector(didTapPagedPub(_:)), for: .touchUpInside)
return btn
}()
public override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: .subtitle, reuseIdentifier: reuseIdentifier)
let stack = UIStackView(arrangedSubviews: [
incitoPubButton, pagedPubButton
])
stack.spacing = 4
stack.axis = .horizontal
stack.alignment = .center
stack.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(stack)
NSLayoutConstraint.activate([
stack.trailingAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.trailingAnchor),
stack.topAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.topAnchor),
stack.bottomAnchor.constraint(equalTo: self.contentView.layoutMarginsGuide.bottomAnchor)
])
}
public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) }
@objc private func didTapIncito(_ sender: UIButton) {
didTapIncitoButton?()
}
@objc private func didTapPagedPub(_ sender: UIButton) {
didTapPagedPubButton?()
}
}
| d1b3e8dae373ffb9537c90aabeb8fce9 | 34.719008 | 127 | 0.62633 | false | false | false | false |
naokits/bluemix-swift-demo-ios | refs/heads/master | Bluemix/bluemix-mobile-app-demo/client/Pods/BMSCore/Source/Network Requests/BMSClient.swift | mit | 2 | /*
* Copyright 2016 IBM Corp.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
A singleton that serves as an entry point to Bluemix client-server communication.
*/
public class BMSClient {
// MARK: Constants
/// The southern United States Bluemix region
/// - Note: Use this in the `BMSClient initializeWithBluemixAppRoute` method.
public static let REGION_US_SOUTH = ".ng.bluemix.net"
/// The United Kingdom Bluemix region
/// - Note: Use this in the `BMSClient initializeWithBluemixAppRoute` method.
public static let REGION_UK = ".eu-gb.bluemix.net"
/// The Sydney Bluemix region
/// - Note: Use this in the `BMSClient initializeWithBluemixAppRoute` method.
public static let REGION_SYDNEY = ".au-syd.bluemix.net"
// MARK: Properties (API)
/// This singleton should be used for all `BMSClient` activity
public static let sharedInstance = BMSClient()
/// Specifies the base backend URL
public private(set) var bluemixAppRoute: String?
// Specifies the bluemix region
public private(set) var bluemixRegion: String?
/// Specifies the backend application id
public private(set) var bluemixAppGUID: String?
/// Specifies the default timeout (in seconds) for all BMS network requests.
public var defaultRequestTimeout: Double = 20.0
public var authorizationManager: AuthorizationManager
// MARK: Initializers
/**
The required intializer for the `BMSClient` class.
Sets the base URL for the authorization server.
- Note: The `backendAppRoute` and `backendAppGUID` parameters are not required to use the `BMSAnalytics` framework.
- parameter backendAppRoute: The base URL for the authorization server
- parameter backendAppGUID: The GUID of the Bluemix application
- parameter bluemixRegion: The region where your Bluemix application is hosted. Use one of the `BMSClient.REGION` constants.
*/
public func initializeWithBluemixAppRoute(bluemixAppRoute: String?, bluemixAppGUID: String?, bluemixRegion: String) {
self.bluemixAppRoute = bluemixAppRoute
self.bluemixAppGUID = bluemixAppGUID
self.bluemixRegion = bluemixRegion
}
private init() {
self.authorizationManager = BaseAuthorizationManager()
} // Prevent users from using BMSClient() initializer - They must use BMSClient.sharedInstance
}
| c4b6f51e2b49f3c793e44833a0e88aeb | 37.910256 | 141 | 0.692916 | false | false | false | false |
h-n-y/UICollectionView-TheCompleteGuide | refs/heads/master | chapter-3/Survey/Survey/CollectionViewCell.swift | mit | 1 |
import UIKit
class CollectionViewCell: UICollectionViewCell {
// MARK: Instance
var image: UIImage? = nil {
didSet {
imageView.image = image
}
}
private let imageView: UIImageView
override init(frame: CGRect) {
imageView = UIImageView(frame: CGRectZero)
imageView.backgroundColor = UIColor.blackColor()
//imageView.contentMode = .ScaleAspectFit
super.init(frame: frame)
self.contentView.addSubview(imageView)
//imageView.frame = CGRectInset(self.contentView.bounds, 30, 10)
imageView.constrainToEdgesOfContainerWithInset(10.0)
let selectedBackgroundView = CollectionViewCell.newSelectedBackgroundView()
self.selectedBackgroundView = selectedBackgroundView
self.backgroundColor = UIColor.whiteColor()
}
required init?(coder aDecoder: NSCoder) {
imageView = CollectionViewCell.newImageView()
super.init(coder: aDecoder)
self.contentView.addSubview(imageView)
//imageView.frame = CGRectInset(self.contentView.bounds, 30, 10)
imageView.constrainToEdgesOfContainerWithInset(10.0)
let selectedBackgroundView = CollectionViewCell.newSelectedBackgroundView()
self.selectedBackgroundView = selectedBackgroundView
self.backgroundColor = UIColor.whiteColor()
}
override func prepareForReuse() {
super.prepareForReuse()
image = nil
self.selected = false
//imageView.constrainToEdgesOfContainerWithInset(10)
}
func setDisabled(disabled: Bool) {
self.contentView.alpha = disabled ? 0.5 : 1.0
self.backgroundColor = disabled ? UIColor.grayColor() : UIColor.whiteColor()
}
// MARK: Class
private static func newImageView() -> UIImageView {
let imageView = UIImageView(frame: CGRectZero)
imageView.backgroundColor = UIColor.blackColor()
return imageView
}
private static func newSelectedBackgroundView() -> UIView {
let selectedBackgroundView = UIView(frame: CGRectZero)
selectedBackgroundView.backgroundColor = UIColor.orangeColor()
return selectedBackgroundView
}
}
// MARK: - UIView Extension ( Constraints )
extension UIView {
/// Constrains `self`'s edges to its superview's edges.
func constrainToEdgesOfContainer() {
self.constrainToEdgesOfContainerWithInset(0.0)
}
/// Constrains `self` such that its edges are inset from its `superview`'s edges by `inset`.
func constrainToEdgesOfContainerWithInset(inset: CGFloat) {
self.constrainToEdgesOfContainerWithInsets(topBottom: inset, leftRight: inset)
}
func constrainToEdgesOfContainerWithInsets(topBottom y: CGFloat, leftRight x: CGFloat) {
guard let superview = self.superview else { print("View does not have a superview."); return }
self.translatesAutoresizingMaskIntoConstraints = false
self.topAnchor.constraintEqualToAnchor(superview.topAnchor, constant: y).active = true
self.bottomAnchor.constraintEqualToAnchor(superview.bottomAnchor, constant: -y).active = true
self.leftAnchor.constraintEqualToAnchor(superview.leftAnchor, constant: x).active = true
self.rightAnchor.constraintEqualToAnchor(superview.rightAnchor, constant: -x).active = true
}
}
| 75cad513cb109637d6d5d4717730f865 | 33.792079 | 102 | 0.670176 | false | false | false | false |
tylerbrockett/cse394-principles-of-mobile-applications | refs/heads/master | lab-3/lab-3/lab-3/Location.swift | mit | 1 | /*
* @author Tyler Brockett
* @project CSE 394 Lab 4
* @version February 16, 2016
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Tyler Brockett
*
* 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
class Location {
var name:String = ""
var image:String = ""
var description:String = ""
init(name:String, image:String, description:String){
self.name = name
self.image = image
self.description = description
}
func getName() -> String {
return self.name
}
func getImage() -> String {
return self.image
}
func getDescription() -> String {
return self.description
}
} | a33d8605244bcdeb3a5e70c0bc82cf92 | 29.561404 | 81 | 0.692131 | false | false | false | false |
OscarSwanros/swift | refs/heads/master | test/Sanitizers/tsan-ignores-arc-locks.swift | apache-2.0 | 11 | // RUN: %target-build-swift -target %sanitizers-target-triple -sanitize=thread %s -o %t_binary
// RUN: %env-TSAN_OPTIONS=ignore_interceptors_accesses=1:halt_on_error=1 %target-run %t_binary
// REQUIRES: executable_test
// REQUIRES: tsan_runtime
// REQUIRES: objc_interop
// Check that TSan ignores the retain count update locks in the runtime.
import Foundation
public class Dummy {
func doNothing() {
}
}
public class DummyNSObject : NSObject {
func doNothing() {
}
}
public class RaceRunner : NSObject {
static var g: Int = 0
static var staticSwiftMember: Dummy = Dummy()
static var staticNSObjectMember: DummyNSObject = DummyNSObject()
var swiftMember: Dummy
var nsObjectMember: DummyNSObject
override init() {
swiftMember = Dummy()
nsObjectMember = DummyNSObject()
}
func triggerRace() {
// Add accesses that potentially lock in Swift runtime.
swiftMember.doNothing()
nsObjectMember.doNothing()
RaceRunner.staticSwiftMember.doNothing()
RaceRunner.staticNSObjectMember.doNothing()
RaceRunner.g = RaceRunner.g + 1
// Add accesses that potentially lock in Swift runtime.
swiftMember.doNothing()
nsObjectMember.doNothing()
RaceRunner.staticSwiftMember.doNothing()
RaceRunner.staticNSObjectMember.doNothing()
}
}
// Execute concurrently.
import StdlibUnittest
var RaceTestSuite = TestSuite("t")
RaceTestSuite
.test("test_tsan_ignores_arc_locks")
.crashOutputMatches("ThreadSanitizer: data race")
.code {
expectCrashLater()
runRaceTest(trials: 1) {
let RaceRunnerInstance: RaceRunner = RaceRunner()
RaceRunnerInstance.triggerRace()
}
}
runAllTests()
| 13ccef54252883c0339ce9962c6c92ad | 24.692308 | 94 | 0.726946 | false | true | false | false |
codestergit/swift | refs/heads/master | test/SILGen/errors.swift | apache-2.0 | 2 | // RUN: %target-swift-frontend -parse-stdlib -emit-silgen -verify -primary-file %s %S/Inputs/errors_other.swift | %FileCheck %s
import Swift
class Cat {}
enum HomeworkError : Error {
case TooHard
case TooMuch
case CatAteIt(Cat)
}
func someValidPointer<T>() -> UnsafePointer<T> { fatalError() }
func someValidPointer<T>() -> UnsafeMutablePointer<T> { fatalError() }
// CHECK: sil hidden @_T06errors10make_a_cat{{.*}}F : $@convention(thin) () -> (@owned Cat, @error Error) {
// CHECK: [[T0:%.*]] = function_ref @_T06errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat
// CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type
// CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]])
// CHECK-NEXT: return [[T2]] : $Cat
func make_a_cat() throws -> Cat {
return Cat()
}
// CHECK: sil hidden @_T06errors15dont_make_a_cat{{.*}}F : $@convention(thin) () -> (@owned Cat, @error Error) {
// CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError
// CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error
// CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type
// CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooHard!enumelt
// CHECK-NEXT: store [[T1]] to [init] [[ADDR]]
// CHECK-NEXT: builtin "willThrow"
// CHECK-NEXT: throw [[BOX]]
func dont_make_a_cat() throws -> Cat {
throw HomeworkError.TooHard
}
// CHECK: sil hidden @_T06errors11dont_return{{.*}}F : $@convention(thin) <T> (@in T) -> (@out T, @error Error) {
// CHECK: [[BOX:%.*]] = alloc_existential_box $Error, $HomeworkError
// CHECK-NEXT: [[ADDR:%.*]] = project_existential_box $HomeworkError in [[BOX]] : $Error
// CHECK-NEXT: [[T0:%.*]] = metatype $@thin HomeworkError.Type
// CHECK-NEXT: [[T1:%.*]] = enum $HomeworkError, #HomeworkError.TooMuch!enumelt
// CHECK-NEXT: store [[T1]] to [init] [[ADDR]]
// CHECK-NEXT: builtin "willThrow"
// CHECK-NEXT: destroy_addr %1 : $*T
// CHECK-NEXT: throw [[BOX]]
func dont_return<T>(_ argument: T) throws -> T {
throw HomeworkError.TooMuch
}
// CHECK: sil hidden @_T06errors16all_together_nowAA3CatCSbF : $@convention(thin) (Bool) -> @owned Cat {
// CHECK: bb0(%0 : $Bool):
// CHECK: [[DR_FN:%.*]] = function_ref @_T06errors11dont_return{{.*}} :
// CHECK-NEXT: [[RET_TEMP:%.*]] = alloc_stack $Cat
// Branch on the flag.
// CHECK: cond_br {{%.*}}, [[FLAG_TRUE:bb[0-9]+]], [[FLAG_FALSE:bb[0-9]+]]
// In the true case, call make_a_cat().
// CHECK: [[FLAG_TRUE]]:
// CHECK: [[MAC_FN:%.*]] = function_ref @_T06errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[MAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[MAC_NORMAL:bb[0-9]+]], error [[MAC_ERROR:bb[0-9]+]]
// CHECK: [[MAC_NORMAL]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: br [[TERNARY_CONT:bb[0-9]+]]([[T0]] : $Cat)
// In the false case, call dont_make_a_cat().
// CHECK: [[FLAG_FALSE]]:
// CHECK: [[DMAC_FN:%.*]] = function_ref @_T06errors15dont_make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[DMAC_FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[DMAC_NORMAL:bb[0-9]+]], error [[DMAC_ERROR:bb[0-9]+]]
// CHECK: [[DMAC_NORMAL]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: br [[TERNARY_CONT]]([[T0]] : $Cat)
// Merge point for the ternary operator. Call dont_return with the result.
// CHECK: [[TERNARY_CONT]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: [[ARG_TEMP:%.*]] = alloc_stack $Cat
// CHECK-NEXT: store [[T0]] to [init] [[ARG_TEMP]]
// CHECK-NEXT: try_apply [[DR_FN]]<Cat>([[RET_TEMP]], [[ARG_TEMP]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[DR_NORMAL:bb[0-9]+]], error [[DR_ERROR:bb[0-9]+]]
// CHECK: [[DR_NORMAL]]({{%.*}} : $()):
// CHECK-NEXT: dealloc_stack [[ARG_TEMP]]
// CHECK-NEXT: [[T0:%.*]] = load [take] [[RET_TEMP]] : $*Cat
// CHECK-NEXT: dealloc_stack [[RET_TEMP]]
// CHECK-NEXT: br [[RETURN:bb[0-9]+]]([[T0]] : $Cat)
// Return block.
// CHECK: [[RETURN]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: return [[T0]] : $Cat
// Catch dispatch block.
// CHECK: [[CATCH:bb[0-9]+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[SRC_TEMP:%.*]] = alloc_stack $Error
// CHECK-NEXT: store [[ERROR]] to [init] [[SRC_TEMP]]
// CHECK-NEXT: [[DEST_TEMP:%.*]] = alloc_stack $HomeworkError
// CHECK-NEXT: checked_cast_addr_br copy_on_success Error in [[SRC_TEMP]] : $*Error to HomeworkError in [[DEST_TEMP]] : $*HomeworkError, [[IS_HWE:bb[0-9]+]], [[NOT_HWE:bb[0-9]+]]
// Catch HomeworkError.
// CHECK: [[IS_HWE]]:
// CHECK-NEXT: [[T0:%.*]] = load [take] [[DEST_TEMP]] : $*HomeworkError
// CHECK-NEXT: switch_enum [[T0]] : $HomeworkError, case #HomeworkError.CatAteIt!enumelt.1: [[MATCH:bb[0-9]+]], default [[NO_MATCH:bb[0-9]+]]
// Catch HomeworkError.CatAteIt.
// CHECK: [[MATCH]]([[T0:%.*]] : $Cat):
// CHECK-NEXT: debug_value
// CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK-NEXT: [[T0_COPY:%.*]] = copy_value [[BORROWED_T0]]
// CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: dealloc_stack [[DEST_TEMP]]
// CHECK-NEXT: destroy_addr [[SRC_TEMP]]
// CHECK-NEXT: dealloc_stack [[SRC_TEMP]]
// CHECK-NEXT: br [[RETURN]]([[T0_COPY]] : $Cat)
// Catch other HomeworkErrors.
// CHECK: [[NO_MATCH]]:
// CHECK-NEXT: dealloc_stack [[DEST_TEMP]]
// CHECK-NEXT: dealloc_stack [[SRC_TEMP]]
// CHECK-NEXT: br [[CATCHALL:bb[0-9]+]]
// Catch other types.
// CHECK: [[NOT_HWE]]:
// CHECK-NEXT: dealloc_stack [[DEST_TEMP]]
// CHECK-NEXT: dealloc_stack [[SRC_TEMP]]
// CHECK-NEXT: br [[CATCHALL:bb[0-9]+]]
// Catch all.
// CHECK: [[CATCHALL]]:
// CHECK: [[T0:%.*]] = function_ref @_T06errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat
// CHECK-NEXT: [[T1:%.*]] = metatype $@thick Cat.Type
// CHECK-NEXT: [[T2:%.*]] = apply [[T0]]([[T1]])
// CHECK-NEXT: destroy_value [[ERROR]] : $Error
// CHECK-NEXT: br [[RETURN]]([[T2]] : $Cat)
// Landing pad.
// CHECK: [[MAC_ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[RET_TEMP]]
// CHECK-NEXT: br [[CATCH]]([[T0]] : $Error)
// CHECK: [[DMAC_ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack [[RET_TEMP]]
// CHECK-NEXT: br [[CATCH]]([[T0]] : $Error)
// CHECK: [[DR_ERROR]]([[T0:%.*]] : $Error):
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: dealloc_stack
// CHECK-NEXT: br [[CATCH]]([[T0]] : $Error)
func all_together_now(_ flag: Bool) -> Cat {
do {
return try dont_return(flag ? make_a_cat() : dont_make_a_cat())
} catch HomeworkError.CatAteIt(let cat) {
return cat
} catch _ {
return Cat()
}
}
// Catch in non-throwing context.
// CHECK-LABEL: sil hidden @_T06errors11catch_a_catAA3CatCyF : $@convention(thin) () -> @owned Cat
// CHECK-NEXT: bb0:
// CHECK: [[F:%.*]] = function_ref @_T06errors3Cat{{.*}} : $@convention(method) (@thick Cat.Type) -> @owned Cat
// CHECK-NEXT: [[M:%.*]] = metatype $@thick Cat.Type
// CHECK-NEXT: [[V:%.*]] = apply [[F]]([[M]])
// CHECK-NEXT: return [[V]] : $Cat
func catch_a_cat() -> Cat {
do {
return Cat()
} catch _ as HomeworkError {} // expected-warning {{'catch' block is unreachable because no errors are thrown in 'do' block}}
}
// Initializers.
class HasThrowingInit {
var field: Int
init(value: Int) throws {
field = value
}
}
// CHECK-LABEL: sil hidden @_T06errors15HasThrowingInit{{.*}} : $@convention(method) (Int, @thick HasThrowingInit.Type) -> (@owned HasThrowingInit, @error Error)
// CHECK: [[SELF:%.*]] = alloc_ref $HasThrowingInit
// CHECK: [[T0:%.*]] = function_ref @_T06errors15HasThrowingInit{{.*}}c : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error)
// CHECK-NEXT: try_apply [[T0]](%0, [[SELF]]) : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error), normal bb1, error bb2
// CHECK: bb1([[SELF:%.*]] : $HasThrowingInit):
// CHECK-NEXT: return [[SELF]]
// CHECK: bb2([[ERROR:%.*]] : $Error):
// CHECK-NEXT: builtin "willThrow"
// CHECK-NEXT: throw [[ERROR]]
// CHECK-LABEL: sil hidden @_T06errors15HasThrowingInit{{.*}} : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error) {
// CHECK: [[T0:%.*]] = mark_uninitialized [rootself] %1 : $HasThrowingInit
// CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[BORROWED_T0]] : $HasThrowingInit
// CHECK-NEXT: assign %0 to [[T1]] : $*Int
// CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK-NEXT: [[T0_RET:%.*]] = copy_value [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: return [[T0_RET]] : $HasThrowingInit
enum ColorError : Error {
case Red, Green, Blue
}
//CHECK-LABEL: sil hidden @_T06errors6IThrows5Int32VyKF
//CHECK: builtin "willThrow"
//CHECK-NEXT: throw
func IThrow() throws -> Int32 {
throw ColorError.Red
return 0 // expected-warning {{will never be executed}}
}
// Make sure that we are not emitting calls to 'willThrow' on rethrow sites.
//CHECK-LABEL: sil hidden @_T06errors12DoesNotThrows5Int32VyKF
//CHECK-NOT: builtin "willThrow"
//CHECK: return
func DoesNotThrow() throws -> Int32 {
_ = try IThrow()
return 2
}
// rdar://20782111
protocol Doomed {
func check() throws
}
// CHECK-LABEL: sil private [transparent] [thunk] @_T06errors12DoomedStructVAA0B0A2aDP5checkyyKFTW : $@convention(witness_method) (@in_guaranteed DoomedStruct) -> @error Error
// CHECK: [[TEMP:%.*]] = alloc_stack $DoomedStruct
// CHECK: copy_addr %0 to [initialization] [[TEMP]]
// CHECK: [[SELF:%.*]] = load [trivial] [[TEMP]] : $*DoomedStruct
// CHECK: [[T0:%.*]] = function_ref @_T06errors12DoomedStructV5checkyyKF : $@convention(method) (DoomedStruct) -> @error Error
// CHECK-NEXT: try_apply [[T0]]([[SELF]])
// CHECK: bb1([[T0:%.*]] : $()):
// CHECK: [[T0:%.*]] = tuple ()
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[T0]] : $()
// CHECK: bb2([[T0:%.*]] : $Error):
// CHECK: builtin "willThrow"([[T0]] : $Error)
// CHECK: dealloc_stack [[TEMP]]
// CHECK: throw [[T0]] : $Error
struct DoomedStruct : Doomed {
func check() throws {}
}
// CHECK-LABEL: sil private [transparent] [thunk] @_T06errors11DoomedClassCAA0B0A2aDP5checkyyKFTW : $@convention(witness_method) (@in_guaranteed DoomedClass) -> @error Error {
// CHECK: [[TEMP:%.*]] = alloc_stack $DoomedClass
// CHECK: copy_addr %0 to [initialization] [[TEMP]]
// CHECK: [[SELF:%.*]] = load [take] [[TEMP]] : $*DoomedClass
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[T0:%.*]] = class_method [[BORROWED_SELF]] : $DoomedClass, #DoomedClass.check!1 : (DoomedClass) -> () throws -> (), $@convention(method) (@guaranteed DoomedClass) -> @error Error
// CHECK-NEXT: try_apply [[T0]]([[BORROWED_SELF]])
// CHECK: bb1([[T0:%.*]] : $()):
// CHECK: [[T0:%.*]] = tuple ()
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
// CHECK: destroy_value [[SELF]] : $DoomedClass
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[T0]] : $()
// CHECK: bb2([[T0:%.*]] : $Error):
// CHECK: builtin "willThrow"([[T0]] : $Error)
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
// CHECK: destroy_value [[SELF]] : $DoomedClass
// CHECK: dealloc_stack [[TEMP]]
// CHECK: throw [[T0]] : $Error
class DoomedClass : Doomed {
func check() throws {}
}
// CHECK-LABEL: sil private [transparent] [thunk] @_T06errors11HappyStructVAA6DoomedA2aDP5checkyyKFTW : $@convention(witness_method) (@in_guaranteed HappyStruct) -> @error Error
// CHECK: [[TEMP:%.*]] = alloc_stack $HappyStruct
// CHECK: copy_addr %0 to [initialization] [[TEMP]]
// CHECK: [[SELF:%.*]] = load [trivial] [[TEMP]] : $*HappyStruct
// CHECK: [[T0:%.*]] = function_ref @_T06errors11HappyStructV5checkyyF : $@convention(method) (HappyStruct) -> ()
// CHECK: [[T1:%.*]] = apply [[T0]]([[SELF]])
// CHECK: [[T1:%.*]] = tuple ()
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[T1]] : $()
struct HappyStruct : Doomed {
func check() {}
}
// CHECK-LABEL: sil private [transparent] [thunk] @_T06errors10HappyClassCAA6DoomedA2aDP5checkyyKFTW : $@convention(witness_method) (@in_guaranteed HappyClass) -> @error Error
// CHECK: [[TEMP:%.*]] = alloc_stack $HappyClass
// CHECK: copy_addr %0 to [initialization] [[TEMP]]
// CHECK: [[SELF:%.*]] = load [take] [[TEMP]] : $*HappyClass
// CHECK: [[BORROWED_SELF:%.*]] = begin_borrow [[SELF]]
// CHECK: [[T0:%.*]] = class_method [[BORROWED_SELF]] : $HappyClass, #HappyClass.check!1 : (HappyClass) -> () -> (), $@convention(method) (@guaranteed HappyClass) -> ()
// CHECK: [[T1:%.*]] = apply [[T0]]([[BORROWED_SELF]])
// CHECK: [[T1:%.*]] = tuple ()
// CHECK: end_borrow [[BORROWED_SELF]] from [[SELF]]
// CHECK: destroy_value [[SELF]] : $HappyClass
// CHECK: dealloc_stack [[TEMP]]
// CHECK: return [[T1]] : $()
class HappyClass : Doomed {
func check() {}
}
func create<T>(_ fn: () throws -> T) throws -> T {
return try fn()
}
func testThunk(_ fn: () throws -> Int) throws -> Int {
return try create(fn)
}
// CHECK-LABEL: sil shared [transparent] [serializable] [reabstraction_thunk] @_T0Sis5Error_pIxdzo_SisAA_pIxrzo_TR : $@convention(thin) (@owned @callee_owned () -> (Int, @error Error)) -> (@out Int, @error Error)
// CHECK: bb0(%0 : $*Int, %1 : $@callee_owned () -> (Int, @error Error)):
// CHECK: try_apply %1()
// CHECK: bb1([[T0:%.*]] : $Int):
// CHECK: store [[T0]] to [trivial] %0 : $*Int
// CHECK: [[T0:%.*]] = tuple ()
// CHECK: return [[T0]]
// CHECK: bb2([[T0:%.*]] : $Error):
// CHECK: builtin "willThrow"([[T0]] : $Error)
// CHECK: throw [[T0]] : $Error
func createInt(_ fn: () -> Int) throws {}
func testForceTry(_ fn: () -> Int) {
try! createInt(fn)
}
// CHECK-LABEL: sil hidden @_T06errors12testForceTryySiycF : $@convention(thin) (@owned @callee_owned () -> Int) -> ()
// CHECK: bb0([[ARG:%.*]] : $@callee_owned () -> Int):
// CHECK: [[FUNC:%.*]] = function_ref @_T06errors9createIntySiycKF : $@convention(thin) (@owned @callee_owned () -> Int) -> @error Error
// CHECK: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK: try_apply [[FUNC]]([[ARG_COPY]])
// CHECK: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK: destroy_value [[ARG]]
// CHECK: return
// CHECK: builtin "unexpectedError"
// CHECK: unreachable
func testForceTryMultiple() {
_ = try! (make_a_cat(), make_a_cat())
}
// CHECK-LABEL: sil hidden @_T06errors20testForceTryMultipleyyF
// CHECK-NEXT: bb0:
// CHECK: [[FN_1:%.+]] = function_ref @_T06errors10make_a_catAA3CatCyKF
// CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]],
// CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat)
// CHECK: [[FN_2:%.+]] = function_ref @_T06errors10make_a_catAA3CatCyKF
// CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]],
// CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat)
// CHECK-NEXT: destroy_value [[VALUE_2]] : $Cat
// CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: = builtin "unexpectedError"([[ERROR]] : $Error)
// CHECK-NEXT: unreachable
// CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_T06errors20testForceTryMultipleyyF'
// Make sure we balance scopes correctly inside a switch.
// <rdar://problem/20923654>
enum CatFood {
case Canned
case Dry
}
// Something we can switch on that throws.
func preferredFood() throws -> CatFood {
return CatFood.Canned
}
func feedCat() throws -> Int {
switch try preferredFood() {
case .Canned:
return 0
case .Dry:
return 1
}
}
// CHECK-LABEL: sil hidden @_T06errors7feedCatSiyKF : $@convention(thin) () -> (Int, @error Error)
// CHECK: debug_value undef : $Error, var, name "$error", argno 1
// CHECK: %1 = function_ref @_T06errors13preferredFoodAA03CatC0OyKF : $@convention(thin) () -> (CatFood, @error Error)
// CHECK: try_apply %1() : $@convention(thin) () -> (CatFood, @error Error), normal bb1, error bb5
// CHECK: bb1([[VAL:%.*]] : $CatFood):
// CHECK: switch_enum [[VAL]] : $CatFood, case #CatFood.Canned!enumelt: bb2, case #CatFood.Dry!enumelt: bb3
// CHECK: bb5([[ERROR:%.*]] : $Error)
// CHECK: throw [[ERROR]] : $Error
// Throwing statements inside cases.
func getHungryCat(_ food: CatFood) throws -> Cat {
switch food {
case .Canned:
return try make_a_cat()
case .Dry:
return try dont_make_a_cat()
}
}
// errors.getHungryCat throws (errors.CatFood) -> errors.Cat
// CHECK-LABEL: sil hidden @_T06errors12getHungryCatAA0D0CAA0D4FoodOKF : $@convention(thin) (CatFood) -> (@owned Cat, @error Error)
// CHECK: bb0(%0 : $CatFood):
// CHECK: debug_value undef : $Error, var, name "$error", argno 2
// CHECK: switch_enum %0 : $CatFood, case #CatFood.Canned!enumelt: bb1, case #CatFood.Dry!enumelt: bb3
// CHECK: bb1:
// CHECK: [[FN:%.*]] = function_ref @_T06errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb2, error bb6
// CHECK: bb3:
// CHECK: [[FN:%.*]] = function_ref @_T06errors15dont_make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal bb4, error bb7
// CHECK: bb6([[ERROR:%.*]] : $Error):
// CHECK: br bb8([[ERROR:%.*]] : $Error)
// CHECK: bb7([[ERROR:%.*]] : $Error):
// CHECK: br bb8([[ERROR]] : $Error)
// CHECK: bb8([[ERROR:%.*]] : $Error):
// CHECK: throw [[ERROR]] : $Error
func take_many_cats(_ cats: Cat...) throws {}
func test_variadic(_ cat: Cat) throws {
try take_many_cats(make_a_cat(), cat, make_a_cat(), make_a_cat())
}
// CHECK-LABEL: sil hidden @_T06errors13test_variadicyAA3CatCKF : $@convention(thin) (@owned Cat) -> @error Error {
// CHECK: bb0([[ARG:%.*]] : $Cat):
// CHECK: debug_value undef : $Error, var, name "$error", argno 2
// CHECK: [[TAKE_FN:%.*]] = function_ref @_T06errors14take_many_catsySayAA3CatCGd_tKF : $@convention(thin) (@owned Array<Cat>) -> @error Error
// CHECK: [[N:%.*]] = integer_literal $Builtin.Word, 4
// CHECK: [[T0:%.*]] = function_ref @_T0s27_allocateUninitializedArray{{.*}}F
// CHECK: [[T1:%.*]] = apply [[T0]]<Cat>([[N]])
// CHECK: [[BORROWED_T1:%.*]] = begin_borrow [[T1]]
// CHECK: [[BORROWED_ARRAY:%.*]] = tuple_extract [[BORROWED_T1]] : $(Array<Cat>, Builtin.RawPointer), 0
// CHECK: [[ARRAY:%.*]] = copy_value [[BORROWED_ARRAY]]
// CHECK: [[T2:%.*]] = tuple_extract [[BORROWED_T1]] : $(Array<Cat>, Builtin.RawPointer), 1
// CHECK: end_borrow [[BORROWED_T1]] from [[T1]]
// CHECK: destroy_value [[T1]]
// CHECK: [[ELT0:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*Cat
// Element 0.
// CHECK: [[T0:%.*]] = function_ref @_T06errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_0:bb[0-9]+]], error [[ERR_0:bb[0-9]+]]
// CHECK: [[NORM_0]]([[CAT0:%.*]] : $Cat):
// CHECK-NEXT: store [[CAT0]] to [init] [[ELT0]]
// Element 1.
// CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 1
// CHECK-NEXT: [[ELT1:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]]
// CHECK-NEXT: [[BORROWED_ARG:%.*]] = begin_borrow [[ARG]]
// CHECK-NEXT: [[ARG_COPY:%.*]] = copy_value [[BORROWED_ARG]]
// CHECK-NEXT: store [[ARG_COPY]] to [init] [[ELT1]]
// Element 2.
// CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 2
// CHECK-NEXT: [[ELT2:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_T06errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_2:bb[0-9]+]], error [[ERR_2:bb[0-9]+]]
// CHECK: [[NORM_2]]([[CAT2:%.*]] : $Cat):
// CHECK-NEXT: store [[CAT2]] to [init] [[ELT2]]
// Element 3.
// CHECK-NEXT: [[T0:%.*]] = integer_literal $Builtin.Word, 3
// CHECK-NEXT: [[ELT3:%.*]] = index_addr [[ELT0]] : $*Cat, [[T0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_T06errors10make_a_catAA3CatCyKF : $@convention(thin) () -> (@owned Cat, @error Error)
// CHECK-NEXT: try_apply [[T0]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[NORM_3:bb[0-9]+]], error [[ERR_3:bb[0-9]+]]
// CHECK: [[NORM_3]]([[CAT3:%.*]] : $Cat):
// CHECK-NEXT: store [[CAT3]] to [init] [[ELT3]]
// Complete the call and return.
// CHECK-NEXT: try_apply [[TAKE_FN]]([[ARRAY]]) : $@convention(thin) (@owned Array<Cat>) -> @error Error, normal [[NORM_CALL:bb[0-9]+]], error [[ERR_CALL:bb[0-9]+]]
// CHECK: [[NORM_CALL]]([[T0:%.*]] : $()):
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: destroy_value [[ARG]] : $Cat
// CHECK-NEXT: [[T0:%.*]] = tuple ()
// CHECK-NEXT: return
// Failure from element 0.
// CHECK: [[ERR_0]]([[ERROR:%.*]] : $Error):
// CHECK-NOT: end_borrow
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_T0s29_deallocateUninitializedArray{{.*}}F
// CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]])
// CHECK-NEXT: br [[RETHROW:.*]]([[ERROR]] : $Error)
// Failure from element 2.
// CHECK: [[ERR_2]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: destroy_addr [[ELT1]]
// CHECK-NEXT: destroy_addr [[ELT0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_T0s29_deallocateUninitializedArray{{.*}}F
// CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]])
// CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error)
// Failure from element 3.
// CHECK: [[ERR_3]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_addr [[ELT2]]
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: destroy_addr [[ELT1]]
// CHECK-NEXT: destroy_addr [[ELT0]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[T0:%.*]] = function_ref @_T0s29_deallocateUninitializedArray{{.*}}F
// CHECK-NEXT: apply [[T0]]<Cat>([[ARRAY]])
// CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error)
// Failure from call.
// CHECK: [[ERR_CALL]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: end_borrow [[BORROWED_ARG]] from [[ARG]]
// CHECK-NEXT: br [[RETHROW]]([[ERROR]] : $Error)
// Rethrow.
// CHECK: [[RETHROW]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ARG]] : $Cat
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '_T06errors13test_variadicyAA3CatCKF'
// rdar://20861374
// Clear out the self box before delegating.
class BaseThrowingInit : HasThrowingInit {
var subField: Int
init(value: Int, subField: Int) throws {
self.subField = subField
try super.init(value: value)
}
}
// CHECK: sil hidden @_T06errors16BaseThrowingInit{{.*}}c : $@convention(method) (Int, Int, @owned BaseThrowingInit) -> (@owned BaseThrowingInit, @error Error)
// CHECK: [[BOX:%.*]] = alloc_box ${ var BaseThrowingInit }
// CHECK: [[PB:%.*]] = project_box [[BOX]]
// CHECK: [[MARKED_BOX:%.*]] = mark_uninitialized [derivedself] [[PB]]
// Initialize subField.
// CHECK: [[T0:%.*]] = load_borrow [[MARKED_BOX]]
// CHECK-NEXT: [[T1:%.*]] = ref_element_addr [[T0]] : $BaseThrowingInit, #BaseThrowingInit.subField
// CHECK-NEXT: assign %1 to [[T1]]
// CHECK-NEXT: end_borrow [[T0]] from [[MARKED_BOX]]
// Super delegation.
// CHECK-NEXT: [[T0:%.*]] = load [take] [[MARKED_BOX]]
// CHECK-NEXT: [[T2:%.*]] = upcast [[T0]] : $BaseThrowingInit to $HasThrowingInit
// CHECK: [[T3:%[0-9]+]] = function_ref @_T06errors15HasThrowingInitCACSi5value_tKcfc : $@convention(method) (Int, @owned HasThrowingInit) -> (@owned HasThrowingInit, @error Error)
// CHECK-NEXT: apply [[T3]](%0, [[T2]])
// Cleanups for writebacks.
protocol Supportable {
mutating func support() throws
}
protocol Buildable {
associatedtype Structure : Supportable
var firstStructure: Structure { get set }
subscript(name: String) -> Structure { get set }
}
func supportFirstStructure<B: Buildable>(_ b: inout B) throws {
try b.firstStructure.support()
}
// CHECK-LABEL: sil hidden @_T06errors21supportFirstStructure{{.*}}F : $@convention(thin) <B where B : Buildable> (@inout B) -> @error Error {
// CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 :
// CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure
// CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer
// CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.firstStructure!materializeForSet.1 :
// CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[BASE:%[0-9]*]])
// CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0
// CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure
// CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B
// CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: throw [[ERROR]]
func supportStructure<B: Buildable>(_ b: inout B, name: String) throws {
try b[name].support()
}
// CHECK-LABEL: sil hidden @_T06errors16supportStructure{{.*}}F
// CHECK: bb0({{.*}}, [[INDEX:%.*]] : $String):
// CHECK: [[SUPPORT:%.*]] = witness_method $B.Structure, #Supportable.support!1 :
// CHECK: [[BORROWED_INDEX:%.*]] = begin_borrow [[INDEX]]
// CHECK: [[INDEX_COPY:%.*]] = copy_value [[BORROWED_INDEX]] : $String
// CHECK: [[MATBUFFER:%.*]] = alloc_stack $Builtin.UnsafeValueBuffer
// CHECK: [[BUFFER:%.*]] = alloc_stack $B.Structure
// CHECK: [[BUFFER_CAST:%.*]] = address_to_pointer [[BUFFER]] : $*B.Structure to $Builtin.RawPointer
// CHECK: [[MAT:%.*]] = witness_method $B, #Buildable.subscript!materializeForSet.1 :
// CHECK: [[T1:%.*]] = apply [[MAT]]<B>([[BUFFER_CAST]], [[MATBUFFER]], [[INDEX_COPY]], [[BASE:%[0-9]*]])
// CHECK: [[T2:%.*]] = tuple_extract [[T1]] : {{.*}}, 0
// CHECK: [[CALLBACK:%.*]] = tuple_extract [[T1]] : {{.*}}, 1
// CHECK: [[T3:%.*]] = pointer_to_address [[T2]] : $Builtin.RawPointer to [strict] $*B.Structure
// CHECK: [[T4:%.*]] = mark_dependence [[T3]] : $*B.Structure on [[BASE]] : $*B
// CHECK: try_apply [[SUPPORT]]<B.Structure>([[T4]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: end_borrow [[BORROWED_INDEX]] from [[INDEX]]
// CHECK: destroy_value [[INDEX]] : $String
// CHECK: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK: switch_enum [[CALLBACK]]
// CHECK: apply
// CHECK: dealloc_stack [[BUFFER]]
// CHECK: dealloc_stack [[MATBUFFER]]
// CHECK: destroy_value [[INDEX]] : $String
// CHECK: throw [[ERROR]]
struct Pylon {
var name: String
mutating func support() throws {}
}
struct Bridge {
var mainPylon : Pylon
subscript(name: String) -> Pylon {
get {
return mainPylon
}
set {}
}
}
func supportStructure(_ b: inout Bridge, name: String) throws {
try b[name].support()
}
// CHECK: sil hidden @_T06errors16supportStructureyAA6BridgeVz_SS4nametKF : $@convention(thin) (@inout Bridge, @owned String) -> @error Error {
// CHECK: bb0([[ARG1:%.*]] : $*Bridge, [[ARG2:%.*]] : $String):
// CHECK: [[SUPPORT:%.*]] = function_ref @_T06errors5PylonV7supportyyKF
// CHECK-NEXT: [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG2]]
// CHECK-NEXT: [[INDEX_COPY_1:%.*]] = copy_value [[BORROWED_ARG2]] : $String
// CHECK-NEXT: [[INDEX_COPY_2:%.*]] = copy_value [[INDEX_COPY_1]] : $String
// CHECK-NEXT: [[TEMP:%.*]] = alloc_stack $Pylon
// CHECK-NEXT: [[BASE:%.*]] = load_borrow [[ARG1]] : $*Bridge
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[GETTER:%.*]] = function_ref @_T06errors6BridgeV9subscriptAA5PylonVSScfg :
// CHECK-NEXT: [[T0:%.*]] = apply [[GETTER]]([[INDEX_COPY_1]], [[BASE]])
// CHECK-NEXT: store [[T0]] to [init] [[TEMP]]
// CHECK-NEXT: end_borrow [[BASE]] from [[ARG1]]
// CHECK-NEXT: try_apply [[SUPPORT]]([[TEMP]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK-NEXT: [[T0:%.*]] = load [take] [[TEMP]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T06errors6BridgeV9subscriptAA5PylonVSScfs :
// CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2]], [[ARG1]])
// CHECK-NEXT: dealloc_stack [[TEMP]]
// CHECK-NEXT: end_borrow [[BORROWED_INDEX]] from [[INDEX]]
// CHECK-NEXT: destroy_value [[INDEX]] : $String
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// We end up with ugly redundancy here because we don't want to
// consume things during cleanup emission. It's questionable.
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[T0:%.*]] = load [copy] [[TEMP]]
// CHECK-NEXT: [[INDEX_COPY_2_COPY:%.*]] = copy_value [[INDEX_COPY_2]]
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[SETTER:%.*]] = function_ref @_T06errors6BridgeV9subscriptAA5PylonVSScfs :
// CHECK-NEXT: apply [[SETTER]]([[T0]], [[INDEX_COPY_2_COPY]], [[ARG1]])
// CHECK-NEXT: destroy_addr [[TEMP]]
// CHECK-NEXT: dealloc_stack [[TEMP]]
// ==> SEMANTIC ARC TODO: INDEX_COPY_2 on the next line should be INDEX_COPY_2_COPY
// CHECK-NEXT: destroy_value [[INDEX_COPY_2]] : $String
// CHECK-NEXT: end_borrow [[BORROWED_INDEX]] from [[INDEX]]
// CHECK-NEXT: destroy_value [[INDEX]] : $String
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '_T06errors16supportStructureyAA6BridgeVz_SS4nametKF'
struct OwnedBridge {
var owner : Builtin.UnknownObject
subscript(name: String) -> Pylon {
addressWithOwner { return (someValidPointer(), owner) }
mutableAddressWithOwner { return (someValidPointer(), owner) }
}
}
func supportStructure(_ b: inout OwnedBridge, name: String) throws {
try b[name].support()
}
// CHECK: sil hidden @_T06errors16supportStructureyAA11OwnedBridgeVz_SS4nametKF :
// CHECK: bb0([[ARG1:%.*]] : $*OwnedBridge, [[ARG2:%.*]] : $String):
// CHECK: [[SUPPORT:%.*]] = function_ref @_T06errors5PylonV7supportyyKF
// CHECK: [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG2]]
// CHECK: [[ARG2_COPY:%.*]] = copy_value [[BORROWED_ARG2]] : $String
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_T06errors11OwnedBridgeV9subscriptAA5PylonVSScfaO :
// CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[ARG1]])
// CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK-NEXT: [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0
// CHECK-NEXT: [[BORROWED_OWNER:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 1
// CHECK-NEXT: [[OWNER:%.*]] = copy_value [[BORROWED_OWNER]]
// CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]]
// CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
// CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]]
// CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK-NEXT: destroy_value [[OWNER]] : $Builtin.UnknownObject
// CHECK-NEXT: end_borrow [[BORROWED_ARG2]] from [[ARG2]]
// CHECK-NEXT: destroy_value [[ARG2]] : $String
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[OWNER]] : $Builtin.UnknownObject
// CHECK-NEXT: end_borrow [[BORROWED_ARG2]] from [[ARG2]]
// CHECK-NEXT: destroy_value [[ARG2]] : $String
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '_T06errors16supportStructureyAA11OwnedBridgeVz_SS4nametKF'
struct PinnedBridge {
var owner : Builtin.NativeObject
subscript(name: String) -> Pylon {
addressWithPinnedNativeOwner { return (someValidPointer(), owner) }
mutableAddressWithPinnedNativeOwner { return (someValidPointer(), owner) }
}
}
func supportStructure(_ b: inout PinnedBridge, name: String) throws {
try b[name].support()
}
// CHECK: sil hidden @_T06errors16supportStructureyAA12PinnedBridgeVz_SS4nametKF :
// CHECK: bb0([[ARG1:%.*]] : $*PinnedBridge, [[ARG2:%.*]] : $String):
// CHECK: [[SUPPORT:%.*]] = function_ref @_T06errors5PylonV7supportyyKF
// CHECK: [[BORROWED_ARG2:%.*]] = begin_borrow [[ARG2]]
// CHECK: [[ARG2_COPY:%.*]] = copy_value [[BORROWED_ARG2]] : $String
// CHECK-NEXT: // function_ref
// CHECK-NEXT: [[ADDRESSOR:%.*]] = function_ref @_T06errors12PinnedBridgeV9subscriptAA5PylonVSScfaP :
// CHECK-NEXT: [[T0:%.*]] = apply [[ADDRESSOR]]([[ARG2_COPY]], [[ARG1]])
// CHECK-NEXT: [[BORROWED_T0:%.*]] = begin_borrow [[T0]]
// CHECK-NEXT: [[T1:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 0
// CHECK-NEXT: [[BORROWED_OWNER:%.*]] = tuple_extract [[BORROWED_T0]] : {{.*}}, 1
// CHECK-NEXT: [[OWNER:%.*]] = copy_value [[BORROWED_OWNER]]
// CHECK-NEXT: end_borrow [[BORROWED_T0]] from [[T0]]
// CHECK-NEXT: destroy_value [[T0]]
// CHECK-NEXT: [[T3:%.*]] = struct_extract [[T1]]
// CHECK-NEXT: [[T4:%.*]] = pointer_to_address [[T3]]
// CHECK-NEXT: [[T5:%.*]] = mark_dependence [[T4]] : $*Pylon on [[OWNER]]
// CHECK-NEXT: try_apply [[SUPPORT]]([[T5]]) : {{.*}}, normal [[BB_NORMAL:bb[0-9]+]], error [[BB_ERROR:bb[0-9]+]]
// CHECK: [[BB_NORMAL]]
// CHECK-NEXT: strong_unpin [[OWNER]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: end_borrow [[BORROWED_ARG2]] from [[ARG2]]
// CHECK-NEXT: destroy_value [[ARG2]] : $String
// CHECK-NEXT: tuple ()
// CHECK-NEXT: return
// CHECK: [[BB_ERROR]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: [[OWNER_COPY:%.*]] = copy_value [[OWNER]]
// CHECK-NEXT: strong_unpin [[OWNER_COPY]] : $Optional<Builtin.NativeObject>
// CHECK-NEXT: destroy_value [[OWNER]]
// CHECK-NEXT: end_borrow [[BORROWED_ARG2]] from [[ARG2]]
// CHECK-NEXT: destroy_value [[ARG2]] : $String
// CHECK-NEXT: throw [[ERROR]]
// CHECK: } // end sil function '_T06errors16supportStructureyAA12PinnedBridgeVz_SS4nametKF'
// ! peepholes its argument with getSemanticsProvidingExpr().
// Test that that doesn't look through try!.
// rdar://21515402
func testForcePeephole(_ f: () throws -> Int?) -> Int {
let x = (try! f())!
return x
}
// CHECK-LABEL: sil hidden @_T06errors15testOptionalTryyyF
// CHECK-NEXT: bb0:
// CHECK: [[FN:%.+]] = function_ref @_T06errors10make_a_catAA3CatCyKF
// CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat)
// CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<Cat>, #Optional.some!enumelt.1, [[VALUE]]
// CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<Cat>)
// CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<Cat>):
// CHECK-NEXT: destroy_value [[RESULT]] : $Optional<Cat>
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: [[NONE:%.+]] = enum $Optional<Cat>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<Cat>)
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_T06errors15testOptionalTryyyF'
func testOptionalTry() {
_ = try? make_a_cat()
}
// CHECK-LABEL: sil hidden @_T06errors18testOptionalTryVaryyF
// CHECK-NEXT: bb0:
// CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<Cat> }
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1
// CHECK: [[FN:%.+]] = function_ref @_T06errors10make_a_catAA3CatCyKF
// CHECK-NEXT: try_apply [[FN]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]([[VALUE:%.+]] : $Cat)
// CHECK-NEXT: store [[VALUE]] to [init] [[BOX_DATA]] : $*Cat
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.some!enumelt.1
// CHECK-NEXT: br [[DONE:[^ ]+]],
// CHECK: [[DONE]]:
// CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<Cat> }
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<Cat>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_T06errors18testOptionalTryVaryyF'
func testOptionalTryVar() {
var cat = try? make_a_cat() // expected-warning {{initialization of variable 'cat' was never used; consider replacing with assignment to '_' or removing it}}
}
// CHECK-LABEL: sil hidden @_T06errors26testOptionalTryAddressOnly{{.*}}F
// CHECK: bb0(%0 : $*T):
// CHECK: [[BOX:%.+]] = alloc_stack $Optional<T>
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK: [[FN:%.+]] = function_ref @_T06errors11dont_return{{.*}}F
// CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T
// CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]] : $*T
// CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]({{%.+}} : $()):
// CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
// CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: br [[DONE:[^ ]+]],
// CHECK: [[DONE]]:
// CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T>
// CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T>
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_T06errors26testOptionalTryAddressOnlyyxlF'
func testOptionalTryAddressOnly<T>(_ obj: T) {
_ = try? dont_return(obj)
}
// CHECK-LABEL: sil hidden @_T06errors29testOptionalTryAddressOnlyVar{{.*}}F
// CHECK: bb0(%0 : $*T):
// CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK: [[FN:%.+]] = function_ref @_T06errors11dont_return{{.*}}F
// CHECK-NEXT: [[ARG_BOX:%.+]] = alloc_stack $T
// CHECK-NEXT: copy_addr %0 to [initialization] [[ARG_BOX]] : $*T
// CHECK-NEXT: try_apply [[FN]]<T>([[BOX_DATA]], [[ARG_BOX]]) : $@convention(thin) <τ_0_0> (@in τ_0_0) -> (@out τ_0_0, @error Error), normal [[SUCCESS:[^ ]+]], error [[CLEANUPS:[^ ]+]],
// CHECK: [[SUCCESS]]({{%.+}} : $()):
// CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: br [[DONE:[^ ]+]],
// CHECK: [[DONE]]:
// CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T>
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]
// CHECK: [[CLEANUPS]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: dealloc_stack [[ARG_BOX]] : $*T
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_T06errors29testOptionalTryAddressOnlyVaryxlF'
func testOptionalTryAddressOnlyVar<T>(_ obj: T) {
var copy = try? dont_return(obj) // expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}}
}
// CHECK-LABEL: sil hidden @_T06errors23testOptionalTryMultipleyyF
// CHECK: bb0:
// CHECK: [[FN_1:%.+]] = function_ref @_T06errors10make_a_catAA3CatCyKF
// CHECK-NEXT: try_apply [[FN_1]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_1:[^ ]+]], error [[CLEANUPS_1:[^ ]+]],
// CHECK: [[SUCCESS_1]]([[VALUE_1:%.+]] : $Cat)
// CHECK: [[FN_2:%.+]] = function_ref @_T06errors10make_a_catAA3CatCyKF
// CHECK-NEXT: try_apply [[FN_2]]() : $@convention(thin) () -> (@owned Cat, @error Error), normal [[SUCCESS_2:[^ ]+]], error [[CLEANUPS_2:[^ ]+]],
// CHECK: [[SUCCESS_2]]([[VALUE_2:%.+]] : $Cat)
// CHECK-NEXT: [[TUPLE:%.+]] = tuple ([[VALUE_1]] : $Cat, [[VALUE_2]] : $Cat)
// CHECK-NEXT: [[WRAPPED:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.some!enumelt.1, [[TUPLE]]
// CHECK-NEXT: br [[DONE:[^ ]+]]([[WRAPPED]] : $Optional<(Cat, Cat)>)
// CHECK: [[DONE]]([[RESULT:%.+]] : $Optional<(Cat, Cat)>):
// CHECK-NEXT: destroy_value [[RESULT]] : $Optional<(Cat, Cat)>
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: [[FAILURE:.+]]([[ERROR:%.*]] : $Error):
// CHECK-NEXT: destroy_value [[ERROR]]
// CHECK-NEXT: [[NONE:%.+]] = enum $Optional<(Cat, Cat)>, #Optional.none!enumelt
// CHECK-NEXT: br [[DONE]]([[NONE]] : $Optional<(Cat, Cat)>)
// CHECK: [[CLEANUPS_1]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: [[CLEANUPS_2]]([[ERROR:%.+]] : $Error):
// CHECK-NEXT: destroy_value [[VALUE_1]] : $Cat
// CHECK-NEXT: br [[FAILURE]]([[ERROR]] : $Error)
// CHECK: } // end sil function '_T06errors23testOptionalTryMultipleyyF'
func testOptionalTryMultiple() {
_ = try? (make_a_cat(), make_a_cat())
}
// CHECK-LABEL: sil hidden @_T06errors25testOptionalTryNeverFailsyyF
// CHECK: bb0:
// CHECK-NEXT: [[VALUE:%.+]] = tuple ()
// CHECK-NEXT: = enum $Optional<()>, #Optional.some!enumelt.1, [[VALUE]]
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: } // end sil function '_T06errors25testOptionalTryNeverFailsyyF'
func testOptionalTryNeverFails() {
_ = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}}
}
// CHECK-LABEL: sil hidden @_T06errors28testOptionalTryNeverFailsVaryyF
// CHECK: bb0:
// CHECK-NEXT: [[BOX:%.+]] = alloc_box ${ var Optional<()> }
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: = init_enum_data_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<()>, #Optional.some!enumelt.1
// CHECK-NEXT: destroy_value [[BOX]] : ${ var Optional<()> }
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK-NEXT: } // end sil function '_T06errors28testOptionalTryNeverFailsVaryyF'
func testOptionalTryNeverFailsVar() {
var unit: ()? = try? () // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{variable 'unit' was never used; consider replacing with '_' or removing it}}
}
// CHECK-LABEL: sil hidden @_T06errors36testOptionalTryNeverFailsAddressOnly{{.*}}F
// CHECK: bb0(%0 : $*T):
// CHECK: [[BOX:%.+]] = alloc_stack $Optional<T>
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T
// CHECK-NEXT: inject_enum_addr [[BOX]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: destroy_addr [[BOX]] : $*Optional<T>
// CHECK-NEXT: dealloc_stack [[BOX]] : $*Optional<T>
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK-NEXT: } // end sil function '_T06errors36testOptionalTryNeverFailsAddressOnlyyxlF'
func testOptionalTryNeverFailsAddressOnly<T>(_ obj: T) {
_ = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}}
}
// CHECK-LABEL: sil hidden @_T06errors39testOptionalTryNeverFailsAddressOnlyVar{{.*}}F
// CHECK: bb0(%0 : $*T):
// CHECK: [[BOX:%.+]] = alloc_box $<τ_0_0> { var Optional<τ_0_0> } <T>
// CHECK-NEXT: [[PB:%.*]] = project_box [[BOX]]
// CHECK-NEXT: [[BOX_DATA:%.+]] = init_enum_data_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: copy_addr %0 to [initialization] [[BOX_DATA]] : $*T
// CHECK-NEXT: inject_enum_addr [[PB]] : $*Optional<T>, #Optional.some!enumelt.1
// CHECK-NEXT: destroy_value [[BOX]] : $<τ_0_0> { var Optional<τ_0_0> } <T>
// CHECK-NEXT: destroy_addr %0 : $*T
// CHECK-NEXT: [[VOID:%.+]] = tuple ()
// CHECK-NEXT: return [[VOID]] : $()
// CHECK: } // end sil function '_T06errors13OtherErrorSubCACycfC'
func testOptionalTryNeverFailsAddressOnlyVar<T>(_ obj: T) {
var copy = try? obj // expected-warning {{no calls to throwing functions occur within 'try' expression}} expected-warning {{initialization of variable 'copy' was never used; consider replacing with assignment to '_' or removing it}}
}
class SomeErrorClass : Error { }
// CHECK-LABEL: sil_vtable SomeErrorClass
// CHECK-NEXT: #SomeErrorClass.init!initializer.1: {{.*}} : _T06errors14SomeErrorClassCACycfc
// CHECK-NEXT: #SomeErrorClass.deinit!deallocator: _T06errors14SomeErrorClassCfD
// CHECK-NEXT: }
class OtherErrorSub : OtherError { }
// CHECK-LABEL: sil_vtable OtherErrorSub {
// CHECK-NEXT: #OtherError.init!initializer.1: {{.*}} : _T06errors13OtherErrorSubCACycfc // OtherErrorSub.init() -> OtherErrorSub
// CHECK-NEXT: #OtherErrorSub.deinit!deallocator: _T06errors13OtherErrorSubCfD // OtherErrorSub.__deallocating_deinit
// CHECK-NEXT:}
| 3fdd66b6fc6ddd5f22241dad6ca10935 | 48.473739 | 234 | 0.603707 | false | false | false | false |
fromkk/SwiftMaterialButton | refs/heads/master | MaterialButton/ViewController.swift | mit | 1 | //
// ViewController.swift
// MaterialButton
//
// Created by Kazuya Ueoka on 2014/12/29.
// Copyright (c) 2014年 fromKK. All rights reserved.
//
import UIKit
class ViewController: UIViewController, MaterialButtonProtocol {
var debugButton: RippleButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var materialButton1 = MaterialButton(type: MaterialButtonType.ArrowLeft)
materialButton1.delegate = self
self.navigationItem.leftBarButtonItem = materialButton1
var materialButton2 = MaterialButton(type: MaterialButtonType.ArrowRight)
materialButton2.delegate = self
self.navigationItem.rightBarButtonItem = materialButton2
self.debugButton = RippleButton()
self.debugButton.setTitle("Ripple Button", forState: UIControlState.Normal)
self.debugButton.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
self.debugButton.backgroundColor = UIColor(red: 240.0 / 255.0, green: 240.0 / 255.0, blue: 240.0 / 255.0, alpha: 1.0)
self.view.addSubview(self.debugButton)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
self.debugButton.frame = CGRect(x: 30.0, y: 100.0, width: 200.0, height: 40.0)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func materialButtonDidTapped(sender: AnyObject?) {
println("\((sender as MaterialButton).activated)")
}
}
| 7ca1299e0e93ff9904c4c681ffd75624 | 33.285714 | 125 | 0.680952 | false | false | false | false |
drewag/Swiftlier | refs/heads/master | Sources/Swiftlier/Model/Observable/EventCenter.swift | mit | 1 | //
// EventCenter.swift
// Swiftlier
//
// Created by Andrew J Wagner on 1/4/15.
// Copyright (c) 2015 Drewag LLC. All rights reserved.
//
import Foundation
/**
Protcol all events must implemenet to work with EventCenter
*/
public protocol EventType: class {
associatedtype CallbackParam
}
/**
A type safe, closure based event center modeled after NSNotificationCenter. Every event is guaranteed
to be unique by the compiler because it is based off of a custom subclass that implements EventType.
That protocol simply requires that the event define a typealias for the parameter to be passed to
registered closures. That type can be `void`, a single type, or a multiple types by using a tuple.
Because the EventCenter is type safe, when registering a callback, the types specified by the event
can be inferred and enforced by the compiler.
*/
open class EventCenter {
fileprivate var _observations = [String:CallbackCollection]()
/**
The main event center
*/
open class func defaultCenter() -> EventCenter {
return Static.DefaultInsance
}
public init() {}
/**
Trigger an event causing all registered callbacks to be called
Callbacks are all executed on the same thread before this method returns
- parameter event: the event to trigger
- parameter params: the parameters to trigger the event with
*/
open func triggerEvent<E: EventType>(_ event: E.Type, params: E.CallbackParam) {
let key = NSStringFromClass(event)
if let callbackCollection = self._observations[key] {
for (_, callbacks) in callbackCollection {
for spec in callbacks {
if let operationQueue = spec.operationQueue {
operationQueue.addOperation {
(spec.callback as! (E.CallbackParam) -> ())(params)
}
}
else {
(spec.callback as! (E.CallbackParam) -> ())(params)
}
}
}
}
}
/**
Add a callback for when an event is triggered
- parameter observer: observing object to be referenced later to remove the hundler
- parameter event: the event to observe
- parameter callback: callback to be called when the event is triggered
*/
open func addObserver<E: EventType>(_ observer: AnyObject, forEvent event: E.Type, callback: @escaping (E.CallbackParam) -> ()) {
self.addObserver(observer, forEvent: event, inQueue: nil, callback: callback)
}
/**
Add a callback for when an event is triggered
- parameter observer: observing object to be referenced later to remove the hundler
- parameter forEvent: the event to observe
- parameter inQueue: queue to call callback in (nil indicates the callback should be called on the same queue as the trigger)
- parameter callback: callback to be called when the event is triggered
*/
open func addObserver<E: EventType>(_ observer: AnyObject, forEvent event: E.Type, inQueue: OperationQueue?, callback: @escaping (E.CallbackParam) -> ()) {
let key = NSStringFromClass(event)
if self._observations[key] == nil {
self._observations[key] = CallbackCollection()
}
addHandler((callback: callback, operationQueue: inQueue), toHandlerCollection: &self._observations[key]!, forObserver: observer)
}
/**
Remove a callback for when an event is triggered
- parameter observer: observing object passed in when registering the callback originally
- parameter event: the event to remove the observer for
*/
open func removeObserver<E: EventType>(_ observer: AnyObject, forEvent event: E.Type?) {
if let event = event {
let key = NSStringFromClass(event)
if var callbackCollection = self._observations[key] {
removecallbacksForObserver(observer, fromHandlerCollection: &callbackCollection)
self._observations[key] = callbackCollection
}
}
}
/**
Remove callbacks for all of the events that an observer is registered for
- parameter observer: observing object passed in when registering the callback originally
*/
open func removeObserverForAllEvents(_ observer: AnyObject) {
for (key, var callbackCollection) in self._observations {
removecallbacksForObserver(observer, fromHandlerCollection: &callbackCollection)
self._observations[key] = callbackCollection
}
}
}
private extension EventCenter {
typealias Callback = Any
typealias CallbackSpec = (callback: Callback, operationQueue: OperationQueue?)
typealias CallbackCollection = [(observer: WeakWrapper<AnyObject>, callbacks: [CallbackSpec])]
struct Static {
static var DefaultInsance = EventCenter()
}
}
private func addHandler(_ handler: EventCenter.CallbackSpec, toHandlerCollection collection: inout EventCenter.CallbackCollection, forObserver observer: AnyObject) {
var found = false
var index = 0
for (possibleObserver, var callbacks) in collection {
if possibleObserver.value === observer {
callbacks.append((callback: handler.callback, operationQueue: handler.operationQueue))
collection[index] = (possibleObserver, callbacks)
found = true
break
}
index += 1
}
if !found {
collection.append((observer: WeakWrapper(observer), callbacks: [handler]))
}
}
private func removecallbacksForObserver(_ observer: AnyObject, fromHandlerCollection collection: inout EventCenter.CallbackCollection) {
var index = 0
for (possibleObserver, _) in collection {
if possibleObserver.value === observer {
collection.remove(at: index)
}
index += 1
}
}
| 2106438b5f5f738dacf6620d6d65facd | 37.585987 | 165 | 0.65038 | false | false | false | false |
ForrestAlfred/firefox-ios | refs/heads/master | Client/Frontend/Browser/TabTrayController.swift | mpl-2.0 | 4 | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import Foundation
import UIKit
import SnapKit
struct TabTrayControllerUX {
static let CornerRadius = CGFloat(4.0)
static let BackgroundColor = UIConstants.AppBackgroundColor
static let CellBackgroundColor = UIColor(red:0.95, green:0.95, blue:0.95, alpha:1)
static let TextBoxHeight = CGFloat(32.0)
static let FaviconSize = CGFloat(18.0)
static let Margin = CGFloat(15)
static let ToolbarBarTintColor = UIConstants.AppBackgroundColor
static let ToolbarButtonOffset = CGFloat(10.0)
static let TabTitleTextColor = UIColor.blackColor()
static let TabTitleTextFont = UIConstants.DefaultSmallFontBold
static let CloseButtonSize = CGFloat(18.0)
static let CloseButtonMargin = CGFloat(6.0)
static let CloseButtonEdgeInset = CGFloat(10)
static let NumberOfColumnsThin = 1
static let NumberOfColumnsWide = 3
static let CompactNumberOfColumnsThin = 2
// Moved from UIConstants temporarily until animation code is merged
static var StatusBarHeight: CGFloat {
if UIScreen.mainScreen().traitCollection.verticalSizeClass == .Compact {
return 0
}
return 20
}
}
protocol TabCellDelegate: class {
func tabCellDidClose(cell: TabCell)
}
// UIcollectionViewController doesn't let us specify a style for recycling views. We override the default style here.
class TabCell: UICollectionViewCell {
let backgroundHolder: UIView
let background: UIImageViewAligned
let titleText: UILabel
let title: UIVisualEffectView
let innerStroke: InnerStrokedView
let favicon: UIImageView
let closeButton: UIButton
var animator: SwipeAnimator!
weak var delegate: TabCellDelegate?
// Changes depending on whether we're full-screen or not.
var margin = CGFloat(0)
override init(frame: CGRect) {
self.backgroundHolder = UIView()
self.backgroundHolder.backgroundColor = UIColor.whiteColor()
self.backgroundHolder.layer.cornerRadius = TabTrayControllerUX.CornerRadius
self.backgroundHolder.clipsToBounds = true
self.backgroundHolder.backgroundColor = TabTrayControllerUX.CellBackgroundColor
self.background = UIImageViewAligned()
self.background.contentMode = UIViewContentMode.ScaleAspectFill
self.background.clipsToBounds = true
self.background.userInteractionEnabled = false
self.background.alignLeft = true
self.background.alignTop = true
self.favicon = UIImageView()
self.favicon.backgroundColor = UIColor.clearColor()
self.favicon.layer.cornerRadius = 2.0
self.favicon.layer.masksToBounds = true
self.title = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.ExtraLight))
self.title.layer.shadowColor = UIColor.blackColor().CGColor
self.title.layer.shadowOpacity = 0.2
self.title.layer.shadowOffset = CGSize(width: 0, height: 0.5)
self.title.layer.shadowRadius = 0
self.titleText = UILabel()
self.titleText.textColor = TabTrayControllerUX.TabTitleTextColor
self.titleText.backgroundColor = UIColor.clearColor()
self.titleText.textAlignment = NSTextAlignment.Left
self.titleText.userInteractionEnabled = false
self.titleText.numberOfLines = 1
self.titleText.font = TabTrayControllerUX.TabTitleTextFont
self.closeButton = UIButton()
self.closeButton.setImage(UIImage(named: "stop"), forState: UIControlState.Normal)
self.closeButton.imageEdgeInsets = UIEdgeInsetsMake(TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset, TabTrayControllerUX.CloseButtonEdgeInset)
self.title.addSubview(self.closeButton)
self.title.addSubview(self.titleText)
self.title.addSubview(self.favicon)
self.innerStroke = InnerStrokedView(frame: self.backgroundHolder.frame)
self.innerStroke.layer.backgroundColor = UIColor.clearColor().CGColor
super.init(frame: frame)
self.opaque = true
self.animator = SwipeAnimator(animatingView: self.backgroundHolder, container: self)
self.closeButton.addTarget(self.animator, action: "SELcloseWithoutGesture", forControlEvents: UIControlEvents.TouchUpInside)
contentView.addSubview(backgroundHolder)
backgroundHolder.addSubview(self.background)
backgroundHolder.addSubview(innerStroke)
backgroundHolder.addSubview(self.title)
self.accessibilityCustomActions = [
UIAccessibilityCustomAction(name: NSLocalizedString("Close", comment: "Accessibility label for action denoting closing a tab in tab list (tray)"), target: self.animator, selector: "SELcloseWithoutGesture")
]
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
let w = frame.width
let h = frame.height
backgroundHolder.frame = CGRect(x: margin,
y: margin,
width: w,
height: h)
background.frame = CGRect(origin: CGPointMake(0, 0), size: backgroundHolder.frame.size)
title.frame = CGRect(x: 0,
y: 0,
width: backgroundHolder.frame.width,
height: TabTrayControllerUX.TextBoxHeight)
favicon.frame = CGRect(x: 6,
y: (TabTrayControllerUX.TextBoxHeight - TabTrayControllerUX.FaviconSize)/2,
width: TabTrayControllerUX.FaviconSize,
height: TabTrayControllerUX.FaviconSize)
let titleTextLeft = favicon.frame.origin.x + favicon.frame.width + 6
titleText.frame = CGRect(x: titleTextLeft,
y: 0,
width: title.frame.width - titleTextLeft - margin - TabTrayControllerUX.CloseButtonSize - TabTrayControllerUX.CloseButtonMargin * 2,
height: title.frame.height)
innerStroke.frame = background.frame
closeButton.snp_makeConstraints { make in
make.size.equalTo(title.snp_height)
make.trailing.centerY.equalTo(title)
}
var top = (TabTrayControllerUX.TextBoxHeight - titleText.bounds.height) / 2.0
titleText.frame.origin = CGPoint(x: titleText.frame.origin.x, y: max(0, top))
}
override func prepareForReuse() {
// Reset any close animations.
backgroundHolder.transform = CGAffineTransformIdentity
backgroundHolder.alpha = 1
}
var tab: Browser? {
didSet {
titleText.text = tab?.title
if let favIcon = tab?.displayFavicon {
favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!)
}
}
}
override func accessibilityScroll(direction: UIAccessibilityScrollDirection) -> Bool {
var right: Bool
switch direction {
case .Left:
right = false
case .Right:
right = true
default:
return false
}
animator.close(right: right)
return true
}
}
class TabTrayController: UIViewController, UITabBarDelegate, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
var tabManager: TabManager!
private let CellIdentifier = "CellIdentifier"
var collectionView: UICollectionView!
var profile: Profile!
var numberOfColumns: Int {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
// iPhone 4-6+ portrait
if traitCollection.horizontalSizeClass == .Compact && traitCollection.verticalSizeClass == .Regular {
return compactLayout ? TabTrayControllerUX.CompactNumberOfColumnsThin : TabTrayControllerUX.NumberOfColumnsThin
} else {
return TabTrayControllerUX.NumberOfColumnsWide
}
}
var navBar: UIView!
var addTabButton: UIButton!
var settingsButton: UIButton!
var collectionViewTransitionSnapshot: UIView?
override func viewDidLoad() {
super.viewDidLoad()
view.accessibilityLabel = NSLocalizedString("Tabs Tray", comment: "Accessibility label for the Tabs Tray view.")
tabManager.addDelegate(self)
navBar = UIView()
navBar.backgroundColor = TabTrayControllerUX.BackgroundColor
let signInButton = UIButton.buttonWithType(UIButtonType.Custom) as! UIButton
signInButton.addTarget(self, action: "SELdidClickDone", forControlEvents: UIControlEvents.TouchUpInside)
signInButton.setTitle(NSLocalizedString("Sign in", comment: "Button that leads to Sign in section of the Settings sheet."), forState: UIControlState.Normal)
signInButton.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
// workaround for VoiceOver bug - if we create the button with UIButton.buttonWithType,
// it gets initial frame with height 0 and accessibility somehow does not update the height
// later and thus the button becomes completely unavailable to VoiceOver unless we
// explicitly set the height to some (reasonable) non-zero value.
// Also note that setting accessibilityFrame instead of frame has no effect.
signInButton.frame.size.height = signInButton.intrinsicContentSize().height
let navItem = UINavigationItem()
navItem.titleView = signInButton
signInButton.hidden = true //hiding sign in button until we decide on UX
addTabButton = UIButton()
addTabButton.setImage(UIImage(named: "add"), forState: .Normal)
addTabButton.addTarget(self, action: "SELdidClickAddTab", forControlEvents: .TouchUpInside)
addTabButton.accessibilityLabel = NSLocalizedString("Add Tab", comment: "Accessibility label for the Add Tab button in the Tab Tray.")
settingsButton = UIButton()
settingsButton.setImage(UIImage(named: "settings"), forState: .Normal)
settingsButton.addTarget(self, action: "SELdidClickSettingsItem", forControlEvents: .TouchUpInside)
settingsButton.accessibilityLabel = NSLocalizedString("Settings", comment: "Accessibility label for the Settings button in the Tab Tray.")
let flowLayout = UICollectionViewFlowLayout()
collectionView = UICollectionView(frame: view.frame, collectionViewLayout: flowLayout)
collectionView.dataSource = self
collectionView.delegate = self
collectionView.registerClass(TabCell.self, forCellWithReuseIdentifier: CellIdentifier)
collectionView.backgroundColor = TabTrayControllerUX.BackgroundColor
view.addSubview(collectionView)
view.addSubview(navBar)
view.addSubview(addTabButton)
view.addSubview(settingsButton)
makeConstraints()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
collectionView.reloadData()
}
private func makeConstraints() {
navBar.snp_makeConstraints { make in
let topLayoutGuide = self.topLayoutGuide as! UIView
make.top.equalTo(topLayoutGuide.snp_bottom)
make.height.equalTo(UIConstants.ToolbarHeight)
make.left.right.equalTo(self.view)
}
addTabButton.snp_makeConstraints { make in
make.trailing.bottom.equalTo(self.navBar)
make.size.equalTo(UIConstants.ToolbarHeight)
}
settingsButton.snp_makeConstraints { make in
make.leading.bottom.equalTo(self.navBar)
make.size.equalTo(UIConstants.ToolbarHeight)
}
collectionView.snp_makeConstraints { make in
make.top.equalTo(navBar.snp_bottom)
make.left.right.bottom.equalTo(self.view)
}
}
func cellHeightForCurrentDevice() -> CGFloat {
let compactLayout = profile.prefs.boolForKey("CompactTabLayout") ?? true
let shortHeight = (compactLayout ? TabTrayControllerUX.TextBoxHeight * 6 : TabTrayControllerUX.TextBoxHeight * 5)
if self.traitCollection.verticalSizeClass == UIUserInterfaceSizeClass.Compact {
return shortHeight
} else if self.traitCollection.horizontalSizeClass == UIUserInterfaceSizeClass.Compact {
return shortHeight
} else {
return TabTrayControllerUX.TextBoxHeight * 8
}
}
func SELdidClickDone() {
presentingViewController!.dismissViewControllerAnimated(true, completion: nil)
}
func SELdidClickSettingsItem() {
let controller = SettingsNavigationController()
controller.profile = profile
controller.tabManager = tabManager
controller.modalPresentationStyle = UIModalPresentationStyle.FormSheet
presentViewController(controller, animated: true, completion: nil)
}
func SELdidClickAddTab() {
// We're only doing one update here, but using a batch update lets us delay selecting the tab
// until after its insert animation finishes.
self.collectionView.performBatchUpdates({ _ in
let tab = self.tabManager.addTab()
self.tabManager.selectTab(tab)
}, completion: { finished in
if finished {
self.navigationController?.popViewControllerAnimated(true)
}
})
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
let tab = tabManager[indexPath.item]
tabManager.selectTab(tab)
self.navigationController?.popViewControllerAnimated(true)
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(CellIdentifier, forIndexPath: indexPath) as! TabCell
cell.animator.delegate = self
cell.delegate = self
if let tab = tabManager[indexPath.item] {
cell.titleText.text = tab.displayTitle
if !tab.displayTitle.isEmpty {
cell.accessibilityLabel = tab.displayTitle
} else {
cell.accessibilityLabel = AboutUtils.getAboutComponent(tab.url)
}
cell.isAccessibilityElement = true
cell.accessibilityHint = NSLocalizedString("Swipe right or left with three fingers to close the tab.", comment: "Accessibility hint for tab tray's displayed tab.")
if let favIcon = tab.displayFavicon {
cell.favicon.sd_setImageWithURL(NSURL(string: favIcon.url)!)
} else {
cell.favicon.image = UIImage(named: "defaultFavicon")
}
cell.background.image = tab.screenshot
}
return cell
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return tabManager.count
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAtIndex section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let cellWidth = (collectionView.bounds.width - TabTrayControllerUX.Margin * CGFloat(numberOfColumns + 1)) / CGFloat(numberOfColumns)
return CGSizeMake(cellWidth, self.cellHeightForCurrentDevice())
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAtIndex section: Int) -> UIEdgeInsets {
return UIEdgeInsetsMake(TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin, TabTrayControllerUX.Margin)
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAtIndex section: Int) -> CGFloat {
return TabTrayControllerUX.Margin
}
override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator)
collectionView.collectionViewLayout.invalidateLayout()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
}
extension TabTrayController: SwipeAnimatorDelegate {
func swipeAnimator(animator: SwipeAnimator, viewDidExitContainerBounds: UIView) {
let tabCell = animator.container as! TabCell
if let indexPath = self.collectionView.indexPathForCell(tabCell) {
if let tab = tabManager[indexPath.item] {
tabManager.removeTab(tab)
UIAccessibilityPostNotification(UIAccessibilityAnnouncementNotification, NSLocalizedString("Closing tab", comment: ""))
}
}
}
}
extension TabTrayController: TabManagerDelegate {
func tabManager(tabManager: TabManager, didSelectedTabChange selected: Browser?, previous: Browser?) {
// Our UI doesn't care about what's selected
}
func tabManager(tabManager: TabManager, didCreateTab tab: Browser, restoring: Bool) {
}
func tabManager(tabManager: TabManager, didAddTab tab: Browser, atIndex index: Int, restoring: Bool) {
self.collectionView.performBatchUpdates({ _ in
self.collectionView.insertItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)])
}, completion: { finished in
if finished {
tabManager.selectTab(tabManager[index])
// don't pop the tab tray view controller if it is not in the foreground
if self.presentedViewController == nil {
self.navigationController?.popViewControllerAnimated(true)
}
}
})
}
func tabManager(tabManager: TabManager, didRemoveTab tab: Browser, atIndex index: Int) {
var newTab: Browser? = nil
self.collectionView.performBatchUpdates({ _ in
self.collectionView.deleteItemsAtIndexPaths([NSIndexPath(forItem: index, inSection: 0)])
}, completion: { finished in
if tabManager.count == 0 {
newTab = tabManager.addTab()
}
})
}
func tabManagerDidAddTabs(tabManager: TabManager) {
}
func tabManagerDidRestoreTabs(tabManager: TabManager) {
}
}
extension TabTrayController: TabCellDelegate {
func tabCellDidClose(cell: TabCell) {
let indexPath = collectionView.indexPathForCell(cell)!
if let tab = tabManager[indexPath.item] {
tabManager.removeTab(tab)
}
}
}
extension TabTrayController: UIScrollViewAccessibilityDelegate {
func accessibilityScrollStatusForScrollView(scrollView: UIScrollView!) -> String! {
var visibleCells = collectionView.visibleCells() as! [TabCell]
var bounds = collectionView.bounds
bounds = CGRectOffset(bounds, collectionView.contentInset.left, collectionView.contentInset.top)
bounds.size.width -= collectionView.contentInset.left + collectionView.contentInset.right
bounds.size.height -= collectionView.contentInset.top + collectionView.contentInset.bottom
// visible cells do sometimes return also not visible cells when attempting to go past the last cell with VoiceOver right-flick gesture; so make sure we have only visible cells (yeah...)
visibleCells = visibleCells.filter { !CGRectIsEmpty(CGRectIntersection($0.frame, bounds)) }
var indexPaths = visibleCells.map { self.collectionView.indexPathForCell($0)! }
indexPaths.sort { $0.section < $1.section || ($0.section == $1.section && $0.row < $1.row) }
if indexPaths.count == 0 {
return NSLocalizedString("No tabs", comment: "Message spoken by VoiceOver to indicate that there are no tabs in the Tabs Tray")
}
let firstTab = indexPaths.first!.row + 1
let lastTab = indexPaths.last!.row + 1
let tabCount = collectionView.numberOfItemsInSection(0)
if (firstTab == lastTab) {
let format = NSLocalizedString("Tab %@ of %@", comment: "Message spoken by VoiceOver saying the position of the single currently visible tab in Tabs Tray, along with the total number of tabs. E.g. \"Tab 2 of 5\" says that tab 2 is visible (and is the only visible tab), out of 5 tabs total.")
return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: tabCount))
} else {
let format = NSLocalizedString("Tabs %@ to %@ of %@", comment: "Message spoken by VoiceOver saying the range of tabs that are currently visible in Tabs Tray, along with the total number of tabs. E.g. \"Tabs 8 to 10 of 15\" says tabs 8, 9 and 10 are visible, out of 15 tabs total.")
return String(format: format, NSNumber(integer: firstTab), NSNumber(integer: lastTab), NSNumber(integer: tabCount))
}
}
}
// A transparent view with a rectangular border with rounded corners, stroked
// with a semi-transparent white border.
class InnerStrokedView: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clearColor()
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func drawRect(rect: CGRect) {
let strokeWidth = 1.0 as CGFloat
let halfWidth = strokeWidth/2 as CGFloat
let path = UIBezierPath(roundedRect: CGRect(x: halfWidth,
y: halfWidth,
width: rect.width - strokeWidth,
height: rect.height - strokeWidth),
cornerRadius: TabTrayControllerUX.CornerRadius)
path.lineWidth = strokeWidth
UIColor.whiteColor().colorWithAlphaComponent(0.2).setStroke()
path.stroke()
}
}
| 2d77329077774c0838658644cfc97c99 | 42.466797 | 304 | 0.695619 | false | false | false | false |
bitboylabs/selluv-ios | refs/heads/master | selluv-ios/selluv-ios/Classes/Base/Extension/Date.swift | mit | 1 | //
// Date.swift
// selluv-ios
//
// Created by 조백근 on 2017. 1. 12..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import Foundation
extension Date {
static func isBetween(start: Date, end: Date) -> Bool {
return Date.isBetween(start: start, end: end, someday: Date())
}
static func isBetween(start: Date, end: Date, someday: Date) -> Bool {
let fallsBetween = (start...end).contains(someday)
return fallsBetween
}
static func timeAgoSince(_ date: Date) -> String {
let calendar = Calendar.current
let now = Date()
let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfYear, .month, .year]
let components = (calendar as NSCalendar).components(unitFlags, from: date, to: now, options: [])
if let year = components.year, year >= 2 {
return "\(year) 년 전"
}
if let year = components.year, year >= 1 {
return "지난해"
}
if let month = components.month, month >= 2 {
return "\(month) 개월 전"
}
if let month = components.month, month >= 1 {
return "지난달"
}
if let week = components.weekOfYear, week >= 2 {
return "\(week) 주 전"
}
if let week = components.weekOfYear, week >= 1 {
return "지난주"
}
if let day = components.day, day >= 2 {
return "\(day) 일 전"
}
if let day = components.day, day >= 1 {
return "어제"
}
if let hour = components.hour, hour >= 2 {
return "\(hour) 시간 전"
}
if let hour = components.hour, hour >= 1 {
return "한시간 전"
}
if let minute = components.minute, minute >= 2 {
return "\(minute) 분 전"
}
if let minute = components.minute, minute >= 1 {
return "일분전"
}
if let second = components.second, second >= 3 {
return "\(second) seconds ago"
}
return "지금"
}
}
| c19f086f68731df9331c0336aaa29413 | 24.528736 | 105 | 0.478163 | false | false | false | false |
isaced/ISEmojiView | refs/heads/master | Sources/ISEmojiView/Classes/Views/EmojiCollectionView/EmojiCollectionView.swift | mit | 1 | //
// EmojiCollectionView.swift
// ISEmojiView
//
// Created by Beniamin Sarkisyan on 01/08/2018.
//
import Foundation
import UIKit
/// emoji view action callback delegate
internal protocol EmojiCollectionViewDelegate: AnyObject {
/// did press a emoji button
///
/// - Parameters:
/// - emojiView: the emoji view
/// - emoji: a emoji
/// - selectedEmoji: the selected emoji
func emojiViewDidSelectEmoji(emojiView: EmojiCollectionView, emoji: Emoji, selectedEmoji: String)
/// changed section
///
/// - Parameters:
/// - category: current category
/// - emojiView: the emoji view
func emojiViewDidChangeCategory(_ category: Category, emojiView: EmojiCollectionView)
}
/// A emoji keyboard view
internal class EmojiCollectionView: UIView {
// MARK: - Public variables
/// the delegate for callback
internal weak var delegate: EmojiCollectionViewDelegate?
/// long press to pop preview effect like iOS10 system emoji keyboard, Default is true
internal var isShowPopPreview = true
internal var emojis: [EmojiCategory]! {
didSet {
collectionView.reloadData()
}
}
// MARK: - Private variables
private var scrollViewWillBeginDragging = false
private var scrollViewWillBeginDecelerating = false
private let emojiCellReuseIdentifier = "EmojiCell"
private lazy var emojiPopView: EmojiPopView = {
let emojiPopView = EmojiPopView()
emojiPopView.delegate = self
emojiPopView.isHidden = true
return emojiPopView
}()
// MARK: - IBOutlets
@IBOutlet private weak var collectionView: UICollectionView! {
didSet {
collectionView.register(EmojiCollectionCell.self, forCellWithReuseIdentifier: emojiCellReuseIdentifier)
}
}
// MARK: - Override variables
internal override var intrinsicContentSize: CGSize {
return CGSize(width: UIView.noIntrinsicMetric, height: frame.size.height)
}
// MARK: - Public
public func popPreviewShowing() -> Bool {
return !self.emojiPopView.isHidden;
}
// MARK: - Init functions
static func loadFromNib(emojis: [EmojiCategory]) -> EmojiCollectionView {
let nibName = String(describing: EmojiCollectionView.self)
guard let nib = Bundle.podBundle.loadNibNamed(nibName, owner: nil, options: nil) as? [EmojiCollectionView] else {
fatalError()
}
guard let view = nib.first else {
fatalError()
}
view.emojis = emojis
view.setupView()
return view
}
// MARK: - Override functions
override public func point(inside point: CGPoint, with event: UIEvent?) -> Bool {
guard point.y < 0 else {
return super.point(inside: point, with: event)
}
return point.y >= -TopPartSize.height
}
// MARK: - Internal functions
internal func updateRecentsEmojis(_ emojis: [Emoji]) {
self.emojis[0].emojis = emojis
collectionView.reloadSections(IndexSet(integer: 0))
}
internal func scrollToCategory(_ category: Category) {
guard var section = emojis.firstIndex(where: { $0.category == category }) else {
return
}
if category == .recents && emojis[section].emojis.isEmpty {
section = emojis.firstIndex(where: { $0.category == Category.smileysAndPeople })!
}
let indexPath = IndexPath(item: 0, section: section)
collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
}
}
// MARK: - UICollectionViewDataSource
extension EmojiCollectionView: UICollectionViewDataSource {
internal func numberOfSections(in collectionView: UICollectionView) -> Int {
return emojis.count
}
internal func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return emojis[section].emojis.count
}
internal func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let emojiCategory = emojis[indexPath.section]
let emoji = emojiCategory.emojis[indexPath.item]
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: emojiCellReuseIdentifier, for: indexPath) as! EmojiCollectionCell
if let selectedEmoji = emoji.selectedEmoji {
cell.setEmoji(selectedEmoji)
} else {
cell.setEmoji(emoji.emoji)
}
return cell
}
}
// MARK: - UICollectionViewDelegate
extension EmojiCollectionView: UICollectionViewDelegate {
internal func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
guard emojiPopView.isHidden else {
dismissPopView(false)
return
}
let emojiCategory = emojis[indexPath.section]
let emoji = emojiCategory.emojis[indexPath.item]
delegate?.emojiViewDidSelectEmoji(emojiView: self, emoji: emoji, selectedEmoji: emoji.selectedEmoji ?? emoji.emoji)
}
func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
if !scrollViewWillBeginDecelerating && !scrollViewWillBeginDragging {
return
}
if let indexPath = collectionView.indexPathsForVisibleItems.min() {
let emojiCategory = emojis[indexPath.section]
delegate?.emojiViewDidChangeCategory(emojiCategory.category, emojiView: self)
}
}
}
// MARK: - UICollectionViewDelegateFlowLayout
extension EmojiCollectionView: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
var inset = UIEdgeInsets.zero
if let recentsEmojis = emojis.first(where: { $0.category == Category.recents }) {
if (!recentsEmojis.emojis.isEmpty && section != 0) || (recentsEmojis.emojis.isEmpty && section > 1) {
inset.left = 15
}
}
if section == 0 {
inset.left = 3
}
if section == emojis.count - 1 {
inset.right = 4
}
return inset
}
}
// MARK: - UIScrollView
extension EmojiCollectionView {
internal func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
scrollViewWillBeginDragging = true
}
internal func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
scrollViewWillBeginDecelerating = true
}
internal func scrollViewDidScroll(_ scrollView: UIScrollView) {
dismissPopView(false)
}
internal func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
scrollViewWillBeginDragging = false
}
internal func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
scrollViewWillBeginDecelerating = false
}
}
// MARK: - EmojiPopViewDelegate
extension EmojiCollectionView: EmojiPopViewDelegate {
internal func emojiPopViewShouldDismiss(emojiPopView: EmojiPopView) {
dismissPopView(true)
}
}
// MARK: - Private functions
extension EmojiCollectionView {
private func setupView() {
let emojiLongPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(emojiLongPressHandle))
addGestureRecognizer(emojiLongPressGestureRecognizer)
addSubview(emojiPopView)
}
@objc private func emojiLongPressHandle(sender: UILongPressGestureRecognizer) {
func longPressLocationInEdge(_ location: CGPoint) -> Bool {
let edgeRect = collectionView.bounds.inset(by: collectionView.contentInset)
return edgeRect.contains(location)
}
guard isShowPopPreview else { return }
let location = sender.location(in: collectionView)
guard longPressLocationInEdge(location) else {
dismissPopView(true)
return
}
guard let indexPath = collectionView.indexPathForItem(at: location) else {
return
}
guard let attr = collectionView.layoutAttributesForItem(at: indexPath) else {
return
}
let emojiCategory = emojis[indexPath.section]
let emoji = emojiCategory.emojis[indexPath.item]
if sender.state == .ended && emoji.emojis.count == 1 {
dismissPopView(true)
return
}
emojiPopView.setEmoji(emoji)
let cellRect = attr.frame
let cellFrameInSuperView = collectionView.convert(cellRect, to: self)
let emojiPopLocation = CGPoint(
x: cellFrameInSuperView.origin.x - ((TopPartSize.width - BottomPartSize.width) / 2.0) + 5,
y: cellFrameInSuperView.origin.y - TopPartSize.height - 10
)
emojiPopView.move(location: emojiPopLocation, animation: sender.state != .began)
}
private func dismissPopView(_ usePopViewEmoji: Bool) {
emojiPopView.dismiss()
let currentEmoji = emojiPopView.currentEmoji
if !currentEmoji.isEmpty && usePopViewEmoji {
self.delegate?.emojiViewDidSelectEmoji(emojiView: self, emoji: Emoji(emojis: emojiPopView.emojiArray), selectedEmoji: currentEmoji)
}
emojiPopView.currentEmoji = ""
}
}
| 28414361a39fa708c30190c3fdab3ad5 | 30.025157 | 162 | 0.643016 | false | false | false | false |
gvsucis/mobile-app-dev-book | refs/heads/master | iOS/ch12/TraxyApp/TraxyApp/LoginViewController.swift | gpl-3.0 | 2 | //
// ViewController.swift
// TraxyApp
//
// Created by Jonathan Engelsma on 1/5/17.
// Copyright © 2017 Jonathan Engelsma. All rights reserved.
//
import UIKit
import FirebaseAuth
class LoginViewController: TraxyLoginViewController {
@IBOutlet weak var emailField: UITextField!
@IBOutlet weak var passwordField: UITextField!
var validationErrors = ""
override func viewDidLoad() {
super.viewDidLoad()
// dismiss keyboard when tapping outside oftext fields
let detectTouch = UITapGestureRecognizer(target: self, action:
#selector(self.dismissKeyboard))
self.view.addGestureRecognizer(detectTouch)
// make this controller the delegate of the text fields.
self.emailField.delegate = self
self.passwordField.delegate = self
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@objc func dismissKeyboard() {
self.view.endEditing(true)
}
func validateFields() -> Bool {
let pwOk = self.isEmptyOrNil(password: self.passwordField.text)
if !pwOk {
self.validationErrors += "Password cannot be blank. "
}
let emailOk = self.isValidEmail(emailStr: self.emailField.text)
if !emailOk {
self.validationErrors += "Invalid email address."
}
return emailOk && pwOk
}
@IBAction func signupButtonPressed(_ sender: UIButton) {
if self.validateFields() {
print("Congratulations! You entered correct values.")
Auth.auth().signIn(withEmail: self.emailField.text!, password:
self.passwordField.text!) { (user, error) in
if let _ = user {
//self.performSegue(withIdentifier: "segueToMain", sender: self)
self.dismiss(animated: true, completion: nil)
} else {
self.reportError(msg: (error?.localizedDescription)!)
self.passwordField.text = ""
self.passwordField.becomeFirstResponder()
}
}
} else {
self.reportError(msg: self.validationErrors)
}
}
// @IBAction func logout(segue : UIStoryboardSegue) {
// do {
// try FIRAuth.auth()?.signOut()
// print("Logged out")
// } catch let signOutError as NSError {
// print ("Error signing out: %@", signOutError)
// }
//
// self.passwordField.text = ""
// }
// override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// if segue.identifier == "segueToMain" {
// if let destVC = segue.destination.childViewControllers[0] as? MainViewController {
// destVC.userEmail = self.emailField.text
// }
// }
// }
}
extension LoginViewController : UITextFieldDelegate {
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == self.emailField {
self.passwordField.becomeFirstResponder()
} else {
if self.validateFields() {
print(NSLocalizedString("Congratulations! You entered correct values.", comment: ""))
}
}
return true
}
}
| f0a748b228bd7d40da7a245d8c067323 | 31.113208 | 101 | 0.585488 | false | false | false | false |
terietor/GTForms | refs/heads/master | Example/SelectionFormTableViewController.swift | mit | 1 | // Copyright (c) 2015-2016 Giorgos Tsiapaliokas <[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 UIKit
import GTForms
import SnapKit
class ExampleSelectionCustomizedFormCell: SelectionCustomizedFormCell {
fileprivate let label = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.label.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(label)
self.label.snp.makeConstraints() { make in
make.edges.equalToSuperview().inset(UIEdgeInsetsMake(10, 10, 10, 10))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func configure(_ text: String, detailText: String?) {
self.label.text = text
self.contentView.backgroundColor = UIColor.red
}
}
class ExampleSelectionCustomizedFormItemCell: SelectionCustomizedFormItemCell {
fileprivate let label = UILabel()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.label.translatesAutoresizingMaskIntoConstraints = false
self.contentView.addSubview(label)
self.label.snp.makeConstraints() { make in
make.edges.equalTo(self.contentView).inset(UIEdgeInsetsMake(10, 10, 10, 10))
}
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func configure(_ text: String, detailText: String?, isSelected: Bool) {
let label = UILabel()
label.translatesAutoresizingMaskIntoConstraints = false
label.text = text
self.contentView.addSubview(label)
label.snp.makeConstraints() { make in
make.edges.equalTo(self.contentView).inset(UIEdgeInsetsMake(10, 10, 10, 10))
}
self.contentView.backgroundColor = isSelected ? UIColor.yellow : UIColor.white
}
override func didSelect() {
self.contentView.backgroundColor = UIColor.yellow
}
override func didDeSelect() {
self.contentView.backgroundColor = UIColor.white
}
}
class SelectionFormTableViewController: FormTableViewController {
var selectionForm: SelectionForm!
override func viewDidLoad() {
super.viewDidLoad()
let selectionItems = [
SelectionFormItem(text: "Apple"),
SelectionFormItem(text: "Orange")
]
selectionForm = SelectionForm(
items: selectionItems,
text: "Choose a fruit"
)
selectionForm.textColor = UIColor.red
selectionForm.textFont = UIFont
.preferredFont(forTextStyle: UIFontTextStyle.headline)
selectionForm.allowsMultipleSelection = true
let section = FormSection()
section.addRow(selectionForm)
self.formSections.append(section)
let selectionItems2 = [
SelectionFormItem(text: "vim"),
SelectionFormItem(text: "emacs")
]
let selectionForm2 = SelectionForm(
items: selectionItems2,
text: "Choose an editor"
)
selectionForm2.allowsMultipleSelection = false
selectionForm2.shouldAlwaysShowAllItems = true
selectionForm2.didSelectItem = { item in
print("Did Select: \(item.text)")
}
selectionForm2.didDeselectItem = { item in
print("Did Deselect: \(item.text)")
}
let section2 = FormSection()
section2.addRow(selectionForm2)
self.formSections.append(section2)
let selectionItems3 = [
SelectionCustomizedFormItem(text: "customized vim", cellReuseIdentifier: "selectionCustomizedCellItem"),
SelectionCustomizedFormItem(text: "customized emacs", cellReuseIdentifier: "selectionCustomizedCellItem"),
SelectionCustomizedFormItem(text: "customized atom", cellReuseIdentifier: "selectionCustomizedCellItem")
]
let selectionForm3 = SelectionCustomizedForm(
items: selectionItems3,
text: "Choose an editor (customized)",
cellReuseIdentifier: "selectionCustomizedCell"
)
selectionForm3.allowsMultipleSelection = false
self.tableView.register(
ExampleSelectionCustomizedFormItemCell.self,
forCellReuseIdentifier: "selectionCustomizedCellItem"
)
self.tableView.register(
ExampleSelectionCustomizedFormCell.self,
forCellReuseIdentifier: "selectionCustomizedCell"
)
let section3 = FormSection()
section3.addRow(selectionForm3)
self.formSections.append(section3)
let selectionItems4 = [
SelectionCustomizedFormItem(text: "Apple", cellReuseIdentifier: "selectionCustomizedCellItem"),
SelectionCustomizedFormItem(text: "Orange", cellReuseIdentifier: "selectionCustomizedCellItem"),
SelectionCustomizedFormItem(text: "Carrot", cellReuseIdentifier: "selectionCustomizedCellItem")
]
let selectionForm4 = SelectionCustomizedForm(
items: selectionItems4,
text: "Choose a fruit (customized)",
cellReuseIdentifier: "selectionCustomizedCell"
)
selectionForm4.shouldAlwaysShowAllItems = true
let section4 = FormSection()
section4.addRow(selectionForm4)
self.formSections.append(section4)
}
}
| 81b67afea9c52f42de35aebfed8c11ac | 34.094737 | 118 | 0.683413 | false | false | false | false |
getcircle/protobuf-swift | refs/heads/master | src/ProtocolBuffers/runtime-pb-swift/RingBuffer.swift | apache-2.0 | 3 | // Protocol Buffers for Swift
//
// Copyright 2014 Alexey Khohklov(AlexeyXo).
// Copyright 2008 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License")
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
internal class RingBuffer
{
internal var buffer:NSMutableData
var position:Int32 = 0
var tail:Int32 = 0
init(data:NSMutableData)
{
buffer = NSMutableData(data: data)
}
func freeSpace() ->UInt32
{
var res:UInt32 = 0
if position < tail
{
res = UInt32(tail - position)
}
else
{
let dataLength = buffer.length
res = UInt32((Int32(dataLength) - position) + tail)
}
if tail != 0
{
res -= 1
}
return res
}
func appendByte(byte aByte:UInt8) -> Bool
{
if freeSpace() < 1
{
return false
}
let pointer = UnsafeMutablePointer<UInt8>(buffer.mutableBytes)
let bpointer = UnsafeMutableBufferPointer(start: pointer, count: buffer.length)
bpointer[Int(position++)] = aByte
return true
}
func appendData(input:NSData, offset:Int32, length:Int32) -> Int32
{
var totalWritten:Int32 = 0
var aLength = length
var aOffset = offset
if (position >= tail)
{
totalWritten = min(Int32(buffer.length) - Int32(position), Int32(aLength))
memcpy(buffer.mutableBytes + Int(position), input.bytes + Int(aOffset), Int(totalWritten))
position += totalWritten
if totalWritten == aLength
{
return aLength
}
aLength -= Int32(totalWritten)
aOffset += Int32(totalWritten)
}
let freeSpaces:UInt32 = freeSpace()
if freeSpaces == 0
{
return totalWritten
}
if (position == Int32(buffer.length)) {
position = 0
}
let written:Int32 = min(Int32(freeSpaces), aLength)
memcpy(buffer.mutableBytes + Int(position), input.bytes + Int(aOffset), Int(written))
position += written
totalWritten += written
return totalWritten
}
func flushToOutputStream(stream:NSOutputStream) ->Int32
{
var totalWritten:Int32 = 0
let data = buffer
let pointer = UnsafeMutablePointer<UInt8>(data.mutableBytes)
if tail > position
{
let written:Int = stream.write(pointer + Int(tail), maxLength:Int(buffer.length - Int(tail)))
if written <= 0
{
return totalWritten
}
totalWritten+=Int32(written)
tail += Int32(written)
if (tail == Int32(buffer.length)) {
tail = 0
}
}
if (tail < position) {
let written:Int = stream.write(pointer + Int(tail), maxLength:Int(position - tail))
if (written <= 0)
{
return totalWritten
}
totalWritten += Int32(written)
tail += Int32(written)
}
if (tail == position) {
tail = 0
position = 0
}
if (position == Int32(buffer.length) && tail > 0) {
position = 0
}
if (tail == Int32(buffer.length)) {
tail = 0
}
return totalWritten
}
}
| ce81940aa9a0358f622f04e5a0c694f2 | 26.47651 | 105 | 0.531021 | false | false | false | false |
pikachu987/PKCUtil | refs/heads/master | PKCUtil/Classes/UI/UIView+.swift | mit | 1 | //Copyright (c) 2017 pikachu987 <[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 UIKit
public extension UIView {
// MARK: initialize
public convenience init(color: UIColor) {
self.init()
self.backgroundColor = color
}
// MARK: property
/// view To UIImage
public var imageWithView: UIImage? {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, self.isOpaque, 0.0)
self.drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
// MARK: func
/**
addSubviewEdgeConstraint
- parameter view: UIView
- parameter leading: CGFloat
- parameter top: CGFloat
- parameter trailing: CGFloat
- parameter bottom: CGFloat
- returns: [NSLayoutConstraint]
*/
@discardableResult
public func addSubviewEdgeConstraint(
_ view: UIView,
leading: CGFloat = 0,
top: CGFloat = 0,
trailing: CGFloat = 0,
bottom: CGFloat = 0) -> [NSLayoutConstraint]{
self.addSubview(view)
return self.addEdgesConstraints(view, leading: leading, top: top, trailing: trailing, bottom: bottom)
}
/**
addEdgesConstraints
- parameter view: UIView
- parameter leading: CGFloat
- parameter top: CGFloat
- parameter trailing: CGFloat
- parameter bottom: CGFloat
- returns: [NSLayoutConstraint]
*/
@discardableResult
public func addEdgesConstraints(
_ view: UIView,
leading: CGFloat = 0,
top: CGFloat = 0,
trailing: CGFloat = 0,
bottom: CGFloat = 0) -> [NSLayoutConstraint]{
view.translatesAutoresizingMaskIntoConstraints = false
let leadingConstraint = NSLayoutConstraint(
item: self,
attribute: .leading,
relatedBy: .equal,
toItem: view,
attribute: .leading,
multiplier: 1,
constant: leading
)
let trailingConstraint = NSLayoutConstraint(
item: self,
attribute: .trailing,
relatedBy: .equal,
toItem: view,
attribute: .trailing,
multiplier: 1,
constant: trailing
)
let topConstraint = NSLayoutConstraint(
item: self,
attribute: .top,
relatedBy: .equal,
toItem: view,
attribute: .top,
multiplier: 1,
constant: top
)
let bottomConstraint = NSLayoutConstraint(
item: self,
attribute: .bottom,
relatedBy: .equal,
toItem: view,
attribute: .bottom,
multiplier: 1,
constant: bottom
)
let constraints = [ leadingConstraint, trailingConstraint, topConstraint, bottomConstraint ]
self.addConstraints(constraints)
return constraints
}
/**
horizontalLayout
- parameter left: CGFloat
- parameter right: CGFloat
- returns: [NSLayoutConstraint]
*/
@discardableResult
public func horizontalLayout(left: CGFloat = 0, right: CGFloat = 0) -> [NSLayoutConstraint]{
return NSLayoutConstraint.constraints(withVisualFormat: "H:|-\(left)-[view]-\(right)-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["view": self])
}
/**
verticalLayout
- parameter top: CGFloat
- parameter bottom: CGFloat
- returns: [NSLayoutConstraint]
*/
@discardableResult
public func verticalLayout(top: CGFloat = 0, bottom: CGFloat = 0) -> [NSLayoutConstraint]{
return NSLayoutConstraint.constraints(withVisualFormat: "V:|-\(top)-[view]-\(bottom)-|", options: NSLayoutFormatOptions.alignAllLeading, metrics: nil, views: ["view": self])
}
/**
pattern border
- parameter color: UIColor
- parameter width: CGFloat
- parameter cornerRadius: CGFloat
- parameter dashPattern: [NSNumber]
- returns: CAShapeLayer
*/
@discardableResult
public func addDashedBorder(_ color : UIColor, borderwidth : CGFloat = 1, cornerRadius : CGFloat, dashPattern : [NSNumber]) -> CAShapeLayer{
let shapeLayer:CAShapeLayer = CAShapeLayer()
let frameSize = self.frame.size
let shapeRect = CGRect(x: 0, y: 0, width: frameSize.width, height: frameSize.height)
shapeLayer.bounds = shapeRect
shapeLayer.position = CGPoint(x: frameSize.width/2, y: frameSize.height/2)
shapeLayer.fillColor = UIColor.clear.cgColor
shapeLayer.strokeColor = color.cgColor
shapeLayer.lineWidth = borderwidth
shapeLayer.lineJoin = kCALineJoinRound
shapeLayer.lineDashPattern = dashPattern
shapeLayer.path = UIBezierPath(roundedRect: shapeRect, cornerRadius: cornerRadius).cgPath
self.layer.addSublayer(shapeLayer)
return shapeLayer
}
}
| 39ae2d5248956ff5d3c8ae0ad1aa0012 | 31.621053 | 181 | 0.633269 | false | false | false | false |
crossroadlabs/ExecutionContext | refs/heads/master | ExecutionContext/DefaultExecutionContext.swift | apache-2.0 | 1 | //===--- DefaultExecutionContext.swift ------------------------------------------------------===//
//Copyright (c) 2016 Daniel Leping (dileping)
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
import Foundation
#if !os(Linux) || dispatch
public typealias DefaultExecutionContext = DispatchExecutionContext
#else
public typealias DefaultExecutionContext = PThreadExecutionContext
#endif
public protocol DefaultExecutionContextType : ExecutionContextType {
init(kind:ExecutionContextKind)
static var main:ExecutionContextType {
get
}
static var global:ExecutionContextType {
get
}
} | eb355d106f023862eff49c9ae7df1993 | 30.692308 | 98 | 0.652632 | false | false | false | false |
popricoly/Contacts | refs/heads/master | Sources/Contacts/AppDelegate.swift | mit | 1 | //
// AppDelegate.swift
// Contacts
//
// Created by Olexandr Matviichuk on 7/25/17.
// Copyright © 2017 Olexandr Matviichuk. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
if UserDefaults.standard.runFirstly {
loadContacts()
UserDefaults.standard.runFirstly = false
}
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 invalidate graphics rendering callbacks. 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 active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
}
func loadContacts() {
do {
if let contactsJsonPath = Bundle.main.url(forResource: "Contacts", withExtension: "json") {
let data = try Data(contentsOf: contactsJsonPath)
let json = try JSONSerialization.jsonObject(with: data, options: [])
for contactInDictionary in (json as? [Dictionary<String, String>])! {
let firstName = contactInDictionary["firstName"] ?? ""
let lastName = contactInDictionary["lastName"] ?? ""
let phoneNumber = contactInDictionary["phoneNumber"] ?? ""
let streetAddress1 = contactInDictionary["streetAddress1"] ?? ""
let streetAddress2 = contactInDictionary["streetAddress2"] ?? ""
let city = contactInDictionary["city"] ?? ""
let state = contactInDictionary["state"] ?? ""
let zipCode = contactInDictionary["zipCode"] ?? ""
OMContactsStorage.sharedStorage.saveContactWith(firstName: firstName, lastName: lastName, phoneNumber: phoneNumber, StreetAddress1: streetAddress1, StreetAddress2: streetAddress2, city: city, state: state, zipCode: zipCode)
}
}
} catch {
print("\(error.localizedDescription)")
}
}
}
| e3d118e416cd2a5f9bd96e56d27b41fd | 51.366197 | 285 | 0.681011 | false | false | false | false |
objecthub/swift-numberkit | refs/heads/master | Sources/NumberKit/IntegerNumber.swift | apache-2.0 | 1 | //
// IntegerNumber.swift
// NumberKit
//
// Created by Matthias Zenger on 23/09/2017.
// Copyright © 2015-2020 Matthias Zenger. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
import Foundation
/// Protocol `IntegerNumber` is used in combination with struct `Rational<T>`.
/// It defines the functionality needed for a signed integer implementation to
/// build rational numbers on top. The `SignedInteger` protocol from the Swift 4
/// standard library is unfortunately not sufficient as it doesn't provide access
/// to methods reporting overflows explicitly. Furthermore, `BigInt` is not yet
/// compliant with `SignedInteger`.
public protocol IntegerNumber: SignedNumeric,
Comparable,
Hashable,
CustomStringConvertible {
/// Value zero
static var zero: Self { get }
/// Value one
static var one: Self { get }
/// Value two
static var two: Self { get }
/// Division operation.
///
/// - Note: It's inexplicable to me why this operation is missing in `SignedNumeric`.
static func /(lhs: Self, rhs: Self) -> Self
/// Division operation.
///
/// - Note: It's inexplicable to me why this operation is missing in `SignedNumeric`.
static func /=(lhs: inout Self, rhs: Self)
/// Remainder operation.
///
/// - Note: It's inexplicable to me why this operation is missing in `SignedNumeric`.
static func %(lhs: Self, rhs: Self) -> Self
/// Constructs an `IntegerNumber` from an `Int64` value. This constructor might crash if
/// the value cannot be converted to this type.
///
/// - Note: This is a hack right now.
init(_ value: Int64)
/// Constructs an `IntegerNumber` from a `Double` value. This constructor might crash if
/// the value cannot be converted to this type.
init(_ value: Double)
/// Returns the integer as a `Double`.
var doubleValue: Double { get }
/// Computes the power of `self` with exponent `exp`.
func toPower(of exp: Self) -> Self
/// Returns true if this is an odd number.
var isOdd: Bool { get }
/// Adds `rhs` to `self` and reports the result together with a boolean indicating an overflow.
func addingReportingOverflow(_ rhs: Self) -> (partialValue: Self, overflow: Bool)
/// Subtracts `rhs` from `self` and reports the result together with a boolean indicating
/// an overflow.
func subtractingReportingOverflow(_ rhs: Self) -> (partialValue: Self, overflow: Bool)
/// Multiplies `rhs` with `self` and reports the result together with a boolean indicating
/// an overflow.
func multipliedReportingOverflow(by rhs: Self) -> (partialValue: Self, overflow: Bool)
/// Divides `self` by `rhs` and reports the result together with a boolean indicating
/// an overflow.
func dividedReportingOverflow(by rhs: Self) -> (partialValue: Self, overflow: Bool)
/// Computes the remainder from dividing `self` by `rhs` and reports the result together
/// with a boolean indicating an overflow.
func remainderReportingOverflow(dividingBy rhs: Self) -> (partialValue: Self, overflow: Bool)
}
/// Provide default implementations of this protocol
extension IntegerNumber {
public func toPower(of exp: Self) -> Self {
precondition(exp >= 0, "IntegerNumber.toPower(of:) with negative exponent")
var (expo, radix) = (exp, self)
var res = Self.one
while expo != 0 {
if expo.isOdd {
res *= radix
}
expo /= Self.two
radix *= radix
}
return res
}
}
/// Provide default implementations of fields needed by this protocol in all the fixed
/// width numeric types.
extension FixedWidthInteger {
public static var zero: Self {
return 0
}
public static var one: Self {
return 1
}
public static var two: Self {
return 2
}
public var isOdd: Bool {
return (self & 1) == 1
}
}
extension Int: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension UInt: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension Int8: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension UInt8: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension Int16: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension UInt16: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension Int32: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension UInt32: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension Int64: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
extension UInt64: IntegerNumber {
public var doubleValue: Double {
return Double(self)
}
}
| 011a03a7fba39740ebdf9ae3679e5aa7 | 27.186528 | 97 | 0.678125 | false | false | false | false |
CoreAnimationAsSwift/WZHQZhiBo | refs/heads/master | ZhiBo/ZhiBo/Main/View/PageContentView.swift | mit | 1 | //
// PageContentView.swift
// ZhiBo
//
// Created by mac on 16/10/30.
// Copyright © 2016年 mac. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(_ contentView : PageContentView,progress:CGFloat,sourceIndex:Int,targetIndex:Int)
}
private let contentCellID = "contentCellID"
class PageContentView: UIView {
//是否禁止执行代理方法
var isYes:Bool = false
weak var delegate:PageContentViewDelegate?
fileprivate var startOffsetX :CGFloat = 0
fileprivate var childVCs:[UIViewController]
fileprivate weak var prententVC:UIViewController?
//MARK:-懒加载属性
fileprivate lazy var collectionView:UICollectionView = {[weak self] in
let layout = UICollectionViewFlowLayout()
layout.minimumInteritemSpacing = 0
layout.minimumLineSpacing = 0
layout.itemSize = self!.bounds.size
layout.scrollDirection = .horizontal
let collecton = UICollectionView(frame: self!.bounds, collectionViewLayout: layout)
collecton.showsHorizontalScrollIndicator = false
collecton.bounces = false
collecton.isPagingEnabled = true
collecton.dataSource = self
collecton.delegate = self
collecton.register(UICollectionViewCell.self, forCellWithReuseIdentifier: contentCellID)
return collecton
}()
init(frame: CGRect,childVCs:[UIViewController],prententVC:UIViewController?) {
self.childVCs = childVCs
self.prententVC = prententVC
super.init(frame: frame)
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension PageContentView {
fileprivate func setupUI() {
//1将子控制器添加到父控制器上
for childVC in childVCs {
prententVC!.addChildViewController(childVC)
}
//2创建集合视图
addSubview(self.collectionView)
}
}
//MARK:-数据源协议
extension PageContentView:UICollectionViewDataSource {
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVCs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: contentCellID, for: indexPath)
//循环利用,先移除,在添加
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let chiledVC = childVCs[indexPath.item]
chiledVC.view.frame = cell.contentView.bounds
cell.contentView.addSubview(chiledVC.view)
return cell
}
}
//MARK: - 公开的方法
extension PageContentView {
func setupSelectedIndex(_ index:Int) {
isYes = true
let offsetX = CGFloat(index) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
// collectionView.scrollRectToVisible(CGRect(origin: CGPoint(x: offsetX, y: 0), size: frame.size), animated: true)
}
}
//MARK: - 代理
extension PageContentView:UICollectionViewDelegate {
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isYes = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
if isYes {
return
}
//1定义需要获取的数据
var progress :CGFloat = 0
var sourceIndex :Int = 0
var targetIndex : Int = 0
//2判断滑动方向
let currecntOffsetX = scrollView.contentOffset.x
if currecntOffsetX > startOffsetX { //左滑
//floor 取整
progress = currecntOffsetX / bounds.width - floor(currecntOffsetX / bounds.width)
sourceIndex = Int(currecntOffsetX / bounds.width)
targetIndex = sourceIndex + 1
if targetIndex >= childVCs.count {
targetIndex = childVCs.count - 1
}
if currecntOffsetX - startOffsetX == bounds.width {
progress = 1
targetIndex = sourceIndex
}
}else {
progress = 1 - (currecntOffsetX / bounds.width - floor(currecntOffsetX / bounds.width))
targetIndex = Int(currecntOffsetX / bounds.width)
sourceIndex = targetIndex + 1
if sourceIndex >= childVCs.count {
sourceIndex = childVCs.count - 1
}
if currecntOffsetX - startOffsetX == -bounds.width {
progress = 1
sourceIndex = targetIndex
}
}
//3
// print("1--\(progress) + 2--\(sourceIndex) + 3--\(targetIndex)")
delegate?.pageContentView(self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
}
| d94097bfc973ad551b82a2de7107741d | 35.218045 | 121 | 0.647498 | false | false | false | false |
Tanglo/VergeOfStrife | refs/heads/master | Vos Map Maker/VoSMapDocument.swift | mit | 1 | //
// VoSMapDocument
// Vos Map Maker
//
// Created by Lee Walsh on 30/03/2015.
// Copyright (c) 2015 Lee David Walsh. All rights reserved.
//
import Cocoa
class VoSMapDocument: NSDocument {
var map = VoSMap()
var mapView: VoSMapView?
@IBOutlet var scrollView: NSScrollView?
@IBOutlet var tileWidthField: NSTextField?
@IBOutlet var tileHeightField: NSTextField?
override init() {
super.init()
// Add your subclass-specific initialization here.
map = VoSMap()
}
override func windowControllerDidLoadNib(aController: NSWindowController) {
super.windowControllerDidLoadNib(aController)
// Add any code here that needs to be executed once the windowController has loaded the document's window.
let (rows,columns) = map.grid.gridSize()
mapView = VoSMapView(frame: NSRect(x: 0.0, y: 0.0, width: Double(columns)*map.tileSize.width, height: Double(rows)*map.tileSize.height))
scrollView!.documentView = mapView
tileWidthField!.doubleValue = map.tileSize.width
tileHeightField!.doubleValue = map.tileSize.height
}
override class func autosavesInPlace() -> Bool {
return true
}
override var windowNibName: String? {
// Returns the nib file name of the document
// If you need to use a subclass of NSWindowController or if your document supports multiple NSWindowControllers, you should remove this property and override -makeWindowControllers instead.
return "VoSMapDocument"
}
override func dataOfType(typeName: String, error outError: NSErrorPointer) -> NSData? {
// Insert code here to write your document to data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning nil.
// You can also choose to override fileWrapperOfType:error:, writeToURL:ofType:error:, or writeToURL:ofType:forSaveOperation:originalContentsURL:error: instead.
outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
return NSKeyedArchiver.archivedDataWithRootObject(map)
}
override func readFromData(data: NSData, ofType typeName: String, error outError: NSErrorPointer) -> Bool {
// Insert code here to read your document from the given data of the specified type. If outError != nil, ensure that you create and set an appropriate error when returning false.
// You can also choose to override readFromFileWrapper:ofType:error: or readFromURL:ofType:error: instead.
// If you override either of these, you should also override -isEntireFileLoaded to return NO if the contents are lazily loaded.
// let testData = NSData() //data
// println("before: \(map.someVar)")
let newMap: AnyObject? = NSKeyedUnarchiver.unarchiveObjectWithData(data) //testData)
if let testMap = newMap as? VoSMap {
map = newMap! as! VoSMap
// println("after: \(map.someVar)")
return true
}
outError.memory = NSError(domain: NSOSStatusErrorDomain, code: unimpErr, userInfo: nil)
return false
}
@IBAction func importMapFromCSV(sender: AnyObject) {
let importOpenPanel = NSOpenPanel()
importOpenPanel.canChooseDirectories = false
importOpenPanel.canChooseFiles = true
importOpenPanel.allowsMultipleSelection = false
importOpenPanel.allowedFileTypes = ["csv", "CSV"]
let result = importOpenPanel.runModal()
if result == NSModalResponseOK {
var outError: NSError?
let mapString: String? = String(contentsOfFile: importOpenPanel.URL!.path!, encoding: NSUTF8StringEncoding, error: &outError)
if (mapString != nil) {
map.importMapFromString(mapString!)
updateMapView()
} else {
let errorAlert = NSAlert(error: outError!)
errorAlert.runModal()
}
}
}
func updateMapView() {
let (rows,columns) = map.grid.gridSize()
mapView!.frame = NSRect(x: 0.0, y: 0.0, width: Double(columns)*map.tileSize.width, height: Double(rows)*map.tileSize.height)
mapView!.needsDisplay = true
}
@IBAction func saveAsPdf(sender: AnyObject){
let savePanel = NSSavePanel()
savePanel.allowedFileTypes = ["pdf", "PDF"]
let saveResult = savePanel.runModal()
if saveResult == NSModalResponseOK {
let pdfData = mapView!.dataWithPDFInsideRect(mapView!.frame)
let success = pdfData.writeToURL(savePanel.URL!, atomically: true)
}
}
override func printOperationWithSettings(printSettings: [NSObject : AnyObject], error outError: NSErrorPointer) -> NSPrintOperation? {
let printOp = NSPrintOperation(view: mapView!)
printOp.printPanel.options = printOp.printPanel.options | NSPrintPanelOptions.ShowsPageSetupAccessory
return printOp
}
@IBAction func updateTileSize(sender: AnyObject){
if sender as? NSTextField == tileWidthField {
map.tileSize.width = sender.doubleValue
} else if sender as? NSTextField == tileHeightField {
map.tileSize.height = sender.doubleValue
}
let (rows,columns) = map.grid.gridSize()
mapView!.frame = NSRect(x: 0.0, y: 0.0, width: Double(columns)*map.tileSize.width, height: Double(rows)*map.tileSize.height)
mapView!.needsDisplay = true
}
}
| e0279e7adcd9ed177f101f113e14f39b | 44.983471 | 198 | 0.667685 | false | false | false | false |
megabitsenmzq/PomoNow-iOS | refs/heads/master | Old-1.0/PomoNow/PomoNow/ChartViewController.swift | mit | 1 | //
// ChartViewController.swift
// PomoNow
//
// Created by Megabits on 15/11/24.
// Copyright © 2015年 ScrewBox. All rights reserved.
//
import UIKit
class ChartViewController: UIViewController {
@IBOutlet var StartLabel: UILabel!
@IBOutlet var StatisticsContainer: UIView!
@IBAction func cancel(sender: AnyObject) {
timer?.invalidate()
timer = nil
self.performSegueWithIdentifier("backToList", sender: self)
}
@IBAction func ok(sender: AnyObject) {
timer?.invalidate()
timer = nil
self.performSegueWithIdentifier("backToList", sender: self)
}
@IBOutlet weak var TimerView: CProgressView!
@IBOutlet weak var timeLabel: UILabel!
var timer: NSTimer?
override func viewDidLoad() {
super.viewDidLoad()
process = pomodoroClass.process
updateUI()
timer = NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector: #selector(ChartViewController.getNowtime(_:)), userInfo: nil, repeats: true)
}
var process: Float { //进度条
get {
return TimerView.valueProgress / 67 * 100
}
set {
TimerView.valueProgress = newValue / 100 * 67
updateUI()
}
}
private func updateUI() {
TimerView.setNeedsDisplay()
timeLabel.text = pomodoroClass.timerLabel
var haveData = 0
for i in 0...6 {
if cManager.chart[i][0] > 0{
haveData += 1
}
}
if haveData == 0 {
StartLabel.hidden = false
StatisticsContainer.hidden = true
} else {
StartLabel.hidden = true
StatisticsContainer.hidden = false
}
}
func getNowtime(timer:NSTimer) { //同步时间
process = pomodoroClass.process
updateUI()
}
}
| 55cde1ff67e57da96df70829ca83bfd5 | 26.086957 | 160 | 0.58962 | false | false | false | false |
yzhou65/DSWeibo | refs/heads/master | DSWeibo/Classes/Tools/NSDate+Category.swift | apache-2.0 | 1 | //
// NSDate+Category.swift
// DSWeibo
//
// Created by Yue on 9/11/16.
// Copyright © 2016 fda. All rights reserved.
//
import UIKit
extension NSDate {
class func dateWithString(time: String) -> NSDate {
//将服务器返回的时间字符串转换为NSDate
//创建formatter
let formatter = NSDateFormatter()
//设置时间格式
formatter.dateFormat = "EEE MMM d HH:mm:ss Z yyyy"
//设置时间的区域(真机必须设置,否则可能不能转换成功)
formatter.locale = NSLocale(localeIdentifier: "en")
//转换字符串,转换好的时间是取出时区的时间
let createdDate = formatter.dateFromString(time)!
return createdDate
}
var descDate: String {
/*
刚刚(一分钟内)
X分钟前(1小时内)
X小时前(当天)
昨天 HH:mm
MM-dd HH:mm(一年内)
yyyy-MM-dd HH:mm(更早期)
*/
let calendar = NSCalendar.currentCalendar()
//判断是否是今天
if calendar.isDateInToday(self) {
//获取当前时间和系统时间之前的差距(秒数)
let since = Int(NSDate().timeIntervalSinceDate(self))
// print("since = \(since)")
//判断是否是刚刚
if since < 60 {
return "刚刚"
}
//多少分钟以前
if since < 60 * 60 {
return "\(since/60)分钟前"
}
//多少小时以前
return "\(since/(60 * 60))小时前"
}
//判断是否是昨天
var formatterStr = "HH:mm"
if calendar.isDateInYesterday(self) {
formatterStr = "昨天: " + formatterStr
} else {
//处理一年以内
formatterStr = "MM-dd " + formatterStr
//处理更早时间
let comps = calendar.components(NSCalendarUnit.Year, fromDate: self, toDate: NSDate(), options: NSCalendarOptions(rawValue:0))
if comps.year >= 1 {
formatterStr = "yyyy-" + formatterStr
}
}
//按照指定的格式将时间转换为字符串
let formatter = NSDateFormatter()
//设置时间格式
formatter.dateFormat = formatterStr
//设置时间的区域(真机必须设置,否则可能不能转换成功)
formatter.locale = NSLocale(localeIdentifier: "en")
//格式化
return formatter.stringFromDate(self)
}
}
| 1308a1d62b6f37e878e97afb4b105e20 | 27.276316 | 138 | 0.525361 | false | false | false | false |
DrGo/LearningSwift | refs/heads/master | PLAYGROUNDS/LSB_002_VariablesAndConstants.playground/section-2.swift | gpl-3.0 | 2 | import UIKit
/*--------------------------/
// Variables and Constants
/--------------------------*/
/*---------------------/
// Let and Var
/---------------------*/
let x = 10
//x++ // error
var y = 10
y++
/*---------------------/
// Computed Variables
/---------------------*/
var w = 10.0
var h = 20.0
var area: Double {
get {
return w * h
}
set(newArea) {
w = newArea
h = 1.0
}
}
w
h
area
area = 100.0
w
h
// Use the default `newValue` in the setter:
var squareArea: Double {
get {
return w * h
}
set {
w = sqrt(newValue)
h = sqrt(newValue)
}
}
w = 100.0
h = 20.0
squareArea
squareArea = 100.0
w
h
// No setter, so we can omit the `get` and `set` keywords:
var fortune: String {
return "You will find \(arc4random_uniform(100)) potatoes."
}
fortune
fortune
/*---------------------/
// Variable Observers
/---------------------*/
var calMsg0 = ""
var calMsg1 = ""
var caloriesEaten: Int = 0 {
willSet(cals) {
calMsg0 = "You are about to eat \(cals) calories."
}
didSet(cals) {
calMsg1 = "Last time you ate \(cals) calories"
}
}
calMsg0
calMsg1
caloriesEaten = 140
calMsg0
calMsg1
// Default variable names:
var alert0 = ""
var alert1 = ""
var alertLevel: Int = 1 {
willSet {
alert0 = "The new alert level is: \(newValue)"
}
didSet {
alert1 = "No longer at alert level: \(oldValue)"
}
}
alert0
alert1
alertLevel = 5
alert0
alert1
// Pick and choose:
alert0 = ""
var defcon: Int = 1 {
willSet {
if newValue >= 5 {
alert0 = "BOOM!"
}
}
}
defcon = 4
alert0
defcon = 5
alert0
| c6f6bcbf2d977735a96a1730f54208d8 | 11.822581 | 61 | 0.526415 | false | false | false | false |
eshurakov/SwiftHTTPClient | refs/heads/master | HTTPClient/DefaultHTTPSession.swift | mit | 1 | //
// DefaultHTTPSession.swift
// HTTPClient
//
// Created by Evgeny Shurakov on 30.07.16.
// Copyright © 2016 Evgeny Shurakov. All rights reserved.
//
import Foundation
public class DefaultHTTPSession: NSObject, HTTPSession {
fileprivate var taskContexts: [Int: TaskContext] = [:]
fileprivate var session: Foundation.URLSession?
private let sessionFactory: HTTPSessionFactory
public var logger: HTTPLogger?
fileprivate class TaskContext {
lazy var data = Data()
let completion: (HTTPRequestResult) -> Void
init(completion: @escaping (HTTPRequestResult) -> Void) {
self.completion = completion
}
}
private override init() {
fatalError("Not implemented")
}
public init(sessionFactory: HTTPSessionFactory) {
self.sessionFactory = sessionFactory
super.init()
}
public func execute(_ request: URLRequest, completion: @escaping (HTTPRequestResult) -> Void) {
if self.session == nil {
self.session = self.sessionFactory.session(withDelegate: self)
}
guard let session = self.session else {
fatalError("Session is nil right after it was created")
}
let task = session.dataTask(with: request)
self.logger?.logStart(of: task)
// TODO: call completion with a failure?
assert(self.taskContexts[task.taskIdentifier] == nil)
self.taskContexts[task.taskIdentifier] = TaskContext(completion: completion)
task.resume()
}
}
extension DefaultHTTPSession: URLSessionDelegate {
public func urlSession(_ session: URLSession, didBecomeInvalidWithError error: Error?) {
self.session = nil
self.logger?.logSessionFailure(error)
let taskContexts = self.taskContexts
self.taskContexts = [:]
for (_, context) in taskContexts {
context.completion(.failure(HTTPSessionError.becameInvalid(error)))
}
}
}
extension DefaultHTTPSession: URLSessionTaskDelegate {
public func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse, newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
self.logger?.logRedirect(of: task)
completionHandler(request)
}
public func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
guard let context = self.taskContexts[task.taskIdentifier] else {
return
}
self.taskContexts[task.taskIdentifier] = nil
if let error = error {
self.logger?.logFailure(of: task, with: error)
context.completion(.failure(error))
} else {
if let response = task.response {
if let httpResponse = response as? HTTPURLResponse {
let response = HTTPResponse(with: httpResponse,
data: context.data)
self.logger?.logSuccess(of: task, with: response)
context.completion(.success(response))
} else {
let error = HTTPSessionError.unsupportedURLResponseSubclass(String(describing: type(of: response)))
self.logger?.logFailure(of: task, with: error)
context.completion(.failure(error))
}
} else {
let error = HTTPSessionError.missingURLResponse
self.logger?.logFailure(of: task, with: error)
context.completion(.failure(error))
}
}
}
}
extension DefaultHTTPSession: URLSessionDataDelegate {
public func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data) {
guard let context = self.taskContexts[dataTask.taskIdentifier] else {
return
}
context.data.append(data)
}
}
| bb3224c175c5abcdbbd7a14f479d0dad | 33.788136 | 211 | 0.609501 | false | false | false | false |
flodolo/firefox-ios | refs/heads/main | Client/Frontend/Home/Wallpapers/v1/UI/WallpaperBackgroundView.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
class WallpaperBackgroundView: UIView {
// MARK: - UI Elements
private lazy var pictureView: UIImageView = .build { imageView in
imageView.image = nil
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
}
// MARK: - Variables
private var wallpaperManager = WallpaperManager()
var notificationCenter: NotificationProtocol = NotificationCenter.default
// MARK: - Initializers & Setup
override init(frame: CGRect) {
super.init(frame: frame)
setupView()
setupNotifications(forObserver: self,
observing: [.WallpaperDidChange])
updateImageToCurrentWallpaper()
}
@available(*, unavailable)
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
deinit {
notificationCenter.removeObserver(self)
}
private func setupView() {
backgroundColor = .clear
addSubview(pictureView)
NSLayoutConstraint.activate([
pictureView.leadingAnchor.constraint(equalTo: leadingAnchor),
pictureView.topAnchor.constraint(equalTo: topAnchor),
pictureView.bottomAnchor.constraint(equalTo: bottomAnchor),
pictureView.trailingAnchor.constraint(equalTo: trailingAnchor),
])
}
// MARK: - Methods
public func updateImageForOrientationChange() {
updateImageToCurrentWallpaper()
}
private func updateImageToCurrentWallpaper() {
ensureMainThread {
let currentWallpaper = self.currentWallpaperImage()
UIView.animate(withDuration: 0.3) {
self.pictureView.image = currentWallpaper
}
}
}
private func currentWallpaperImage() -> UIImage? {
return UIDevice.current.orientation.isLandscape ? wallpaperManager.currentWallpaper.landscape : wallpaperManager.currentWallpaper.portrait
}
}
// MARK: - Notifiable
extension WallpaperBackgroundView: Notifiable {
func handleNotifications(_ notification: Notification) {
switch notification.name {
case .WallpaperDidChange: updateImageToCurrentWallpaper()
default: break
}
}
}
| 0534765a6799a110e74de7872fc0bbe7 | 30.346154 | 146 | 0.667485 | false | false | false | false |
JaSpa/swift | refs/heads/master | test/SILGen/default_constructor.swift | apache-2.0 | 4 | // RUN: %target-swift-frontend -Xllvm -sil-full-demangle -emit-silgen -primary-file %s | %FileCheck %s
struct B {
var i : Int, j : Float
var c : C
}
struct C {
var x : Int
init() { x = 17 }
}
struct D {
var (i, j) : (Int, Double) = (2, 3.5)
}
// CHECK-LABEL: sil hidden [transparent] @_TIvV19default_constructor1D1iSii : $@convention(thin) () -> (Int, Double)
// CHECK: [[FN:%.*]] = function_ref @_TFSiCfT22_builtinIntegerLiteralBi2048__Si : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Int.Type
// CHECK-NEXT: [[VALUE:%.*]] = integer_literal $Builtin.Int2048, 2
// CHECK-NEXT: [[LEFT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.Int2048, @thin Int.Type) -> Int
// CHECK: [[FN:%.*]] = function_ref @_TFSdCfT20_builtinFloatLiteralBf{{64|80}}__Sd : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Double.Type
// CHECK-NEXT: [[VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x400C000000000000|0x4000E000000000000000}}
// CHECK-NEXT: [[RIGHT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double
// CHECK-NEXT: [[RESULT:%.*]] = tuple ([[LEFT]] : $Int, [[RIGHT]] : $Double)
// CHECK-NEXT: return [[RESULT]] : $(Int, Double)
// CHECK-LABEL: sil hidden @_TFV19default_constructor1DC{{.*}} : $@convention(method) (@thin D.Type) -> D
// CHECK: [[THISBOX:%[0-9]+]] = alloc_box ${ var D }
// CHECK: [[THIS:%[0-9]+]] = mark_uninit
// CHECK: [[INIT:%[0-9]+]] = function_ref @_TIvV19default_constructor1D1iSii
// CHECK: [[RESULT:%[0-9]+]] = apply [[INIT]]()
// CHECK: [[INTVAL:%[0-9]+]] = tuple_extract [[RESULT]] : $(Int, Double), 0
// CHECK: [[FLOATVAL:%[0-9]+]] = tuple_extract [[RESULT]] : $(Int, Double), 1
// CHECK: [[IADDR:%[0-9]+]] = struct_element_addr [[THIS]] : $*D, #D.i
// CHECK: assign [[INTVAL]] to [[IADDR]]
// CHECK: [[JADDR:%[0-9]+]] = struct_element_addr [[THIS]] : $*D, #D.j
// CHECK: assign [[FLOATVAL]] to [[JADDR]]
class E {
var i = Int64()
}
// CHECK-LABEL: sil hidden [transparent] @_TIvC19default_constructor1E1iVs5Int64i : $@convention(thin) () -> Int64
// CHECK: [[FN:%.*]] = function_ref @_TFVs5Int64CfT_S_ : $@convention(method) (@thin Int64.Type) -> Int64
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Int64.Type
// CHECK-NEXT: [[VALUE:%.*]] = apply [[FN]]([[METATYPE]]) : $@convention(method) (@thin Int64.Type) -> Int64
// CHECK-NEXT: return [[VALUE]] : $Int64
// CHECK-LABEL: sil hidden @_TFC19default_constructor1Ec{{.*}} : $@convention(method) (@owned E) -> @owned E
// CHECK: bb0([[SELFIN:%[0-9]+]] : $E)
// CHECK: [[SELF:%[0-9]+]] = mark_uninitialized
// CHECK: [[INIT:%[0-9]+]] = function_ref @_TIvC19default_constructor1E1iVs5Int64i : $@convention(thin) () -> Int64
// CHECK-NEXT: [[VALUE:%[0-9]+]] = apply [[INIT]]() : $@convention(thin) () -> Int64
// CHECK-NEXT: [[IREF:%[0-9]+]] = ref_element_addr [[SELF]] : $E, #E.i
// CHECK-NEXT: assign [[VALUE]] to [[IREF]] : $*Int64
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value [[SELF]]
// CHECK-NEXT: destroy_value [[SELF]]
// CHECK-NEXT: return [[SELF_COPY]] : $E
class F : E { }
// CHECK-LABEL: sil hidden @_TFC19default_constructor1Fc{{.*}} : $@convention(method) (@owned F) -> @owned F
// CHECK: bb0([[ORIGSELF:%[0-9]+]] : $F)
// CHECK-NEXT: [[SELF_BOX:%[0-9]+]] = alloc_box ${ var F }
// CHECK-NEXT: project_box [[SELF_BOX]]
// CHECK-NEXT: [[SELF:%[0-9]+]] = mark_uninitialized [derivedself]
// CHECK-NEXT: store [[ORIGSELF]] to [init] [[SELF]] : $*F
// SEMANTIC ARC TODO: This is incorrect. Why are we doing a +0 produce and passing off to a +1 consumer. This should be a copy. Or a mutable borrow perhaps?
// CHECK-NEXT: [[SELFP:%[0-9]+]] = load_borrow [[SELF]] : $*F
// CHECK-NEXT: [[E:%[0-9]]] = upcast [[SELFP]] : $F to $E
// CHECK: [[E_CTOR:%[0-9]+]] = function_ref @_TFC19default_constructor1EcfT_S0_ : $@convention(method) (@owned E) -> @owned E
// CHECK-NEXT: [[ESELF:%[0-9]]] = apply [[E_CTOR]]([[E]]) : $@convention(method) (@owned E) -> @owned E
// CHECK-NEXT: [[ESELFW:%[0-9]+]] = unchecked_ref_cast [[ESELF]] : $E to $F
// CHECK-NEXT: store [[ESELFW]] to [init] [[SELF]] : $*F
// CHECK-NEXT: [[SELFP:%[0-9]+]] = load [copy] [[SELF]] : $*F
// CHECK-NEXT: destroy_value [[SELF_BOX]] : ${ var F }
// CHECK-NEXT: return [[SELFP]] : $F
// <rdar://problem/19780343> Default constructor for a struct with optional doesn't compile
// This shouldn't get a default init, since it would be pointless (bar can never
// be reassigned). It should get a memberwise init though.
struct G {
let bar: Int32?
}
// CHECK-NOT: default_constructor.G.init ()
// CHECK-LABEL: default_constructor.G.init (bar : Swift.Optional<Swift.Int32>)
// CHECK-NEXT: sil hidden @_TFV19default_constructor1GC
// CHECK-NOT: default_constructor.G.init ()
struct H<T> {
var opt: T?
// CHECK-LABEL: sil hidden @_TFV19default_constructor1HCurfqd__GS0_x_ : $@convention(method) <T><U> (@in U, @thin H<T>.Type) -> @out H<T> {
// CHECK: [[INIT_FN:%[0-9]+]] = function_ref @_TIvV19default_constructor1H3optGSqx_i : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0>
// CHECK-NEXT: [[OPT_T:%[0-9]+]] = alloc_stack $Optional<T>
// CHECK-NEXT: apply [[INIT_FN]]<T>([[OPT_T]]) : $@convention(thin) <τ_0_0> () -> @out Optional<τ_0_0>
init<U>(_: U) { }
}
// <rdar://problem/29605388> Member initializer for non-generic type with generic constructor doesn't compile
struct I {
var x: Int = 0
// CHECK-LABEL: sil hidden @_TFV19default_constructor1ICurfxS0_ : $@convention(method) <T> (@in T, @thin I.Type) -> I {
// CHECK: [[INIT_FN:%[0-9]+]] = function_ref @_TIvV19default_constructor1I1xSii : $@convention(thin) () -> Int
// CHECK: [[RESULT:%[0-9]+]] = apply [[INIT_FN]]() : $@convention(thin) () -> Int
// CHECK: [[X_ADDR:%[0-9]+]] = struct_element_addr {{.*}} : $*I, #I.x
// CHECK: assign [[RESULT]] to [[X_ADDR]] : $*Int
init<T>(_: T) {}
}
| 7680123e16d2e5ba90e137d495bf4096 | 50.025424 | 165 | 0.607208 | false | false | false | false |
PiXeL16/BudgetShare | refs/heads/master | BudgetShare/Modules/BudgetCreate/Wireframe/BudgetCreateWireframeProvider.swift | mit | 1 | //
// Created by Chris Jimenez on 3/5/17.
// Copyright (c) 2017 Chris Jimenez. All rights reserved.
//
import Foundation
import UIKit
internal class BudgetCreateWireframeProvider: Wireframe, BudgetCreateWireframe {
var root: RootWireframeInterface?
// Inits and starts all the wiring
required init(root: RootWireframeInterface?) {
self.root = root
}
// Show the view controller in the window
func attachRoot(with controller: UIViewController, in window: UIWindow) {
root?.showRoot(with: controller, in: window)
}
// Show an error Alert
func showErrorAlert(title: String, message: String, from controller: UIViewController?) {
guard let viewController = controller else {
return
}
// Use the dialog util provider
let alert = AlertDialogUtilProvider()
alert.showErrorAlert(message: message, title: title, with: viewController)
}
}
extension BudgetCreateWireframeProvider {
class func createViewController() -> UINavigationController {
let sb = UIStoryboard(name: "BudgetCreateModule", bundle: nil)
let vc = sb.instantiateViewController(withIdentifier: "BudgetCreateNavigationViewController") as! UINavigationController
return vc
}
// func pushSignUp(from controller: UIViewController?) {
// // TODO: Use SignUp wireframe to push it
//
// guard controller != nil else {
// return
// }
//
// let vc = SignUpWireframe.createViewController()
// let wireframe = SignUpWireframe(root: root, view: vc)
// wireframe.push(controller: vc, from: controller!)
//
// }
}
| 6820617b935bcf232d254c1325b958e9 | 29.017544 | 128 | 0.654004 | false | false | false | false |
heilb1314/500px_Challenge | refs/heads/master | PhotoWall_500px_challenge/PhotoWall_500px_challenge/PhotoWallViewController.swift | mit | 1 | //
// PhotoWallViewController.swift
// PhotoWall_500px_challenge
//
// Created by Jianxiong Wang on 2/1/17.
// Copyright © 2017 JianxiongWang. All rights reserved.
//
import UIKit
class PhotoWallViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {
@IBOutlet weak var collectionView: UICollectionView!
fileprivate var photos:[Photo]!
fileprivate var gridSizes: [CGSize]!
fileprivate var itemsPerRow: Int = 3
fileprivate var lastViewdIndexPath: IndexPath?
fileprivate var isLandscape = false
fileprivate var isLoading = false
fileprivate var searchController: UISearchController!
fileprivate var searchTerm: String = CATEGORIES[0]
fileprivate var page: Int = 1
private var pageSize: Int = 30
private var photoSizes: [Int] = [3,4]
private var selectedIndex: Int?
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
self.navigationController?.navigationBar.barStyle = .default
self.navigationController?.navigationBar.titleTextAttributes = nil
let rightBarItem = UIBarButtonItem(barButtonSystemItem: .edit, target: self, action: #selector(changeTerm(sender:)))
rightBarItem.tintColor = UIColor.orange
self.navigationItem.rightBarButtonItem = rightBarItem
self.navigationItem.title = searchTerm.capitalized
self.updateCollectionViewLayout()
}
func changeTerm(sender: UIBarButtonItem) {
self.performSegue(withIdentifier: "showCategories", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
self.isLandscape = UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation)
if let layout = collectionView?.collectionViewLayout as? PhotoWallLayout {
layout.delegate = self
}
self.photos = [Photo]()
getPhotos(resetPhotos: true, completionHandler: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
/// Get next page Photos. Auto reload collectionView.
fileprivate func getPhotos(resetPhotos: Bool, completionHandler handler: (()->())?) {
QueryModel.getPhotos(forSearchTerm: searchTerm, page: page, resultsPerPage: pageSize, photoSizes: photoSizes) { (photos, error) in
if(photos != nil) {
self.page += 1
resetPhotos ? self.photos = photos : self.photos.append(contentsOf: photos!)
self.collectionView.layoutIfNeeded()
self.collectionView.reloadData()
} else {
let alert = UIAlertController(title: "Oops", message: error?.localizedDescription, preferredStyle: .alert)
let cancel = UIAlertAction(title: "Cancel", style: .cancel, handler: nil)
alert.addAction(cancel)
self.present(alert, animated: true, completion: nil)
}
handler?()
}
}
/// update collectionView layout and move to last viewed indexPath if any.
fileprivate func updateCollectionViewLayout() {
self.collectionView.collectionViewLayout.invalidateLayout()
let curOrientation = UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation)
if self.lastViewdIndexPath != nil && self.isLandscape != curOrientation {
self.isLandscape = curOrientation
DispatchQueue.main.async {
self.collectionView.scrollToItem(at: self.lastViewdIndexPath!, at: curOrientation ? .right : .bottom, animated: false)
}
}
}
// MARK: - UIScrollView Delegates
func scrollViewDidScroll(_ scrollView: UIScrollView) {
self.lastViewdIndexPath = self.collectionView.indexPathsForVisibleItems.last
// load next page when scrollView reaches the end
guard self.isLoading == false else { return }
var offset:CGFloat = 0
var sizeLength:CGFloat = 0
if UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) {
offset = scrollView.contentOffset.x
sizeLength = scrollView.contentSize.width - scrollView.frame.size.width
} else {
offset = scrollView.contentOffset.y
sizeLength = scrollView.contentSize.height - scrollView.frame.size.height
}
if offset >= sizeLength {
self.isLoading = true
self.getPhotos(resetPhotos: false, completionHandler: {
self.isLoading = false
})
}
}
// MARK: - UICollectionView DataSources
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.photos?.count ?? 0
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! PhotoThumbnailCollectionViewCell
cell.photo = self.photos?[indexPath.row]
return cell
}
// MARK: - UICollectionView Delegates
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
self.selectedIndex = indexPath.row
performSegue(withIdentifier: "showPhotoDetail", sender: self)
}
// Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "showPhotoDetail" {
let svc = segue.destination as! PhotoDetailViewController
if self.photos != nil && self.selectedIndex != nil && self.selectedIndex! < self.photos!.count {
svc.photo = self.photos![self.selectedIndex!]
}
} else if segue.identifier == "showCategories" {
let svc = segue.destination as! SearchTermTableViewController
svc.delegate = self
}
}
}
// MARK: Extension - PhotoWallLayoutDelegate
extension PhotoWallViewController: PhotoWallLayoutDelegate {
func collectionView(collectionView: UICollectionView, sizeForPhotoAtIndexPath indexPath: IndexPath) -> CGSize {
return photos[indexPath.item].getPhotoSize()
}
// Update grids when device rotates
override func viewWillLayoutSubviews() {
if self.isLandscape != UIInterfaceOrientationIsLandscape(UIApplication.shared.statusBarOrientation) {
updateCollectionViewLayout()
}
}
override func didRotate(from fromInterfaceOrientation: UIInterfaceOrientation) {
updateCollectionViewLayout()
}
}
// MARK: Extension - SearchTerm Delegate
extension PhotoWallViewController: SearchTermDelegate {
func searchTermDidChange(sender: SearchTermTableViewController, newTerm: String) {
if newTerm != self.searchTerm {
self.searchTerm = newTerm
self.page = 1
self.getPhotos(resetPhotos: true, completionHandler: {
self.collectionView.scrollToItem(at: IndexPath(item: 0, section: 0), at: .top, animated: false)
})
}
}
}
| 019b3d862d31010927fda05b10b0deea | 38.175532 | 138 | 0.664902 | false | false | false | false |
imfeemily/NPSegmentedControl | refs/heads/master | NPSegmentedControl/Classes/NPSegmentedControl/NPSegmentedControl.swift | apache-2.0 | 1 | /*
Copyright 2015 NEOPIXL S.A.
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
public class NPSegmentedControl : UIControl {
private var views = [UIView]()
private var labels = [UILabel]()
public var cursor:UIView?
{
didSet{
if views.count > 0
{
self.setItems(items)
if let cur = oldValue
{
cur.removeFromSuperview()
}
}
}
}
private var animationChecks = [Bool]()
private var items:[String]!
private var currentIndex:Int = 0
public var selectedColor:UIColor? = UIColor.lightGrayColor()
{
didSet{
if self.currentIndex <= views.count - 1 && self.currentIndex >= 0
{
var view = views[self.currentIndex]
view.backgroundColor = self.selectedColor
}
}
}
public var selectedTextColor:UIColor?
{
didSet{
if self.currentIndex <= views.count - 1 && self.currentIndex >= 0
{
var lab = labels[self.currentIndex]
lab.textColor = self.selectedTextColor
}
}
}
public var unselectedColor:UIColor? = UIColor.grayColor()
{
didSet{
for index in 0..<views.count
{
if(index != self.currentIndex)
{
var view = views[index]
view.backgroundColor = self.unselectedColor
}
}
}
}
public var unselectedTextColor:UIColor?
{
didSet{
for index in 0..<views.count
{
if(index != self.currentIndex)
{
var lab = labels[index]
lab.textColor = self.unselectedTextColor
}
}
}
}
public var selectedFont:UIFont?
{
didSet{
if self.currentIndex <= views.count - 1 && self.currentIndex >= 0
{
var lab = labels[self.currentIndex]
lab.font = self.selectedFont
}
}
}
public var unselectedFont:UIFont?
{
didSet{
for index in 0..<views.count
{
if(index != self.currentIndex)
{
var lab = labels[index]
lab.font = self.unselectedFont
}
}
}
}
private var cursorCenterXConstraint:NSLayoutConstraint!
private var tapGestureRecogniser:UITapGestureRecognizer!
private func initComponents()
{
tapGestureRecogniser = UITapGestureRecognizer(target: self, action: "didTap:")
self.addGestureRecognizer(tapGestureRecogniser)
}
init() {
super.init(frame: CGRectZero)
self.initComponents()
}
required public init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initComponents()
}
override init(frame: CGRect) {
super.init(frame: frame)
self.initComponents()
}
public func setItems(items:[String])
{
self.items = items
var previousView:UIView?
for lab in labels
{
lab.removeFromSuperview()
}
for view in views
{
view.removeFromSuperview()
}
labels.removeAll(keepCapacity: false)
views.removeAll(keepCapacity: false)
for i in 0..<items.count
{
var view = UIView()
view.backgroundColor = unselectedColor
self.addSubview(view)
views.append(view)
var label = UILabel()
label.text = items[i]
label.textColor = unselectedTextColor
if let font = unselectedFont
{
label.font = font
}
view.addSubview(label)
labels.append(label)
label.setTranslatesAutoresizingMaskIntoConstraints(false)
var itemHeight = self.frame.height
if let cur = self.cursor
{
itemHeight -= cur.frame.height
}
let centerXConstraint = NSLayoutConstraint(item:label,
attribute:NSLayoutAttribute.CenterX,
relatedBy:NSLayoutRelation.Equal,
toItem:view,
attribute:NSLayoutAttribute.CenterX,
multiplier:1,
constant:0)
view.addConstraint(centerXConstraint)
let centerYConstraint = NSLayoutConstraint(item:label,
attribute:NSLayoutAttribute.CenterY,
relatedBy:NSLayoutRelation.Equal,
toItem:view,
attribute:NSLayoutAttribute.CenterY,
multiplier:1,
constant:0)
view.addConstraint(centerYConstraint)
view.setTranslatesAutoresizingMaskIntoConstraints(false)
var viewDict = [ "view" : view ] as Dictionary<NSObject,AnyObject>
var constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[view(\(itemHeight))]", options: nil, metrics: nil, views: viewDict)
view.addConstraints(constraints)
if let previous = previousView
{
let leftConstraint = NSLayoutConstraint(item:view,
attribute:NSLayoutAttribute.Left,
relatedBy:NSLayoutRelation.Equal,
toItem:previous,
attribute:NSLayoutAttribute.Right,
multiplier:1,
constant:0)
self.addConstraint(leftConstraint)
let widthConstraint = NSLayoutConstraint(item:view,
attribute:NSLayoutAttribute.Width,
relatedBy:NSLayoutRelation.Equal,
toItem:previous,
attribute:NSLayoutAttribute.Width,
multiplier:1,
constant:0)
self.addConstraint(widthConstraint)
}
else
{
let leftConstraint = NSLayoutConstraint(item:view,
attribute:NSLayoutAttribute.Left,
relatedBy:NSLayoutRelation.Equal,
toItem:self,
attribute:NSLayoutAttribute.Left,
multiplier:1.0,
constant:0)
self.addConstraint(leftConstraint)
}
let topConstraint = NSLayoutConstraint(item:view,
attribute:NSLayoutAttribute.Top,
relatedBy:NSLayoutRelation.Equal,
toItem:self,
attribute:NSLayoutAttribute.Top,
multiplier:1.0,
constant:0)
self.addConstraint(topConstraint)
previousView = view
}
if let previous = previousView
{
let leftConstraint = NSLayoutConstraint(item:previous,
attribute:NSLayoutAttribute.Right,
relatedBy:NSLayoutRelation.Equal,
toItem:self,
attribute:NSLayoutAttribute.Right,
multiplier:1.0,
constant:0)
self.addConstraint(leftConstraint)
}
if let cur = cursor
{
cur.setTranslatesAutoresizingMaskIntoConstraints(false)
self.addSubview(cur)
let bottomConstraint = NSLayoutConstraint(item:cur,
attribute:NSLayoutAttribute.Bottom,
relatedBy:NSLayoutRelation.Equal,
toItem:self,
attribute:NSLayoutAttribute.Bottom,
multiplier:1.0,
constant:0)
self.addConstraint(bottomConstraint)
cursorCenterXConstraint = NSLayoutConstraint(item:cur,
attribute:NSLayoutAttribute.CenterX,
relatedBy:NSLayoutRelation.Equal,
toItem:self,
attribute:NSLayoutAttribute.CenterX,
multiplier:1.0,
constant:0)
self.addConstraint(cursorCenterXConstraint)
var viewDict = [ "cursor" : cur ] as Dictionary<NSObject,AnyObject>
var constraints = NSLayoutConstraint.constraintsWithVisualFormat("V:[cursor(\(cur.frame.height))]", options: nil, metrics: nil, views: viewDict)
cur.addConstraints(constraints)
constraints = NSLayoutConstraint.constraintsWithVisualFormat("H:[cursor(\(cur.frame.width))]", options: nil, metrics: nil, views: viewDict)
cur.addConstraints(constraints)
}
selectCell(currentIndex,animate: false)
}
//MARK: select cell at index
public func selectCell(index:Int, animate:Bool)
{
var newView = views[index]
var newLabel = labels[index]
var oldView = views[currentIndex]
var oldLabel = labels[currentIndex]
var duration:NSTimeInterval = 0
if animate
{
duration = 0.4
}
if (duration == 0 || index != currentIndex) && index < items.count
{
UIView.animateWithDuration(duration, delay: 0, usingSpringWithDamping: 1, initialSpringVelocity: 10, options: .CurveEaseInOut | .AllowUserInteraction, animations:
{
self.animationChecks.append(true)
oldView.backgroundColor = self.unselectedColor
oldLabel.textColor = self.unselectedTextColor
if let font = self.unselectedFont
{
oldLabel.font = font
}
newView.backgroundColor = self.selectedColor
newLabel.textColor = self.selectedTextColor
if let font = self.selectedFont
{
newLabel.font = font
}
if let cur = self.cursor
{
cur.center.x = newView.center.x
}
},
completion: { finished in
if self.animationChecks.count == 1
{
if let cur = self.cursor
{
self.removeConstraint(self.cursorCenterXConstraint)
self.cursorCenterXConstraint = NSLayoutConstraint(item:cur,
attribute:NSLayoutAttribute.CenterX,
relatedBy:NSLayoutRelation.Equal,
toItem:newView,
attribute:NSLayoutAttribute.CenterX,
multiplier:1.0,
constant:0)
self.addConstraint(self.cursorCenterXConstraint)
}
}
self.animationChecks.removeLast()
})
currentIndex = index
}
}
internal func didTap(recognizer:UITapGestureRecognizer)
{
if recognizer.state == UIGestureRecognizerState.Ended
{
var currentPoint = recognizer.locationInView(self)
var index = indexFromPoint(currentPoint)
selectCell(index, animate: true)
self.sendActionsForControlEvents(UIControlEvents.ValueChanged)
}
}
//MARK: getIndex from point
private func indexFromPoint(point:CGPoint) -> Int
{
var position = 0
for pos in 0..<views.count
{
let view = views[pos]
if point.x >= view.frame.minX && point.x < view.frame.maxX
{
return pos
}
}
return 0
}
//MARK: selectedIndex
public func selectedIndex() -> Int
{
return self.currentIndex
}
} | c638437a8ebaad751081e079ee12da33 | 31.912145 | 174 | 0.523241 | false | false | false | false |
klaaspieter/Letters | refs/heads/master | Sources/Recorder/Prelude/Parallel.swift | mit | 1 | import Dispatch
final class Parallel<A> {
private let queue = DispatchQueue(label: "Recorder.Parellel")
private var computed: A?
private let compute: (@escaping (A) -> Void) -> Void
init(_ compute: @escaping (@escaping (A) -> Void) -> Void) {
self.compute = compute
}
func run(_ callback: @escaping (A) -> Void) {
queue.async {
guard let computed = self.computed else {
return self.compute { computed in
self.computed = computed
callback(computed)
}
}
callback(computed)
}
}
}
extension Parallel {
static func pure(_ x: A) -> Parallel<A> {
return Parallel({ $0(x) })
}
func map<B>(_ f: @escaping (A) -> B) -> Parallel<B> {
return Parallel<B> { completion in
self.run({ completion(f($0)) })
}
}
static func <^> <B> (_ f: @escaping (A) -> B, _ x: Parallel<A>) -> Parallel<B> {
return x.map(f)
}
func apply<B>(_ f: Parallel<(A) -> B>) -> Parallel<B> {
return Parallel<B> { g in
f.run { f in if let x = self.computed { g(f(x)) } }
self.run { x in if let f = f.computed { g(f(x)) } }
}
}
static func <*> <B> (_ f: Parallel<(A) -> B>, _ x: Parallel<A>) -> Parallel<B> {
return x.apply(f)
}
}
| 81f43aa7c3b8ef154cb1caa55b16e016 | 23.333333 | 82 | 0.547945 | false | false | false | false |
ceecer1/open-muvr | refs/heads/master | ios/Lift/UIImage+Effects.swift | apache-2.0 | 5 | /*
File: UIImage+ImageEffects.m
Abstract: This is a category of UIImage that adds methods to apply blur and tint effects to an image. This is the code you’ll want to look out to find out how to use vImage to efficiently calculate a blur.
Version: 1.0
Disclaimer: IMPORTANT: This Apple software is supplied to you by Apple
Inc. ("Apple") in consideration of your agreement to the following
terms, and your use, installation, modification or redistribution of
this Apple software constitutes acceptance of these terms. If you do
not agree with these terms, please do not use, install, modify or
redistribute this Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a personal, non-exclusive
license, under Apple's copyrights in this original Apple software (the
"Apple Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE
MAKES NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION
THE IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS
FOR A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
Copyright (C) 2013 Apple Inc. All Rights Reserved.
Copyright © 2013 Apple Inc. All rights reserved.
WWDC 2013 License
NOTE: This Apple Software was supplied by Apple as part of a WWDC 2013
Session. Please refer to the applicable WWDC 2013 Session for further
information.
IMPORTANT: This Apple software is supplied to you by Apple Inc.
("Apple") in consideration of your agreement to the following terms, and
your use, installation, modification or redistribution of this Apple
software constitutes acceptance of these terms. If you do not agree with
these terms, please do not use, install, modify or redistribute this
Apple software.
In consideration of your agreement to abide by the following terms, and
subject to these terms, Apple grants you a non-exclusive license, under
Apple's copyrights in this original Apple software (the "Apple
Software"), to use, reproduce, modify and redistribute the Apple
Software, with or without modifications, in source and/or binary forms;
provided that if you redistribute the Apple Software in its entirety and
without modifications, you must retain this notice and the following
text and disclaimers in all such redistributions of the Apple Software.
Neither the name, trademarks, service marks or logos of Apple Inc. may
be used to endorse or promote products derived from the Apple Software
without specific prior written permission from Apple. Except as
expressly stated in this notice, no other rights or licenses, express or
implied, are granted by Apple herein, including but not limited to any
patent rights that may be infringed by your derivative works or by other
works in which the Apple Software may be incorporated.
The Apple Software is provided by Apple on an "AS IS" basis. APPLE MAKES
NO WARRANTIES, EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION THE
IMPLIED WARRANTIES OF NON-INFRINGEMENT, MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE, REGARDING THE APPLE SOFTWARE OR ITS USE AND
OPERATION ALONE OR IN COMBINATION WITH YOUR PRODUCTS.
IN NO EVENT SHALL APPLE BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL
OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) ARISING IN ANY WAY OUT OF THE USE, REPRODUCTION,
MODIFICATION AND/OR DISTRIBUTION OF THE APPLE SOFTWARE, HOWEVER CAUSED
AND WHETHER UNDER THEORY OF CONTRACT, TORT (INCLUDING NEGLIGENCE),
STRICT LIABILITY OR OTHERWISE, EVEN IF APPLE HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
EA1002
5/3/2013
*/
//
// UIImage.swift
// Today
//
// Created by Alexey Globchastyy on 15/09/14.
// Copyright (c) 2014 Alexey Globchastyy. All rights reserved.
//
import UIKit
import Accelerate
public extension UIImage {
func averageColor() -> UIColor {
let size = CGSize(width: 1, height: 1)
UIGraphicsBeginImageContext(size)
let ctx = UIGraphicsGetCurrentContext()
CGContextSetInterpolationQuality(ctx, kCGInterpolationMedium)
drawInRect(CGRect(origin: CGPoint(x: 0, y: 0), size: size), blendMode:kCGBlendModeCopy, alpha:1)
let data = UnsafeMutablePointer<UInt8>(CGBitmapContextGetData(ctx))
let color = UIColor(red: CGFloat(data[2]) / 255.0, green: CGFloat(data[1]) / 255.0, blue: CGFloat(data[0]) / 255.0, alpha: 1)
UIGraphicsEndImageContext()
return color
}
public func applyLightEffect() -> UIImage? {
return applyBlurWithRadius(30, tintColor: UIColor(white: 1.0, alpha: 0.3), saturationDeltaFactor: 1.8)
}
public func applyExtraLightEffect() -> UIImage? {
return applyBlurWithRadius(20, tintColor: UIColor(white: 0.97, alpha: 0.82), saturationDeltaFactor: 1.8)
}
public func applyDarkEffect() -> UIImage? {
return applyBlurWithRadius(20, tintColor: UIColor(white: 0.11, alpha: 0.73), saturationDeltaFactor: 1.8)
}
public func applyTintEffectWithColor(tintColor: UIColor) -> UIImage? {
let effectColorAlpha: CGFloat = 0.6
var effectColor = tintColor
let componentCount = CGColorGetNumberOfComponents(tintColor.CGColor)
if componentCount == 2 {
var b: CGFloat = 0
if tintColor.getWhite(&b, alpha: nil) {
effectColor = UIColor(white: b, alpha: effectColorAlpha)
}
} else {
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
if tintColor.getRed(&red, green: &green, blue: &blue, alpha: nil) {
effectColor = UIColor(red: red, green: green, blue: blue, alpha: effectColorAlpha)
}
}
return applyBlurWithRadius(10, tintColor: effectColor, saturationDeltaFactor: -1.0, maskImage: nil)
}
public func applyBlurWithRadius(blurRadius: CGFloat, tintColor: UIColor?, saturationDeltaFactor: CGFloat, maskImage: UIImage? = nil) -> UIImage? {
// Check pre-conditions.
if (size.width < 1 || size.height < 1) {
println("*** error: invalid size: \(size.width) x \(size.height). Both dimensions must be >= 1: \(self)")
return nil
}
if self.CGImage == nil {
println("*** error: image must be backed by a CGImage: \(self)")
return nil
}
if maskImage != nil && maskImage!.CGImage == nil {
println("*** error: maskImage must be backed by a CGImage: \(maskImage)")
return nil
}
let __FLT_EPSILON__ = CGFloat(FLT_EPSILON)
let screenScale = UIScreen.mainScreen().scale
let imageRect = CGRect(origin: CGPointZero, size: size)
var effectImage = self
let hasBlur = blurRadius > __FLT_EPSILON__
let hasSaturationChange = fabs(saturationDeltaFactor - 1.0) > __FLT_EPSILON__
if hasBlur || hasSaturationChange {
func createEffectBuffer(context: CGContext) -> vImage_Buffer {
let data = CGBitmapContextGetData(context)
let width = CGBitmapContextGetWidth(context)
let height = CGBitmapContextGetHeight(context)
let rowBytes = CGBitmapContextGetBytesPerRow(context)
return vImage_Buffer(data: data, height: height, width: width, rowBytes: rowBytes)
}
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let effectInContext = UIGraphicsGetCurrentContext()
CGContextScaleCTM(effectInContext, 1.0, -1.0)
CGContextTranslateCTM(effectInContext, 0, -size.height)
CGContextDrawImage(effectInContext, imageRect, self.CGImage)
var effectInBuffer = createEffectBuffer(effectInContext)
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let effectOutContext = UIGraphicsGetCurrentContext()
var effectOutBuffer = createEffectBuffer(effectOutContext)
if hasBlur {
// A description of how to compute the box kernel width from the Gaussian
// radius (aka standard deviation) appears in the SVG spec:
// http://www.w3.org/TR/SVG/filters.html#feGaussianBlurElement
//
// For larger values of 's' (s >= 2.0), an approximation can be used: Three
// successive box-blurs build a piece-wise quadratic convolution kernel, which
// approximates the Gaussian kernel to within roughly 3%.
//
// let d = floor(s * 3*sqrt(2*pi)/4 + 0.5)
//
// ... if d is odd, use three box-blurs of size 'd', centered on the output pixel.
//
let inputRadius = blurRadius * screenScale
var radius = UInt32(floor(inputRadius * 3.0 * CGFloat(sqrt(2 * M_PI)) / 4 + 0.5))
if radius % 2 != 1 {
radius += 1 // force radius to be odd so that the three box-blur methodology works.
}
let imageEdgeExtendFlags = vImage_Flags(kvImageEdgeExtend)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectOutBuffer, &effectInBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
vImageBoxConvolve_ARGB8888(&effectInBuffer, &effectOutBuffer, nil, 0, 0, radius, radius, nil, imageEdgeExtendFlags)
}
var effectImageBuffersAreSwapped = false
if hasSaturationChange {
let s: CGFloat = saturationDeltaFactor
let floatingPointSaturationMatrix: [CGFloat] = [
0.0722 + 0.9278 * s, 0.0722 - 0.0722 * s, 0.0722 - 0.0722 * s, 0,
0.7152 - 0.7152 * s, 0.7152 + 0.2848 * s, 0.7152 - 0.7152 * s, 0,
0.2126 - 0.2126 * s, 0.2126 - 0.2126 * s, 0.2126 + 0.7873 * s, 0,
0, 0, 0, 1
]
let divisor: CGFloat = 256
let matrixSize = floatingPointSaturationMatrix.count
var saturationMatrix = [Int16](count: matrixSize, repeatedValue: 0)
for var i: Int = 0; i < matrixSize; ++i {
saturationMatrix[i] = Int16(round(floatingPointSaturationMatrix[i] * divisor))
}
if hasBlur {
vImageMatrixMultiply_ARGB8888(&effectOutBuffer, &effectInBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
effectImageBuffersAreSwapped = true
} else {
vImageMatrixMultiply_ARGB8888(&effectInBuffer, &effectOutBuffer, saturationMatrix, Int32(divisor), nil, nil, vImage_Flags(kvImageNoFlags))
}
}
if !effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
if effectImageBuffersAreSwapped {
effectImage = UIGraphicsGetImageFromCurrentImageContext()
}
UIGraphicsEndImageContext()
}
// Set up output context.
UIGraphicsBeginImageContextWithOptions(size, false, screenScale)
let outputContext = UIGraphicsGetCurrentContext()
CGContextScaleCTM(outputContext, 1.0, -1.0)
CGContextTranslateCTM(outputContext, 0, -size.height)
// Draw base image.
CGContextDrawImage(outputContext, imageRect, self.CGImage)
// Draw effect image.
if hasBlur {
CGContextSaveGState(outputContext)
if let image = maskImage {
CGContextClipToMask(outputContext, imageRect, image.CGImage);
}
CGContextDrawImage(outputContext, imageRect, effectImage.CGImage)
CGContextRestoreGState(outputContext)
}
// Add in color tint.
if let color = tintColor {
CGContextSaveGState(outputContext)
CGContextSetFillColorWithColor(outputContext, color.CGColor)
CGContextFillRect(outputContext, imageRect)
CGContextRestoreGState(outputContext)
}
// Output image is ready.
let outputImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return outputImage
}
}
| 76c436a6800ffab465578ae58877c3eb | 46.124183 | 205 | 0.658669 | false | false | false | false |
aKirill1942/NetRoute | refs/heads/master | NetRoute/NetResponse.swift | apache-2.0 | 1 | //
// NetResponse.swift
// NetRoute
//
// Created by Kirill Averkiev on 15.04.16.
// Copyright © 2016 Kirill Averkiev. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import Foundation
/// The response of the request.
public class NetResponse: NetRouteObject {
// MARK: - Constants
/// Response data.
public let data: Data?
/// HTTP response.
public let httpResponse: URLResponse?
/// Error.
public let error: Error?
// MARK: - Variables
/// Encoding for the string conversion. Default is `NSUTF8StringEncoding`.
public var encoding = String.Encoding.utf8
/// String conversion.Returns nil if the data can not be presented as `String`.
public override var description: String {
if let dictionary = dictionary {
var finalString = "{\n"
for (key, value) in dictionary {
finalString += " " + "\(key): \(value)\n"
}
finalString += "}"
return finalString
}
return "Response"
}
/// String value of the data. Returns nil if the data can not be presented as `String`.
public var stringValue: String? {
// Check if data is not nil.
if data != nil {
if let responseString = String(data: data!, encoding: encoding) {
return responseString
} else {
return nil
}
} else {
return nil
}
}
/// Dictionary of the data. Returns nil if the data can not be presented as `Dictionary`.
public var dictionary: Dictionary<String, AnyObject>? {
// Check if data is not nil.
if data != nil {
do {
let responseJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
return responseJSON as? Dictionary
} catch _ {
return nil
}
} else {
return nil
}
}
// MARK: - Initialization
/// Initializes a new instance from default `NSURLSession` output.
public init(data: Data?, response: URLResponse?, error: Error?) {
self.data = data
self.httpResponse = response
self.error = error
}
// MARK: - Header Values
/// Get a header value from response.
///
/// - Parameter forHeader: Name of the header.
///
/// - Returns: Value for provided header. Nil if no response or the provided header is wrong.
public func value(for header: String) -> Any? {
if let response = httpResponse as? HTTPURLResponse {
return response.allHeaderFields[header]
} else {
return nil
}
}
/// Get a header value from response.
///
/// - Parameter forHeader: Name of the header.
///
/// - Returns: String for provided header converted to String. Nil if no response, the provided header is wrong or the data cannot be converted to String.
public func string(for header: String) -> String? {
return self.value(forHeader: header) as? String
}
}
| c6853a39926ba4021e385a5ffae7aa29 | 26.856115 | 158 | 0.573089 | false | false | false | false |
steveholt55/Football-College-Trivia-iOS | refs/heads/master | FootballCollegeTrivia/Game/GameTimer.swift | mit | 1 | //
// Copyright © 2016 Brandon Jenniges. All rights reserved.
//
import UIKit
protocol GameTimerProtocol {
func timeTicked(displayText: String, color: UIColor)
func timeFinished()
}
class GameTimer: NSObject {
static var timer = NSTimer()
static var minutes = 0
static var seconds = 0
static var secondsLeft = 0
static var presenter: GamePresenter!
static func start() {
secondsLeft = 120;
timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: #selector(GameTimer.updateCounter), userInfo: nil, repeats: true)
}
static func stop() {
timer.invalidate()
}
static func updateCounter() {
if GameTimer.secondsLeft > 0 {
GameTimer.secondsLeft -= 1
GameTimer.minutes = (GameTimer.secondsLeft % 3600) / 60
GameTimer.seconds = (GameTimer.secondsLeft % 3600) % 60
let displayText = String(format: "%d", GameTimer.minutes) + ":" + String(format: "%02d", GameTimer.seconds)
var color: UIColor = .darkGrayColor()
if GameTimer.secondsLeft <= 10 {
color = .redColor()
}
presenter.timeTicked(displayText, color: color)
} else {
stop()
presenter.timeFinished()
}
}
} | 8f2affc694d0fac58ad40a6f40a91cc3 | 28.6 | 149 | 0.601052 | false | false | false | false |
Sage-Bionetworks/BridgeAppSDK | refs/heads/master | BridgeAppSDKTests/SBAOnboardingManagerTests.swift | bsd-3-clause | 1 | //
// SBAOnboardingManagerTests.swift
// BridgeAppSDK
//
// Copyright © 2016 Sage Bionetworks. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
//
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation and/or
// other materials provided with the distribution.
//
// 3. Neither the name of the copyright holder(s) nor the names of any contributors
// may be used to endorse or promote products derived from this software without
// specific prior written permission. No license is granted to the trademarks of
// the copyright holders even if such marks are included in this software.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
import XCTest
import BridgeAppSDK
class SBAOnboardingManagerTests: ResourceTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testCreateManager() {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")
XCTAssertNotNil(manager)
XCTAssertNotNil(manager?.sections)
guard let sections = manager?.sections else { return }
XCTAssertEqual(sections.count, 8)
}
func testShouldInclude() {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")!
let expectedNonNil: [SBAOnboardingSectionBaseType : [SBAOnboardingTaskType]] = [
.login: [.login],
.eligibility: [.signup],
.consent: [.login, .signup, .reconsent],
.registration: [.signup],
.passcode: [.login, .signup, .reconsent],
.emailVerification: [.signup],
.permissions: [.login, .signup],
.profile: [.signup],
.completion: [.login, .signup]]
for sectionType in SBAOnboardingSectionBaseType.all {
let include = expectedNonNil[sectionType]
XCTAssertNotNil(include, "\(sectionType)")
if include != nil {
for taskType in SBAOnboardingTaskType.all {
let expectedShouldInclude = include!.contains(taskType)
let section: NSDictionary = ["onboardingType": sectionType.rawValue]
let shouldInclude = manager.shouldInclude(section: section, onboardingTaskType: taskType)
XCTAssertEqual(shouldInclude, expectedShouldInclude, "\(sectionType) \(taskType)")
}
}
}
}
func testShouldInclude_HasPasscode() {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")!
manager._hasPasscode = true
// Check that if the passcode has been set that it is not included
for taskType in SBAOnboardingTaskType.all {
let section: NSDictionary = ["onboardingType": SBAOnboardingSectionBaseType.passcode.rawValue]
let shouldInclude = manager.shouldInclude(section: section, onboardingTaskType: taskType)
XCTAssertFalse(shouldInclude, "\(taskType)")
}
}
func testShouldInclude_HasRegistered() {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")!
// If the user has registered and this is a completion of the registration
// then only include email verification and those sections AFTER verification
// However, if the user is being reconsented then include the reconsent section
manager.mockAppDelegate.mockCurrentUser.isRegistered = true
manager._hasPasscode = true
let taskTypes: [SBAOnboardingTaskType] = [.signup, .reconsent]
let expectedNonNil: [SBAOnboardingSectionBaseType : [SBAOnboardingTaskType]] = [
.login: [.login],
// eligibility should *not* be included in registration if the user is at the email verification step
.eligibility: [],
// consent should *not* be included in registration if the user is at the email verification step
.consent: [.login, .reconsent],
// registration should *not* be included in registration if the user is at the email verification step
.registration: [],
// passcode should *not* be included in registration if the user is at the email verification step
// and has already set the passcode
.passcode: [],
.emailVerification: [.signup],
.permissions: [.login, .signup],
.profile: [.signup],
.completion: [.login, .signup]]
for sectionType in SBAOnboardingSectionBaseType.all {
let include = expectedNonNil[sectionType]
XCTAssertNotNil(include, "\(sectionType)")
if include != nil {
for taskType in taskTypes {
let expectedShouldInclude = include!.contains(taskType)
let section: NSDictionary = ["onboardingType": sectionType.rawValue]
let shouldInclude = manager.shouldInclude(section: section, onboardingTaskType: taskType)
XCTAssertEqual(shouldInclude, expectedShouldInclude, "\(sectionType) \(taskType)")
}
}
}
}
func testSortOrder() {
let inputSections = [
["onboardingType" : "customWelcome"],
["onboardingType" : "consent"],
["onboardingType" : "passcode"],
["onboardingType" : "emailVerification"],
["onboardingType" : "registration"],
["onboardingType" : "login"],
["onboardingType" : "eligibility"],
["onboardingType" : "profile"],
["onboardingType" : "permissions"],
["onboardingType" : "completion"],
["onboardingType" : "customEnd"],]
let input: NSDictionary = ["sections" : inputSections];
guard let sections = SBAOnboardingManager(dictionary: input).sections else {
XCTAssert(false, "failed to create onboarding manager sections")
return
}
let expectedOrder = ["customWelcome",
"login",
"eligibility",
"consent",
"registration",
"passcode",
"emailVerification",
"permissions",
"profile",
"completion",
"customEnd",]
let actualOrder = sections.sba_mapAndFilter({ $0.onboardingSectionType?.identifier })
XCTAssertEqual(actualOrder, expectedOrder)
}
func testEligibilitySection() {
guard let steps = checkOnboardingSteps( .base(.eligibility), .signup) else { return }
let expectedSteps: [ORKStep] = [SBAToggleFormStep(identifier: "inclusionCriteria"),
SBAInstructionStep(identifier: "ineligibleInstruction"),
SBAInstructionStep(identifier: "eligibleInstruction")]
XCTAssertEqual(steps.count, expectedSteps.count)
for (idx, expectedStep) in expectedSteps.enumerated() {
if idx < steps.count {
XCTAssertEqual(steps[idx].identifier, expectedStep.identifier)
let stepClass = NSStringFromClass(steps[idx].classForCoder)
let expectedStepClass = NSStringFromClass(expectedStep.classForCoder)
XCTAssertEqual(stepClass, expectedStepClass)
}
}
}
func testPasscodeSection() {
guard let steps = checkOnboardingSteps( .base(.passcode), .signup) else { return }
XCTAssertEqual(steps.count, 1)
guard let step = steps.first as? ORKPasscodeStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step.identifier, "passcode")
XCTAssertEqual(step.passcodeType, ORKPasscodeType.type4Digit)
XCTAssertEqual(step.title, "Identification")
XCTAssertEqual(step.text, "Select a 4-digit passcode. Setting up a passcode will help provide quick and secure access to this application.")
}
func testLoginSection() {
guard let steps = checkOnboardingSteps( .base(.login), .login) else { return }
XCTAssertEqual(steps.count, 1)
guard let step = steps.first as? SBALoginStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step.identifier, "login")
}
func testRegistrationSection() {
guard let steps = checkOnboardingSteps( .base(.registration), .signup) else { return }
XCTAssertEqual(steps.count, 2)
guard let step1 = steps.first as? SBASinglePermissionStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step1.identifier, "healthKitPermissions")
guard let step2 = steps.last as? SBARegistrationStep else {
XCTAssert(false, "\(String(describing: steps.last)) not of expected type")
return
}
XCTAssertEqual(step2.identifier, "registration")
}
func testEmailVerificationSection() {
guard let steps = checkOnboardingSteps( .base(.emailVerification), .signup) else { return }
XCTAssertEqual(steps.count, 1)
guard let step = steps.first as? SBAEmailVerificationStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step.identifier, "emailVerification")
}
func testProfileSection() {
guard let steps = checkOnboardingSteps( .base(.profile), .signup) else { return }
XCTAssertEqual(steps.count, 3)
for step in steps {
XCTAssertTrue(step is SBAProfileFormStep)
}
}
func testPermissionsSection() {
guard let steps = checkOnboardingSteps( .base(.permissions), .signup) else { return }
XCTAssertEqual(steps.count, 1)
guard let step = steps.first as? SBAPermissionsStep else {
XCTAssert(false, "\(String(describing: steps.first)) not of expected type")
return
}
XCTAssertEqual(step.identifier, "permissions")
}
func testCreateTask_Login() {
guard let manager = MockOnboardingManager(jsonNamed: "Onboarding") else { return }
guard let task = manager.createTask(for: .login) else {
XCTAssert(false, "Created task is nil")
return
}
let expectedCount = 4
XCTAssertEqual(task.steps.count, expectedCount)
guard task.steps.count == expectedCount else {
XCTAssert(false, "Exit early b/c step count doesn't match expected")
return
}
var ii = 0
XCTAssertTrue(task.steps[ii] is SBALoginStep)
XCTAssertEqual(task.steps[ii].identifier, "login")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "consent")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is ORKPasscodeStep)
XCTAssertEqual(task.steps[ii].identifier, "passcode")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAPermissionsStep)
XCTAssertEqual(task.steps[ii].identifier, "permissions")
}
func testCreateTask_SignUp_Row0() {
guard let manager = MockOnboardingManager(jsonNamed: "Onboarding") else { return }
guard let task = manager.createTask(for: .signup, tableRow: 0) else {
XCTAssert(false, "Created task is nil")
return
}
let expectedCount = 7
XCTAssertEqual(task.steps.count, expectedCount)
guard task.steps.count == expectedCount else {
XCTAssert(false, "Exit early b/c step count doesn't match expected")
return
}
var ii = 0
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "eligibility")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "consent")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "registration")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is ORKPasscodeStep)
XCTAssertEqual(task.steps[ii].identifier, "passcode")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAEmailVerificationStep)
XCTAssertEqual(task.steps[ii].identifier, "emailVerification")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAPermissionsStep)
XCTAssertEqual(task.steps[ii].identifier, "permissions")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "profile")
}
func testCreateTask_SignUp_Row2() {
guard let manager = MockOnboardingManager(jsonNamed: "Onboarding") else { return }
guard let task = manager.createTask(for: .signup, tableRow: 2) else {
XCTAssert(false, "Created task is nil")
return
}
let expectedCount = 5
XCTAssertEqual(task.steps.count, expectedCount)
guard task.steps.count == expectedCount else {
XCTAssert(false, "Exit early b/c step count doesn't match expected")
return
}
var ii = 0
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "registration")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is ORKPasscodeStep)
XCTAssertEqual(task.steps[ii].identifier, "passcode")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAEmailVerificationStep)
XCTAssertEqual(task.steps[ii].identifier, "emailVerification")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBAPermissionsStep)
XCTAssertEqual(task.steps[ii].identifier, "permissions")
ii = ii + 1
XCTAssertTrue(task.steps[ii] is SBASubtaskStep)
XCTAssertEqual(task.steps[ii].identifier, "profile")
}
func testSignupState() {
guard let manager = MockOnboardingManager(jsonNamed: "Onboarding") else { return }
let eligibilityState1 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState1, .current)
let consentState1 = manager.signupState(for: 1)
XCTAssertEqual(consentState1, .locked)
let registrationState1 = manager.signupState(for: 2)
XCTAssertEqual(registrationState1, .locked)
let profileState1 = manager.signupState(for: 3)
XCTAssertEqual(profileState1, .locked)
// For any step in the consent flow except the last, then the consent is the current section
manager.sharedUser.onboardingStepIdentifier = "eligibility.eligibleInstruction"
let eligibilityState2 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState2, .completed)
let consentState2 = manager.signupState(for: 1)
XCTAssertEqual(consentState2, .current)
let registrationState2 = manager.signupState(for: 2)
XCTAssertEqual(registrationState2, .locked)
let profileState2 = manager.signupState(for: 3)
XCTAssertEqual(profileState2, .locked)
// Once we enter the consent flow then that becomes the current section
manager.sharedUser.onboardingStepIdentifier = "consent.consentVisual"
let eligibilityState3 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState3, .completed)
let consentState3 = manager.signupState(for: 1)
XCTAssertEqual(consentState3, .current)
let registrationState3 = manager.signupState(for: 2)
XCTAssertEqual(registrationState3, .locked)
let profileState3 = manager.signupState(for: 3)
XCTAssertEqual(profileState3, .locked)
// For any step in the consent flow except the last, then the consent is the current section
manager.sharedUser.onboardingStepIdentifier = "consent.consentCompletion"
let eligibilityState4 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState4, .completed)
let consentState4 = manager.signupState(for: 1)
XCTAssertEqual(consentState4, .completed)
let registrationState4 = manager.signupState(for: 2)
XCTAssertEqual(registrationState4, .current)
let profileState4 = manager.signupState(for: 3)
XCTAssertEqual(profileState4, .locked)
// Set the steps to the registration section
manager.sharedUser.onboardingStepIdentifier = "registration.registration"
let eligibilityState5 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState5, .completed)
let consentState5 = manager.signupState(for: 1)
XCTAssertEqual(consentState5, .completed)
let registrationState5 = manager.signupState(for: 2)
XCTAssertEqual(registrationState5, .current)
let profileState5 = manager.signupState(for: 3)
XCTAssertEqual(profileState5, .locked)
// For registration, there isn't a completion step and the final step is email verification
// so the current section remains the email verification *until* login is verified
manager.sharedUser.isRegistered = true
manager.sharedUser.isLoginVerified = false
manager.sharedUser.isConsentVerified = false
manager.sharedUser.onboardingStepIdentifier = "emailVerification"
let eligibilityState6 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState6, .completed)
let consentState6 = manager.signupState(for: 1)
XCTAssertEqual(consentState6, .completed)
let registrationState6 = manager.signupState(for: 2)
XCTAssertEqual(registrationState6, .current)
let profileState6 = manager.signupState(for: 3)
XCTAssertEqual(profileState6, .locked)
// Once login and consent are verified, then ready for the profile section
manager.sharedUser.isLoginVerified = true
manager.sharedUser.isConsentVerified = true
let eligibilityState7 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState7, .completed)
let consentState7 = manager.signupState(for: 1)
XCTAssertEqual(consentState7, .completed)
let registrationState7 = manager.signupState(for: 2)
XCTAssertEqual(registrationState7, .completed)
let profileState7 = manager.signupState(for: 3)
XCTAssertEqual(profileState7, .current)
manager.sharedUser.onboardingStepIdentifier = "SBAOnboardingCompleted"
let eligibilityState8 = manager.signupState(for: 0)
XCTAssertEqual(eligibilityState8, .completed)
let consentState8 = manager.signupState(for: 1)
XCTAssertEqual(consentState8, .completed)
let registrationState8 = manager.signupState(for: 2)
XCTAssertEqual(registrationState8, .completed)
let profileState8 = manager.signupState(for: 3)
XCTAssertEqual(profileState8, .completed)
}
func checkOnboardingSteps(_ sectionType: SBAOnboardingSectionType, _ taskType: SBAOnboardingTaskType) -> [ORKStep]? {
let manager = MockOnboardingManager(jsonNamed: "Onboarding")
let section = manager?.section(for: sectionType)
XCTAssertNotNil(section, "sectionType:\(sectionType) taskType:\(taskType)")
guard section != nil else { return nil}
let steps = manager?.steps(for: section!, with: taskType)
XCTAssertNotNil(steps, "sectionType:\(sectionType) taskType:\(taskType)")
return steps
}
}
class MockOnboardingManager: SBAOnboardingManager {
var mockAppDelegate:MockAppInfoDelegate = MockAppInfoDelegate()
override var sharedAppDelegate: SBAAppInfoDelegate {
get { return mockAppDelegate }
set {}
}
var _hasPasscode = false
override var hasPasscode: Bool {
return _hasPasscode
}
}
| ca5ddbc9b0dabdf09fa93c0176f99a40 | 39.771481 | 148 | 0.627881 | false | false | false | false |
kstaring/swift | refs/heads/upstream-master | test/attr/attributes.swift | apache-2.0 | 1 | // RUN: %target-parse-verify-swift
@unknown func f0() {} // expected-error{{unknown attribute 'unknown'}}
@unknown(x,y) func f1() {} // expected-error{{unknown attribute 'unknown'}}
enum binary {
case Zero
case One
init() { self = .Zero }
}
func f5(x: inout binary) {}
//===---
//===--- IB attributes
//===---
@IBDesignable
class IBDesignableClassTy {
@IBDesignable func foo() {} // expected-error {{@IBDesignable cannot be applied to this declaration}} {{3-17=}}
}
@IBDesignable // expected-error {{@IBDesignable cannot be applied to this declaration}} {{1-15=}}
struct IBDesignableStructTy {}
@IBDesignable // expected-error {{@IBDesignable cannot be applied to this declaration}} {{1-15=}}
protocol IBDesignableProtTy {}
@IBDesignable // expected-error {{@IBDesignable can only be applied to classes and extensions of classes}} {{1-15=}}
extension IBDesignableStructTy {}
class IBDesignableClassExtensionTy {}
@IBDesignable // okay
extension IBDesignableClassExtensionTy {}
class Inspect {
@IBInspectable var value : Int = 0 // okay
@GKInspectable var value2: Int = 0 // okay
@IBInspectable func foo() {} // expected-error {{@IBInspectable may only be used on 'var' declarations}} {{3-18=}}
@GKInspectable func foo2() {} // expected-error {{@GKInspectable may only be used on 'var' declarations}} {{3-18=}}
@IBInspectable class var cval: Int { return 0 } // expected-error {{only instance properties can be declared @IBInspectable}} {{3-18=}}
@GKInspectable class var cval2: Int { return 0 } // expected-error {{only instance properties can be declared @GKInspectable}} {{3-18=}}
}
@IBInspectable var ibinspectable_global : Int // expected-error {{only instance properties can be declared @IBInspectable}} {{1-16=}}
@GKInspectable var gkinspectable_global : Int // expected-error {{only instance properties can be declared @GKInspectable}} {{1-16=}}
func foo(x: @convention(block) Int) {} // expected-error {{@convention attribute only applies to function types}}
func foo(x: @convention(block) (Int) -> Int) {}
@_transparent
func zim() {}
@_transparent
func zung<T>(_: T) {}
@_transparent // expected-error{{@_transparent cannot be applied to stored properties}} {{1-15=}}
var zippity : Int
func zoom(x: @_transparent () -> ()) { } // expected-error{{attribute can only be applied to declarations, not types}} {{1-1=@_transparent }} {{14-28=}}
protocol ProtoWithTransparent {
@_transparent// expected-error{{@_transparent is not supported on declarations within protocols}} {{3-16=}}
func transInProto()
}
class TestTranspClass : ProtoWithTransparent {
@_transparent // expected-error{{@_transparent is not supported on declarations within classes}} {{3-17=}}
init () {}
@_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{3-17=}}
deinit {}
@_transparent // expected-error{{@_transparent is not supported on declarations within classes}} {{3-17=}}
class func transStatic() {}
@_transparent// expected-error{{@_transparent is not supported on declarations within classes}} {{3-16=}}
func transInProto() {}
}
struct TestTranspStruct : ProtoWithTransparent{
@_transparent
init () {}
@_transparent
init <T> (x : T) { }
@_transparent
static func transStatic() {}
@_transparent
func transInProto() {}
}
@_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{1-15=}}
struct CannotHaveTransparentStruct {
func m1() {}
}
@_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{1-15=}}
extension TestTranspClass {
func tr1() {}
}
@_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{1-15=}}
extension TestTranspStruct {
func tr1() {}
}
@_transparent // expected-error{{@_transparent cannot be applied to this declaration}} {{1-15=}}
extension binary {
func tr1() {}
}
class transparentOnClassVar {
@_transparent var max: Int { return 0xFF }; // expected-error {{@_transparent is not supported on declarations within classes}} {{3-17=}}
func blah () {
var _: Int = max
}
};
class transparentOnClassVar2 {
var max: Int {
@_transparent // expected-error {{@_transparent is not supported on declarations within classes}} {{5-19=}}
get {
return 0xFF
}
}
func blah () {
var _: Int = max
}
};
@thin // expected-error {{attribute can only be applied to types, not declarations}}
func testThinDecl() -> () {}
protocol Class : class {}
protocol NonClass {}
@objc
class Ty0 : Class, NonClass {
init() { }
}
// Attributes that should be reported by parser as unknown
// See rdar://19533915
@__accessibility struct S__accessibility {} // expected-error{{unknown attribute '__accessibility'}}
@__raw_doc_comment struct S__raw_doc_comment {} // expected-error{{unknown attribute '__raw_doc_comment'}}
@__objc_bridged struct S__objc_bridged {} // expected-error{{unknown attribute '__objc_bridged'}}
weak
var weak0 : Ty0?
weak
var weak0x : Ty0?
weak unowned var weak1 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
weak weak var weak2 : Ty0? // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
unowned var weak3 : Ty0
unowned var weak3a : Ty0
unowned(safe) var weak3b : Ty0
unowned(unsafe) var weak3c : Ty0
unowned unowned var weak4 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
unowned weak var weak5 : Ty0 // expected-error {{duplicate modifier}} expected-note {{modifier already specified here}}
weak
var weak6 : Int // expected-error {{'weak' may only be applied to class and class-bound protocol types, not 'Int'}}
unowned
var weak7 : Int // expected-error {{'unowned' may only be applied to class and class-bound protocol types, not 'Int'}}
weak
var weak8 : Class? = Ty0()
unowned var weak9 : Class = Ty0()
weak
var weak10 : NonClass = Ty0() // expected-error {{'weak' may not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
unowned
var weak11 : NonClass = Ty0() // expected-error {{'unowned' may not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
unowned
var weak12 : NonClass = Ty0() // expected-error {{'unowned' may not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
unowned
var weak13 : NonClass = Ty0() // expected-error {{'unowned' may not be applied to non-class-bound 'NonClass'; consider adding a protocol conformance that has a class bound}}
weak
var weak14 : Ty0 // expected-error {{'weak' variable should have optional type 'Ty0?'}}
weak
var weak15 : Class // expected-error {{'weak' variable should have optional type 'Class?'}}
weak var weak16 : Class!
@weak var weak17 : Class? // expected-error {{'weak' is a declaration modifier, not an attribute}} {{1-2=}}
@_exported var exportVar: Int // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}}
@_exported func exportFunc() {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}}
@_exported struct ExportStruct {} // expected-error {{@_exported may only be used on 'import' declarations}}{{1-12=}}
// Function result type attributes.
var func_result_type_attr : () -> @xyz Int // expected-error {{unknown attribute 'xyz'}}
func func_result_attr() -> @xyz Int { // expected-error {{unknown attribute 'xyz'}}
return 4
}
func func_with_unknown_attr1(@unknown(*) x: Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr2(x: @unknown(_) Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr3(x: @unknown(Int) -> Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr4(x: @unknown(Int) throws -> Int) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr5(x: @unknown (x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}}
func func_with_unknown_attr6(x: @unknown(x: Int, y: Int)) {} // expected-error {{unknown attribute 'unknown'}} expected-error {{expected parameter type following ':'}}
func func_with_unknown_attr7(x: @unknown (Int) () -> Int) {} // expected-error {{unknown attribute 'unknown'}} expected-error {{expected ',' separator}} {{47-47=,}} expected-error {{unnamed parameters must be written with the empty name '_'}} {{48-48=_: }}
func func_type_attribute_with_space(x: @convention (c) () -> Int) {} // OK. Known attributes can have space before its paren.
// @thin is not supported except in SIL.
var thinFunc : @thin () -> () // expected-error {{attribute is not supported}}
@inline(never) func nolineFunc() {}
@inline(never) var noinlineVar : Int // expected-error {{@inline(never) cannot be applied to this declaration}} {{1-16=}}
@inline(never) class FooClass { // expected-error {{@inline(never) cannot be applied to this declaration}} {{1-16=}}
}
@inline(__always) func AlwaysInlineFunc() {}
@inline(__always) var alwaysInlineVar : Int // expected-error {{@inline(__always) cannot be applied to this declaration}} {{1-19=}}
@inline(__always) class FooClass2 { // expected-error {{@inline(__always) cannot be applied to this declaration}} {{1-19=}}
}
class A {
@inline(never) init(a : Int) {}
var b : Int {
@inline(never) get {
return 42
}
@inline(never) set {
}
}
}
class B {
@inline(__always) init(a : Int) {}
var b : Int {
@inline(__always) get {
return 42
}
@inline(__always) set {
}
}
}
class SILStored {
@sil_stored var x : Int = 42 // expected-error {{'sil_stored' only allowed in SIL modules}}
}
@_show_in_interface protocol _underscored {}
@_show_in_interface class _notapplicable {} // expected-error {{may only be used on 'protocol' declarations}}
| a9803b50e406f658da3195a1f7c86c9d | 39.440816 | 256 | 0.693581 | false | false | false | false |
eure/ReceptionApp | refs/heads/master | iOS/Pods/CoreStore/CoreStore/Observing/ObjectMonitor.swift | mit | 1 | //
// ObjectMonitor.swift
// CoreStore
//
// Copyright © 2015 John Rommel Estropia
//
// 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 CoreData
#if USE_FRAMEWORKS
import GCDKit
#endif
// MARK: - ObjectMonitor
/**
The `ObjectMonitor` monitors changes to a single `NSManagedObject` instance. Observers that implement the `ObjectObserver` protocol may then register themselves to the `ObjectMonitor`'s `addObserver(_:)` method:
```
let monitor = CoreStore.monitorObject(object)
monitor.addObserver(self)
```
The created `ObjectMonitor` instance needs to be held on (retained) for as long as the object needs to be observed.
Observers registered via `addObserver(_:)` are not retained. `ObjectMonitor` only keeps a `weak` reference to all observers, thus keeping itself free from retain-cycles.
*/
@available(OSX, unavailable)
public final class ObjectMonitor<T: NSManagedObject> {
/**
Returns the `NSManagedObject` instance being observed, or `nil` if the object was already deleted.
*/
public var object: T? {
return self.fetchedResultsController.fetchedObjects?.first as? T
}
/**
Returns `true` if the `NSManagedObject` instance being observed still exists, or `false` if the object was already deleted.
*/
public var isObjectDeleted: Bool {
return self.object?.managedObjectContext == nil
}
/**
Registers an `ObjectObserver` to be notified when changes to the receiver's `object` are made.
To prevent retain-cycles, `ObjectMonitor` only keeps `weak` references to its observers.
For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread.
Calling `addObserver(_:)` multiple times on the same observer is safe, as `ObjectMonitor` unregisters previous notifications to the observer before re-registering them.
- parameter observer: an `ObjectObserver` to send change notifications to
*/
public func addObserver<U: ObjectObserver where U.ObjectEntityType == T>(observer: U) {
CoreStore.assert(
NSThread.isMainThread(),
"Attempted to add an observer of type \(typeName(observer)) outside the main thread."
)
self.removeObserver(observer)
self.registerChangeNotification(
&self.willChangeObjectKey,
name: ObjectMonitorWillChangeObjectNotification,
toObserver: observer,
callback: { [weak observer] (monitor) -> Void in
guard let object = monitor.object, let observer = observer else {
return
}
observer.objectMonitor(monitor, willUpdateObject: object)
}
)
self.registerObjectNotification(
&self.didDeleteObjectKey,
name: ObjectMonitorDidDeleteObjectNotification,
toObserver: observer,
callback: { [weak observer] (monitor, object) -> Void in
guard let observer = observer else {
return
}
observer.objectMonitor(monitor, didDeleteObject: object)
}
)
self.registerObjectNotification(
&self.didUpdateObjectKey,
name: ObjectMonitorDidUpdateObjectNotification,
toObserver: observer,
callback: { [weak self, weak observer] (monitor, object) -> Void in
guard let strongSelf = self, let observer = observer else {
return
}
let previousCommitedAttributes = strongSelf.lastCommittedAttributes
let currentCommitedAttributes = object.committedValuesForKeys(nil) as! [String: NSObject]
var changedKeys = Set<String>()
for key in currentCommitedAttributes.keys {
if previousCommitedAttributes[key] != currentCommitedAttributes[key] {
changedKeys.insert(key)
}
}
strongSelf.lastCommittedAttributes = currentCommitedAttributes
observer.objectMonitor(
monitor,
didUpdateObject: object,
changedPersistentKeys: changedKeys
)
}
)
}
/**
Unregisters an `ObjectObserver` from receiving notifications for changes to the receiver's `object`.
For thread safety, this method needs to be called from the main thread. An assertion failure will occur (on debug builds only) if called from any thread other than the main thread.
- parameter observer: an `ObjectObserver` to unregister notifications to
*/
public func removeObserver<U: ObjectObserver where U.ObjectEntityType == T>(observer: U) {
CoreStore.assert(
NSThread.isMainThread(),
"Attempted to remove an observer of type \(typeName(observer)) outside the main thread."
)
let nilValue: AnyObject? = nil
setAssociatedRetainedObject(nilValue, forKey: &self.willChangeObjectKey, inObject: observer)
setAssociatedRetainedObject(nilValue, forKey: &self.didDeleteObjectKey, inObject: observer)
setAssociatedRetainedObject(nilValue, forKey: &self.didUpdateObjectKey, inObject: observer)
}
// MARK: Internal
internal convenience init(dataStack: DataStack, object: T) {
self.init(context: dataStack.mainContext, object: object)
}
internal convenience init(unsafeTransaction: UnsafeDataTransaction, object: T) {
self.init(context: unsafeTransaction.context, object: object)
}
private init(context: NSManagedObjectContext, object: T) {
let fetchRequest = NSFetchRequest()
fetchRequest.entity = object.entity
fetchRequest.fetchLimit = 0
fetchRequest.resultType = .ManagedObjectResultType
fetchRequest.sortDescriptors = []
fetchRequest.includesPendingChanges = false
fetchRequest.shouldRefreshRefetchedObjects = true
let fetchedResultsController = CoreStoreFetchedResultsController<T>(
context: context,
fetchRequest: fetchRequest,
fetchClauses: [Where("SELF", isEqualTo: object.objectID)]
)
let fetchedResultsControllerDelegate = FetchedResultsControllerDelegate()
self.fetchedResultsController = fetchedResultsController
self.fetchedResultsControllerDelegate = fetchedResultsControllerDelegate
fetchedResultsControllerDelegate.handler = self
fetchedResultsControllerDelegate.fetchedResultsController = fetchedResultsController
try! fetchedResultsController.performFetchFromSpecifiedStores()
self.lastCommittedAttributes = (self.object?.committedValuesForKeys(nil) as? [String: NSObject]) ?? [:]
}
deinit {
self.fetchedResultsControllerDelegate.fetchedResultsController = nil
}
// MARK: Private
private let fetchedResultsController: CoreStoreFetchedResultsController<T>
private let fetchedResultsControllerDelegate: FetchedResultsControllerDelegate
private var lastCommittedAttributes = [String: NSObject]()
private var willChangeObjectKey: Void?
private var didDeleteObjectKey: Void?
private var didUpdateObjectKey: Void?
private func registerChangeNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<T>) -> Void) {
setAssociatedRetainedObject(
NotificationObserver(
notificationName: name,
object: self,
closure: { [weak self] (note) -> Void in
guard let strongSelf = self else {
return
}
callback(monitor: strongSelf)
}
),
forKey: notificationKey,
inObject: observer
)
}
private func registerObjectNotification(notificationKey: UnsafePointer<Void>, name: String, toObserver observer: AnyObject, callback: (monitor: ObjectMonitor<T>, object: T) -> Void) {
setAssociatedRetainedObject(
NotificationObserver(
notificationName: name,
object: self,
closure: { [weak self] (note) -> Void in
guard let strongSelf = self,
let userInfo = note.userInfo,
let object = userInfo[UserInfoKeyObject] as? T else {
return
}
callback(monitor: strongSelf, object: object)
}
),
forKey: notificationKey,
inObject: observer
)
}
}
// MARK: - ObjectMonitor: Equatable
@available(OSX, unavailable)
public func ==<T: NSManagedObject>(lhs: ObjectMonitor<T>, rhs: ObjectMonitor<T>) -> Bool {
return lhs === rhs
}
@available(OSX, unavailable)
extension ObjectMonitor: Equatable { }
// MARK: - ObjectMonitor: FetchedResultsControllerHandler
@available(OSX, unavailable)
extension ObjectMonitor: FetchedResultsControllerHandler {
// MARK: FetchedResultsControllerHandler
internal func controllerWillChangeContent(controller: NSFetchedResultsController) {
NSNotificationCenter.defaultCenter().postNotificationName(
ObjectMonitorWillChangeObjectNotification,
object: self
)
}
internal func controllerDidChangeContent(controller: NSFetchedResultsController) { }
internal func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Delete:
NSNotificationCenter.defaultCenter().postNotificationName(
ObjectMonitorDidDeleteObjectNotification,
object: self,
userInfo: [UserInfoKeyObject: anObject]
)
case .Update:
NSNotificationCenter.defaultCenter().postNotificationName(
ObjectMonitorDidUpdateObjectNotification,
object: self,
userInfo: [UserInfoKeyObject: anObject]
)
default:
break
}
}
internal func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { }
internal func controller(controller: NSFetchedResultsController, sectionIndexTitleForSectionName sectionName: String?) -> String? {
return sectionName
}
}
private let ObjectMonitorWillChangeObjectNotification = "ObjectMonitorWillChangeObjectNotification"
private let ObjectMonitorDidDeleteObjectNotification = "ObjectMonitorDidDeleteObjectNotification"
private let ObjectMonitorDidUpdateObjectNotification = "ObjectMonitorDidUpdateObjectNotification"
private let UserInfoKeyObject = "UserInfoKeyObject"
| 90a5389943ad34deb1a935dc579ba0ed | 38.009091 | 220 | 0.641265 | false | false | false | false |
hovansuit/FoodAndFitness | refs/heads/master | FoodAndFitness/Controllers/SignUp/Cell/Avatar/AvatarCell.swift | mit | 1 | //
// AvatarCell.swift
// FoodAndFitness
//
// Created by Mylo Ho on 4/5/17.
// Copyright © 2017 SuHoVan. All rights reserved.
//
import UIKit
protocol AvatarCellDelegate: NSObjectProtocol {
func cell(_ cell: AvatarCell, needsPerformAction action: AvatarCell.Action)
}
final class AvatarCell: BaseTableViewCell {
@IBOutlet fileprivate(set) weak var titleLabel: UILabel!
@IBOutlet fileprivate(set) weak var avatarImageView: UIImageView!
weak var delegate: AvatarCellDelegate?
enum Action {
case showActionSheet
}
struct Data {
var title: String
var image: UIImage?
}
var data: Data? {
didSet {
guard let data = data else { return }
titleLabel.text = data.title
if let image = data.image {
avatarImageView.image = image
} else {
avatarImageView.image = #imageLiteral(resourceName: "img_avatar_default")
}
}
}
@IBAction fileprivate func showActionSheet(_ sender: Any) {
delegate?.cell(self, needsPerformAction: .showActionSheet)
}
}
| d1b2c25ce6492b0adcf870dc04ad5fe6 | 24.111111 | 89 | 0.629204 | false | false | false | false |
8bytes/drift-sdk-ios | refs/heads/master | Drift/Birdsong/Push.swift | mit | 2 | //
// Message.swift
// Pods
//
// Created by Simon Manning on 23/06/2016.
//
//
import Foundation
internal class Push {
public let topic: String
public let event: String
public let payload: Socket.Payload
let ref: String?
var receivedStatus: String?
var receivedResponse: Socket.Payload?
fileprivate var callbacks: [String: [(Socket.Payload) -> ()]] = [:]
fileprivate var alwaysCallbacks: [() -> ()] = []
// MARK: - JSON parsing
func toJson() throws -> Data {
let dict = [
"topic": topic,
"event": event,
"payload": payload,
"ref": ref ?? ""
] as [String : Any]
return try JSONSerialization.data(withJSONObject: dict, options: JSONSerialization.WritingOptions())
}
init(_ event: String, topic: String, payload: Socket.Payload, ref: String = UUID().uuidString) {
(self.topic, self.event, self.payload, self.ref) = (topic, event, payload, ref)
}
// MARK: - Callback registration
@discardableResult
func receive(_ status: String, callback: @escaping (Socket.Payload) -> ()) -> Self {
if receivedStatus == status,
let receivedResponse = receivedResponse {
callback(receivedResponse)
}
else {
if (callbacks[status] == nil) {
callbacks[status] = [callback]
}
else {
callbacks[status]?.append(callback)
}
}
return self
}
@discardableResult
func always(_ callback: @escaping () -> ()) -> Self {
alwaysCallbacks.append(callback)
return self
}
// MARK: - Response handling
func handleResponse(_ response: Response) {
receivedStatus = response.payload["status"] as? String
receivedResponse = response.payload
fireCallbacksAndCleanup()
}
func handleParseError() {
receivedStatus = "error"
receivedResponse = ["reason": "Invalid payload request." as AnyObject]
fireCallbacksAndCleanup()
}
func handleNotConnected() {
receivedStatus = "error"
receivedResponse = ["reason": "Not connected to socket." as AnyObject]
fireCallbacksAndCleanup()
}
func fireCallbacksAndCleanup() {
defer {
callbacks.removeAll()
alwaysCallbacks.removeAll()
}
guard let status = receivedStatus else {
return
}
alwaysCallbacks.forEach({$0()})
if let matchingCallbacks = callbacks[status],
let receivedResponse = receivedResponse {
matchingCallbacks.forEach({$0(receivedResponse)})
}
}
}
| 878fdc4b7bfca45b90c1314b894886f7 | 24.632075 | 108 | 0.58042 | false | false | false | false |
22377832/ccyswift | refs/heads/master | EnumPlayground.playground/Contents.swift | mit | 1 | //: Playground - noun: a place where people can play
import UIKit
var str = "Hello, playground"
enum SomeEnumerstion{
}
enum CompassPoint{
case north
case south
case east
case west
}
enum Planet{
case mercury, venus, earth, mars, jupoter
}
var directionToHead: CompassPoint = .east
switch directionToHead {
case .north:
print("")
default:
print("")
}
// 关联值 ..
enum Barcode{
case upa(Int, Int, Int, Int)
case qrCode(String)
}
var productBarcode = Barcode.qrCode("asdfasdfasd")
productBarcode = .upa(0, 9, 0, 9)
// 原始值
enum StatusCode: String{
case 你好
case status2 = "ab"
case status3 = "abc"
case status4 = "abcd"
func statusString() -> String{
return self.rawValue
}
}
let status = StatusCode.你好
status.rawValue
// 递归枚举
enum ArithmeticExpression0{
case number(Int)
indirect case addition(ArithmeticExpression0, ArithmeticExpression0)
indirect case nultiplication(ArithmeticExpression0, ArithmeticExpression0)
}
indirect enum ArithmeticExpression{
case number(Int)
case addition(ArithmeticExpression, ArithmeticExpression)
case multiplication(ArithmeticExpression, ArithmeticExpression)
}
// (5 + 4) * 2
let five = ArithmeticExpression.number(5)
let four = ArithmeticExpression.number(4)
let sum = ArithmeticExpression.addition(five, four)
let product = ArithmeticExpression.multiplication(sum, ArithmeticExpression.number(2))
print(product)
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))
| a46ef8d5153e3e5801801e4655c95ec4 | 18.136842 | 86 | 0.69912 | false | false | false | false |
benlangmuir/swift | refs/heads/master | SwiftCompilerSources/Sources/SIL/Location.swift | apache-2.0 | 2 | //===--- Location.swift - Source location ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import SILBridging
public struct Location {
let bridged: BridgedLocation
/// Keeps the debug scope but marks it as auto-generated.
public var autoGenerated: Location {
Location(bridged: SILLocation_getAutogeneratedLocation(bridged))
}
}
| f3b04089e0fa56df373d9c74aa8849ab | 34.136364 | 80 | 0.627426 | false | false | false | false |
overtake/TelegramSwift | refs/heads/master | Telegram-Mac/ListViewIntermediateState.swift | gpl-2.0 | 1 | //
// ListViewIntermediateState.swift
// Telegram
//
// Created by keepcoder on 19/04/2017.
// Copyright © 2017 Telegram. All rights reserved.
//
import Cocoa
import SwiftSignalKit
public enum ListViewCenterScrollPositionOverflow {
case Top
case Bottom
}
public enum ListViewScrollPosition: Equatable {
case Top
case Bottom
case Center(ListViewCenterScrollPositionOverflow)
}
public func ==(lhs: ListViewScrollPosition, rhs: ListViewScrollPosition) -> Bool {
switch lhs {
case .Top:
switch rhs {
case .Top:
return true
default:
return false
}
case .Bottom:
switch rhs {
case .Bottom:
return true
default:
return false
}
case let .Center(lhsOverflow):
switch rhs {
case let .Center(rhsOverflow) where lhsOverflow == rhsOverflow:
return true
default:
return false
}
}
}
public enum ListViewScrollToItemDirectionHint {
case Up
case Down
}
public enum ListViewAnimationCurve {
case Spring(duration: Double)
case Default
}
public struct ListViewScrollToItem {
public let index: Int
public let position: ListViewScrollPosition
public let animated: Bool
public let curve: ListViewAnimationCurve
public let directionHint: ListViewScrollToItemDirectionHint
public init(index: Int, position: ListViewScrollPosition, animated: Bool, curve: ListViewAnimationCurve, directionHint: ListViewScrollToItemDirectionHint) {
self.index = index
self.position = position
self.animated = animated
self.curve = curve
self.directionHint = directionHint
}
}
public enum ListViewItemOperationDirectionHint {
case Up
case Down
}
public struct ListViewDeleteItem {
public let index: Int
public let directionHint: ListViewItemOperationDirectionHint?
public init(index: Int, directionHint: ListViewItemOperationDirectionHint?) {
self.index = index
self.directionHint = directionHint
}
}
public struct ListViewInsertItem {
public let index: Int
public let previousIndex: Int?
public let item: ListViewItem
public let directionHint: ListViewItemOperationDirectionHint?
public let forceAnimateInsertion: Bool
public init(index: Int, previousIndex: Int?, item: ListViewItem, directionHint: ListViewItemOperationDirectionHint?, forceAnimateInsertion: Bool = false) {
self.index = index
self.previousIndex = previousIndex
self.item = item
self.directionHint = directionHint
self.forceAnimateInsertion = forceAnimateInsertion
}
}
public struct ListViewUpdateItem {
public let index: Int
public let previousIndex: Int
public let item: ListViewItem
public let directionHint: ListViewItemOperationDirectionHint?
public init(index: Int, previousIndex: Int, item: ListViewItem, directionHint: ListViewItemOperationDirectionHint?) {
self.index = index
self.previousIndex = previousIndex
self.item = item
self.directionHint = directionHint
}
}
public struct ListViewDeleteAndInsertOptions: OptionSet {
public let rawValue: Int
public init(rawValue: Int) {
self.rawValue = rawValue
}
public static let AnimateInsertion = ListViewDeleteAndInsertOptions(rawValue: 1)
public static let AnimateAlpha = ListViewDeleteAndInsertOptions(rawValue: 2)
public static let LowLatency = ListViewDeleteAndInsertOptions(rawValue: 4)
public static let Synchronous = ListViewDeleteAndInsertOptions(rawValue: 8)
public static let RequestItemInsertionAnimations = ListViewDeleteAndInsertOptions(rawValue: 16)
public static let AnimateTopItemPosition = ListViewDeleteAndInsertOptions(rawValue: 32)
public static let PreferSynchronousDrawing = ListViewDeleteAndInsertOptions(rawValue: 64)
public static let PreferSynchronousResourceLoading = ListViewDeleteAndInsertOptions(rawValue: 128)
}
public struct ListViewItemRange: Equatable {
public let firstIndex: Int
public let lastIndex: Int
}
public func ==(lhs: ListViewItemRange, rhs: ListViewItemRange) -> Bool {
return lhs.firstIndex == rhs.firstIndex && lhs.lastIndex == rhs.lastIndex
}
public struct ListViewDisplayedItemRange: Equatable {
public let loadedRange: ListViewItemRange?
public let visibleRange: ListViewItemRange?
}
public func ==(lhs: ListViewDisplayedItemRange, rhs: ListViewDisplayedItemRange) -> Bool {
return lhs.loadedRange == rhs.loadedRange && lhs.visibleRange == rhs.visibleRange
}
struct IndexRange {
let first: Int
let last: Int
func contains(_ index: Int) -> Bool {
return index >= first && index <= last
}
var empty: Bool {
return first > last
}
}
struct OffsetRanges {
var offsets: [(IndexRange, CGFloat)] = []
mutating func append(_ other: OffsetRanges) {
self.offsets.append(contentsOf: other.offsets)
}
mutating func offset(_ indexRange: IndexRange, offset: CGFloat) {
self.offsets.append((indexRange, offset))
}
func offsetForIndex(_ index: Int) -> CGFloat {
var result: CGFloat = 0.0
for offset in self.offsets {
if offset.0.contains(index) {
result += offset.1
}
}
return result
}
}
func binarySearch(_ inputArr: [Int], searchItem: Int) -> Int? {
var lowerIndex = 0;
var upperIndex = inputArr.count - 1
if lowerIndex > upperIndex {
return nil
}
while (true) {
let currentIndex = (lowerIndex + upperIndex) / 2
if (inputArr[currentIndex] == searchItem) {
return currentIndex
} else if (lowerIndex > upperIndex) {
return nil
} else {
if (inputArr[currentIndex] > searchItem) {
upperIndex = currentIndex - 1
} else {
lowerIndex = currentIndex + 1
}
}
}
}
struct TransactionState {
let visibleSize: CGSize
let items: [ListViewItem]
}
enum ListViewInsertionOffsetDirection {
case Up
case Down
init(_ hint: ListViewItemOperationDirectionHint) {
switch hint {
case .Up:
self = .Up
case .Down:
self = .Down
}
}
func inverted() -> ListViewInsertionOffsetDirection {
switch self {
case .Up:
return .Down
case .Down:
return .Up
}
}
}
struct ListViewInsertionPoint {
let index: Int
let point: CGPoint
let direction: ListViewInsertionOffsetDirection
}
public protocol ListViewItem {
}
public struct ListViewUpdateSizeAndInsets {
public let size: CGSize
public let insets: NSEdgeInsets
public let duration: Double
public let curve: ListViewAnimationCurve
public init(size: CGSize, insets: NSEdgeInsets, duration: Double, curve: ListViewAnimationCurve) {
self.size = size
self.insets = insets
self.duration = duration
self.curve = curve
}
}
| 9f10a8173a97f05023dca71cdbcf5025 | 25.955224 | 160 | 0.665975 | false | false | false | false |
tempestrock/CarPlayer | refs/heads/master | CarPlayer/TrackListViewController.swift | gpl-3.0 | 1 | //
// TrackListViewController.swift
// CarPlayer
//
// Created by Peter Störmer on 18.12.14.
// Copyright (c) 2014 Tempest Rock Studios. All rights reserved.
//
import Foundation
import UIKit
import MediaPlayer
//
// A view controller to show the list of tracks in a modal view.
//
class TracklistViewController: ModalViewController {
var scrollView: UIScrollView!
var _initialSetup: Bool = true
override func viewDidLoad() {
super.viewDidLoad() // Paints the black background rectangle
// Set notification handler for music changing in the background. The complete track list is re-painted
_controller.setNotificationHandler(self, notificationFunctionName: #selector(TracklistViewController.createTrackList))
createTrackList()
}
//
// Creates the complete track list.
//
func createTrackList() {
// DEBUG print("TrackListViewController.createTrackList()")
// Set some hard-coded limit for the number of tracks to be shown:
let maxNum = MyBasics.TrackListView_MaxNumberOfTracks
// Find out whether we are creating the tracklist for the first time:
_initialSetup = (scrollView == nil)
if _initialSetup {
// This is the initial setup of the scroll view.
scrollView = UIScrollView()
// Create an underlying close button also on the scrollview:
let closeButtonOnScrollView = UIButton(type: UIButtonType.Custom)
var ySizeOfButton = CGFloat(_controller.currentPlaylist().count * yPosOfView * 2 + yPosOfView)
if ySizeOfButton < CGFloat(heightOfView) - 20.0 {
ySizeOfButton = CGFloat(heightOfView) - 20.0
}
closeButtonOnScrollView.addTarget(self,
action: #selector(ModalViewController.closeViewWithoutAction),
forControlEvents: .TouchUpInside)
closeButtonOnScrollView.frame = CGRectMake(CGFloat(xPosOfView) + 10.0, CGFloat(yPosOfView) + 5.0, CGFloat(widthOfView) - 20.0, ySizeOfButton)
scrollView.addSubview(closeButtonOnScrollView)
// Set basic stuff for scrollview:
scrollView.scrollEnabled = true
scrollView.frame = CGRectMake(CGFloat(xPosOfView), CGFloat(yPosOfView) + 5.0,
CGFloat(widthOfView) - 20.0, CGFloat(heightOfView) - 20.0)
}
// Variable to keep the y position of the now playing item:
var yPosOfNowPlayingItem: CGFloat = -1.0
// Fill the scrollview with track names:
var curYPos: Int = 0
var counter: Int = 1
for track in _controller.currentPlaylist() {
// Set the text color depending on whether we show the name of the currently playing item or not:
var labelTextColor: UIColor
if track == _controller.nowPlayingItem() {
labelTextColor = UIColor.darkGrayColor()
yPosOfNowPlayingItem = CGFloat(curYPos)
} else {
labelTextColor = UIColor.whiteColor()
}
// Make a label for the counter:
let number = UILabel()
number.text = counter.description
number.font = MyBasics.fontForMediumText
number.textColor = labelTextColor
number.textAlignment = NSTextAlignment.Right
number.frame = CGRect(x: 0.0, y: CGFloat(curYPos) + 7.5, width: CGFloat(60), height: CGFloat(2 * yPosOfView))
scrollView.addSubview(number)
// Make a small album artwork for an easier identification if an artwork exists:
if (track.artwork != nil) {
let sizeOfArtistImage = CGSize(width: MyBasics.TrackListView_ArtistImage_Width, height: MyBasics.TrackListView_ArtistImage_Height)
let albumCoverImage: UIImageView = UIImageView()
albumCoverImage.image = track.artwork!.imageWithSize(sizeOfArtistImage)
albumCoverImage.frame = CGRectMake(70, CGFloat(curYPos) + 10,
CGFloat(MyBasics.TrackListView_ArtistImage_Width), CGFloat(MyBasics.TrackListView_ArtistImage_Height))
scrollView.addSubview(albumCoverImage)
}
// Make a button for the actual track title:
let button = UIButtonWithFeatures(type: UIButtonType.Custom)
button.setTitle(track.title!, forState: .Normal)
button.titleLabel!.font = MyBasics.fontForMediumText
button.setTitleColor(labelTextColor, forState: UIControlState.Normal)
button.titleLabel!.textAlignment = NSTextAlignment.Left
button.frame = CGRect(x: 110, y: curYPos, width: widthOfView, height: heightOfView) // width and height are just dummies due to following "sizeToFit"
button.sizeToFit()
button.addTarget(self, action: #selector(TracklistViewController.trackNameTapped(_:)), forControlEvents: UIControlEvents.TouchUpInside)
button.setMediaItem(track)
scrollView.addSubview(button)
// Increase y position:
curYPos += 2 * yPosOfView
counter += 1
if counter > maxNum {
break
}
}
if _initialSetup {
scrollView.contentSize = CGSizeMake(CGFloat(widthOfView) - 20.0, CGFloat(curYPos + yPosOfView));
scrollView.contentOffset = CGPoint(x: 0, y: 0)
}
view.addSubview(scrollView)
// Tweak the y-position of the currently playing item in order to find a nice looking position:
tweakYPosOfNowPlayingItem(curYPos, scrollView: scrollView, yPosOfNowPlayingItem: &yPosOfNowPlayingItem)
// Force jumping to the new y position into a different runloop.
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(0.5 * Double(NSEC_PER_SEC)))
dispatch_after(time, dispatch_get_main_queue()) {
self.jumpToPosition(yPosOfNowPlayingItem)
}
}
//
// Tweaks the y-position of the currently playing item in order to find a nice looking position.
//
func tweakYPosOfNowPlayingItem(totalHeightOfScrollView: Int, scrollView: UIScrollView, inout yPosOfNowPlayingItem: CGFloat) {
let minVal: CGFloat = 80.0
let maxVal: CGFloat = scrollView.contentSize.height - CGFloat(self.heightOfView) + CGFloat(self.yPosOfView / 2)
// DEBUG print("yPosOfNowPlayingItem: \(yPosOfNowPlayingItem), maxVal: \(maxVal)")
if totalHeightOfScrollView < self.heightOfView {
// The list is smaller than the screen height. => Set the scroll position to the top:
// DEBUG print("list is smaller than screen height")
yPosOfNowPlayingItem = 0
return
}
if yPosOfNowPlayingItem < minVal {
// This track is among the first ones or not on the list (if it is -1). => Move to the top:
yPosOfNowPlayingItem = 0
// DEBUG print("track is one of the first tracks => moving yPos to the top")
return
}
yPosOfNowPlayingItem -= minVal
// DEBUG print("track is in mid range => moving yPos up by \(minVal) to \(yPosOfNowPlayingItem)")
if yPosOfNowPlayingItem >= maxVal {
// DEBUG print("yPos too high -> setting yPos to \(maxVal)")
yPosOfNowPlayingItem = maxVal
}
}
//
// Jumps the scroll view to the position of the currently playing track.
//
func jumpToPosition(yPosOfNowPlayingItem: CGFloat) {
UIView.jumpSpringyToPosition(scrollView, pointToJumpTo: CGPoint(x: 0.0, y: yPosOfNowPlayingItem))
}
//
// This function is called whenever a track name has been tapped on.
// The chosen track is found out, the music player is switched to that track, and the modal view closes.
//
func trackNameTapped(sender: UIButtonWithFeatures) {
// var trackName: String = sender.mediaItem().title!
// DEBUG print("New track title: \"\(trackName)\"")
// Set the chosen track:
_controller.setTrack(sender.mediaItem())
// Close this view:
// dismissViewControllerAnimated(true, completion: nil) // Feature: We do not close the view! :)
}
}
| d9c0b64f28f7ce3e75f4dbdce5fe4411 | 37.781395 | 162 | 0.638402 | false | false | false | false |
PJayRushton/stats | refs/heads/master | Pods/TextFieldEffects/TextFieldEffects/TextFieldEffects/IsaoTextField.swift | mit | 4 | //
// IsaoTextField.swift
// TextFieldEffects
//
// Created by Raúl Riera on 29/01/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import UIKit
/**
An IsaoTextField is a subclass of the TextFieldEffects object, is a control that displays an UITextField with a customizable visual effect around the lower edge of the control.
*/
@IBDesignable open class IsaoTextField: TextFieldEffects {
/**
The color of the border when it has no content.
This property applies a color to the lower edge of the control. The default value for this property is a clear color. This value is also applied to the placeholder color.
*/
@IBInspectable dynamic open var inactiveColor: UIColor? {
didSet {
updateBorder()
}
}
/**
The color of the border when it has content.
This property applies a color to the lower edge of the control. The default value for this property is a clear color.
*/
@IBInspectable dynamic open var activeColor: UIColor? {
didSet {
updateBorder()
}
}
/**
The scale of the placeholder font.
This property determines the size of the placeholder label relative to the font size of the text field.
*/
@IBInspectable dynamic open var placeholderFontScale: CGFloat = 0.7 {
didSet {
updatePlaceholder()
}
}
override open var placeholder: String? {
didSet {
updatePlaceholder()
}
}
override open var bounds: CGRect {
didSet {
updateBorder()
updatePlaceholder()
}
}
private let borderThickness: (active: CGFloat, inactive: CGFloat) = (4, 2)
private let placeholderInsets = CGPoint(x: 6, y: 6)
private let textFieldInsets = CGPoint(x: 6, y: 6)
private let borderLayer = CALayer()
// MARK: - TextFieldEffects
override open func drawViewsForRect(_ rect: CGRect) {
let frame = CGRect(origin: .zero, size: CGSize(width: rect.size.width, height: rect.size.height))
placeholderLabel.frame = frame.insetBy(dx: placeholderInsets.x, dy: placeholderInsets.y)
placeholderLabel.font = placeholderFontFromFont(font!)
updateBorder()
updatePlaceholder()
layer.addSublayer(borderLayer)
addSubview(placeholderLabel)
}
override open func animateViewsForTextEntry() {
updateBorder()
if let activeColor = activeColor {
performPlaceholderAnimationWithColor(activeColor)
}
}
override open func animateViewsForTextDisplay() {
updateBorder()
if let inactiveColor = inactiveColor {
performPlaceholderAnimationWithColor(inactiveColor)
}
}
// MARK: - Private
private func updateBorder() {
borderLayer.frame = rectForBorder(frame)
borderLayer.backgroundColor = isFirstResponder ? activeColor?.cgColor : inactiveColor?.cgColor
}
private func updatePlaceholder() {
placeholderLabel.text = placeholder
placeholderLabel.textColor = inactiveColor
placeholderLabel.sizeToFit()
layoutPlaceholderInTextRect()
if isFirstResponder {
animateViewsForTextEntry()
}
}
private func placeholderFontFromFont(_ font: UIFont) -> UIFont! {
let smallerFont = UIFont(name: font.fontName, size: font.pointSize * placeholderFontScale)
return smallerFont
}
private func rectForBorder(_ bounds: CGRect) -> CGRect {
var newRect:CGRect
if isFirstResponder {
newRect = CGRect(x: 0, y: bounds.size.height - font!.lineHeight + textFieldInsets.y - borderThickness.active, width: bounds.size.width, height: borderThickness.active)
} else {
newRect = CGRect(x: 0, y: bounds.size.height - font!.lineHeight + textFieldInsets.y - borderThickness.inactive, width: bounds.size.width, height: borderThickness.inactive)
}
return newRect
}
private func layoutPlaceholderInTextRect() {
let textRect = self.textRect(forBounds: bounds)
var originX = textRect.origin.x
switch textAlignment {
case .center:
originX += textRect.size.width/2 - placeholderLabel.bounds.width/2
case .right:
originX += textRect.size.width - placeholderLabel.bounds.width
default:
break
}
placeholderLabel.frame = CGRect(x: originX, y: bounds.height - placeholderLabel.frame.height,
width: placeholderLabel.frame.size.width, height: placeholderLabel.frame.size.height)
}
private func performPlaceholderAnimationWithColor(_ color: UIColor) {
let yOffset: CGFloat = 4
UIView.animate(withDuration: 0.15, animations: {
self.placeholderLabel.transform = CGAffineTransform(translationX: 0, y: -yOffset)
self.placeholderLabel.alpha = 0
}) { _ in
self.placeholderLabel.transform = .identity
self.placeholderLabel.transform = CGAffineTransform(translationX: 0, y: yOffset)
UIView.animate(withDuration: 0.15, animations: {
self.placeholderLabel.textColor = color
self.placeholderLabel.transform = .identity
self.placeholderLabel.alpha = 1
}) { _ in
self.animationCompletionHandler?(self.isFirstResponder ? .textEntry : .textDisplay)
}
}
}
// MARK: - Overrides
override open func editingRect(forBounds bounds: CGRect) -> CGRect {
let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y)
return newBounds.insetBy(dx: textFieldInsets.x, dy: 0)
}
override open func textRect(forBounds bounds: CGRect) -> CGRect {
let newBounds = CGRect(x: 0, y: 0, width: bounds.size.width, height: bounds.size.height - font!.lineHeight + textFieldInsets.y)
return newBounds.insetBy(dx: textFieldInsets.x, dy: 0)
}
}
| c12731dc3e3a424646a3341f05035c3e | 34.438202 | 183 | 0.626823 | false | false | false | false |
Somnibyte/MLKit | refs/heads/master | Example/Pods/Upsurge/Source/2D/2DTensorSlice.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.
open class TwoDimensionalTensorSlice<T: Value>: MutableQuadraticType, Equatable {
public typealias Index = [Int]
public typealias Slice = TwoDimensionalTensorSlice<Element>
public typealias Element = T
open var arrangement: QuadraticArrangement {
return .rowMajor
}
open let rows: Int
open let columns: Int
open var stride: Int
var base: Tensor<Element>
open var span: Span
open func withUnsafeBufferPointer<R>(_ body: (UnsafeBufferPointer<Element>) throws -> R) rethrows -> R {
return try base.withUnsafeBufferPointer(body)
}
open func withUnsafePointer<R>(_ body: (UnsafePointer<Element>) throws -> R) rethrows -> R {
return try base.withUnsafePointer(body)
}
open func withUnsafeMutableBufferPointer<R>(_ body: (UnsafeMutableBufferPointer<Element>) throws -> R) rethrows -> R {
return try base.withUnsafeMutableBufferPointer(body)
}
open func withUnsafeMutablePointer<R>(_ body: (UnsafeMutablePointer<Element>) throws -> R) rethrows -> R {
return try base.withUnsafeMutablePointer(body)
}
open var step: Int {
return base.elements.step
}
init(base: Tensor<Element>, span: Span) {
assert(span.dimensions.count == base.dimensions.count)
self.base = base
self.span = span
assert(base.spanIsValid(span))
assert(span.dimensions.reduce(0) { $0.1 > 1 ? $0.0 + 1 : $0.0 } <= 2)
assert(span.dimensions.last! >= 1)
var rowIndex: Int
if let index = span.dimensions.index(where: { $0 > 1 }) {
rowIndex = index
} else {
rowIndex = span.dimensions.count - 2
}
rows = span.dimensions[rowIndex]
columns = span.dimensions.last!
stride = span.dimensions.suffix(from: rowIndex + 1).reduce(1, *)
}
open subscript(row: Int, column: Int) -> Element {
get {
return self[[row, column]]
}
set {
self[[row, column]] = newValue
}
}
open subscript(indices: Index) -> Element {
get {
var index = span.startIndex
let indexReplacementRage: CountableClosedRange<Int> = span.startIndex.count - indices.count ... span.startIndex.count - 1
index.replaceSubrange(indexReplacementRage, with: indices)
assert(indexIsValid(index))
return base[index]
}
set {
var index = span.startIndex
let indexReplacementRage: CountableClosedRange<Int> = span.startIndex.count - indices.count ... span.startIndex.count - 1
index.replaceSubrange(indexReplacementRage, with: indices)
assert(indexIsValid(index))
base[index] = newValue
}
}
open subscript(slice: [IntervalType]) -> Slice {
get {
let span = Span(base: self.span, intervals: slice)
return self[span]
}
set {
let span = Span(base: self.span, intervals: slice)
assert(span ≅ newValue.span)
self[span] = newValue
}
}
open subscript(slice: IntervalType...) -> Slice {
get {
return self[slice]
}
set {
self[slice] = newValue
}
}
subscript(span: Span) -> Slice {
get {
assert(self.span.contains(span))
return Slice(base: base, span: span)
}
set {
assert(self.span.contains(span))
assert(span ≅ newValue.span)
for (lhsIndex, rhsIndex) in zip(span, newValue.span) {
base[lhsIndex] = newValue[rhsIndex]
}
}
}
open var isContiguous: Bool {
let onesCount: Int
if let index = dimensions.index(where: { $0 != 1 }) {
onesCount = index
} else {
onesCount = rank
}
let diff = (0..<rank).map({ dimensions[$0] - base.dimensions[$0] }).reversed()
let fullCount: Int
if let index = diff.index(where: { $0 != 0 }), index.base < count {
fullCount = rank - index.base
} else {
fullCount = rank
}
return rank - fullCount - onesCount <= 1
}
open func indexIsValid(_ indices: [Int]) -> Bool {
assert(indices.count == rank)
for (i, index) in indices.enumerated() {
if index < span[i].lowerBound || span[i].upperBound < index {
return false
}
}
return true
}
}
| 70b9734c35d0f3307687fa139dc290b8 | 32.988024 | 133 | 0.605884 | false | false | false | false |
Pstoppani/swipe | refs/heads/master | browser/SwipeBrowser.swift | mit | 1 | //
// SwipeBrowser.swift
// sample
//
// Created by satoshi on 10/8/15.
// Copyright © 2015 Satoshi Nakajima. All rights reserved.
//
#if os(OSX) // WARNING: OSX support is not done yet
import Cocoa
public typealias UIViewController = NSViewController
#else
import UIKit
#endif
//
// Change s_verbosLevel to 1 to see debug messages for this class
//
private func MyLog(_ text:String, level:Int = 0) {
let s_verbosLevel = 0
if level <= s_verbosLevel {
print(text)
}
}
protocol SwipeBrowserDelegate: NSObjectProtocol {
func documentDidLoad(browser:SwipeBrowser)
}
//
// SwipeBrowser is the main UIViewController that is pushed into the navigation stack.
// SwipeBrowser "hosts" another UIViewController, which supports SwipeDocumentViewer protocol.
//
class SwipeBrowser: UIViewController, SwipeDocumentViewerDelegate {
//
// This is the place you can add more document types.
// Those UIViewControllers MUST support SwipeDocumentViewer protocol.
//
static private var typeMapping:[String:(Void) -> UIViewController] = [
"net.swipe.list": { return SwipeTableViewController(nibName:"SwipeTableViewController", bundle:nil) },
"net.swipe.swipe": { return SwipeViewController() },
]
static var stack = [SwipeBrowser]()
static func register(type:String, factory:@escaping (Void) -> UIViewController) {
typeMapping[type] = factory
}
public weak var delegate:SwipeBrowserDelegate?
var notificationManager = SNNotificationManager()
#if os(iOS)
private var fVisibleUI = true
@IBOutlet var toolbar:UIView?
@IBOutlet var bottombar:UIView?
@IBOutlet var slider:UISlider!
@IBOutlet var labelTitle:UILabel?
@IBOutlet var btnExport:UIButton?
private var landscapeMode = false
#elseif os(tvOS)
override weak var preferredFocusedView: UIView? { return controller?.view }
#endif
@IBOutlet var viewLoading:UIView?
@IBOutlet var progress:UIProgressView?
@IBOutlet var labelLoading:UILabel?
@IBOutlet var btnLanguage:UIButton?
private var resourceRequest:NSBundleResourceRequest?
var url:URL? = Bundle.main.url(forResource: "index.swipe", withExtension: nil)
var jsonDocument:[String:Any]?
var controller:UIViewController?
var documentViewer:SwipeDocumentViewer?
var ignoreViewState = false
func browseTo(_ url:URL) {
let browser = SwipeBrowser(nibName: "SwipeBrowser", bundle: nil)
browser.delegate = self.delegate
browser.url = url //
//MyLog("SWBrows url \(browser.url!)")
#if os(OSX)
self.presentViewControllerAsSheet(browser)
#else
self.present(browser, animated: true) { () -> Void in
SwipeBrowser.stack.append(browser)
MyLog("SWBrows push \(SwipeBrowser.stack.count)", level: 1)
}
#endif
}
deinit {
if let request = self.resourceRequest {
request.endAccessingResources()
}
MyLog("SWBrows deinit", level:1)
}
override func viewDidLoad() {
super.viewDidLoad()
viewLoading?.alpha = 0
btnLanguage?.isEnabled = false
if SwipeBrowser.stack.count == 0 {
SwipeBrowser.stack.append(self) // special case for the first one
MyLog("SWBrows push first \(SwipeBrowser.stack.count)", level: 1)
}
#if os(iOS)
btnExport?.isEnabled = false
slider.isHidden = true
#endif
if let document = self.jsonDocument {
self.openDocument(document, localResource: true)
} else if let url = self.url {
if url.scheme == "file" {
if let data = try? Data(contentsOf: url) {
self.openData(data, localResource: true)
} else {
// On-demand resource support
if let urlLocal = Bundle.main.url(forResource: url.lastPathComponent, withExtension: nil),
let data = try? Data(contentsOf: urlLocal) {
self.openData(data, localResource: true)
} else {
self.processError("Missing resource:".localized + "\(url)")
}
}
} else {
let manager = SwipeAssetManager.sharedInstance()
manager.loadAsset(url, prefix: "", bypassCache:true) { (urlLocal:URL?, error:NSError?) -> Void in
if let urlL = urlLocal, error == nil,
let data = try? Data(contentsOf: urlL) {
self.openData(data, localResource: false)
} else {
self.processError(error?.localizedDescription ?? "")
}
}
}
} else {
MyLog("SWBrows nil URL")
processError("No URL to load".localized)
}
}
// NOTE: documentViewer and vc always points to the same UIController.
private func loadDocumentView(_ documentViewer:SwipeDocumentViewer, vc:UIViewController, document:[String:Any]) {
#if os(iOS)
if let title = documentViewer.documentTitle() {
labelTitle?.text = title
} else {
labelTitle?.text = url?.lastPathComponent
}
#endif
if let languages = documentViewer.languages(), languages.count > 0 {
btnLanguage?.isEnabled = true
}
controller = vc
self.addChildViewController(vc)
vc.view.autoresizingMask = UIViewAutoresizing([.flexibleWidth, .flexibleHeight])
#if os(OSX)
self.view.addSubview(vc.view, positioned: .Below, relativeTo: nil)
#else
self.view.insertSubview(vc.view, at: 0)
#endif
var rcFrame = self.view.bounds
#if os(iOS)
if let _ = controller as? SwipeViewController {
btnExport?.isEnabled = true
}
if documentViewer.hideUI() {
let tap = UITapGestureRecognizer(target: self, action: #selector(SwipeBrowser.tapped))
self.view.addGestureRecognizer(tap)
hideUI()
} else if let toolbar = self.toolbar, let bottombar = self.bottombar {
rcFrame.origin.y = toolbar.bounds.size.height
rcFrame.size.height -= rcFrame.origin.y + bottombar.bounds.size.height
}
#endif
vc.view.frame = rcFrame
delegate?.documentDidLoad(browser: self)
}
private func openDocumentViewer(_ document:[String:Any]) {
var documentType = "net.swipe.swipe" // default
if let type = document["type"] as? String {
documentType = type
}
guard let type = SwipeBrowser.typeMapping[documentType] else {
return processError("Unknown type:".localized + "\(SwipeBrowser.typeMapping[documentType]).")
}
let vc = type()
guard let documentViewer = vc as? SwipeDocumentViewer else {
return processError("Programming Error: Not SwipeDocumentViewer.".localized)
}
self.documentViewer = documentViewer
documentViewer.setDelegate(self)
do {
let defaults = UserDefaults.standard
var state:[String:Any]? = nil
if let url = self.url, ignoreViewState == false {
state = defaults.object(forKey: url.absoluteString) as? [String:Any]
}
self.viewLoading?.alpha = 1.0
self.labelLoading?.text = "Loading Network Resources...".localized
try documentViewer.loadDocument(document, size:self.view.frame.size, url: url, state:state) { (progress:Float, error:NSError?) -> (Void) in
self.progress?.progress = progress
if progress >= 1 {
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.viewLoading?.alpha = 0.0
}, completion: { (_:Bool) -> Void in
self.loadDocumentView(documentViewer, vc:vc, document: document)
})
}
}
} catch let error as NSError {
self.viewLoading?.alpha = 0.0
return processError("Load Document Error:".localized + "\(error.localizedDescription).")
}
}
private func openDocumentWithODR(_ document:[String:Any], localResource:Bool) {
if let tags = document["resources"] as? [String], localResource {
//NSLog("tags = \(tags)")
let request = NSBundleResourceRequest(tags: Set<String>(tags))
self.resourceRequest = request
request.conditionallyBeginAccessingResources() { (resourcesAvailable:Bool) -> Void in
MyLog("SWBrows resourceAvailable(\(tags)) = \(resourcesAvailable)", level:1)
DispatchQueue.main.async {
if resourcesAvailable {
self.openDocumentViewer(document)
} else {
let alert = UIAlertController(title: "Swipe", message: "Loading Resources...".localized, preferredStyle: UIAlertControllerStyle.alert)
self.present(alert, animated: true) { () -> Void in
request.beginAccessingResources() { (error:Swift.Error?) -> Void in
DispatchQueue.main.async {
self.dismiss(animated: false, completion: nil)
if let e = error {
MyLog("SWBrows resource error=\(error)", level:0)
return self.processError(e.localizedDescription)
} else {
self.openDocumentViewer(document)
}
}
}
}
}
}
}
} else {
self.openDocumentViewer(document)
}
}
private func openDocument(_ document:[String:Any], localResource:Bool) {
var deferred = false
#if os(iOS)
if let orientation = document["orientation"] as? String, orientation == "landscape" {
self.landscapeMode = true
if !localResource {
// HACK ALERT: If the resource is remote and the orientation is landscape, it is too late to specify
// the allowed orientations. Until iOS7, we could just call attemptRotationToDeviceOrientation(),
// but it no longer works. Therefore, we work-around by presenting a dummy VC, and dismiss it
// before opening the document.
deferred = true
//UIViewController.attemptRotationToDeviceOrientation() // NOTE: attempt but not working
let vcDummy = UIViewController()
self.present(vcDummy, animated: false, completion: { () -> Void in
self.dismiss(animated: false, completion: nil)
self.openDocumentWithODR(document, localResource: localResource)
})
}
}
#endif
if !deferred {
self.openDocumentWithODR(document, localResource: localResource)
}
}
private func openData(_ dataRetrieved:Data?, localResource:Bool) {
guard let data = dataRetrieved else {
return processError("Failed to open: No data".localized)
}
do {
guard let document = try JSONSerialization.jsonObject(with: data, options: JSONSerialization.ReadingOptions()) as? [String:Any] else {
return processError("Not a dictionary.".localized)
}
openDocument(document, localResource: localResource)
} catch let error as NSError {
let value = error.userInfo["NSDebugDescription"]!
processError("Invalid JSON file".localized + "\(error.localizedDescription). \(value)")
return
}
}
#if os(iOS)
override var prefersStatusBarHidden: Bool {
return true
}
// NOTE: This function and supportedInterfaceOrientations will not be called on iPad
// as long as the app supports multitasking.
override var shouldAutorotate: Bool {
return true
}
override var supportedInterfaceOrientations: UIInterfaceOrientationMask {
if let documentViewer = self.documentViewer, documentViewer.landscape() {
return UIInterfaceOrientationMask.landscape
}
return landscapeMode ?
UIInterfaceOrientationMask.landscape
: UIInterfaceOrientationMask.portrait
}
@IBAction func tapped() {
MyLog("SWBrows tapped", level: 1)
if fVisibleUI {
hideUI()
} else {
showUI()
}
}
private func showUI() {
fVisibleUI = true
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.toolbar?.alpha = 1.0
self.bottombar?.alpha = 1.0
})
}
private func hideUI() {
fVisibleUI = false
UIView.animate(withDuration: 0.2, animations: { () -> Void in
self.toolbar?.alpha = 0.0
self.bottombar?.alpha = 0.0
})
}
@IBAction func slided(_ sender:UISlider) {
MyLog("SWBrows \(slider.value)")
}
#else
func tapped() {
}
#endif
private func processError(_ message:String) {
DispatchQueue.main.async {
#if !os(OSX) // REVIEW
let alert = UIAlertController(title: "Can't open the document.", message: message, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default) { (_:UIAlertAction) -> Void in
self.presentingViewController?.dismiss(animated: true, completion: nil)
})
self.present(alert, animated: true, completion: nil)
#endif
}
}
#if !os(OSX)
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
#endif
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
if self.isBeingDismissed {
if let documentViewer = self.documentViewer,
let state = documentViewer.saveState(),
let url = self.url {
MyLog("SWBrows state=\(state)", level:1)
let defaults = UserDefaults.standard
defaults.set(state, forKey: url.absoluteString)
defaults.synchronize()
}
_ = SwipeBrowser.stack.popLast()
MyLog("SWBrows pop \(SwipeBrowser.stack.count)", level:1)
if SwipeBrowser.stack.count == 1 {
// Wait long enough (200ms > 1/30fps) and check the memory leak.
// This gives the timerTick() in SwipePage to complete the shutdown sequence
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + Double(Int64(200 * NSEC_PER_MSEC)) / Double(NSEC_PER_SEC)) { () -> Void in
SwipePage.checkMemoryLeak()
SwipeElement.checkMemoryLeak()
}
}
}
}
@IBAction func close(_ sender:Any) {
#if os(OSX)
self.presentingViewController!.dismissViewController(self)
#else
self.presentingViewController!.dismiss(animated: true, completion: nil)
#endif
}
func becomeZombie() {
if let documentViewer = self.documentViewer {
documentViewer.becomeZombie()
}
}
static func openURL(_ urlString:String) {
NSLog("SWBrose openURL \(SwipeBrowser.stack.count) \(urlString)")
#if os(OSX)
while SwipeBrowser.stack.count > 1 {
let lastVC = SwipeBrowser.stack.last!
lastVC.becomeZombie()
SwipeBrowser.stack.last!.dismissViewController(lastVC)
}
#else
if SwipeBrowser.stack.count > 1 {
let lastVC = SwipeBrowser.stack.last!
lastVC.becomeZombie()
SwipeBrowser.stack.last!.dismiss(animated: false, completion: { () -> Void in
openURL(urlString)
})
return
}
#endif
DispatchQueue.main.async { () -> Void in
if let url = URL.url(urlString, baseURL: nil) {
SwipeBrowser.stack.last!.browseTo(url)
}
}
}
@IBAction func language() {
if let languages = documentViewer?.languages() {
let alert = UIAlertController(title: "Swipe", message: "Choose a language", preferredStyle: UIAlertControllerStyle.actionSheet)
alert.popoverPresentationController?.sourceView = self.view
alert.popoverPresentationController?.sourceRect = btnLanguage!.frame
for language in languages {
guard let title = language["title"] as? String,
let langId = language["id"] as? String else {
continue
}
alert.addAction(UIAlertAction(title: title, style: UIAlertActionStyle.default, handler: { (_:UIAlertAction) -> Void in
//print("SwipeB language selected \(langId)")
self.documentViewer?.reloadWithLanguageId(langId)
#if os(iOS)
self.hideUI()
#endif
}))
}
self.present(alert, animated: true, completion: nil)
}
}
}
| f07d0088dc13893295135963d78b43a3 | 37.642857 | 162 | 0.580407 | false | false | false | false |
hooman/swift | refs/heads/main | stdlib/public/core/DictionaryBuilder.swift | apache-2.0 | 5 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// Initializes a `Dictionary` from unique members.
///
/// Using a builder can be faster than inserting members into an empty
/// `Dictionary`.
@frozen
public // SPI(Foundation)
struct _DictionaryBuilder<Key: Hashable, Value> {
@usableFromInline
internal var _target: _NativeDictionary<Key, Value>
@usableFromInline
internal let _requestedCount: Int
@inlinable
public init(count: Int) {
_target = _NativeDictionary(capacity: count)
_requestedCount = count
}
@inlinable
public mutating func add(key newKey: Key, value: Value) {
_precondition(_target.count < _requestedCount,
"Can't add more members than promised")
_target._unsafeInsertNew(key: newKey, value: value)
}
@inlinable
public __consuming func take() -> Dictionary<Key, Value> {
_precondition(_target.count == _requestedCount,
"The number of members added does not match the promised count")
return Dictionary(_native: _target)
}
}
extension Dictionary {
/// Creates a new dictionary with the specified capacity, then calls the given
/// closure to initialize its contents.
///
/// Foundation uses this initializer to bridge the contents of an NSDictionary
/// instance without allocating a pair of intermediary buffers. Pass the
/// required capacity and a closure that can initialize the dictionary's
/// elements. The closure must return `c`, the number of initialized elements
/// in both buffers, such that the elements in the range `0..<c` are
/// initialized and the elements in the range `c..<capacity` are
/// uninitialized.
///
/// The resulting dictionary has a `count` less than or equal to `c`. The
/// actual count is less iff some of the initialized keys were duplicates.
/// (This cannot happen if `allowingDuplicates` is false.)
///
/// The buffers passed to the closure are only valid for the duration of the
/// call. After the closure returns, this initializer moves all initialized
/// elements into their correct buckets.
///
/// - Parameters:
/// - capacity: The capacity of the new dictionary.
/// - allowingDuplicates: If false, then the caller guarantees that all keys
/// are unique. This promise isn't verified -- if it turns out to be
/// false, then the resulting dictionary won't be valid.
/// - body: A closure that can initialize the dictionary's elements. This
/// closure must return the count of the initialized elements, starting at
/// the beginning of the buffer.
@_alwaysEmitIntoClient // Introduced in 5.1
public // SPI(Foundation)
init(
_unsafeUninitializedCapacity capacity: Int,
allowingDuplicates: Bool,
initializingWith initializer: (
_ keys: UnsafeMutableBufferPointer<Key>,
_ values: UnsafeMutableBufferPointer<Value>
) -> Int
) {
self.init(_native: _NativeDictionary(
_unsafeUninitializedCapacity: capacity,
allowingDuplicates: allowingDuplicates,
initializingWith: initializer))
}
}
extension _NativeDictionary {
@_alwaysEmitIntoClient // Introduced in 5.1
internal init(
_unsafeUninitializedCapacity capacity: Int,
allowingDuplicates: Bool,
initializingWith initializer: (
_ keys: UnsafeMutableBufferPointer<Key>,
_ values: UnsafeMutableBufferPointer<Value>
) -> Int
) {
self.init(capacity: capacity)
let initializedCount = initializer(
UnsafeMutableBufferPointer(start: _keys, count: capacity),
UnsafeMutableBufferPointer(start: _values, count: capacity))
_precondition(initializedCount >= 0 && initializedCount <= capacity)
_storage._count = initializedCount
// Hash initialized elements and move each of them into their correct
// buckets.
//
// - We have some number of unprocessed elements at the start of the
// key/value buffers -- buckets up to and including `bucket`. Everything
// in this region is either unprocessed or in use. There are no
// uninitialized entries in it.
//
// - Everything after `bucket` is either uninitialized or in use. This
// region works exactly like regular dictionary storage.
//
// - "in use" is tracked by the bitmap in `hashTable`, the same way it would
// be for a working Dictionary.
//
// Each iteration of the loop below processes an unprocessed element, and/or
// reduces the size of the unprocessed region, while ensuring the above
// invariants.
var bucket = _HashTable.Bucket(offset: initializedCount - 1)
while bucket.offset >= 0 {
if hashTable._isOccupied(bucket) {
// We've moved an element here in a previous iteration.
bucket.offset -= 1
continue
}
// Find the target bucket for this entry and mark it as in use.
let target: Bucket
if _isDebugAssertConfiguration() || allowingDuplicates {
let (b, found) = find(_keys[bucket.offset])
if found {
_internalInvariant(b != bucket)
_precondition(allowingDuplicates, "Duplicate keys found")
// Discard duplicate entry.
uncheckedDestroy(at: bucket)
_storage._count -= 1
bucket.offset -= 1
continue
}
hashTable.insert(b)
target = b
} else {
let hashValue = self.hashValue(for: _keys[bucket.offset])
target = hashTable.insertNew(hashValue: hashValue)
}
if target > bucket {
// The target is outside the unprocessed region. We can simply move the
// entry, leaving behind an uninitialized bucket.
moveEntry(from: bucket, to: target)
// Restore invariants by lowering the region boundary.
bucket.offset -= 1
} else if target == bucket {
// Already in place.
bucket.offset -= 1
} else {
// The target bucket is also in the unprocessed region. Swap the current
// item into place, then try again with the swapped-in value, so that we
// don't lose it.
swapEntry(target, with: bucket)
}
}
// When there are no more unprocessed entries, we're left with a valid
// Dictionary.
}
}
| c5dafb7438c06793d876b4499e00fe7b | 38.05848 | 80 | 0.659081 | false | false | false | false |
Eflet/Charts | refs/heads/master | Charts/Classes/Renderers/ChartXAxisRenderer.swift | apache-2.0 | 2 | //
// ChartXAxisRenderer.swift
// Charts
//
// Created by Daniel Cohen Gindi on 3/3/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/Charts
//
import Foundation
import CoreGraphics
#if !os(OSX)
import UIKit
#endif
public class ChartXAxisRenderer: ChartAxisRendererBase
{
public var xAxis: ChartXAxis?
public init(viewPortHandler: ChartViewPortHandler, xAxis: ChartXAxis, transformer: ChartTransformer!)
{
super.init(viewPortHandler: viewPortHandler, transformer: transformer)
self.xAxis = xAxis
}
public func computeAxis(xValAverageLength xValAverageLength: Double, xValues: [String?])
{
guard let xAxis = xAxis else { return }
var a = ""
let max = Int(round(xValAverageLength + Double(xAxis.spaceBetweenLabels)))
for _ in 0 ..< max
{
a += "h"
}
let widthText = a as NSString
let labelSize = widthText.sizeWithAttributes([NSFontAttributeName: xAxis.labelFont])
let labelWidth = labelSize.width
let labelHeight = labelSize.height
let labelRotatedSize = ChartUtils.sizeOfRotatedRectangle(labelSize, degrees: xAxis.labelRotationAngle)
xAxis.labelWidth = labelWidth
xAxis.labelHeight = labelHeight
xAxis.labelRotatedWidth = labelRotatedSize.width
xAxis.labelRotatedHeight = labelRotatedSize.height
xAxis.values = xValues
}
public override func renderAxisLabels(context context: CGContext)
{
guard let xAxis = xAxis else { return }
if (!xAxis.isEnabled || !xAxis.isDrawLabelsEnabled)
{
return
}
let yOffset = xAxis.yOffset
if (xAxis.labelPosition == .Top)
{
drawLabels(context: context, pos: viewPortHandler.contentTop - yOffset, anchor: CGPoint(x: 0.5, y: 1.0))
}
else if (xAxis.labelPosition == .TopInside)
{
drawLabels(context: context, pos: viewPortHandler.contentTop + yOffset + xAxis.labelRotatedHeight, anchor: CGPoint(x: 0.5, y: 1.0))
}
else if (xAxis.labelPosition == .Bottom)
{
drawLabels(context: context, pos: viewPortHandler.contentBottom + yOffset, anchor: CGPoint(x: 0.5, y: 0.0))
}
else if (xAxis.labelPosition == .BottomInside)
{
drawLabels(context: context, pos: viewPortHandler.contentBottom - yOffset - xAxis.labelRotatedHeight, anchor: CGPoint(x: 0.5, y: 0.0))
}
else
{ // BOTH SIDED
drawLabels(context: context, pos: viewPortHandler.contentTop - yOffset, anchor: CGPoint(x: 0.5, y: 1.0))
drawLabels(context: context, pos: viewPortHandler.contentBottom + yOffset, anchor: CGPoint(x: 0.5, y: 0.0))
}
}
private var _axisLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderAxisLine(context context: CGContext)
{
guard let xAxis = xAxis else { return }
if (!xAxis.isEnabled || !xAxis.isDrawAxisLineEnabled)
{
return
}
CGContextSaveGState(context)
CGContextSetStrokeColorWithColor(context, xAxis.axisLineColor.CGColor)
CGContextSetLineWidth(context, xAxis.axisLineWidth)
if (xAxis.axisLineDashLengths != nil)
{
CGContextSetLineDash(context, xAxis.axisLineDashPhase, xAxis.axisLineDashLengths, xAxis.axisLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
if (xAxis.labelPosition == .Top
|| xAxis.labelPosition == .TopInside
|| xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentTop
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
if (xAxis.labelPosition == .Bottom
|| xAxis.labelPosition == .BottomInside
|| xAxis.labelPosition == .BothSided)
{
_axisLineSegmentsBuffer[0].x = viewPortHandler.contentLeft
_axisLineSegmentsBuffer[0].y = viewPortHandler.contentBottom
_axisLineSegmentsBuffer[1].x = viewPortHandler.contentRight
_axisLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _axisLineSegmentsBuffer, 2)
}
CGContextRestoreGState(context)
}
/// draws the x-labels on the specified y-position
public func drawLabels(context context: CGContext, pos: CGFloat, anchor: CGPoint)
{
guard let xAxis = xAxis else { return }
let paraStyle = NSParagraphStyle.defaultParagraphStyle().mutableCopy() as! NSMutableParagraphStyle
paraStyle.alignment = .Center
let labelAttrs = [NSFontAttributeName: xAxis.labelFont,
NSForegroundColorAttributeName: xAxis.labelTextColor,
NSParagraphStyleAttributeName: paraStyle]
let labelRotationAngleRadians = xAxis.labelRotationAngle * ChartUtils.Math.FDEG2RAD
let valueToPixelMatrix = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
var labelMaxSize = CGSize()
if (xAxis.isWordWrapEnabled)
{
labelMaxSize.width = xAxis.wordWrapWidthPercent * valueToPixelMatrix.a
}
for i in self.minX.stride(to: min(self.maxX + 1, xAxis.values.count), by: xAxis.axisLabelModulus)
{
let label = xAxis.values[i]
if (label == nil)
{
continue
}
position.x = CGFloat(i)
position.y = 0.0
position = CGPointApplyAffineTransform(position, valueToPixelMatrix)
if (viewPortHandler.isInBoundsX(position.x))
{
let labelns = label! as NSString
if (xAxis.isAvoidFirstLastClippingEnabled)
{
// avoid clipping of the last
if (i == xAxis.values.count - 1 && xAxis.values.count > 1)
{
let width = labelns.boundingRectWithSize(labelMaxSize, options: .UsesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width
if (width > viewPortHandler.offsetRight * 2.0
&& position.x + width > viewPortHandler.chartWidth)
{
position.x -= width / 2.0
}
}
else if (i == 0)
{ // avoid clipping of the first
let width = labelns.boundingRectWithSize(labelMaxSize, options: .UsesLineFragmentOrigin, attributes: labelAttrs, context: nil).size.width
position.x += width / 2.0
}
}
drawLabel(context: context, label: label!, xIndex: i, x: position.x, y: pos, attributes: labelAttrs, constrainedToSize: labelMaxSize, anchor: anchor, angleRadians: labelRotationAngleRadians)
}
}
}
public func drawLabel(context context: CGContext, label: String, xIndex: Int, x: CGFloat, y: CGFloat, attributes: [String: NSObject], constrainedToSize: CGSize, anchor: CGPoint, angleRadians: CGFloat)
{
guard let xAxis = xAxis else { return }
let formattedLabel = xAxis.valueFormatter?.stringForXValue(xIndex, original: label, viewPortHandler: viewPortHandler) ?? label
ChartUtils.drawMultilineText(context: context, text: formattedLabel, point: CGPoint(x: x, y: y), attributes: attributes, constrainedToSize: constrainedToSize, anchor: anchor, angleRadians: angleRadians)
}
private var _gridLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public override func renderGridLines(context context: CGContext)
{
guard let xAxis = xAxis else { return }
if (!xAxis.isDrawGridLinesEnabled || !xAxis.isEnabled)
{
return
}
CGContextSaveGState(context)
CGContextSetShouldAntialias(context, xAxis.gridAntialiasEnabled)
CGContextSetStrokeColorWithColor(context, xAxis.gridColor.CGColor)
CGContextSetLineWidth(context, xAxis.gridLineWidth)
CGContextSetLineCap(context, xAxis.gridLineCap)
if (xAxis.gridLineDashLengths != nil)
{
CGContextSetLineDash(context, xAxis.gridLineDashPhase, xAxis.gridLineDashLengths, xAxis.gridLineDashLengths.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
let valueToPixelMatrix = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in self.minX.stride(to: self.maxX, by: xAxis.axisLabelModulus)
{
position.x = CGFloat(i)
position.y = 0.0
position = CGPointApplyAffineTransform(position, valueToPixelMatrix)
if (position.x >= viewPortHandler.offsetLeft
&& position.x <= viewPortHandler.chartWidth)
{
_gridLineSegmentsBuffer[0].x = position.x
_gridLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_gridLineSegmentsBuffer[1].x = position.x
_gridLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextStrokeLineSegments(context, _gridLineSegmentsBuffer, 2)
}
}
CGContextRestoreGState(context)
}
public override func renderLimitLines(context context: CGContext)
{
guard let xAxis = xAxis else { return }
var limitLines = xAxis.limitLines
if (limitLines.count == 0)
{
return
}
CGContextSaveGState(context)
let trans = transformer.valueToPixelMatrix
var position = CGPoint(x: 0.0, y: 0.0)
for i in 0 ..< limitLines.count
{
let l = limitLines[i]
if !l.isEnabled
{
continue
}
position.x = CGFloat(l.limit)
position.y = 0.0
position = CGPointApplyAffineTransform(position, trans)
renderLimitLineLine(context: context, limitLine: l, position: position)
renderLimitLineLabel(context: context, limitLine: l, position: position, yOffset: 2.0 + l.yOffset)
}
CGContextRestoreGState(context)
}
private var _limitLineSegmentsBuffer = [CGPoint](count: 2, repeatedValue: CGPoint())
public func renderLimitLineLine(context context: CGContext, limitLine: ChartLimitLine, position: CGPoint)
{
_limitLineSegmentsBuffer[0].x = position.x
_limitLineSegmentsBuffer[0].y = viewPortHandler.contentTop
_limitLineSegmentsBuffer[1].x = position.x
_limitLineSegmentsBuffer[1].y = viewPortHandler.contentBottom
CGContextSetStrokeColorWithColor(context, limitLine.lineColor.CGColor)
CGContextSetLineWidth(context, limitLine.lineWidth)
if (limitLine.lineDashLengths != nil)
{
CGContextSetLineDash(context, limitLine.lineDashPhase, limitLine.lineDashLengths!, limitLine.lineDashLengths!.count)
}
else
{
CGContextSetLineDash(context, 0.0, nil, 0)
}
CGContextStrokeLineSegments(context, _limitLineSegmentsBuffer, 2)
}
public func renderLimitLineLabel(context context: CGContext, limitLine: ChartLimitLine, position: CGPoint, yOffset: CGFloat)
{
let label = limitLine.label
// if drawing the limit-value label is enabled
if (label.characters.count > 0)
{
let labelLineHeight = limitLine.valueFont.lineHeight
let xOffset: CGFloat = limitLine.lineWidth + limitLine.xOffset
if (limitLine.labelPosition == .RightTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x + xOffset,
y: viewPortHandler.contentTop + yOffset),
align: .Left,
attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor])
}
else if (limitLine.labelPosition == .RightBottom)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x + xOffset,
y: viewPortHandler.contentBottom - labelLineHeight - yOffset),
align: .Left,
attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor])
}
else if (limitLine.labelPosition == .LeftTop)
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x - xOffset,
y: viewPortHandler.contentTop + yOffset),
align: .Right,
attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor])
}
else
{
ChartUtils.drawText(context: context,
text: label,
point: CGPoint(
x: position.x - xOffset,
y: viewPortHandler.contentBottom - labelLineHeight - yOffset),
align: .Right,
attributes: [NSFontAttributeName: limitLine.valueFont, NSForegroundColorAttributeName: limitLine.valueTextColor])
}
}
}
}
| df5d2904c67f5f76d777b6455ccb2e46 | 37.317708 | 210 | 0.587332 | false | false | false | false |
coodly/ios-gambrinus | refs/heads/main | Packages/Sources/KioskCore/Network/PullPostMappingsOperation.swift | apache-2.0 | 1 | /*
* Copyright 2018 Coodly LLC
*
* 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 CloudKit
import CoreDataPersistence
import Foundation
import Puff
import PuffSerialization
internal struct CloudPost: RemoteRecord {
var parent: CKRecord.ID?
var recordData: Data?
var recordName: String?
static var recordType: String {
return "Post"
}
var identifier: String?
var rateBeers: [String]?
var untappd: [NSNumber]?
var modificationDate: Date?
mutating func loadFields(from record: CKRecord) -> Bool {
identifier = record["identifier"] as? String
rateBeers = record["rateBeers"] as? [String]
untappd = record["untappd"] as? [NSNumber]
modificationDate = record.modificationDate
return true
}
}
internal class PullPostMappingsOperation: CloudKitRequest<CloudPost>, GambrinusContainerConsumer, PersistenceConsumer {
var gambrinusContainer: CKContainer! {
didSet {
container = gambrinusContainer
}
}
var persistence: Persistence!
override func performRequest() {
Log.debug("Pull mapping updates")
persistence.performInBackground() {
context in
let lastKnownTime = context.lastKnownMappingTime
Log.debug("Pull mappings after \(lastKnownTime)")
let sort = NSSortDescriptor(key: "modificationDate", ascending: true)
let timePredicate = NSPredicate(format: "modificationDate >= %@", lastKnownTime as NSDate)
self.fetch(predicate: timePredicate, sort: [sort], inDatabase: .public)
}
}
override func handle(result: CloudResult<CloudPost>, completion: @escaping () -> ()) {
let save: ContextClosure = {
context in
context.createMappings(from: result.records)
guard let maxDate = result.records.compactMap({ $0.modificationDate }).max() else {
return
}
Log.debug("Mark mappings max time to \(maxDate)")
context.lastKnownMappingTime = maxDate
}
persistence.performInBackground(task: save, completion: completion)
}
}
| 01d57b1c6a3e87aa875cbc7c3af92bb7 | 31.505882 | 119 | 0.64857 | false | false | false | false |
2794129697/-----mx | refs/heads/master | CoolXuePlayer/ViewController.swift | lgpl-3.0 | 1 | //
// ViewController.swift
// CoolXuePlayer
//
// Created by lion-mac on 15/5/29.
//
import UIKit
class ViewController: UIViewController,UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate {
@IBOutlet weak var bigScrollView: UIScrollView!
@IBOutlet weak var channelTableView: UITableView!
@IBOutlet weak var topscrollview: UIScrollView!
var channelList:Array<Channel> = []
func getChannelData(){
var channel_url = "http://www.icoolxue.com/album/recommend/100"
var url = NSURL(string: channel_url)
var request = NSURLRequest(URL: url!)
NSURLConnection.sendAsynchronousRequest(
request, queue: NSOperationQueue.mainQueue()) { (response:NSURLResponse!, data:NSData!, error:NSError!) -> Void in
println("responseerror=\(error)")
var httpResponse = response as! NSHTTPURLResponse
if httpResponse.statusCode == 200 {
var bdict:NSDictionary = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments, error: nil) as!NSDictionary
//println(bdict)
var c_array = bdict["data"] as! NSArray
if c_array.count > 0 {
for dict in c_array{
var channel = Channel(dictChannel: dict as! NSDictionary)
self.channelList.append(channel)
var uv = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 50))
var imgview = UIImageView()
var imgurl:NSURL = NSURL(string: "")!
if channel.defaultCover != nil {
imgurl = NSURL(string:channel.defaultCover)!
}else if channel.cover != nil {
imgurl = NSURL(string:channel.cover)!
}
uv.addSubview(imgview)
imgview.sd_setImageWithURL(imgurl)
self.topscrollview.addSubview(uv)
//self.topscrollview.insertSubview(uv, atIndex: 0)
}
self.topscrollview.contentSize = CGSize(width: 2000, height: 100)
self.channelTableView.reloadData()
}
}
}
}
func scrollViewDidScroll(scrollView: UIScrollView) {
if scrollView.isKindOfClass(UITableView){
println("tableview move")
channelTableView.scrollEnabled = false;
}else{
println("scrollview move")
}
}
override func viewDidLoad() {
super.viewDidLoad()
getChannelData()
self.bigScrollView.contentSize=CGSizeMake(320, 1264);
// Do any additional setup after loading the view, typically from a nib.
}
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
println("numberOfRowsInSection=\(section)")
return self.channelList.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("channelCell", forIndexPath: indexPath) as! UITableViewCell
var channel = self.channelList[indexPath.row]
if channel.name == nil {
return cell
}
cell.textLabel?.text = channel.name
var imgurl:NSURL = NSURL(string: "")!
if channel.defaultCover != nil {
imgurl = NSURL(string:channel.defaultCover)!
}else if channel.cover != nil {
imgurl = NSURL(string:channel.cover)!
}
println("imgurl=\(imgurl)")
cell.imageView?.sd_setImageWithURL(imgurl, placeholderImage: UIImage(named: "default_hoder_170x100.jpg"), options: SDWebImageOptions.ContinueInBackground, progress: { (a:Int, b:Int) -> Void in
println("image pross=\(a/b)")
}, completed: { (image:UIImage!, error:NSError!, cacheType:SDImageCacheType, imgurl:NSURL!) -> Void in
println("cached finished")
})
return cell
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| 308f4ba62e2c6e843ef53c7791cc421b | 42.219048 | 200 | 0.578669 | false | false | false | false |
LocationKit/Vacation-Tracker-Swift | refs/heads/master | Vacation-Tracker-Swift/VTTabBarViewController.swift | mit | 2 | //
// VTTabBarViewController.swift
// Vacation-Tracker-Swift
//
// Created by Spencer Atkin on 7/29/15.
// Copyright (c) 2015 SocialRadar. All rights reserved.
//
import Foundation
import UIKit
class VTTabBarViewController: UITabBarController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func loadView() {
super.loadView()
self.tabBar.tintColor = UIColor(red: 0.97, green: 0.33, blue: 0.1, alpha: 1)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
if !NSUserDefaults.standardUserDefaults().boolForKey("HasLaunchedOnce") {
VTTabBarViewController.showWelcome(self)
NSUserDefaults.standardUserDefaults().setBool(true, forKey: "HasLaunchedOnce")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
static func showWelcome(sender: UIViewController) {
// Welcome page
var welcomePage = OnboardingContentViewController(title: "Welcome!", body: "Thank you for downloading VacationTracker.", image: nil, buttonText: nil, action: nil)
welcomePage.titleTextColor = UIColor(red: 0.97, green: 0.33, blue: 0.1, alpha: 1)
welcomePage.underTitlePadding = 185
// First info page
var firstPage = OnboardingContentViewController(title: "Introduction", body: "VacationTracker automatically saves the places you visit during your vacations so they can easily be viewed later.", image: nil, buttonText: nil, action: nil)
firstPage.underTitlePadding = 150
// Second info page
var secondPage = OnboardingContentViewController(title: "Features", body: "Visits can be shown on the map or viewed in the list view. When viewing a visit, you can add a rating and comments.", image: nil, buttonText: nil, action: nil)
secondPage.underTitlePadding = 150
// Third info page
var thirdPage = OnboardingContentViewController(title: "Controls", body: "You can use the search button to discover places around you, and the pin button creates a visit at your current location.", image: nil, buttonText: "Get Started!") { () -> Void in
sender.dismissViewControllerAnimated(true, completion: nil)
UIApplication.sharedApplication().statusBarHidden = false
}
thirdPage.underTitlePadding = 150
thirdPage.buttonTextColor = UIColor(red: 0.97, green: 0.33, blue: 0.1, alpha: 1)
// Main onboarding vc
var onboardingVC = OnboardingViewController(backgroundImage: UIImage(named: "info-background"), contents: [welcomePage, firstPage, secondPage, thirdPage])
// Configures appearance
onboardingVC.topPadding = 10
onboardingVC.bottomPadding = 10
onboardingVC.shouldFadeTransitions = true
// Configures page control
onboardingVC.pageControl.currentPageIndicatorTintColor = UIColor.whiteColor()
onboardingVC.pageControl.backgroundColor = UIColor.clearColor()
onboardingVC.pageControl.opaque = false
// Allows info to be skipped
onboardingVC.allowSkipping = true
onboardingVC.skipHandler = { () -> Void in
sender.dismissViewControllerAnimated(true, completion: nil)
UIApplication.sharedApplication().statusBarHidden = true
}
sender.presentViewController(onboardingVC, animated: true, completion: nil)
UIApplication.sharedApplication().statusBarHidden = true
}
} | d9a5e4766e17a9deb3a633729d0326e3 | 45.894737 | 261 | 0.681729 | false | false | false | false |
jakub-tucek/fit-checker-2.0 | refs/heads/master | fit-checker/controller/SettingsViewController.swift | mit | 1 | //
// SettingsViewController.swift
// fit-checker
//
// Created by Josef Dolezal on 20/01/2017.
// Copyright © 2017 Josef Dolezal. All rights reserved.
//
import UIKit
/// User settings view controller.
class SettingsViewController: UIViewController {
/// Shared operations queue
private let operationQueue = OperationQueue()
/// Database context manager
private let contextManager: ContextManager
//MARK: - Initializers
init(contextManager: ContextManager) {
self.contextManager = contextManager
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK: - Logic
/// Logout button
private let logoutButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle(tr(.logout), for: .normal)
return button
}()
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
/// Run logout procedure
func logout() {
let logoutOperation = LogoutOperation(contextManager: contextManager)
operationQueue.addOperation(logoutOperation)
}
//MARK: - Private methods
/// Configure view and subviews
private func configureView() {
view.addSubview(logoutButton)
view.backgroundColor = .white
logoutButton.addTarget(self, action: #selector(logout),
for: .touchUpInside)
logoutButton.translatesAutoresizingMaskIntoConstraints = false
let constraints = [
logoutButton.centerXAnchor.constraint(equalTo: view.centerXAnchor),
logoutButton.centerYAnchor.constraint(equalTo: view.centerYAnchor),
logoutButton.widthAnchor.constraint(equalToConstant: 150),
logoutButton.heightAnchor.constraint(equalToConstant: 22)
]
constraints.forEach({ $0.isActive = true })
}
}
| 50a0ec145070ab0575d743593b9c5fca | 25.306667 | 79 | 0.65484 | false | false | false | false |
lyft/SwiftLint | refs/heads/master | Source/SwiftLintFramework/Models/Correction.swift | mit | 1 | public struct Correction: Equatable {
public let ruleDescription: RuleDescription
public let location: Location
public var consoleDescription: String {
return "\(location) Corrected \(ruleDescription.name)"
}
}
// MARK: Equatable
public func == (lhs: Correction, rhs: Correction) -> Bool {
return lhs.ruleDescription == rhs.ruleDescription &&
lhs.location == rhs.location
}
| c33018f0a324b353d20737d12d33802d | 26.533333 | 62 | 0.694915 | false | false | false | false |
HTWDD/HTWDresden-iOS | refs/heads/master | HTWDD/Components/Dashboard/Main/Views/DashboardTimeTableNoStudyTokenViewCell.swift | gpl-2.0 | 1 | //
// DashboardTimeTableNoStudyTokenViewCell.swift
// HTWDD
//
// Created by Mustafa Karademir on 30.09.19.
// Copyright © 2019 HTW Dresden. All rights reserved.
//
import UIKit
class DashboardTimeTableNoStudyTokenViewCell: UITableViewCell {
// MARK: - Outlets
@IBOutlet weak var mainView: UIView!
@IBOutlet weak var lblTitle: UILabel!
@IBOutlet weak var lblMessage: UILabel!
@IBOutlet weak var chevron: UIImageView!
override func awakeFromNib() {
super.awakeFromNib()
mainView.apply {
$0.backgroundColor = UIColor.htw.cellBackground
$0.layer.cornerRadius = 4
}
lblTitle.apply {
$0.textColor = UIColor.htw.Label.primary
$0.text = R.string.localizable.examsNoCredentialsTitle()
}
lblMessage.apply {
$0.textColor = UIColor.htw.Label.secondary
$0.text = R.string.localizable.onboardingStudygroupInformation()
}
chevron.apply {
$0.tintColor = UIColor.htw.Icon.primary
}
}
}
// MARK: - Loadable
extension DashboardTimeTableNoStudyTokenViewCell: FromNibLoadable {}
| 52be1c6bc7a2235db02cf0b3f85c32ab | 24.914894 | 76 | 0.614943 | false | false | false | false |
finngaida/wwdc | refs/heads/master | 2016/Finn Gaida/AppBoxWidget.swift | gpl-2.0 | 1 | //
// AppBoxWidget.swift
// Finn Gaida
//
// Created by Finn Gaida on 24.04.16.
// Copyright © 2016 Finn Gaida. All rights reserved.
//
import UIKit
import GradientView
class AppBoxWidget: UIView {
override init(frame: CGRect) {
super.init(frame: frame)
self.layer.masksToBounds = true
self.layer.cornerRadius = frame.height / 20
let gradientView = GradientView(frame: CGRectMake(0, 0, frame.width, frame.height))
gradientView.colors = [UIColor(red: 229/255, green: 57/255, blue: 53/255, alpha: 1), UIColor(red: 255/255, green: 179/255, blue: 0/255, alpha: 1)]
self.addSubview(gradientView)
let confetti = SAConfettiView(frame: gradientView.frame)
confetti.startConfetti()
self.layer.addSublayer(confetti.layer)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| 308d5e99566105e4e8e2adcd29ebbce3 | 27.147059 | 154 | 0.636364 | false | false | false | false |
ArnavChawla/InteliChat | refs/heads/master | CodedayProject/EulaViewController.swift | mit | 1 | import UIKit
import FirebaseAuth
import FirebaseDatabase
class EulaViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func Disagree(_ sender: Any) {
var storyboard = UIStoryboard(name: "Main", bundle: nil)
if s == true
{
storyboard = UIStoryboard(name: "Main", bundle: nil)
}
else if p == true{
storyboard = UIStoryboard(name: "big", bundle: nil)
}
else if se == true
{
storyboard = UIStoryboard(name: "se", bundle: nil)
}
else if os == true{
storyboard = UIStoryboard(name: "4s", bundle: nil)
}
else if ip1 == true
{
storyboard = UIStoryboard(name: "ipad1", bundle: nil)
}
else if ipb == true
{
storyboard = UIStoryboard(name: "ipadbig", bundle: nil)
}
let naviVC = storyboard.instantiateViewController(withIdentifier: "hello")as! UIViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = naviVC
}
@IBAction func agree(_ sender: Any) {
if x == true
{
let user = FIRAuth.auth()!.currentUser
let newUser = FIRDatabase.database().reference().child("Users").child(user!.uid)
newUser.setValue(["dislayName": "\(user!.displayName!)", "id": "\(user!.uid)", "url": "\(user!.photoURL!)", "Agreed": "true", "blocked by" : "nil"])
var storyboard = UIStoryboard(name: "Main", bundle: nil)
if s == true
{
storyboard = UIStoryboard(name: "Main", bundle: nil)
}
else if p == true{
storyboard = UIStoryboard(name: "big", bundle: nil)
}
else if se == true
{
storyboard = UIStoryboard(name: "se", bundle: nil)
}
else if os == true{
storyboard = UIStoryboard(name: "4s", bundle: nil)
}
else if ip1 == true
{
storyboard = UIStoryboard(name: "ipad1", bundle: nil)
}
else if ipb == true
{
storyboard = UIStoryboard(name: "ipadbig", bundle: nil)
}
let naviVC = storyboard.instantiateViewController(withIdentifier: "yo")as! UIViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = naviVC
}
else
{
FIRAuth.auth()?.createUser(withEmail: EmailString, password: PASSWORD, completion: { (user, error) in
if error != nil{
print(error?.localizedDescription)
}
else
{
isNew = true
print("userLoggedIn")
FIRAuth.auth()?.signIn(withEmail: EmailString, password: PASSWORD, completion: { (user, error) in
if error != nil{
print(error?.localizedDescription)
}
else
{
print(user?.uid)
}
})
var storyboard = UIStoryboard(name: "Main", bundle: nil)
if s == true
{
storyboard = UIStoryboard(name: "Main", bundle: nil)
}
else if p == true{
storyboard = UIStoryboard(name: "big", bundle: nil)
}
else if se == true
{
storyboard = UIStoryboard(name: "se", bundle: nil)
}
else if os == true{
storyboard = UIStoryboard(name: "4s", bundle: nil)
}
else if ip1 == true
{
storyboard = UIStoryboard(name: "ipad1", bundle: nil)
}
else if ipb == true
{
storyboard = UIStoryboard(name: "ipadbig", bundle: nil)
}
let naviVC = storyboard.instantiateViewController(withIdentifier: "eula") as! UIViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = naviVC
ne = true
}
})
var storyboard = UIStoryboard(name: "Main", bundle: nil)
if s == true
{
storyboard = UIStoryboard(name: "Main", bundle: nil)
}
else if p == true{
storyboard = UIStoryboard(name: "big", bundle: nil)
}
else if se == true
{
storyboard = UIStoryboard(name: "se", bundle: nil)
}
else if os == true{
storyboard = UIStoryboard(name: "4s", bundle: nil)
}
else if ip1 == true
{
storyboard = UIStoryboard(name: "ipad1", bundle: nil)
}
else if ipb == true
{
storyboard = UIStoryboard(name: "ipadbig", bundle: nil)
}
let naviVC = storyboard.instantiateViewController(withIdentifier: "pls")as! UIViewController
let appDelegate = UIApplication.shared.delegate as! AppDelegate
appDelegate.window?.rootViewController = naviVC
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| 2ab7e66cf4147948759538fa472f2248 | 36.532544 | 160 | 0.49125 | false | false | false | false |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.